unsigned long # define BN_LONG long # define BN_BITS 128 # define BN_BYTES 8 # define BN_BITS2 64 # define BN_BITS4 32 # define BN_MASK ( 0xffffffffffffffffffffffffffffffffLL ) # define BN_MASK2 ( 0xffffffffffffffffL ) # define BN_MASK2l ( 0xffffffffL ) # define BN_MASK2h ( 0xffffffff00000000L ) # define BN_MASK2h1 ( 0xffffffff80000000L ) # define BN_TBIT ( 0x8000000000000000L ) # define BN_DEC_CONV ( 10000000000000000000UL ) # define BN_DEC_FMT1 "%lu" # define BN_DEC_FMT2 "%019lu" # define BN_DEC_NUM 19 # define BN_HEX_FMT1 "%lX" # define BN_HEX_FMT2 "%016lX" # endif # ifdef SIXTY_FOUR_BIT # undef BN_LLONG # undef BN_ULLONG # define BN_ULONG unsigned long long # define BN_LONG long long # define BN_BITS 128 # define BN_BYTES 8 # define BN_BITS2 64 # define BN_BITS4 32 # define BN_MASK2 ( 0xffffffffffffffffLL ) # define BN_MASK2l ( 0xffffffffL ) # define BN_MASK2h ( 0xffffffff00000000LL ) # define BN_MASK2h1 ( 0xffffffff80000000LL ) # define BN_TBIT ( 0x8000000000000000LL ) # define BN_DEC_CONV ( 10000000000000000000ULL ) # define BN_DEC_FMT1 "%llu" # define BN_DEC_FMT2 "%019llu" # define BN_DEC_NUM 19 # define BN_HEX_FMT1 "%llX" # define BN_HEX_FMT2 "%016llX" # endif # ifdef THIRTY_TWO_BIT # ifdef BN_LLONG # if defined ( _WIN32 ) && ! defined ( __GNUC__ ) # define BN_ULLONG unsigned __int64 # define BN_MASK ( 0xffffffffffffffffI64 ) # else # define BN_ULLONG unsigned long long # define BN_MASK ( 0xffffffffffffffffLL ) # endif # endif # define BN_ULONG unsigned int # define BN_LONG int # define BN_BITS 64 # define BN_BYTES 4 # define BN_BITS2 32 # define BN_BITS4 16 # define BN_MASK2 ( 0xffffffffL ) # define BN_MASK2l ( 0xffff ) # define BN_MASK2h1 ( 0xffff8000L ) # define BN_MASK2h ( 0xffff0000L ) # define BN_TBIT ( 0x80000000L ) # define BN_DEC_CONV ( 1000000000L ) # define BN_DEC_FMT1 "%u" # define BN_DEC_FMT2 "%09u" # define BN_DEC_NUM 9 # define BN_HEX_FMT1 "%X" # define BN_HEX_FMT2 "%08X" # endif # define BN_DEFAULT_BITS 1280 # define BN_FLG_MALLOCED 0x01 # define BN_FLG_STATIC_DATA 0x02 # define BN_FLG_CONSTTIME 0x04 # ifndef OPENSSL_NO_DEPRECATED # define BN_FLG_EXP_CONSTTIME BN_FLG_CONSTTIME # endif # ifndef OPENSSL_NO_DEPRECATED # define BN_FLG_FREE 0x8000 # endif # define BN_set_flags ( b , n ) ( ( b ) -> flags |= ( n ) ) # define BN_get_flags ( b , n ) ( ( b ) -> flags & ( n ) ) # define BN_with_flags ( dest , b , n ) ( ( dest ) -> d = ( b ) -> d , \ ( dest ) -> top = ( b ) -> top , \ ( dest ) -> dmax = ( b ) -> dmax , \ ( dest ) -> neg = ( b ) -> neg , \ ( dest ) -> flags = ( ( ( dest ) -> flags & BN_FLG_MALLOCED ) \ | ( ( b ) -> flags & ~ BN_FLG_MALLOCED ) \ | BN_FLG_STATIC_DATA \ | ( n ) ) ) # if 0 typedef struct bignum_st BIGNUM ;
 typedef struct bignum_ctx BN_CTX ;
 typedef struct bn_blinding_st BN_BLINDING ;
 typedef struct bn_mont_ctx_st BN_MONT_CTX ;
 typedef struct bn_recp_ctx_st BN_RECP_CTX ;
 typedef struct bn_gencb_st BN_GENCB ;
 # endif struct bignum_st {
 BN_ULONG * d ;
 int top ;
 int dmax ;
 int neg ;
 int flags ;
 }
 ;
 struct bn_mont_ctx_st {
 int ri ;
 BIGNUM RR ;
 BIGNUM N ;
 BIGNUM Ni ;
 BN_ULONG n0 [ 2 ] ;
 int flags ;
 }
 ;
 struct bn_recp_ctx_st {
 BIGNUM N ;
 BIGNUM Nr ;
 int num_bits ;
 int shift ;
 int flags ;
 }
 ;
 struct bn_gencb_st {
 unsigned int ver ;
 void * arg ;
 union {
 void ( * cb_1 ) ( int , int , void * ) ;
 int ( * cb_2 ) ( int , int , BN_GENCB * ) ;
 }
 cb ;
 }
 ;
 int BN_GENCB_call ( BN_GENCB * cb , int a , int b ) ;
 # define BN_GENCB_set_old ( gencb , callback , cb_arg ) {
 \ BN_GENCB * tmp_gencb = ( gencb ) ;
 \ tmp_gencb -> ver = 1 ;
 \ tmp_gencb -> arg = ( cb_arg ) ;
 \ tmp_gencb -> cb . cb_1 = ( callback ) ;
 }
 # define BN_GENCB_set ( gencb , callback , cb_arg ) {
 \ BN_GENCB * tmp_gencb = ( gencb ) ;
 \ tmp_gencb -> ver = 2 ;
 \ tmp_gencb -> arg = ( cb_arg ) ;
 \ tmp_gencb -> cb . cb_2 = ( callback ) ;
 }
 # define BN_prime_checks 0 # define BN_prime_checks_for_size ( b ) ( ( b ) >= 1300 ? 2 : \ ( b ) >= 850 ? 3 : \ ( b ) >= 650 ? 4 : \ ( b ) >= 550 ? 5 : \ ( b ) >= 450 ? 6 : \ ( b ) >= 400 ? 7 : \ ( b ) >= 350 ? 8 : \ ( b ) >= 300 ? 9 : \ ( b ) >= 250 ? 12 : \ ( b ) >= 200 ? 15 : \ ( b ) >= 150 ? 18 : \ 27 ) # define BN_num_bytes ( a ) ( ( BN_num_bits ( a ) + 7 ) / 8 ) # define BN_abs_is_word ( a , w ) ( ( ( ( a ) -> top == 1 ) && ( ( a ) -> d [ 0 ] == ( BN_ULONG ) ( w ) ) ) || \ ( ( ( w ) == 0 ) && ( ( a ) -> top == 0 ) ) ) # define BN_is_zero ( a ) ( ( a ) -> top == 0 ) # define BN_is_one ( a ) ( BN_abs_is_word ( ( a ) , 1 ) && ! ( a ) -> neg ) # define BN_is_word ( a , w ) ( BN_abs_is_word ( ( a ) , ( w ) ) && ( ! ( w ) || ! ( a ) -> neg ) ) # define BN_is_odd ( a ) ( ( ( a ) -> top > 0 ) && ( ( a ) -> d [ 0 ] & 1 ) ) # define BN_one ( a ) ( BN_set_word ( ( a ) , 1 ) ) # define BN_zero_ex ( a ) \ do {
 \ BIGNUM * _tmp_bn = ( a ) ;
 \ _tmp_bn -> top = 0 ;
 \ _tmp_bn -> neg = 0 ;
 \ }
 while ( 0 ) # ifdef OPENSSL_NO_DEPRECATED # define BN_zero ( a ) BN_zero_ex ( a ) # else # define BN_zero ( a ) ( BN_set_word ( ( a ) , 0 ) ) # endif const BIGNUM * BN_value_one ( void ) ;
 char * BN_options ( void ) ;
 BN_CTX * BN_CTX_new ( void ) ;
 # ifndef OPENSSL_NO_DEPRECATED void BN_CTX_init ( BN_CTX * c ) ;
 # endif void BN_CTX_free ( BN_CTX * c ) ;
 void BN_CTX_start ( BN_CTX * ctx ) ;
 BIGNUM * BN_CTX_get ( BN_CTX * ctx ) ;
 void BN_CTX_end ( BN_CTX * ctx ) ;
 int BN_rand ( BIGNUM * rnd , int bits , int top , int bottom ) ;
 int BN_pseudo_rand ( BIGNUM * rnd , int bits , int top , int bottom ) ;
 int BN_rand_range ( BIGNUM * rnd , const BIGNUM * range ) ;
 int BN_pseudo_rand_range ( BIGNUM * rnd , const BIGNUM * range ) ;
 int BN_num_bits ( const BIGNUM * a ) ;
 int BN_num_bits_word ( BN_ULONG l ) ;
 BIGNUM * BN_new ( void ) ;
 void BN_init ( BIGNUM * ) ;
 void BN_clear_free ( BIGNUM * a ) ;
 BIGNUM * BN_copy ( BIGNUM * a , const BIGNUM * b ) ;
 void BN_swap ( BIGNUM * a , BIGNUM * b ) ;
 BIGNUM * BN_bin2bn ( const unsigned char * s , int len , BIGNUM * ret ) ;
 int BN_bn2bin ( const BIGNUM * a , unsigned char * to ) ;
 BIGNUM * BN_mpi2bn ( const unsigned char * s , int len , BIGNUM * ret ) ;
 int BN_bn2mpi ( const BIGNUM * a , unsigned char * to ) ;
 int BN_sub ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b ) ;
 int BN_usub ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b ) ;
 int BN_uadd ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b ) ;
 int BN_add ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b ) ;
 int BN_mul ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , BN_CTX * ctx ) ;
 int BN_sqr ( BIGNUM * r , const BIGNUM * a , BN_CTX * ctx ) ;
 void BN_set_negative ( BIGNUM * b , int n ) ;
 # define BN_is_negative ( a ) ( ( a ) -> neg != 0 ) int BN_div ( BIGNUM * dv , BIGNUM * rem , const BIGNUM * m , const BIGNUM * d , BN_CTX * ctx ) ;
 # define BN_mod ( rem , m , d , ctx ) BN_div ( NULL , ( rem ) , ( m ) , ( d ) , ( ctx ) ) int BN_nnmod ( BIGNUM * r , const BIGNUM * m , const BIGNUM * d , BN_CTX * ctx ) ;
 int BN_mod_add ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const BIGNUM * m , BN_CTX * ctx ) ;
 int BN_mod_add_quick ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const BIGNUM * m ) ;
 int BN_mod_sub ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const BIGNUM * m , BN_CTX * ctx ) ;
 int BN_mod_sub_quick ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const BIGNUM * m ) ;
 int BN_mod_mul ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const BIGNUM * m , BN_CTX * ctx ) ;
 int BN_mod_sqr ( BIGNUM * r , const BIGNUM * a , const BIGNUM * m , BN_CTX * ctx ) ;
 int BN_mod_lshift1 ( BIGNUM * r , const BIGNUM * a , const BIGNUM * m , BN_CTX * ctx ) ;
 int BN_mod_lshift1_quick ( BIGNUM * r , const BIGNUM * a , const BIGNUM * m ) ;
 int BN_mod_lshift ( BIGNUM * r , const BIGNUM * a , int n , const BIGNUM * m , BN_CTX * ctx ) ;
 int BN_mod_lshift_quick ( BIGNUM * r , const BIGNUM * a , int n , const BIGNUM * m ) ;
 BN_ULONG BN_mod_word ( const BIGNUM * a , BN_ULONG w ) ;
 BN_ULONG BN_div_word ( BIGNUM * a , BN_ULONG w ) ;
 int BN_mul_word ( BIGNUM * a , BN_ULONG w ) ;
 int BN_add_word ( BIGNUM * a , BN_ULONG w ) ;
 int BN_sub_word ( BIGNUM * a , BN_ULONG w ) ;
 int BN_set_word ( BIGNUM * a , BN_ULONG w ) ;
 BN_ULONG BN_get_word ( const BIGNUM * a ) ;
 int BN_cmp ( const BIGNUM * a , const BIGNUM * b ) ;
 void BN_free ( BIGNUM * a ) ;
 int BN_is_bit_set ( const BIGNUM * a , int n ) ;
 int BN_lshift ( BIGNUM * r , const BIGNUM * a , int n ) ;
 int BN_lshift1 ( BIGNUM * r , const BIGNUM * a ) ;
 int BN_exp ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_mod_exp ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , const BIGNUM * m , BN_CTX * ctx ) ;
 int BN_mod_exp_mont ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , const BIGNUM * m , BN_CTX * ctx , BN_MONT_CTX * m_ctx ) ;
 int BN_mod_exp_mont_consttime ( BIGNUM * rr , const BIGNUM * a , const BIGNUM * p , const BIGNUM * m , BN_CTX * ctx , BN_MONT_CTX * in_mont ) ;
 int BN_mod_exp_mont_word ( BIGNUM * r , BN_ULONG a , const BIGNUM * p , const BIGNUM * m , BN_CTX * ctx , BN_MONT_CTX * m_ctx ) ;
 int BN_mod_exp2_mont ( BIGNUM * r , const BIGNUM * a1 , const BIGNUM * p1 , const BIGNUM * a2 , const BIGNUM * p2 , const BIGNUM * m , BN_CTX * ctx , BN_MONT_CTX * m_ctx ) ;
 int BN_mod_exp_simple ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , const BIGNUM * m , BN_CTX * ctx ) ;
 int BN_mask_bits ( BIGNUM * a , int n ) ;
 # ifndef OPENSSL_NO_FP_API int BN_print_fp ( FILE * fp , const BIGNUM * a ) ;
 # endif # ifdef HEADER_BIO_H int BN_print ( BIO * fp , const BIGNUM * a ) ;
 # else int BN_print ( void * fp , const BIGNUM * a ) ;
 # endif int BN_reciprocal ( BIGNUM * r , const BIGNUM * m , int len , BN_CTX * ctx ) ;
 int BN_rshift ( BIGNUM * r , const BIGNUM * a , int n ) ;
 int BN_rshift1 ( BIGNUM * r , const BIGNUM * a ) ;
 void BN_clear ( BIGNUM * a ) ;
 BIGNUM * BN_dup ( const BIGNUM * a ) ;
 int BN_ucmp ( const BIGNUM * a , const BIGNUM * b ) ;
 int BN_set_bit ( BIGNUM * a , int n ) ;
 int BN_clear_bit ( BIGNUM * a , int n ) ;
 char * BN_bn2hex ( const BIGNUM * a ) ;
 char * BN_bn2dec ( const BIGNUM * a ) ;
 int BN_hex2bn ( BIGNUM * * a , const char * str ) ;
 int BN_dec2bn ( BIGNUM * * a , const char * str ) ;
 int BN_asc2bn ( BIGNUM * * a , const char * str ) ;
 int BN_gcd ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , BN_CTX * ctx ) ;
 int BN_kronecker ( const BIGNUM * a , const BIGNUM * b , BN_CTX * ctx ) ;
 BIGNUM * BN_mod_inverse ( BIGNUM * ret , const BIGNUM * a , const BIGNUM * n , BN_CTX * ctx ) ;
 BIGNUM * BN_mod_sqrt ( BIGNUM * ret , const BIGNUM * a , const BIGNUM * n , BN_CTX * ctx ) ;
 # ifndef OPENSSL_NO_DEPRECATED BIGNUM * BN_generate_prime ( BIGNUM * ret , int bits , int safe , const BIGNUM * add , const BIGNUM * rem , void ( * callback ) ( int , int , void * ) , void * cb_arg ) ;
 int BN_is_prime ( const BIGNUM * p , int nchecks , void ( * callback ) ( int , int , void * ) , BN_CTX * ctx , void * cb_arg ) ;
 int BN_is_prime_fasttest ( const BIGNUM * p , int nchecks , void ( * callback ) ( int , int , void * ) , BN_CTX * ctx , void * cb_arg , int do_trial_division ) ;
 # endif int BN_generate_prime_ex ( BIGNUM * ret , int bits , int safe , const BIGNUM * add , const BIGNUM * rem , BN_GENCB * cb ) ;
 int BN_is_prime_ex ( const BIGNUM * p , int nchecks , BN_CTX * ctx , BN_GENCB * cb ) ;
 int BN_is_prime_fasttest_ex ( const BIGNUM * p , int nchecks , BN_CTX * ctx , int do_trial_division , BN_GENCB * cb ) ;
 int BN_X931_generate_Xpq ( BIGNUM * Xp , BIGNUM * Xq , int nbits , BN_CTX * ctx ) ;
 int BN_X931_derive_prime_ex ( BIGNUM * p , BIGNUM * p1 , BIGNUM * p2 , const BIGNUM * Xp , const BIGNUM * Xp1 , const BIGNUM * Xp2 , const BIGNUM * e , BN_CTX * ctx , BN_GENCB * cb ) ;
 int BN_X931_generate_prime_ex ( BIGNUM * p , BIGNUM * p1 , BIGNUM * p2 , BIGNUM * Xp1 , BIGNUM * Xp2 , const BIGNUM * Xp , const BIGNUM * e , BN_CTX * ctx , BN_GENCB * cb ) ;
 BN_MONT_CTX * BN_MONT_CTX_new ( void ) ;
 void BN_MONT_CTX_init ( BN_MONT_CTX * ctx ) ;
 int BN_mod_mul_montgomery ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , BN_MONT_CTX * mont , BN_CTX * ctx ) ;
 # define BN_to_montgomery ( r , a , mont , ctx ) BN_mod_mul_montgomery ( \ ( r ) , ( a ) , & ( ( mont ) -> RR ) , ( mont ) , ( ctx ) ) int BN_from_montgomery ( BIGNUM * r , const BIGNUM * a , BN_MONT_CTX * mont , BN_CTX * ctx ) ;
 void BN_MONT_CTX_free ( BN_MONT_CTX * mont ) ;
 int BN_MONT_CTX_set ( BN_MONT_CTX * mont , const BIGNUM * mod , BN_CTX * ctx ) ;
 BN_MONT_CTX * BN_MONT_CTX_copy ( BN_MONT_CTX * to , BN_MONT_CTX * from ) ;
 BN_MONT_CTX * BN_MONT_CTX_set_locked ( BN_MONT_CTX * * pmont , int lock , const BIGNUM * mod , BN_CTX * ctx ) ;
 # define BN_BLINDING_NO_UPDATE 0x00000001 # define BN_BLINDING_NO_RECREATE 0x00000002 BN_BLINDING * BN_BLINDING_new ( const BIGNUM * A , const BIGNUM * Ai , BIGNUM * mod ) ;
 void BN_BLINDING_free ( BN_BLINDING * b ) ;
 int BN_BLINDING_update ( BN_BLINDING * b , BN_CTX * ctx ) ;
 int BN_BLINDING_convert ( BIGNUM * n , BN_BLINDING * b , BN_CTX * ctx ) ;
 int BN_BLINDING_invert ( BIGNUM * n , BN_BLINDING * b , BN_CTX * ctx ) ;
 int BN_BLINDING_convert_ex ( BIGNUM * n , BIGNUM * r , BN_BLINDING * b , BN_CTX * ) ;
 int BN_BLINDING_invert_ex ( BIGNUM * n , const BIGNUM * r , BN_BLINDING * b , BN_CTX * ) ;
 # ifndef OPENSSL_NO_DEPRECATED unsigned long BN_BLINDING_get_thread_id ( const BN_BLINDING * ) ;
 void BN_BLINDING_set_thread_id ( BN_BLINDING * , unsigned long ) ;
 # endif CRYPTO_THREADID * BN_BLINDING_thread_id ( BN_BLINDING * ) ;
 unsigned long BN_BLINDING_get_flags ( const BN_BLINDING * ) ;
 void BN_BLINDING_set_flags ( BN_BLINDING * , unsigned long ) ;
 BN_BLINDING * BN_BLINDING_create_param ( BN_BLINDING * b , const BIGNUM * e , BIGNUM * m , BN_CTX * ctx , int ( * bn_mod_exp ) ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , const BIGNUM * m , BN_CTX * ctx , BN_MONT_CTX * m_ctx ) , BN_MONT_CTX * m_ctx ) ;
 # ifndef OPENSSL_NO_DEPRECATED void BN_set_params ( int mul , int high , int low , int mont ) ;
 int BN_get_params ( int which ) ;
 # endif void BN_RECP_CTX_init ( BN_RECP_CTX * recp ) ;
 BN_RECP_CTX * BN_RECP_CTX_new ( void ) ;
 void BN_RECP_CTX_free ( BN_RECP_CTX * recp ) ;
 int BN_RECP_CTX_set ( BN_RECP_CTX * recp , const BIGNUM * rdiv , BN_CTX * ctx ) ;
 int BN_mod_mul_reciprocal ( BIGNUM * r , const BIGNUM * x , const BIGNUM * y , BN_RECP_CTX * recp , BN_CTX * ctx ) ;
 int BN_mod_exp_recp ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , const BIGNUM * m , BN_CTX * ctx ) ;
 int BN_div_recp ( BIGNUM * dv , BIGNUM * rem , const BIGNUM * m , BN_RECP_CTX * recp , BN_CTX * ctx ) ;
 # ifndef OPENSSL_NO_EC2M int BN_GF2m_add ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b ) ;
 # define BN_GF2m_sub ( r , a , b ) BN_GF2m_add ( r , a , b ) int BN_GF2m_mod ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p ) ;
 int BN_GF2m_mod_mul ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_GF2m_mod_sqr ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_GF2m_mod_inv ( BIGNUM * r , const BIGNUM * b , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_GF2m_mod_div ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_GF2m_mod_exp ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_GF2m_mod_sqrt ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_GF2m_mod_solve_quad ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , BN_CTX * ctx ) ;
 # define BN_GF2m_cmp ( a , b ) BN_ucmp ( ( a ) , ( b ) ) int BN_GF2m_mod_arr ( BIGNUM * r , const BIGNUM * a , const int p [ ] ) ;
 int BN_GF2m_mod_mul_arr ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const int p [ ] , BN_CTX * ctx ) ;
 int BN_GF2m_mod_sqr_arr ( BIGNUM * r , const BIGNUM * a , const int p [ ] , BN_CTX * ctx ) ;
 int BN_GF2m_mod_inv_arr ( BIGNUM * r , const BIGNUM * b , const int p [ ] , BN_CTX * ctx ) ;
 int BN_GF2m_mod_div_arr ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const int p [ ] , BN_CTX * ctx ) ;
 int BN_GF2m_mod_exp_arr ( BIGNUM * r , const BIGNUM * a , const BIGNUM * b , const int p [ ] , BN_CTX * ctx ) ;
 int BN_GF2m_mod_sqrt_arr ( BIGNUM * r , const BIGNUM * a , const int p [ ] , BN_CTX * ctx ) ;
 int BN_GF2m_mod_solve_quad_arr ( BIGNUM * r , const BIGNUM * a , const int p [ ] , BN_CTX * ctx ) ;
 int BN_GF2m_poly2arr ( const BIGNUM * a , int p [ ] , int max ) ;
 int BN_GF2m_arr2poly ( const int p [ ] , BIGNUM * a ) ;
 # endif int BN_nist_mod_192 ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_nist_mod_224 ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_nist_mod_256 ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_nist_mod_384 ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , BN_CTX * ctx ) ;
 int BN_nist_mod_521 ( BIGNUM * r , const BIGNUM * a , const BIGNUM * p , BN_CTX * ctx ) ;
 const BIGNUM * BN_get0_nist_prime_192 ( void ) ;
 const BIGNUM * BN_get0_nist_prime_224 ( void ) ;
 const BIGNUM * BN_get0_nist_prime_256 ( void ) ;
 const BIGNUM * BN_get0_nist_prime_384 ( void ) ;
 const BIGNUM * BN_get0_nist_prime_521 ( void ) ;
 int ( * BN_nist_mod_func ( const BIGNUM * p ) ) ( BIGNUM * r , const BIGNUM * a , const BIGNUM * field , BN_CTX * ctx ) ;
 int BN_generate_dsa_nonce ( BIGNUM * out , const BIGNUM * range , const BIGNUM * priv , const unsigned char * message , size_t message_len , BN_CTX * ctx ) ;
 # define bn_expand ( a , bits ) ( ( ( ( ( ( bits + BN_BITS2 - 1 ) ) / BN_BITS2 ) ) <= ( a ) -> dmax ) ? \ ( a ) : bn_expand2 ( ( a ) , ( bits + BN_BITS2 - 1 ) / BN_BITS2 ) ) # define bn_wexpand ( a , words ) ( ( ( words ) <= ( a ) -> dmax ) ? ( a ) : bn_expand2 ( ( a ) , ( words ) ) ) BIGNUM * bn_expand2 ( BIGNUM * a , int words ) ;
 # ifndef OPENSSL_NO_DEPRECATED BIGNUM * bn_dup_expand ( const BIGNUM * a , int words ) ;
 # endif # ifdef BN_DEBUG # include < assert . h > # ifdef BN_DEBUG_RAND # ifndef RAND_pseudo_bytes int RAND_pseudo_bytes ( unsigned char * buf , int num ) ;
 # define BN_DEBUG_TRIX # endif # define bn_pollute ( a ) \ do {
 \ const BIGNUM * _bnum1 = ( a ) ;
 \ if ( _bnum1 -> top < _bnum1 -> dmax ) {
 \ unsigned char _tmp_char ;
 \ \ BN_ULONG * _not_const ;
 \ memcpy ( & _not_const , & _bnum1 -> d , sizeof ( BN_ULONG * ) ) ;
 \ RAND_pseudo_bytes ( & _tmp_char , 1 ) ;
 \ memset ( ( unsigned char * ) ( _not_const + _bnum1 -> top ) , _tmp_char , \ ( _bnum1 -> dmax - _bnum1 -> top ) * sizeof ( BN_ULONG ) ) ;
 \ }
 \ }
 while ( 0 ) # ifdef BN_DEBUG_TRIX # undef RAND_pseudo_bytes # endif # else # define bn_pollute ( a ) # endif # define bn_check_top ( a ) \ do {
 \ const BIGNUM * _bnum2 = ( a ) ;
 \ if ( _bnum2 != NULL ) {
 \ assert ( ( _bnum2 -> top == 0 ) || \ ( _bnum2 -> d [ _bnum2 -> top - 1 ] != 0 ) ) ;
 \ bn_pollute ( _bnum2 ) ;
 \ }
 \ }
 while ( 0 ) # define bn_fix_top ( a ) bn_check_top ( a ) # else # define bn_pollute ( a ) # define bn_check_top ( a ) # define bn_fix_top ( a ) bn_correct_top ( a ) # endif # define bn_correct_top ( a ) \ {
 \ BN_ULONG * ftl ;
 \ int tmp_top = ( a ) -> top ;
 \ if ( tmp_top > 0 ) \ {
 \ for ( ftl = & ( ( a ) -> d [ tmp_top - 1 ] ) ;
 tmp_top > 0 ;
 tmp_top -- ) \ if ( * ( ftl -- ) ) break ;
 \ ( a ) -> top = tmp_top ;
 \ }
 \ bn_pollute ( a ) ;
 \ }
 BN_ULONG bn_mul_add_words ( BN_ULONG * rp , const BN_ULONG * ap , int num , BN_ULONG w ) ;
 BN_ULONG bn_mul_words ( BN_ULONG * rp , const BN_ULONG * ap , int num , BN_ULONG w )


writeRead (const Array2D<unsigned int> &pi1,
           const Array2D<half> &ph1,
           const Array2D<float> &pf1,
           const char fileName[],
           LineOrder lorder,
           int width,
           int height,
           int xSize,
           int ySize,
           int xOffset,
           int yOffset,
           Compression comp,
           LevelMode mode,
	   LevelRoundingMode rmode)
{
    //
    // Write the pixel data in pi1, ph1 and ph2 to a tiled
    // image file using the specified parameters.
    // Read the pixel data back from the file using the scanline
    // interface one scanline at a time, and verify that the data did
    // not change.
    // For MIPMAP and RIPMAP_LEVELS, the lower levels of the images
    // are filled in cropped versions of the level(0,0) image,
    // i.e. no filtering is done.
    //

    cout << "levelMode " << mode <<
	    ", roundingMode " << rmode <<
            ", line order " << lorder <<
            ",\ntileSize " << xSize << "x" << ySize <<
            ", xOffset " << xOffset <<
            ", yOffset "<< yOffset << endl;

    Header hdr ((Box2i (V2i (0, 0),                     // display window
                        V2i (width - 1, height -1))),
                (Box2i (V2i (xOffset, yOffset),         // data window
                        V2i (xOffset + width - 1, yOffset + height - 1))));
    hdr.lineOrder() = lorder;
    hdr.compression() = comp;

    hdr.channels().insert ("I", Channel (IMF::UINT));
    hdr.channels().insert ("H", Channel (IMF::HALF));
    hdr.channels().insert ("F", Channel (IMF::FLOAT));

    hdr.setTileDescription(TileDescription(xSize, ySize, mode, rmode));
    {
        FrameBuffer fb;

        fb.insert ("I",                                       // name
                   Slice (IMF::UINT,                          // type
                          (char *) &pi1[-yOffset][-xOffset],  // base
                          sizeof (pi1[0][0]),                 // xStride
                          sizeof (pi1[0][0]) * width)         // yStride
                  );

        fb.insert ("H",                                       // name
                   Slice (IMF::HALF,                          // type
                          (char *) &ph1[-yOffset][-xOffset],  // base
                          sizeof (ph1[0][0]),                 // xStride
                          sizeof (ph1[0][0]) * width)         // yStride
                  );

        fb.insert ("F",                                       // name
                   Slice (IMF::FLOAT,                              // type
                          (char *) &pf1[-yOffset][-xOffset],  // base
                          sizeof (pf1[0][0]),                 // xStride
                          sizeof (pf1[0][0]) * width)         // yStride
                  );

        cout << " writing" << flush;

        remove (fileName);
        TiledOutputFile out (fileName, hdr);
        out.setFrameBuffer (fb);

        int startTileY = -1;
	int endTileY = -1;
        int dy;

        switch (mode)
        {
          case ONE_LEVEL:
          {
            if (lorder == DECREASING_Y)
            {
                startTileY = out.numYTiles() - 1;
                endTileY = -1;

                dy = -1;
            }
            else
            {
                startTileY = 0;
                endTileY = out.numYTiles();

                dy = 1;
            }

            for (int tileY = startTileY; tileY != endTileY; tileY += dy)
                for (int tileX = 0; tileX < out.numXTiles(); ++tileX)
                    out.writeTile (tileX, tileY);
          }
          break;

          case MIPMAP_LEVELS:
          {
            if (lorder == DECREASING_Y)
            {
                endTileY = -1;
                dy = -1;
            }
            else
            {
                startTileY = 0;
                dy = 1;
            }

            for (int level = 0; level < out.numLevels(); ++level)
            {
                if (lorder == DECREASING_Y)
                    startTileY = out.numYTiles(level) - 1;
                else
                    endTileY = out.numYTiles(level);

                for (int tileY = startTileY; tileY != endTileY; tileY += dy)
                    for (int tileX = 0; tileX < out.numXTiles(level); ++tileX)
                        out.writeTile (tileX, tileY, level);
            }
          }
          break;

          case RIPMAP_LEVELS:
          {
            for (int ylevel = 0; ylevel < out.numYLevels(); ++ylevel)
            {
                if (lorder == DECREASING_Y)
                {
                    startTileY = out.numYTiles(ylevel) - 1;
                    endTileY = -1;

                    dy = -1;
                }
                else
                {
                    startTileY = 0;
                    endTileY = out.numYTiles(ylevel);

                    dy = 1;
                }

                for (int xlevel = 0; xlevel < out.numXLevels(); ++xlevel)
                {
                    for (int tileY = startTileY; tileY != endTileY;
                         tileY += dy)
                        for (int tileX = 0; tileX < out.numXTiles (xlevel);
                             ++tileX)
                            out.writeTile (tileX, tileY, xlevel, ylevel);
                }
            }
          }
          break;
			case NUM_LEVELMODES:
			default:
				std::cerr << "Invalid tile mode " << int(mode) << std::endl;
				break;
        }
    }

    {
        cout << " reading INCREASING_Y" << flush;

        InputFile in (fileName);

        const Box2i &dw = in.header().dataWindow();
        int w = dw.max.x - dw.min.x + 1;
        int h = dw.max.y - dw.min.y + 1;
        int dwx = dw.min.x;
        int dwy = dw.min.y;

        Array2D<unsigned int> pi2 (h, w);
        Array2D<half>         ph2 (h, w);
        Array2D<float>        pf2 (h, w);

        FrameBuffer fb;

        fb.insert ("I",                             // name
                   Slice (IMF::UINT,                // type
                          (char *) &pi2[-dwy][-dwx],// base
                          sizeof (pi2[0][0]),       // xStride
                          sizeof (pi2[0][0]) * w)   // yStride
                  );

        fb.insert ("H",                             // name
                   Slice (IMF::HALF,                // type
                          (char *) &ph2[-dwy][-dwx],// base
                          sizeof (ph2[0][0]),       // xStride
                          sizeof (ph2[0][0]) * w)   // yStride
                  );

        fb.insert ("F",                             // name
                   Slice (IMF::FLOAT,               // type
                          (char *) &pf2[-dwy][-dwx],// base
                          sizeof (pf2[0][0]),       // xStride
                          sizeof (pf2[0][0]) * w)   // yStride
                  );

        in.setFrameBuffer (fb);
        for (int y = dw.min.y; y <= dw.max.y; ++y)
            in.readPixels (y);

        cout << " comparing" << flush;

        assert (in.header().displayWindow() == hdr.displayWindow());
        assert (in.header().dataWindow() == hdr.dataWindow());
        assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio());
        assert (in.header().screenWindowCenter() == hdr.screenWindowCenter());
        assert (in.header().screenWindowWidth() == hdr.screenWindowWidth());
        assert (in.header().lineOrder() == hdr.lineOrder());
        assert (in.header().compression() == hdr.compression());

        ChannelList::ConstIterator hi = hdr.channels().begin();
        ChannelList::ConstIterator ii = in.header().channels().begin();

        while (hi != hdr.channels().end())
        {
            assert (!strcmp (hi.name(), ii.name()));
            assert (hi.channel().type == ii.channel().type);
            assert (hi.channel().xSampling == ii.channel().xSampling);
            assert (hi.channel().ySampling == ii.channel().ySampling);

            ++hi;
            ++ii;
        }

        assert (ii == in.header().channels().end());

        for (int y = 0; y < h; ++y)
        {
            for (int x = 0; x < w; ++x)
            {
                assert (pi1[y][x] == pi2[y][x]);
                assert (ph1[y][x] == ph2[y][x]);
                assert (pf1[y][x] == pf2[y][x]);
            }
        }
    }

    {
        cout << endl << "         reading DECREASING_Y" << flush;

        InputFile in (fileName);

        const Box2i &dw = in.header().dataWindow();
        int w = dw.max.x - dw.min.x + 1;
        int h = dw.max.y - dw.min.y + 1;
        int dwx = dw.min.x;
        int dwy = dw.min.y;

        Array2D<unsigned int> pi2 (h, w);
        Array2D<half>         ph2 (h, w);
        Array2D<float>        pf2 (h, w);

        FrameBuffer fb;

        fb.insert ("I",                             // name
                   Slice (IMF::UINT,                // type
                          (char *) &pi2[-dwy][-dwx],// base
                          sizeof (pi2[0][0]),       // xStride
                          sizeof (pi2[0][0]) * w)   // yStride
                  );

        fb.insert ("H",                             // name
                   Slice (IMF::HALF,                // type
                          (char *) &ph2[-dwy][-dwx],// base
                          sizeof (ph2[0][0]),       // xStride
                          sizeof (ph2[0][0]) * w)   // yStride
                  );

        fb.insert ("F",                             // name
                   Slice (IMF::FLOAT,               // type
                          (char *) &pf2[-dwy][-dwx],// base
                          sizeof (pf2[0][0]),       // xStride
                          sizeof (pf2[0][0]) * w)   // yStride
                  );

        in.setFrameBuffer (fb);
        for (int y = dw.max.y; y >= dw.min.y; --y)
            in.readPixels (y);

        cout << " comparing" << flush;

        assert (in.header().displayWindow() == hdr.displayWindow());
        assert (in.header().dataWindow() == hdr.dataWindow());
        assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio());
        assert (in.header().screenWindowCenter() == hdr.screenWindowCenter());
        assert (in.header().screenWindowWidth() == hdr.screenWindowWidth());
        assert (in.header().lineOrder() == hdr.lineOrder());
        assert (in.header().compression() == hdr.compression());

        ChannelList::ConstIterator hi = hdr.channels().begin();
        ChannelList::ConstIterator ii = in.header().channels().begin();

        while (hi != hdr.channels().end())
        {
            assert (!strcmp (hi.name(), ii.name()));
            assert (hi.channel().type == ii.channel().type);
            assert (hi.channel().xSampling == ii.channel().xSampling);
            assert (hi.channel().ySampling == ii.channel().ySampling);

            ++hi;
            ++ii;
        }

        assert (ii == in.header().channels().end());

        for (int y = 0; y < h; ++y)
        {
            for (int x = 0; x < w; ++x)
            {
                assert (pi1[y][x] == pi2[y][x]);
                assert (ph1[y][x] == ph2[y][x]);
                assert (pf1[y][x] == pf2[y][x]);
            }
        }
    }

    {
        cout << endl << "         reading INCREASING_Y "
		        "(new frame buffer on every line)" << flush;

        InputFile in (fileName);

        const Box2i &dw = in.header().dataWindow();
        int w = dw.max.x - dw.min.x + 1;
        int h = dw.max.y - dw.min.y + 1;
        int dwx = dw.min.x;
        int dwy = dw.min.y;

        Array2D<unsigned int> pi2 (h, w);
        Array2D<half>         ph2 (h, w);
        Array2D<float>        pf2 (h, w);

        for (int y = dw.min.y; y <= dw.max.y; ++y)
	{
	    FrameBuffer fb;

	    fb.insert ("I",					// name
		       Slice (IMF::UINT,			// type
			      (char *) &pi2[y - dwy][-dwx],	// base
			      sizeof (pi2[0][0]),		// xStride
			      0)				// yStride
		      );

	    fb.insert ("H",					// name
		       Slice (IMF::HALF,			// type
			      (char *) &ph2[y - dwy][-dwx],	// base
			      sizeof (ph2[0][0]),		// xStride
			      0)				// yStride
		      );

	    fb.insert ("F",                     	        // name
		       Slice (IMF::FLOAT,			// type
			      (char *) &pf2[y - dwy][-dwx],	// base
			      sizeof (pf2[0][0]),		// xStride
			      0)				// yStride
		      );

	    in.setFrameBuffer (fb);
            in.readPixels (y);
	}

        cout << " comparing" << flush;

        assert (in.header().displayWindow() == hdr.displayWindow());
        assert (in.header().dataWindow() == hdr.dataWindow());
        assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio());
        assert (in.header().screenWindowCenter() == hdr.screenWindowCenter());
        assert (in.header().screenWindowWidth() == hdr.screenWindowWidth());
        assert (in.header().lineOrder() == hdr.lineOrder());
        assert (in.header().compression() == hdr.compression());

        ChannelList::ConstIterator hi = hdr.channels().begin();
        ChannelList::ConstIterator ii = in.header().channels().begin();

        while (hi != hdr.channels().end())
        {
            assert (!strcmp (hi.name(), ii.name()));
            assert (hi.channel().type == ii.channel().type);
            assert (hi.channel().xSampling == ii.channel().xSampling);
            assert (hi.channel().ySampling == ii.channel().ySampling);

            ++hi;
            ++ii;
        }

        assert (ii == in.header().channels().end());

        for (int y = 0; y < h; ++y)
        {
            for (int x = 0; x < w; ++x)
            {
                assert (pi1[y][x] == pi2[y][x]);
                assert (ph1[y][x] == ph2[y][x]);
                assert (pf1[y][x] == pf2[y][x]);
            }
        }
    }

    remove (fileName);
    cout << endl;
}


static int sunrast_decode_frame ( AVCodecContext * avctx , void * data , int * got_frame , AVPacket * avpkt ) {
 const uint8_t * buf = avpkt -> data ;
 const uint8_t * buf_end = avpkt -> data + avpkt -> size ;
 SUNRASTContext * const s = avctx -> priv_data ;
 AVFrame * picture = data ;
 AVFrame * const p = & s -> picture ;
 unsigned int w , h , depth , type , maptype , maplength , stride , x , y , len , alen ;
 uint8_t * ptr ;
 const uint8_t * bufstart = buf ;
 int ret ;
 if ( avpkt -> size < 32 ) return AVERROR_INVALIDDATA ;
 if ( AV_RB32 ( buf ) != RAS_MAGIC ) {
 av_log ( avctx , AV_LOG_ERROR , "this is not sunras encoded data\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 w = AV_RB32 ( buf + 4 ) ;
 h = AV_RB32 ( buf + 8 ) ;
 depth = AV_RB32 ( buf + 12 ) ;
 type = AV_RB32 ( buf + 20 ) ;
 maptype = AV_RB32 ( buf + 24 ) ;
 maplength = AV_RB32 ( buf + 28 ) ;
 buf += 32 ;
 if ( type == RT_FORMAT_TIFF || type == RT_FORMAT_IFF || type == RT_EXPERIMENTAL ) {
 av_log_ask_for_sample ( avctx , "unsupported (compression) type\n" ) ;
 return AVERROR_PATCHWELCOME ;
 }
 if ( type > RT_FORMAT_IFF ) {
 av_log ( avctx , AV_LOG_ERROR , "invalid (compression) type\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 if ( av_image_check_size ( w , h , 0 , avctx ) ) {
 av_log ( avctx , AV_LOG_ERROR , "invalid image size\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 if ( maptype == RMT_RAW ) {
 av_log_ask_for_sample ( avctx , "unsupported colormap type\n" ) ;
 return AVERROR_PATCHWELCOME ;
 }
 if ( maptype > RMT_RAW ) {
 av_log ( avctx , AV_LOG_ERROR , "invalid colormap type\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 switch ( depth ) {
 case 1 : avctx -> pix_fmt = AV_PIX_FMT_MONOWHITE ;
 break ;
 case 8 : avctx -> pix_fmt = maplength ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_GRAY8 ;
 break ;
 case 24 : avctx -> pix_fmt = ( type == RT_FORMAT_RGB ) ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24 ;
 break ;
 default : av_log ( avctx , AV_LOG_ERROR , "invalid depth\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 if ( p -> data [ 0 ] ) avctx -> release_buffer ( avctx , p ) ;
 if ( w != avctx -> width || h != avctx -> height ) avcodec_set_dimensions ( avctx , w , h ) ;
 if ( ( ret = ff_get_buffer ( avctx , p ) ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "get_buffer() failed\n" ) ;
 return ret ;
 }
 p -> pict_type = AV_PICTURE_TYPE_I ;
 if ( buf_end - buf < maplength ) return AVERROR_INVALIDDATA ;
 if ( depth != 8 && maplength ) {
 av_log ( avctx , AV_LOG_WARNING , "useless colormap found or file is corrupted, trying to recover\n" ) ;
 }
 else if ( maplength ) {
 unsigned int len = maplength / 3 ;
 if ( maplength % 3 || maplength > 768 ) {
 av_log ( avctx , AV_LOG_WARNING , "invalid colormap length\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 ptr = p -> data [ 1 ] ;
 for ( x = 0 ;
 x < len ;
 x ++ , ptr += 4 ) * ( uint32_t * ) ptr = ( buf [ x ] << 16 ) + ( buf [ len + x ] << 8 ) + buf [ len + len + x ] ;
 }
 buf += maplength ;
 ptr = p -> data [ 0 ] ;
 stride = p -> linesize [ 0 ] ;
 len = ( depth * w + 7 ) >> 3 ;
 alen = len + ( len & 1 ) ;
 if ( type == RT_BYTE_ENCODED ) {
 int value , run ;
 uint8_t * end = ptr + h * stride ;
 x = 0 ;
 while ( ptr != end && buf < buf_end ) {
 run = 1 ;
 if ( buf_end - buf < 1 ) return AVERROR_INVALIDDATA ;
 if ( ( value = * buf ++ ) == RLE_TRIGGER ) {
 run = * buf ++ + 1 ;
 if ( run != 1 ) value = * buf ++ ;
 }
 while ( run -- ) {
 if ( x < len ) ptr [ x ] = value ;
 if ( ++ x >= alen ) {
 x = 0 ;
 ptr += stride ;
 if ( ptr == end ) break ;
 }
 }
 }
 }
 else {
 for ( y = 0 ;
 y < h ;
 y ++ ) {
 if ( buf_end - buf < len ) break ;
 memcpy ( ptr , buf , len ) ;
 ptr += stride ;
 buf += alen ;
 }
 }
 * picture = s -> picture ;
 * got_frame = 1 ;
 return buf - bufstart ;
 }


hufDecode
    (const Int64 * 	hcode,	// i : encoding table
     const HufDec * 	hdecod,	// i : decoding table
     const char* 	in,	// i : compressed input buffer
     int		ni,	// i : input size (in bits)
     int		rlc,	// i : run-length code
     int		no,	// i : expected output size (in bytes)
     unsigned short*	out)	//  o: uncompressed output buffer
{
    Int64 c = 0;
    int lc = 0;
    unsigned short * outb = out;
    unsigned short * oe = out + no;
    const char * ie = in + (ni + 7) / 8; // input byte size

    //
    // Loop on input bytes
    //

    while (in < ie)
    {
	getChar (c, lc, in);

	//
	// Access decoding table
	//

	while (lc >= HUF_DECBITS)
	{
	    const HufDec pl = hdecod[(c >> (lc-HUF_DECBITS)) & HUF_DECMASK];

	    if (pl.len)
	    {
		//
		// Get short code
		//

		lc -= pl.len;
		getCode (pl.lit, rlc, c, lc, in, out, outb, oe);
	    }
	    else
	    {
		if (!pl.p)
		    invalidCode(); // wrong code

		//
		// Search long code
		//

		int j;

		for (j = 0; j < pl.lit; j++)
		{
		    int	l = hufLength (hcode[pl.p[j]]);

		    while (lc < l && in < ie)	// get more bits
			getChar (c, lc, in);

		    if (lc >= l)
		    {
			if (hufCode (hcode[pl.p[j]]) ==
				((c >> (lc - l)) & ((Int64(1) << l) - 1)))
			{
			    //
			    // Found : get long code
			    //

			    lc -= l;
			    getCode (pl.p[j], rlc, c, lc, in, out, outb, oe);
			    break;
			}
		    }
		}

		if (j == pl.lit)
		    invalidCode(); // Not found
	    }
	}
    }

    //
    // Get remaining (short) codes
    //

    int i = (8 - ni) & 7;
    c >>= i;
    lc -= i;

    while (lc > 0)
    {
	const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];

	if (pl.len)
	{
	    lc -= pl.len;
	    getCode (pl.lit, rlc, c, lc, in, out, outb, oe);
	}
	else
	{
	    invalidCode(); // wrong (long) code
	}
    }

    if (out - outb != no)
	notEnoughData ();
}


static int vp3_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; Vp3DecodeContext *s = avctx->priv_data; GetBitContext gb; int i, ret; if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0) return ret; #if CONFIG_THEORA_DECODER if (s->theora && get_bits1(&gb)) { int type = get_bits(&gb, 7); skip_bits_long(&gb, 6*8); /* "theora" */ if (s->avctx->active_thread_type&FF_THREAD_FRAME) { av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n"); return AVERROR_PATCHWELCOME; } if (type == 0) { vp3_decode_end(avctx); ret = theora_decode_header(avctx, &gb); if (ret < 0) { vp3_decode_end(avctx); } else ret = vp3_decode_init(avctx); return ret; } else if (type == 2) { ret = theora_decode_tables(avctx, &gb); if (ret < 0) { vp3_decode_end(avctx); } else ret = vp3_decode_init(avctx); return ret; } av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n"); return -1; } #endif s->keyframe = !get_bits1(&gb); if (!s->all_fragments) { av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n"); return -1; } if (!s->theora) skip_bits(&gb, 1); for (i = 0; i < 3; i++) s->last_qps[i] = s->qps[i]; s->nqps = 0; do { s->qps[s->nqps++] = get_bits(&gb, 6); } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb)); for (i = s->nqps; i < 3; i++) s->qps[i] = -1; if (s->avctx->debug & FF_DEBUG_PICT_INFO) av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n", s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]); s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] || avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL : AVDISCARD_NONKEY); if (s->qps[0] != s->last_qps[0]) init_loop_filter(s); for (i = 0; i < s->nqps; i++) // reinit all dequantizers if the first one changed, because // the DC of the first quantizer must be used for all matrices if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0]) init_dequantizer(s, i); if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe) return buf_size; s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; s->current_frame.f->key_frame = s->keyframe; if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0) goto error; if (!s->edge_emu_buffer) s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0])); if (s->keyframe) { if (!s->theora) { skip_bits(&gb, 4); /* width code */ skip_bits(&gb, 4); /* height code */ if (s->version) { s->version = get_bits(&gb, 5); if (avctx->frame_number == 0) av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version); } } if (s->version || s->theora) { if (get_bits1(&gb)) av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n"); skip_bits(&gb, 2); /* reserved? */ } } else { if (!s->golden_frame.f->data[0]) { av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n"); s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I; if (ff_thread_get_buffer(avctx, &s->golden_frame, AV_GET_BUFFER_FLAG_REF) < 0) goto error; ff_thread_release_buffer(avctx, &s->last_frame); if ((ret = ff_thread_ref_frame(&s->last_frame, &s->golden_frame)) < 0) goto error; ff_thread_report_progress(&s->last_frame, INT_MAX, 0); } } memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment)); ff_thread_finish_setup(avctx); if (unpack_superblocks(s, &gb)) { av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n"); goto error; } if (unpack_modes(s, &gb)) { av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n"); goto error; } if (unpack_vectors(s, &gb)) { av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n"); goto error; } if (unpack_block_qpis(s, &gb)) { av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n"); goto error; } if (unpack_dct_coeffs(s, &gb)) { av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n"); goto error; } for (i = 0; i < 3; i++) { int height = s->height >> (i && s->chroma_y_shift); if (s->flipped_image) s->data_offset[i] = 0; else s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i]; } s->last_slice_end = 0; for (i = 0; i < s->c_superblock_height; i++) render_slice(s, i); // filter the last row for (i = 0; i < 3; i++) { int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1; apply_loop_filter(s, i, row, row + 1); } vp3_draw_horiz_band(s, s->height); /* output frame, offset as needed */ if ((ret = av_frame_ref(data, s->current_frame.f)) < 0) return ret; for (i = 0; i < 3; i++) { AVFrame *dst = data; int off = (s->offset_x >> (i && s->chroma_y_shift)) + (s->offset_y >> (i && s->chroma_y_shift)) * dst->linesize[i]; dst->data[i] += off; } *got_frame = 1; if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) { ret = update_frames(avctx); if (ret < 0) return ret; } return buf_size; error: ff_thread_report_progress(&s->current_frame, INT_MAX, 0); if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) av_frame_unref(s->current_frame.f); return -1; }


error_t dm9000SendPacket(NetInterface *interface,
   const NetBuffer *buffer, size_t offset, NetTxAncillary *ancillary)
{
   size_t i;
   size_t length;
   uint16_t *p;
   Dm9000Context *context;

   //Point to the driver context
   context = (Dm9000Context *) interface->nicContext;

   //Retrieve the length of the packet
   length = netBufferGetLength(buffer) - offset;

   //Check the frame length
   if(length > ETH_MAX_FRAME_SIZE)
   {
      //The transmitter can accept another packet
      osSetEvent(&interface->nicTxEvent);
      //Report an error
      return ERROR_INVALID_LENGTH;
   }

   //Copy user data
   netBufferRead(context->txBuffer, buffer, offset, length);

   //A dummy write is required before accessing FIFO
   dm9000WriteReg(DM9000_MWCMDX, 0);
   //Select MWCMD register
   DM9000_INDEX_REG = DM9000_MWCMD;

   //Point to the beginning of the buffer
   p = (uint16_t *) context->txBuffer;

   //Write data to the FIFO using 16-bit mode
   for(i = length; i > 1; i -= 2)
   {
      DM9000_DATA_REG = *(p++);
   }

   //Odd number of bytes?
   if(i > 0)
   {
      DM9000_DATA_REG = *((uint8_t *) p);
   }

   //Write the number of bytes to send
   dm9000WriteReg(DM9000_TXPLL, LSB(length));
   dm9000WriteReg(DM9000_TXPLH, MSB(length));

   //Clear interrupt flag
   dm9000WriteReg(DM9000_ISR, DM9000_ISR_PT);
   //Start data transfer
   dm9000WriteReg(DM9000_TCR, DM9000_TCR_TXREQ);

   //The packet was successfully written to FIFO
   context->queuedPackets++;

   //Successful processing
   return NO_ERROR;
}


error_t dm9000UpdateMacAddrFilter(NetInterface *interface)
{
   uint_t i;
   uint_t k;
   uint32_t crc;
   uint8_t hashTable[8];
   MacFilterEntry *entry;

   //Debug message
   TRACE_DEBUG("Updating MAC filter...\r\n");

   //Clear hash table
   osMemset(hashTable, 0, sizeof(hashTable));
   //Always accept broadcast packets regardless of the MAC filter table
   hashTable[7] = 0x80;

   //The MAC address filter contains the list of MAC addresses to accept
   //when receiving an Ethernet frame
   for(i = 0; i < MAC_ADDR_FILTER_SIZE; i++)
   {
      //Point to the current entry
      entry = &interface->macAddrFilter[i];

      //Valid entry?
      if(entry->refCount > 0)
      {
         //Compute CRC over the current MAC address
         crc = dm9000CalcCrc(&entry->addr, sizeof(MacAddr));
         //Calculate the corresponding index in the table
         k = crc & 0x3F;
         //Update hash table contents
         hashTable[k / 8] |= (1 << (k % 8));
      }
   }

   //Write the hash table to the DM9000 controller
   for(i = 0; i < 8; i++)
   {
      dm9000WriteReg(DM9000_MAR0 + i, hashTable[i]);
   }

   //Debug message
   TRACE_DEBUG("  MAR = %02" PRIX8 " %02" PRIX8 " %02" PRIX8 " %02" PRIX8 " "
      "%02" PRIX8 " %02" PRIX8 " %02" PRIX8 " %02" PRIX8 "\r\n",
      dm9000ReadReg(DM9000_MAR0), dm9000ReadReg(DM9000_MAR1),
      dm9000ReadReg(DM9000_MAR2), dm9000ReadReg(DM9000_MAR3),
      dm9000ReadReg(DM9000_MAR4), dm9000ReadReg(DM9000_MAR5),
      dm9000ReadReg(DM9000_MAR6), dm9000ReadReg(DM9000_MAR7));

   //Successful processing
   return NO_ERROR;
}


void ide_exec_cmd(IDEBus *bus, uint32_t val) { uint16_t *identify_data; IDEState *s; int n; int lba48 = 0; #if defined(DEBUG_IDE) printf("ide: CMD=%02x\n", val); #endif s = idebus_active_if(bus); /* ignore commands to non existent slave */ if (s != bus->ifs && !s->bs) return; /* Only DEVICE RESET is allowed while BSY or/and DRQ are set */ if ((s->status & (BUSY_STAT|DRQ_STAT)) && val != WIN_DEVICE_RESET) return; if (!ide_cmd_permitted(s, val)) { goto abort_cmd; } if (ide_cmd_table[val].handler != NULL) { bool complete; s->status = READY_STAT | BUSY_STAT; s->error = 0; complete = ide_cmd_table[val].handler(s, val); if (complete) { s->status &= ~BUSY_STAT; assert(!!s->error == !!(s->status & ERR_STAT)); if ((ide_cmd_table[val].flags & SET_DSC) && !s->error) { s->status |= SEEK_STAT; } ide_set_irq(s->bus); } return; } switch(val) { case WIN_SETMULT: if (s->drive_kind == IDE_CFATA && s->nsector == 0) { /* Disable Read and Write Multiple */ s->mult_sectors = 0; s->status = READY_STAT | SEEK_STAT; } else if ((s->nsector & 0xff) != 0 && ((s->nsector & 0xff) > MAX_MULT_SECTORS || (s->nsector & (s->nsector - 1)) != 0)) { ide_abort_command(s); } else { s->mult_sectors = s->nsector & 0xff; s->status = READY_STAT | SEEK_STAT; } ide_set_irq(s->bus); break; case WIN_VERIFY_EXT: lba48 = 1; /* fall through */ case WIN_VERIFY: case WIN_VERIFY_ONCE: /* do sector number check ? */ ide_cmd_lba48_transform(s, lba48); s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case WIN_READ_EXT: lba48 = 1; /* fall through */ case WIN_READ: case WIN_READ_ONCE: if (s->drive_kind == IDE_CD) { ide_set_signature(s); /* odd, but ATA4 8.27.5.2 requires it */ goto abort_cmd; } if (!s->bs) { goto abort_cmd; } ide_cmd_lba48_transform(s, lba48); s->req_nb_sectors = 1; ide_sector_read(s); break; case WIN_WRITE_EXT: lba48 = 1; /* fall through */ case WIN_WRITE: case WIN_WRITE_ONCE: case CFA_WRITE_SECT_WO_ERASE: case WIN_WRITE_VERIFY: if (!s->bs) { goto abort_cmd; } ide_cmd_lba48_transform(s, lba48); s->error = 0; s->status = SEEK_STAT | READY_STAT; s->req_nb_sectors = 1; ide_transfer_start(s, s->io_buffer, 512, ide_sector_write); s->media_changed = 1; break; case WIN_MULTREAD_EXT: lba48 = 1; /* fall through */ case WIN_MULTREAD: if (!s->bs) { goto abort_cmd; } if (!s->mult_sectors) { goto abort_cmd; } ide_cmd_lba48_transform(s, lba48); s->req_nb_sectors = s->mult_sectors; ide_sector_read(s); break; case WIN_MULTWRITE_EXT: lba48 = 1; /* fall through */ case WIN_MULTWRITE: case CFA_WRITE_MULTI_WO_ERASE: if (!s->bs) { goto abort_cmd; } if (!s->mult_sectors) { goto abort_cmd; } ide_cmd_lba48_transform(s, lba48); s->error = 0; s->status = SEEK_STAT | READY_STAT; s->req_nb_sectors = s->mult_sectors; n = s->nsector; if (n > s->req_nb_sectors) n = s->req_nb_sectors; ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_write); s->media_changed = 1; break; case WIN_READDMA_EXT: lba48 = 1; /* fall through */ case WIN_READDMA: case WIN_READDMA_ONCE: if (!s->bs) { goto abort_cmd; } ide_cmd_lba48_transform(s, lba48); ide_sector_start_dma(s, IDE_DMA_READ); break; case WIN_WRITEDMA_EXT: lba48 = 1; /* fall through */ case WIN_WRITEDMA: case WIN_WRITEDMA_ONCE: if (!s->bs) { goto abort_cmd; } ide_cmd_lba48_transform(s, lba48); ide_sector_start_dma(s, IDE_DMA_WRITE); s->media_changed = 1; break; case WIN_READ_NATIVE_MAX_EXT: lba48 = 1; /* fall through */ case WIN_READ_NATIVE_MAX: /* Refuse if no sectors are addressable (e.g. medium not inserted) */ if (s->nb_sectors == 0) { goto abort_cmd; } ide_cmd_lba48_transform(s, lba48); ide_set_sector(s, s->nb_sectors - 1); s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case WIN_CHECKPOWERMODE1: case WIN_CHECKPOWERMODE2: s->error = 0; s->nsector = 0xff; /* device active or idle */ s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case WIN_SETFEATURES: if (!s->bs) goto abort_cmd; /* XXX: valid for CDROM ? */ switch(s->feature) { case 0x02: /* write cache enable */ bdrv_set_enable_write_cache(s->bs, true); identify_data = (uint16_t *)s->identify_data; put_le16(identify_data + 85, (1 << 14) | (1 << 5) | 1); s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case 0x82: /* write cache disable */ bdrv_set_enable_write_cache(s->bs, false); identify_data = (uint16_t *)s->identify_data; put_le16(identify_data + 85, (1 << 14) | 1); ide_flush_cache(s); break; case 0xcc: /* reverting to power-on defaults enable */ case 0x66: /* reverting to power-on defaults disable */ case 0xaa: /* read look-ahead enable */ case 0x55: /* read look-ahead disable */ case 0x05: /* set advanced power management mode */ case 0x85: /* disable advanced power management mode */ case 0x69: /* NOP */ case 0x67: /* NOP */ case 0x96: /* NOP */ case 0x9a: /* NOP */ case 0x42: /* enable Automatic Acoustic Mode */ case 0xc2: /* disable Automatic Acoustic Mode */ s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case 0x03: { /* set transfer mode */ uint8_t val = s->nsector & 0x07; identify_data = (uint16_t *)s->identify_data; switch (s->nsector >> 3) { case 0x00: /* pio default */ case 0x01: /* pio mode */ put_le16(identify_data + 62,0x07); put_le16(identify_data + 63,0x07); put_le16(identify_data + 88,0x3f); break; case 0x02: /* sigle word dma mode*/ put_le16(identify_data + 62,0x07 | (1 << (val + 8))); put_le16(identify_data + 63,0x07); put_le16(identify_data + 88,0x3f); break; case 0x04: /* mdma mode */ put_le16(identify_data + 62,0x07); put_le16(identify_data + 63,0x07 | (1 << (val + 8))); put_le16(identify_data + 88,0x3f); break; case 0x08: /* udma mode */ put_le16(identify_data + 62,0x07); put_le16(identify_data + 63,0x07); put_le16(identify_data + 88,0x3f | (1 << (val + 8))); break; default: goto abort_cmd; } s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; } default: goto abort_cmd; } break; case WIN_FLUSH_CACHE: case WIN_FLUSH_CACHE_EXT: ide_flush_cache(s); break; case WIN_SEEK: /* XXX: Check that seek is within bounds */ s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; /* ATAPI commands */ case WIN_PIDENTIFY: ide_atapi_identify(s); s->status = READY_STAT | SEEK_STAT; ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop); ide_set_irq(s->bus); break; case WIN_DIAGNOSE: ide_set_signature(s); if (s->drive_kind == IDE_CD) s->status = 0; /* ATAPI spec (v6) section 9.10 defines packet * devices to return a clear status register * with READY_STAT *not* set. */ else s->status = READY_STAT | SEEK_STAT; s->error = 0x01; /* Device 0 passed, Device 1 passed or not * present. */ ide_set_irq(s->bus); break; case WIN_DEVICE_RESET: ide_set_signature(s); s->status = 0x00; /* NOTE: READY is _not_ set */ s->error = 0x01; break; case WIN_PACKETCMD: /* overlapping commands not supported */ if (s->feature & 0x02) goto abort_cmd; s->status = READY_STAT | SEEK_STAT; s->atapi_dma = s->feature & 1; s->nsector = 1; ide_transfer_start(s, s->io_buffer, ATAPI_PACKET_SIZE, ide_atapi_cmd); break; /* CF-ATA commands */ case CFA_REQ_EXT_ERROR_CODE: s->error = 0x09; /* miscellaneous error */ s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case CFA_ERASE_SECTORS: case CFA_WEAR_LEVEL: #if 0 /* This one has the same ID as CFA_WEAR_LEVEL and is required for Windows 8 to work with AHCI */ case WIN_SECURITY_FREEZE_LOCK: #endif if (val == CFA_WEAR_LEVEL) s->nsector = 0; if (val == CFA_ERASE_SECTORS) s->media_changed = 1; s->error = 0x00; s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case CFA_TRANSLATE_SECTOR: s->error = 0x00; s->status = READY_STAT | SEEK_STAT; memset(s->io_buffer, 0, 0x200); s->io_buffer[0x00] = s->hcyl; /* Cyl MSB */ s->io_buffer[0x01] = s->lcyl; /* Cyl LSB */ s->io_buffer[0x02] = s->select; /* Head */ s->io_buffer[0x03] = s->sector; /* Sector */ s->io_buffer[0x04] = ide_get_sector(s) >> 16; /* LBA MSB */ s->io_buffer[0x05] = ide_get_sector(s) >> 8; /* LBA */ s->io_buffer[0x06] = ide_get_sector(s) >> 0; /* LBA LSB */ s->io_buffer[0x13] = 0x00; /* Erase flag */ s->io_buffer[0x18] = 0x00; /* Hot count */ s->io_buffer[0x19] = 0x00; /* Hot count */ s->io_buffer[0x1a] = 0x01; /* Hot count */ ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop); ide_set_irq(s->bus); break; case CFA_ACCESS_METADATA_STORAGE: switch (s->feature) { case 0x02: /* Inquiry Metadata Storage */ ide_cfata_metadata_inquiry(s); break; case 0x03: /* Read Metadata Storage */ ide_cfata_metadata_read(s); break; case 0x04: /* Write Metadata Storage */ ide_cfata_metadata_write(s); break; default: goto abort_cmd; } ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop); s->status = 0x00; /* NOTE: READY is _not_ set */ ide_set_irq(s->bus); break; case IBM_SENSE_CONDITION: switch (s->feature) { case 0x01: /* sense temperature in device */ s->nsector = 0x50; /* +20 C */ break; default: goto abort_cmd; } s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case WIN_SMART: if (s->hcyl != 0xc2 || s->lcyl != 0x4f) goto abort_cmd; if (!s->smart_enabled && s->feature != SMART_ENABLE) goto abort_cmd; switch (s->feature) { case SMART_DISABLE: s->smart_enabled = 0; s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case SMART_ENABLE: s->smart_enabled = 1; s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case SMART_ATTR_AUTOSAVE: switch (s->sector) { case 0x00: s->smart_autosave = 0; break; case 0xf1: s->smart_autosave = 1; break; default: goto abort_cmd; } s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case SMART_STATUS: if (!s->smart_errors) { s->hcyl = 0xc2; s->lcyl = 0x4f; } else { s->hcyl = 0x2c; s->lcyl = 0xf4; } s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; case SMART_READ_THRESH: memset(s->io_buffer, 0, 0x200); s->io_buffer[0] = 0x01; /* smart struct version */ for (n = 0; n < ARRAY_SIZE(smart_attributes); n++) { s->io_buffer[2+0+(n*12)] = smart_attributes[n][0]; s->io_buffer[2+1+(n*12)] = smart_attributes[n][11]; } for (n=0; n<511; n++) /* checksum */ s->io_buffer[511] += s->io_buffer[n]; s->io_buffer[511] = 0x100 - s->io_buffer[511]; s->status = READY_STAT | SEEK_STAT; ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop); ide_set_irq(s->bus); break; case SMART_READ_DATA: memset(s->io_buffer, 0, 0x200); s->io_buffer[0] = 0x01; /* smart struct version */ for (n = 0; n < ARRAY_SIZE(smart_attributes); n++) { int i; for(i = 0; i < 11; i++) { s->io_buffer[2+i+(n*12)] = smart_attributes[n][i]; } } s->io_buffer[362] = 0x02 | (s->smart_autosave?0x80:0x00); if (s->smart_selftest_count == 0) { s->io_buffer[363] = 0; } else { s->io_buffer[363] = s->smart_selftest_data[3 + (s->smart_selftest_count - 1) * 24]; } s->io_buffer[364] = 0x20; s->io_buffer[365] = 0x01; /* offline data collection capacity: execute + self-test*/ s->io_buffer[367] = (1<<4 | 1<<3 | 1); s->io_buffer[368] = 0x03; /* smart capability (1) */ s->io_buffer[369] = 0x00; /* smart capability (2) */ s->io_buffer[370] = 0x01; /* error logging supported */ s->io_buffer[372] = 0x02; /* minutes for poll short test */ s->io_buffer[373] = 0x36; /* minutes for poll ext test */ s->io_buffer[374] = 0x01; /* minutes for poll conveyance */ for (n=0; n<511; n++) s->io_buffer[511] += s->io_buffer[n]; s->io_buffer[511] = 0x100 - s->io_buffer[511]; s->status = READY_STAT | SEEK_STAT; ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop); ide_set_irq(s->bus); break; case SMART_READ_LOG: switch (s->sector) { case 0x01: /* summary smart error log */ memset(s->io_buffer, 0, 0x200); s->io_buffer[0] = 0x01; s->io_buffer[1] = 0x00; /* no error entries */ s->io_buffer[452] = s->smart_errors & 0xff; s->io_buffer[453] = (s->smart_errors & 0xff00) >> 8; for (n=0; n<511; n++) s->io_buffer[511] += s->io_buffer[n]; s->io_buffer[511] = 0x100 - s->io_buffer[511]; break; case 0x06: /* smart self test log */ memset(s->io_buffer, 0, 0x200); s->io_buffer[0] = 0x01; if (s->smart_selftest_count == 0) { s->io_buffer[508] = 0; } else { s->io_buffer[508] = s->smart_selftest_count; for (n=2; n<506; n++) s->io_buffer[n] = s->smart_selftest_data[n]; } for (n=0; n<511; n++) s->io_buffer[511] += s->io_buffer[n]; s->io_buffer[511] = 0x100 - s->io_buffer[511]; break; default: goto abort_cmd; } s->status = READY_STAT | SEEK_STAT; ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop); ide_set_irq(s->bus); break; case SMART_EXECUTE_OFFLINE: switch (s->sector) { case 0: /* off-line routine */ case 1: /* short self test */ case 2: /* extended self test */ s->smart_selftest_count++; if(s->smart_selftest_count > 21) s->smart_selftest_count = 0; n = 2 + (s->smart_selftest_count - 1) * 24; s->smart_selftest_data[n] = s->sector; s->smart_selftest_data[n+1] = 0x00; /* OK and finished */ s->smart_selftest_data[n+2] = 0x34; /* hour count lsb */ s->smart_selftest_data[n+3] = 0x12; /* hour count msb */ s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); break; default: goto abort_cmd; } break; default: goto abort_cmd; } break; default: /* should not be reachable */ abort_cmd: ide_abort_command(s); ide_set_irq(s->bus); break; } }


autoar_extractor_check_file_conflict (GFile  *file,
                                      mode_t  extracted_filetype)
{
  GFileType file_type;

  file_type = g_file_query_file_type (file,
                                      G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
                                      NULL);
  /* If there is no file with the given name, there will be no conflict */
  if (file_type == G_FILE_TYPE_UNKNOWN) {
    return FALSE;
  }

  /* It is not problem if the directory already exists */
  if (file_type == G_FILE_TYPE_DIRECTORY &&
      extracted_filetype == AE_IFDIR) {
    return FALSE;
  }

  return TRUE;
}


error_t enc28j60ReceivePacket(NetInterface *interface)
{
   error_t error;
   uint16_t length;
   uint16_t status;
   uint8_t header[6];
   Enc28j60Context *context;

   //Point to the driver context
   context = (Enc28j60Context *) interface->nicContext;

   //Any packet pending in the receive buffer?
   if(enc28j60ReadReg(interface, ENC28J60_EPKTCNT) != 0)
   {
      //Point to the start of the received packet
      enc28j60WriteReg(interface, ENC28J60_ERDPTL, LSB(context->nextPacket));
      enc28j60WriteReg(interface, ENC28J60_ERDPTH, MSB(context->nextPacket));

      //The packet is preceded by a 6-byte header
      enc28j60ReadBuffer(interface, header, sizeof(header));

      //The first two bytes are the address of the next packet
      context->nextPacket = LOAD16LE(header);
      //Get the length of the received packet
      length = LOAD16LE(header + 2);
      //Get the receive status vector (RSV)
      status = LOAD16LE(header + 4);

      //Make sure no error occurred
      if((status & ENC28J60_RSV_RECEIVED_OK) != 0)
      {
         //Limit the number of data to read
         length = MIN(length, ETH_MAX_FRAME_SIZE);
         //Read the Ethernet frame
         enc28j60ReadBuffer(interface, context->rxBuffer, length);
         //Valid packet received
         error = NO_ERROR;
      }
      else
      {
         //The received packet contains an error
         error = ERROR_INVALID_PACKET;
      }

      //Advance the ERXRDPT pointer, taking care to wrap back at the
      //end of the received memory buffer
      if(context->nextPacket == ENC28J60_RX_BUFFER_START)
      {
         enc28j60WriteReg(interface, ENC28J60_ERXRDPTL, LSB(ENC28J60_RX_BUFFER_STOP));
         enc28j60WriteReg(interface, ENC28J60_ERXRDPTH, MSB(ENC28J60_RX_BUFFER_STOP));
      }
      else
      {
         enc28j60WriteReg(interface, ENC28J60_ERXRDPTL, LSB(context->nextPacket - 1));
         enc28j60WriteReg(interface, ENC28J60_ERXRDPTH, MSB(context->nextPacket - 1));
      }

      //Decrement the packet counter
      enc28j60SetBit(interface, ENC28J60_ECON2, ENC28J60_ECON2_PKTDEC);
   }
   else
   {
      //No more data in the receive buffer
      error = ERROR_BUFFER_EMPTY;
   }

   //Check whether a valid packet has been received
   if(!error)
   {
      NetRxAncillary ancillary;

      //Additional options can be passed to the stack along with the packet
      ancillary = NET_DEFAULT_RX_ANCILLARY;

      //Pass the packet to the upper layer
      nicProcessPacket(interface, context->rxBuffer, length, &ancillary);
   }

   //Return status code
   return error;
}


static void vmsvga_class_init ( ObjectClass * klass , void * data ) {
 DeviceClass * dc = DEVICE_CLASS ( klass ) ;
 PCIDeviceClass * k = PCI_DEVICE_CLASS ( klass ) ;
 k -> init = pci_vmsvga_initfn ;
 k -> romfile = "vgabios-vmware.bin" ;
 k -> vendor_id = PCI_VENDOR_ID_VMWARE ;
 k -> device_id = SVGA_PCI_DEVICE_ID ;
 k -> class_id = PCI_CLASS_DISPLAY_VGA ;
 k -> subsystem_vendor_id = PCI_VENDOR_ID_VMWARE ;
 k -> subsystem_id = SVGA_PCI_DEVICE_ID ;
 dc -> reset = vmsvga_reset ;
 dc -> vmsd = & vmstate_vmware_vga ;
 dc -> props = vga_vmware_properties ;
 dc -> hotpluggable = false ;
 set_bit ( DEVICE_CATEGORY_DISPLAY , dc -> categories ) ;
 }


static void check_pred16x16(H264PredContext *h, uint8_t *buf0, uint8_t *buf1, int codec, int chroma_format, int bit_depth) { if (chroma_format == 1) { int pred_mode; declare_func(void, uint8_t *src, ptrdiff_t stride); for (pred_mode = 0; pred_mode < 9; pred_mode++) { if (check_pred_func(h->pred16x16[pred_mode], "16x16", pred16x16_modes[codec][pred_mode])) { randomize_buffers(); call_ref(src0, 48); call_new(src1, 48); if (memcmp(buf0, buf1, BUF_SIZE)) fail(); bench_new(src1, 48); } } } }


schannel_connect_step1(struct Curl_easy *data, struct connectdata *conn,
                       int sockindex)
{
  ssize_t written = -1;
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  SecBuffer outbuf;
  SecBufferDesc outbuf_desc;
  SecBuffer inbuf;
  SecBufferDesc inbuf_desc;
#ifdef HAS_ALPN
  unsigned char alpn_buffer[128];
#endif
  SCHANNEL_CRED schannel_cred;
  PCCERT_CONTEXT client_certs[1] = { NULL };
  SECURITY_STATUS sspi_status = SEC_E_OK;
  struct Curl_schannel_cred *old_cred = NULL;
  struct in_addr addr;
#ifdef ENABLE_IPV6
  struct in6_addr addr6;
#endif
  TCHAR *host_name;
  CURLcode result;
#ifndef CURL_DISABLE_PROXY
  char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
    conn->host.name;
#else
  char * const hostname = conn->host.name;
#endif

  DEBUGF(infof(data,
               "schannel: SSL/TLS connection with %s port %hu (step 1/3)\n",
               hostname, conn->remote_port));

  if(curlx_verify_windows_version(5, 1, PLATFORM_WINNT,
                                  VERSION_LESS_THAN_EQUAL)) {
    /* Schannel in Windows XP (OS version 5.1) uses legacy handshakes and
       algorithms that may not be supported by all servers. */
    infof(data, "schannel: Windows version is old and may not be able to "
          "connect to some servers due to lack of SNI, algorithms, etc.\n");
  }

#ifdef HAS_ALPN
  /* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above.
     Also it doesn't seem to be supported for Wine, see curl bug #983. */
  BACKEND->use_alpn = conn->bits.tls_enable_alpn &&
    !GetProcAddress(GetModuleHandle(TEXT("ntdll")),
                    "wine_get_version") &&
    curlx_verify_windows_version(6, 3, PLATFORM_WINNT,
                                 VERSION_GREATER_THAN_EQUAL);
#else
  BACKEND->use_alpn = false;
#endif

#ifdef _WIN32_WCE
#ifdef HAS_MANUAL_VERIFY_API
  /* certificate validation on CE doesn't seem to work right; we'll
   * do it following a more manual process. */
  BACKEND->use_manual_cred_validation = true;
#else
#error "compiler too old to support requisite manual cert verify for Win CE"
#endif
#else
#ifdef HAS_MANUAL_VERIFY_API
  if(SSL_CONN_CONFIG(CAfile)) {
    if(curlx_verify_windows_version(6, 1, PLATFORM_WINNT,
                                    VERSION_GREATER_THAN_EQUAL)) {
      BACKEND->use_manual_cred_validation = true;
    }
    else {
      failf(data, "schannel: this version of Windows is too old to support "
            "certificate verification via CA bundle file.");
      return CURLE_SSL_CACERT_BADFILE;
    }
  }
  else
    BACKEND->use_manual_cred_validation = false;
#else
  if(SSL_CONN_CONFIG(CAfile)) {
    failf(data, "schannel: CA cert support not built in");
    return CURLE_NOT_BUILT_IN;
  }
#endif
#endif

  BACKEND->cred = NULL;

  /* check for an existing re-usable credential handle */
  if(SSL_SET_OPTION(primary.sessionid)) {
    Curl_ssl_sessionid_lock(data);
    if(!Curl_ssl_getsessionid(data, conn,
                              (void **)&old_cred, NULL, sockindex)) {
      BACKEND->cred = old_cred;
      DEBUGF(infof(data, "schannel: re-using existing credential handle\n"));

      /* increment the reference counter of the credential/session handle */
      BACKEND->cred->refcount++;
      DEBUGF(infof(data,
                   "schannel: incremented credential handle refcount = %d\n",
                   BACKEND->cred->refcount));
    }
    Curl_ssl_sessionid_unlock(data);
  }

  if(!BACKEND->cred) {
    /* setup Schannel API options */
    memset(&schannel_cred, 0, sizeof(schannel_cred));
    schannel_cred.dwVersion = SCHANNEL_CRED_VERSION;

    if(conn->ssl_config.verifypeer) {
#ifdef HAS_MANUAL_VERIFY_API
      if(BACKEND->use_manual_cred_validation)
        schannel_cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION;
      else
#endif
        schannel_cred.dwFlags = SCH_CRED_AUTO_CRED_VALIDATION;

      if(SSL_SET_OPTION(no_revoke)) {
        schannel_cred.dwFlags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
          SCH_CRED_IGNORE_REVOCATION_OFFLINE;

        DEBUGF(infof(data, "schannel: disabled server certificate revocation "
                     "checks\n"));
      }
      else if(SSL_SET_OPTION(revoke_best_effort)) {
        schannel_cred.dwFlags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
          SCH_CRED_IGNORE_REVOCATION_OFFLINE | SCH_CRED_REVOCATION_CHECK_CHAIN;

        DEBUGF(infof(data, "schannel: ignore revocation offline errors"));
      }
      else {
        schannel_cred.dwFlags |= SCH_CRED_REVOCATION_CHECK_CHAIN;

        DEBUGF(infof(data,
                     "schannel: checking server certificate revocation\n"));
      }
    }
    else {
      schannel_cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION |
        SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
        SCH_CRED_IGNORE_REVOCATION_OFFLINE;
      DEBUGF(infof(data,
                   "schannel: disabled server cert revocation checks\n"));
    }

    if(!conn->ssl_config.verifyhost) {
      schannel_cred.dwFlags |= SCH_CRED_NO_SERVERNAME_CHECK;
      DEBUGF(infof(data, "schannel: verifyhost setting prevents Schannel from "
                   "comparing the supplied target name with the subject "
                   "names in server certificates.\n"));
    }

    switch(conn->ssl_config.version) {
    case CURL_SSLVERSION_DEFAULT:
    case CURL_SSLVERSION_TLSv1:
    case CURL_SSLVERSION_TLSv1_0:
    case CURL_SSLVERSION_TLSv1_1:
    case CURL_SSLVERSION_TLSv1_2:
    case CURL_SSLVERSION_TLSv1_3:
    {
      result = set_ssl_version_min_max(&schannel_cred, data, conn);
      if(result != CURLE_OK)
        return result;
      break;
    }
    case CURL_SSLVERSION_SSLv3:
      schannel_cred.grbitEnabledProtocols = SP_PROT_SSL3_CLIENT;
      break;
    case CURL_SSLVERSION_SSLv2:
      schannel_cred.grbitEnabledProtocols = SP_PROT_SSL2_CLIENT;
      break;
    default:
      failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
      return CURLE_SSL_CONNECT_ERROR;
    }

    if(SSL_CONN_CONFIG(cipher_list)) {
      result = set_ssl_ciphers(&schannel_cred, SSL_CONN_CONFIG(cipher_list));
      if(CURLE_OK != result) {
        failf(data, "Unable to set ciphers to passed via SSL_CONN_CONFIG");
        return result;
      }
    }

#ifdef HAS_CLIENT_CERT_PATH
    /* client certificate */
    if(data->set.ssl.primary.clientcert || data->set.ssl.primary.cert_blob) {
      DWORD cert_store_name = 0;
      TCHAR *cert_store_path = NULL;
      TCHAR *cert_thumbprint_str = NULL;
      CRYPT_HASH_BLOB cert_thumbprint;
      BYTE cert_thumbprint_data[CERT_THUMBPRINT_DATA_LEN];
      HCERTSTORE cert_store = NULL;
      FILE *fInCert = NULL;
      void *certdata = NULL;
      size_t certsize = 0;
      bool blob = data->set.ssl.primary.cert_blob != NULL;
      TCHAR *cert_path = NULL;
      if(blob) {
        certdata = data->set.ssl.primary.cert_blob->data;
        certsize = data->set.ssl.primary.cert_blob->len;
      }
      else {
        cert_path = curlx_convert_UTF8_to_tchar(
          data->set.ssl.primary.clientcert);
        if(!cert_path)
          return CURLE_OUT_OF_MEMORY;

        result = get_cert_location(cert_path, &cert_store_name,
          &cert_store_path, &cert_thumbprint_str);

        if(result && (data->set.ssl.primary.clientcert[0]!='\0'))
          fInCert = fopen(data->set.ssl.primary.clientcert, "rb");

        if(result && !fInCert) {
          failf(data, "schannel: Failed to get certificate location"
                " or file for %s",
                data->set.ssl.primary.clientcert);
          curlx_unicodefree(cert_path);
          return result;
        }
      }

      if((fInCert || blob) && (data->set.ssl.cert_type) &&
          (!strcasecompare(data->set.ssl.cert_type, "P12"))) {
        failf(data, "schannel: certificate format compatibility error "
                " for %s",
                blob ? "(memory blob)" : data->set.ssl.primary.clientcert);
        curlx_unicodefree(cert_path);
        return CURLE_SSL_CERTPROBLEM;
      }

      if(fInCert || blob) {
        /* Reading a .P12 or .pfx file, like the example at bottom of
             https://social.msdn.microsoft.com/Forums/windowsdesktop/
                            en-US/3e7bc95f-b21a-4bcd-bd2c-7f996718cae5
        */
        CRYPT_DATA_BLOB datablob;
        WCHAR* pszPassword;
        size_t pwd_len = 0;
        int str_w_len = 0;
        const char *cert_showfilename_error = blob ?
          "(memory blob)" : data->set.ssl.primary.clientcert;
        curlx_unicodefree(cert_path);
        if(fInCert) {
          long cert_tell = 0;
          bool continue_reading = fseek(fInCert, 0, SEEK_END) == 0;
          if(continue_reading)
            cert_tell = ftell(fInCert);
          if(cert_tell < 0)
            continue_reading = FALSE;
          else
            certsize = (size_t)cert_tell;
          if(continue_reading)
            continue_reading = fseek(fInCert, 0, SEEK_SET) == 0;
          if(continue_reading)
            certdata = malloc(certsize + 1);
          if((!certdata) ||
             ((int) fread(certdata, certsize, 1, fInCert) != 1))
            continue_reading = FALSE;
          fclose(fInCert);
          if(!continue_reading) {
            failf(data, "schannel: Failed to read cert file %s",
                data->set.ssl.primary.clientcert);
            free(certdata);
            return CURLE_SSL_CERTPROBLEM;
          }
        }

        /* Convert key-pair data to the in-memory certificate store */
        datablob.pbData = (BYTE*)certdata;
        datablob.cbData = (DWORD)certsize;

        if(data->set.ssl.key_passwd != NULL)
          pwd_len = strlen(data->set.ssl.key_passwd);
        pszPassword = (WCHAR*)malloc(sizeof(WCHAR)*(pwd_len + 1));
        if(pszPassword) {
          if(pwd_len > 0)
            str_w_len = MultiByteToWideChar(CP_UTF8,
               MB_ERR_INVALID_CHARS,
               data->set.ssl.key_passwd, (int)pwd_len,
               pszPassword, (int)(pwd_len + 1));

          if((str_w_len >= 0) && (str_w_len <= (int)pwd_len))
            pszPassword[str_w_len] = 0;
          else
            pszPassword[0] = 0;

          cert_store = PFXImportCertStore(&datablob, pszPassword, 0);
          free(pszPassword);
        }
        if(!blob)
          free(certdata);
        if(cert_store == NULL) {
          DWORD errorcode = GetLastError();
          if(errorcode == ERROR_INVALID_PASSWORD)
            failf(data, "schannel: Failed to import cert file %s, "
                  "password is bad",
                  cert_showfilename_error);
          else
            failf(data, "schannel: Failed to import cert file %s, "
                  "last error is 0x%x",
                  cert_showfilename_error, errorcode);
          return CURLE_SSL_CERTPROBLEM;
        }

        client_certs[0] = CertFindCertificateInStore(
          cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
          CERT_FIND_ANY, NULL, NULL);

        if(client_certs[0] == NULL) {
          failf(data, "schannel: Failed to get certificate from file %s"
                ", last error is 0x%x",
                cert_showfilename_error, GetLastError());
          CertCloseStore(cert_store, 0);
          return CURLE_SSL_CERTPROBLEM;
        }

        schannel_cred.cCreds = 1;
        schannel_cred.paCred = client_certs;
      }
      else {
        cert_store =
          CertOpenStore(CURL_CERT_STORE_PROV_SYSTEM, 0,
                        (HCRYPTPROV)NULL,
                        CERT_STORE_OPEN_EXISTING_FLAG | cert_store_name,
                        cert_store_path);
        if(!cert_store) {
          failf(data, "schannel: Failed to open cert store %x %s, "
                "last error is 0x%x",
                cert_store_name, cert_store_path, GetLastError());
          free(cert_store_path);
          curlx_unicodefree(cert_path);
          return CURLE_SSL_CERTPROBLEM;
        }
        free(cert_store_path);

        cert_thumbprint.pbData = cert_thumbprint_data;
        cert_thumbprint.cbData = CERT_THUMBPRINT_DATA_LEN;

        if(!CryptStringToBinary(cert_thumbprint_str,
                                CERT_THUMBPRINT_STR_LEN,
                                CRYPT_STRING_HEX,
                                cert_thumbprint_data,
                                &cert_thumbprint.cbData,
                                NULL, NULL)) {
          curlx_unicodefree(cert_path);
          CertCloseStore(cert_store, 0);
          return CURLE_SSL_CERTPROBLEM;
        }

        client_certs[0] = CertFindCertificateInStore(
          cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
          CERT_FIND_HASH, &cert_thumbprint, NULL);

        curlx_unicodefree(cert_path);

        if(client_certs[0]) {
          schannel_cred.cCreds = 1;
          schannel_cred.paCred = client_certs;
        }
        else {
          /* CRYPT_E_NOT_FOUND / E_INVALIDARG */
          CertCloseStore(cert_store, 0);
          return CURLE_SSL_CERTPROBLEM;
        }
      }
      CertCloseStore(cert_store, 0);
    }
#else
    if(data->set.ssl.primary.clientcert || data->set.ssl.primary.cert_blob) {
      failf(data, "schannel: client cert support not built in");
      return CURLE_NOT_BUILT_IN;
    }
#endif

    /* allocate memory for the re-usable credential handle */
    BACKEND->cred = (struct Curl_schannel_cred *)
      calloc(1, sizeof(struct Curl_schannel_cred));
    if(!BACKEND->cred) {
      failf(data, "schannel: unable to allocate memory");

      if(client_certs[0])
        CertFreeCertificateContext(client_certs[0]);

      return CURLE_OUT_OF_MEMORY;
    }
    BACKEND->cred->refcount = 1;

    /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa374716.aspx
     */
    sspi_status =
      s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *)UNISP_NAME,
                                         SECPKG_CRED_OUTBOUND, NULL,
                                         &schannel_cred, NULL, NULL,
                                         &BACKEND->cred->cred_handle,
                                         &BACKEND->cred->time_stamp);

    if(client_certs[0])
      CertFreeCertificateContext(client_certs[0]);

    if(sspi_status != SEC_E_OK) {
      char buffer[STRERROR_LEN];
      failf(data, "schannel: AcquireCredentialsHandle failed: %s",
            Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
      Curl_safefree(BACKEND->cred);
      switch(sspi_status) {
      case SEC_E_INSUFFICIENT_MEMORY:
        return CURLE_OUT_OF_MEMORY;
      case SEC_E_NO_CREDENTIALS:
      case SEC_E_SECPKG_NOT_FOUND:
      case SEC_E_NOT_OWNER:
      case SEC_E_UNKNOWN_CREDENTIALS:
      case SEC_E_INTERNAL_ERROR:
      default:
        return CURLE_SSL_CONNECT_ERROR;
      }
    }
  }

  /* Warn if SNI is disabled due to use of an IP address */
  if(Curl_inet_pton(AF_INET, hostname, &addr)
#ifdef ENABLE_IPV6
     || Curl_inet_pton(AF_INET6, hostname, &addr6)
#endif
    ) {
    infof(data, "schannel: using IP address, SNI is not supported by OS.\n");
  }

#ifdef HAS_ALPN
  if(BACKEND->use_alpn) {
    int cur = 0;
    int list_start_index = 0;
    unsigned int *extension_len = NULL;
    unsigned short* list_len = NULL;

    /* The first four bytes will be an unsigned int indicating number
       of bytes of data in the rest of the buffer. */
    extension_len = (unsigned int *)(&alpn_buffer[cur]);
    cur += sizeof(unsigned int);

    /* The next four bytes are an indicator that this buffer will contain
       ALPN data, as opposed to NPN, for example. */
    *(unsigned int *)&alpn_buffer[cur] =
      SecApplicationProtocolNegotiationExt_ALPN;
    cur += sizeof(unsigned int);

    /* The next two bytes will be an unsigned short indicating the number
       of bytes used to list the preferred protocols. */
    list_len = (unsigned short*)(&alpn_buffer[cur]);
    cur += sizeof(unsigned short);

    list_start_index = cur;

#ifdef USE_NGHTTP2
    if(data->state.httpversion >= CURL_HTTP_VERSION_2) {
      memcpy(&alpn_buffer[cur], NGHTTP2_PROTO_ALPN, NGHTTP2_PROTO_ALPN_LEN);
      cur += NGHTTP2_PROTO_ALPN_LEN;
      infof(data, "schannel: ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
    }
#endif

    alpn_buffer[cur++] = ALPN_HTTP_1_1_LENGTH;
    memcpy(&alpn_buffer[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
    cur += ALPN_HTTP_1_1_LENGTH;
    infof(data, "schannel: ALPN, offering %s\n", ALPN_HTTP_1_1);

    *list_len = curlx_uitous(cur - list_start_index);
    *extension_len = *list_len + sizeof(unsigned int) + sizeof(unsigned short);

    InitSecBuffer(&inbuf, SECBUFFER_APPLICATION_PROTOCOLS, alpn_buffer, cur);
    InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  }
  else {
    InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0);
    InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  }
#else /* HAS_ALPN */
  InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0);
  InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
#endif

  /* setup output buffer */
  InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
  InitSecBufferDesc(&outbuf_desc, &outbuf, 1);

  /* setup request flags */
  BACKEND->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT |
    ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY |
    ISC_REQ_STREAM;

  /* allocate memory for the security context handle */
  BACKEND->ctxt = (struct Curl_schannel_ctxt *)
    calloc(1, sizeof(struct Curl_schannel_ctxt));
  if(!BACKEND->ctxt) {
    failf(data, "schannel: unable to allocate memory");
    return CURLE_OUT_OF_MEMORY;
  }

  host_name = curlx_convert_UTF8_to_tchar(hostname);
  if(!host_name)
    return CURLE_OUT_OF_MEMORY;

  /* Schannel InitializeSecurityContext:
     https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx

     At the moment we don't pass inbuf unless we're using ALPN since we only
     use it for that, and Wine (for which we currently disable ALPN) is giving
     us problems with inbuf regardless. https://github.com/curl/curl/issues/983
  */
  sspi_status = s_pSecFn->InitializeSecurityContext(
    &BACKEND->cred->cred_handle, NULL, host_name, BACKEND->req_flags, 0, 0,
    (BACKEND->use_alpn ? &inbuf_desc : NULL),
    0, &BACKEND->ctxt->ctxt_handle,
    &outbuf_desc, &BACKEND->ret_flags, &BACKEND->ctxt->time_stamp);

  curlx_unicodefree(host_name);

  if(sspi_status != SEC_I_CONTINUE_NEEDED) {
    char buffer[STRERROR_LEN];
    Curl_safefree(BACKEND->ctxt);
    switch(sspi_status) {
    case SEC_E_INSUFFICIENT_MEMORY:
      failf(data, "schannel: initial InitializeSecurityContext failed: %s",
            Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
      return CURLE_OUT_OF_MEMORY;
    case SEC_E_WRONG_PRINCIPAL:
      failf(data, "schannel: SNI or certificate check failed: %s",
            Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
      return CURLE_PEER_FAILED_VERIFICATION;
      /*
        case SEC_E_INVALID_HANDLE:
        case SEC_E_INVALID_TOKEN:
        case SEC_E_LOGON_DENIED:
        case SEC_E_TARGET_UNKNOWN:
        case SEC_E_NO_AUTHENTICATING_AUTHORITY:
        case SEC_E_INTERNAL_ERROR:
        case SEC_E_NO_CREDENTIALS:
        case SEC_E_UNSUPPORTED_FUNCTION:
        case SEC_E_APPLICATION_PROTOCOL_MISMATCH:
      */
    default:
      failf(data, "schannel: initial InitializeSecurityContext failed: %s",
            Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
      return CURLE_SSL_CONNECT_ERROR;
    }
  }

  DEBUGF(infof(data, "schannel: sending initial handshake data: "
               "sending %lu bytes...\n", outbuf.cbBuffer));

  /* send initial handshake data which is now stored in output buffer */
  result = Curl_write_plain(data, conn->sock[sockindex], outbuf.pvBuffer,
                            outbuf.cbBuffer, &written);
  s_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
  if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) {
    failf(data, "schannel: failed to send initial handshake data: "
          "sent %zd of %lu bytes", written, outbuf.cbBuffer);
    return CURLE_SSL_CONNECT_ERROR;
  }

  DEBUGF(infof(data, "schannel: sent initial handshake data: "
               "sent %zd bytes\n", written));

  BACKEND->recv_unrecoverable_err = CURLE_OK;
  BACKEND->recv_sspi_close_notify = false;
  BACKEND->recv_connection_closed = false;
  BACKEND->encdata_is_incomplete = false;

  /* continue to second handshake step */
  connssl->connecting_state = ssl_connect_2;

  return CURLE_OK;
}


uint16_t enc624j600ReadPhyReg(NetInterface *interface, uint8_t address)
{
   //Write the address of the PHY register to read from
   enc624j600WriteReg(interface, ENC624J600_REG_MIREGADR, MIREGADR_R8 | address);
   //Start read operation
   enc624j600WriteReg(interface, ENC624J600_REG_MICMD, MICMD_MIIRD);

   //Wait at least 25.6us before polling the BUSY bit
   usleep(100);
   //Wait for the read operation to complete
   while((enc624j600ReadReg(interface, ENC624J600_REG_MISTAT) & MISTAT_BUSY) != 0)
   {
   }

   //Clear command register
   enc624j600WriteReg(interface, ENC624J600_REG_MICMD, 0x00);

   //Return register contents
   return enc624j600ReadReg(interface, ENC624J600_REG_MIRD);
}


static CURLcode bearssl_connect_step1(struct Curl_easy *data,
                                      struct connectdata *conn, int sockindex)
{
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  struct ssl_backend_data *backend = connssl->backend;
  const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
#ifndef CURL_DISABLE_PROXY
  const char *hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
    conn->host.name;
#else
  const char *hostname = conn->host.name;
#endif
  const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
  const bool verifyhost = SSL_CONN_CONFIG(verifyhost);
  CURLcode ret;
  unsigned version_min, version_max;
#ifdef ENABLE_IPV6
  struct in6_addr addr;
#else
  struct in_addr addr;
#endif

  switch(SSL_CONN_CONFIG(version)) {
  case CURL_SSLVERSION_SSLv2:
    failf(data, "BearSSL does not support SSLv2");
    return CURLE_SSL_CONNECT_ERROR;
  case CURL_SSLVERSION_SSLv3:
    failf(data, "BearSSL does not support SSLv3");
    return CURLE_SSL_CONNECT_ERROR;
  case CURL_SSLVERSION_TLSv1_0:
    version_min = BR_TLS10;
    version_max = BR_TLS10;
    break;
  case CURL_SSLVERSION_TLSv1_1:
    version_min = BR_TLS11;
    version_max = BR_TLS11;
    break;
  case CURL_SSLVERSION_TLSv1_2:
    version_min = BR_TLS12;
    version_max = BR_TLS12;
    break;
  case CURL_SSLVERSION_DEFAULT:
  case CURL_SSLVERSION_TLSv1:
    version_min = BR_TLS10;
    version_max = BR_TLS12;
    break;
  default:
    failf(data, "BearSSL: unknown CURLOPT_SSLVERSION");
    return CURLE_SSL_CONNECT_ERROR;
  }

  if(ssl_cafile) {
    ret = load_cafile(ssl_cafile, &backend->anchors, &backend->anchors_len);
    if(ret != CURLE_OK) {
      if(verifypeer) {
        failf(data, "error setting certificate verify locations."
              " CAfile: %s", ssl_cafile);
        return ret;
      }
      infof(data, "error setting certificate verify locations,"
            " continuing anyway:\n");
    }
  }

  /* initialize SSL context */
  br_ssl_client_init_full(&backend->ctx, &backend->x509.minimal,
                          backend->anchors, backend->anchors_len);
  br_ssl_engine_set_versions(&backend->ctx.eng, version_min, version_max);
  br_ssl_engine_set_buffer(&backend->ctx.eng, backend->buf,
                           sizeof(backend->buf), 1);

  /* initialize X.509 context */
  backend->x509.vtable = &x509_vtable;
  backend->x509.verifypeer = verifypeer;
  backend->x509.verifyhost = verifyhost;
  br_ssl_engine_set_x509(&backend->ctx.eng, &backend->x509.vtable);

  if(SSL_SET_OPTION(primary.sessionid)) {
    void *session;

    Curl_ssl_sessionid_lock(data);
    if(!Curl_ssl_getsessionid(data, conn, &session, NULL, sockindex)) {
      br_ssl_engine_set_session_parameters(&backend->ctx.eng, session);
      infof(data, "BearSSL: re-using session ID\n");
    }
    Curl_ssl_sessionid_unlock(data);
  }

  if(conn->bits.tls_enable_alpn) {
    int cur = 0;

    /* NOTE: when adding more protocols here, increase the size of the
     * protocols array in `struct ssl_backend_data`.
     */

#ifdef USE_NGHTTP2
    if(data->state.httpversion >= CURL_HTTP_VERSION_2
#ifndef CURL_DISABLE_PROXY
      && (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)
#endif
      ) {
      backend->protocols[cur++] = NGHTTP2_PROTO_VERSION_ID;
      infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
    }
#endif

    backend->protocols[cur++] = ALPN_HTTP_1_1;
    infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);

    br_ssl_engine_set_protocol_names(&backend->ctx.eng,
                                     backend->protocols, cur);
  }

  if((1 == Curl_inet_pton(AF_INET, hostname, &addr))
#ifdef ENABLE_IPV6
      || (1 == Curl_inet_pton(AF_INET6, hostname, &addr))
#endif
     ) {
    if(verifyhost) {
      failf(data, "BearSSL: "
            "host verification of IP address is not supported");
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    hostname = NULL;
  }

  if(!br_ssl_client_reset(&backend->ctx, hostname, 0))
    return CURLE_FAILED_INIT;
  backend->active = TRUE;

  connssl->connecting_state = ssl_connect_2;

  return CURLE_OK;
}


mbed_connect_step3(struct Curl_easy *data, struct connectdata *conn,
                   int sockindex)
{
  CURLcode retcode = CURLE_OK;
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  struct ssl_backend_data *backend = connssl->backend;

  DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);

  if(SSL_SET_OPTION(primary.sessionid)) {
    int ret;
    mbedtls_ssl_session *our_ssl_sessionid;
    void *old_ssl_sessionid = NULL;

    our_ssl_sessionid = malloc(sizeof(mbedtls_ssl_session));
    if(!our_ssl_sessionid)
      return CURLE_OUT_OF_MEMORY;

    mbedtls_ssl_session_init(our_ssl_sessionid);

    ret = mbedtls_ssl_get_session(&backend->ssl, our_ssl_sessionid);
    if(ret) {
      if(ret != MBEDTLS_ERR_SSL_ALLOC_FAILED)
        mbedtls_ssl_session_free(our_ssl_sessionid);
      free(our_ssl_sessionid);
      failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret);
      return CURLE_SSL_CONNECT_ERROR;
    }

    /* If there's already a matching session in the cache, delete it */
    Curl_ssl_sessionid_lock(data);
    if(!Curl_ssl_getsessionid(data, conn, &old_ssl_sessionid, NULL, sockindex))
      Curl_ssl_delsessionid(data, old_ssl_sessionid);

    retcode = Curl_ssl_addsessionid(data, conn,
                                    our_ssl_sessionid, 0, sockindex);
    Curl_ssl_sessionid_unlock(data);
    if(retcode) {
      mbedtls_ssl_session_free(our_ssl_sessionid);
      free(our_ssl_sessionid);
      failf(data, "failed to store ssl session");
      return retcode;
    }
  }

  connssl->connecting_state = ssl_connect_done;

  return CURLE_OK;
}


IN_PROC_BROWSER_TEST_F ( ContentFaviconDriverTest , AssociateIconWithInitialPageDespiteMetaRefreshTagAndLandingPageCached ) {
 ASSERT_TRUE ( embedded_test_server ( ) -> Start ( ) ) ;
 GURL url_with_meta_refresh_tag = embedded_test_server ( ) -> GetURL ( "/favicon/page_with_meta_refresh_tag.html" ) ;
 GURL landing_url = embedded_test_server ( ) -> GetURL ( "/favicon/page_with_favicon.html" ) ;
 {
 PendingTaskWaiter waiter ( web_contents ( ) ) ;
 ui_test_utils : : NavigateToURLWithDisposition ( browser ( ) , landing_url , WindowOpenDisposition : : CURRENT_TAB , ui_test_utils : : BROWSER_TEST_NONE ) ;
 waiter . Wait ( ) ;
 }
 ASSERT_NE ( nullptr , GetFaviconForPageURL ( landing_url , favicon_base : : IconType : : kFavicon ) . bitmap_data ) ;
 PendingTaskWaiter waiter ( web_contents ( ) ) ;
 waiter . AlsoRequireUrl ( landing_url ) ;
 ui_test_utils : : NavigateToURLWithDisposition ( browser ( ) , url_with_meta_refresh_tag , WindowOpenDisposition : : CURRENT_TAB , ui_test_utils : : BROWSER_TEST_NONE ) ;
 waiter . Wait ( ) ;
 EXPECT_NE ( nullptr , GetFaviconForPageURL ( url_with_meta_refresh_tag , favicon_base : : IconType : : kFavicon ) . bitmap_data ) ;
 EXPECT_NE ( nullptr , GetFaviconForPageURL ( landing_url , favicon_base : : IconType : : kFavicon ) . bitmap_data ) ;
 }


static void gen_mulo(DisasContext *ctx) { int l1 = gen_new_label(); TCGv_i64 t0 = tcg_temp_new_i64(); TCGv_i64 t1 = tcg_temp_new_i64(); TCGv t2 = tcg_temp_new(); /* Start with XER OV disabled, the most likely case */ tcg_gen_movi_tl(cpu_ov, 0); tcg_gen_extu_tl_i64(t0, cpu_gpr[rA(ctx->opcode)]); tcg_gen_extu_tl_i64(t1, cpu_gpr[rB(ctx->opcode)]); tcg_gen_mul_i64(t0, t0, t1); tcg_gen_trunc_i64_tl(t2, t0); gen_store_spr(SPR_MQ, t2); tcg_gen_shri_i64(t1, t0, 32); tcg_gen_trunc_i64_tl(cpu_gpr[rD(ctx->opcode)], t1); tcg_gen_ext32s_i64(t1, t0); tcg_gen_brcond_i64(TCG_COND_EQ, t0, t1, l1); tcg_gen_movi_tl(cpu_ov, 1); tcg_gen_movi_tl(cpu_so, 1); gen_set_label(l1); tcg_temp_free_i64(t0); tcg_temp_free_i64(t1); tcg_temp_free(t2); if (unlikely(Rc(ctx->opcode) != 0)) gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]); }


error_t ksz8851UpdateMacAddrFilter(NetInterface *interface)
{
   uint_t i;
   uint_t k;
   uint32_t crc;
   uint16_t hashTable[4];
   MacFilterEntry *entry;

   //Debug message
   TRACE_DEBUG("Updating MAC filter...\r\n");

   //Clear hash table
   osMemset(hashTable, 0, sizeof(hashTable));

   //The MAC address filter contains the list of MAC addresses to accept
   //when receiving an Ethernet frame
   for(i = 0; i < MAC_ADDR_FILTER_SIZE; i++)
   {
      //Point to the current entry
      entry = &interface->macAddrFilter[i];

      //Valid entry?
      if(entry->refCount > 0)
      {
         //Compute CRC over the current MAC address
         crc = ksz8851CalcCrc(&entry->addr, sizeof(MacAddr));
         //Calculate the corresponding index in the table
         k = (crc >> 26) & 0x3F;
         //Update hash table contents
         hashTable[k / 16] |= (1 << (k % 16));
      }
   }

   //Write the hash table to the KSZ8851 controller
   ksz8851WriteReg(interface, KSZ8851_MAHTR0, hashTable[0]);
   ksz8851WriteReg(interface, KSZ8851_MAHTR1, hashTable[1]);
   ksz8851WriteReg(interface, KSZ8851_MAHTR2, hashTable[2]);
   ksz8851WriteReg(interface, KSZ8851_MAHTR3, hashTable[3]);

   //Debug message
   TRACE_DEBUG("  MAHTR0 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_MAHTR0));
   TRACE_DEBUG("  MAHTR1 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_MAHTR1));
   TRACE_DEBUG("  MAHTR2 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_MAHTR2));
   TRACE_DEBUG("  MAHTR3 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_MAHTR3));

   //Successful processing
   return NO_ERROR;
}


error_t ksz8851UpdateMacAddrFilter(NetInterface *interface)
{
   uint_t i;
   uint_t k;
   uint32_t crc;
   uint16_t hashTable[4];
   MacFilterEntry *entry;

   //Debug message
   TRACE_DEBUG("Updating MAC filter...\r\n");

   //Clear hash table
   osMemset(hashTable, 0, sizeof(hashTable));

   //The MAC address filter contains the list of MAC addresses to accept
   //when receiving an Ethernet frame
   for(i = 0; i < MAC_ADDR_FILTER_SIZE; i++)
   {
      //Point to the current entry
      entry = &interface->macAddrFilter[i];

      //Valid entry?
      if(entry->refCount > 0)
      {
         //Compute CRC over the current MAC address
         crc = ksz8851CalcCrc(&entry->addr, sizeof(MacAddr));
         //Calculate the corresponding index in the table
         k = (crc >> 26) & 0x3F;
         //Update hash table contents
         hashTable[k / 16] |= (1 << (k % 16));
      }
   }

   //Write the hash table to the KSZ8851 controller
   ksz8851WriteReg(interface, KSZ8851_REG_MAHTR0, hashTable[0]);
   ksz8851WriteReg(interface, KSZ8851_REG_MAHTR1, hashTable[1]);
   ksz8851WriteReg(interface, KSZ8851_REG_MAHTR2, hashTable[2]);
   ksz8851WriteReg(interface, KSZ8851_REG_MAHTR3, hashTable[3]);

   //Debug message
   TRACE_DEBUG("  MAHTR0 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR0));
   TRACE_DEBUG("  MAHTR1 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR1));
   TRACE_DEBUG("  MAHTR2 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR2));
   TRACE_DEBUG("  MAHTR3 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR3));

   //Successful processing
   return NO_ERROR;
}


gostdsa_vko (const struct ecc_scalar *priv,
		const struct ecc_point *pub,
		size_t ukm_length, const uint8_t *ukm,
		uint8_t *out)
{
  const struct ecc_curve *ecc = priv->ecc;
  unsigned bsize = (ecc_bit_size (ecc) + 7) / 8;
  mp_size_t size = ecc->p.size;
  mp_size_t itch = 4*size + ecc->mul_itch;
  mp_limb_t *scratch;

  if (itch < 5*size + ecc->h_to_a_itch)
      itch = 5*size + ecc->h_to_a_itch;

  assert (pub->ecc == ecc);
  assert (priv->ecc == ecc);
  assert (ukm_length <= bsize);

  scratch = gmp_alloc_limbs (itch);

#define UKM scratch
#define TEMP (scratch + 3*size)
#define XYZ scratch
#define TEMP_Y (scratch + 4*size)

  mpn_set_base256_le (UKM, size, ukm, ukm_length);

  /* If ukm is 0, set it to 1, otherwise the result will be allways equal to 0,
   * no matter what private and public keys are. See RFC 4357 referencing GOST
   * R 34.10-2001 (RFC 5832) Section 6.1 step 2. */
  if (mpn_zero_p (UKM, size))
    UKM[0] = 1;

  ecc_mod_mul (&ecc->q, TEMP, priv->p, UKM, TEMP); /* TEMP = UKM * priv */
  ecc->mul (ecc, XYZ, TEMP, pub->p, scratch + 4*size); /* XYZ = UKM * priv * pub */
  ecc->h_to_a (ecc, 0, TEMP, XYZ, scratch + 5*size); /* TEMP = XYZ */
  mpn_get_base256_le (out, bsize, TEMP, size);
  mpn_get_base256_le (out+bsize, bsize, TEMP_Y, size);
  gmp_free_limbs (scratch, itch);
}