repo_id
stringlengths
27
162
file_path
stringlengths
42
195
content
stringlengths
4
5.16M
__index_level_0__
int64
0
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\psa_its_file.c
/* * PSA ITS simulator over stdio files. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(MBEDTLS_CONFIG_FILE) #include MBEDTLS_CONFIG_FILE #else #include "mbedtls/config.h" #endif #if defined(MBEDTLS_PSA_ITS_FILE_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #define mbedtls_snprintf snprintf #endif #if defined(_WIN32) #include <windows.h> #endif #include "psa_crypto_its.h" #include <limits.h> #include <stdint.h> #include <stdio.h> #include <string.h> #if !defined(PSA_ITS_STORAGE_PREFIX) #define PSA_ITS_STORAGE_PREFIX "" #endif #define PSA_ITS_STORAGE_FILENAME_PATTERN "%08lx%08lx" #define PSA_ITS_STORAGE_SUFFIX ".psa_its" #define PSA_ITS_STORAGE_FILENAME_LENGTH \ ( sizeof( PSA_ITS_STORAGE_PREFIX ) - 1 + /*prefix without terminating 0*/ \ 16 + /*UID (64-bit number in hex)*/ \ sizeof( PSA_ITS_STORAGE_SUFFIX ) - 1 + /*suffix without terminating 0*/ \ 1 /*terminating null byte*/ ) #define PSA_ITS_STORAGE_TEMP \ PSA_ITS_STORAGE_PREFIX "tempfile" PSA_ITS_STORAGE_SUFFIX /* The maximum value of psa_storage_info_t.size */ #define PSA_ITS_MAX_SIZE 0xffffffff #define PSA_ITS_MAGIC_STRING "PSA\0ITS\0" #define PSA_ITS_MAGIC_LENGTH 8 /* As rename fails on Windows if the new filepath already exists, * use MoveFileExA with the MOVEFILE_REPLACE_EXISTING flag instead. * Returns 0 on success, nonzero on failure. */ #if defined(_WIN32) #define rename_replace_existing( oldpath, newpath ) \ ( ! MoveFileExA( oldpath, newpath, MOVEFILE_REPLACE_EXISTING ) ) #else #define rename_replace_existing( oldpath, newpath ) rename( oldpath, newpath ) #endif typedef struct { uint8_t magic[PSA_ITS_MAGIC_LENGTH]; uint8_t size[sizeof( uint32_t )]; uint8_t flags[sizeof( psa_storage_create_flags_t )]; } psa_its_file_header_t; static void psa_its_fill_filename( psa_storage_uid_t uid, char *filename ) { /* Break up the UID into two 32-bit pieces so as not to rely on * long long support in snprintf. */ mbedtls_snprintf( filename, PSA_ITS_STORAGE_FILENAME_LENGTH, "%s" PSA_ITS_STORAGE_FILENAME_PATTERN "%s", PSA_ITS_STORAGE_PREFIX, (unsigned long) ( uid >> 32 ), (unsigned long) ( uid & 0xffffffff ), PSA_ITS_STORAGE_SUFFIX ); } static psa_status_t psa_its_read_file( psa_storage_uid_t uid, struct psa_storage_info_t *p_info, FILE **p_stream ) { char filename[PSA_ITS_STORAGE_FILENAME_LENGTH]; psa_its_file_header_t header; size_t n; *p_stream = NULL; psa_its_fill_filename( uid, filename ); *p_stream = fopen( filename, "rb" ); if( *p_stream == NULL ) return( PSA_ERROR_DOES_NOT_EXIST ); n = fread( &header, 1, sizeof( header ), *p_stream ); if( n != sizeof( header ) ) return( PSA_ERROR_DATA_CORRUPT ); if( memcmp( header.magic, PSA_ITS_MAGIC_STRING, PSA_ITS_MAGIC_LENGTH ) != 0 ) return( PSA_ERROR_DATA_CORRUPT ); p_info->size = ( header.size[0] | header.size[1] << 8 | header.size[2] << 16 | header.size[3] << 24 ); p_info->flags = ( header.flags[0] | header.flags[1] << 8 | header.flags[2] << 16 | header.flags[3] << 24 ); return( PSA_SUCCESS ); } psa_status_t psa_its_get_info( psa_storage_uid_t uid, struct psa_storage_info_t *p_info ) { psa_status_t status; FILE *stream = NULL; status = psa_its_read_file( uid, p_info, &stream ); if( stream != NULL ) fclose( stream ); return( status ); } psa_status_t psa_its_get( psa_storage_uid_t uid, uint32_t data_offset, uint32_t data_length, void *p_data, size_t *p_data_length ) { psa_status_t status; FILE *stream = NULL; size_t n; struct psa_storage_info_t info; status = psa_its_read_file( uid, &info, &stream ); if( status != PSA_SUCCESS ) goto exit; status = PSA_ERROR_INVALID_ARGUMENT; if( data_offset + data_length < data_offset ) goto exit; #if SIZE_MAX < 0xffffffff if( data_offset + data_length > SIZE_MAX ) goto exit; #endif if( data_offset + data_length > info.size ) goto exit; status = PSA_ERROR_STORAGE_FAILURE; #if LONG_MAX < 0xffffffff while( data_offset > LONG_MAX ) { if( fseek( stream, LONG_MAX, SEEK_CUR ) != 0 ) goto exit; data_offset -= LONG_MAX; } #endif if( fseek( stream, data_offset, SEEK_CUR ) != 0 ) goto exit; n = fread( p_data, 1, data_length, stream ); if( n != data_length ) goto exit; status = PSA_SUCCESS; if( p_data_length != NULL ) *p_data_length = n; exit: if( stream != NULL ) fclose( stream ); return( status ); } psa_status_t psa_its_set( psa_storage_uid_t uid, uint32_t data_length, const void *p_data, psa_storage_create_flags_t create_flags ) { psa_status_t status = PSA_ERROR_STORAGE_FAILURE; char filename[PSA_ITS_STORAGE_FILENAME_LENGTH]; FILE *stream = NULL; psa_its_file_header_t header; size_t n; memcpy( header.magic, PSA_ITS_MAGIC_STRING, PSA_ITS_MAGIC_LENGTH ); header.size[0] = data_length & 0xff; header.size[1] = ( data_length >> 8 ) & 0xff; header.size[2] = ( data_length >> 16 ) & 0xff; header.size[3] = ( data_length >> 24 ) & 0xff; header.flags[0] = create_flags & 0xff; header.flags[1] = ( create_flags >> 8 ) & 0xff; header.flags[2] = ( create_flags >> 16 ) & 0xff; header.flags[3] = ( create_flags >> 24 ) & 0xff; psa_its_fill_filename( uid, filename ); stream = fopen( PSA_ITS_STORAGE_TEMP, "wb" ); if( stream == NULL ) goto exit; status = PSA_ERROR_INSUFFICIENT_STORAGE; n = fwrite( &header, 1, sizeof( header ), stream ); if( n != sizeof( header ) ) goto exit; if( data_length != 0 ) { n = fwrite( p_data, 1, data_length, stream ); if( n != data_length ) goto exit; } status = PSA_SUCCESS; exit: if( stream != NULL ) { int ret = fclose( stream ); if( status == PSA_SUCCESS && ret != 0 ) status = PSA_ERROR_INSUFFICIENT_STORAGE; } if( status == PSA_SUCCESS ) { if( rename_replace_existing( PSA_ITS_STORAGE_TEMP, filename ) != 0 ) status = PSA_ERROR_STORAGE_FAILURE; } /* The temporary file may still exist, but only in failure cases where * we're already reporting an error. So there's nothing we can do on * failure. If the function succeeded, and in some error cases, the * temporary file doesn't exist and so remove() is expected to fail. * Thus we just ignore the return status of remove(). */ (void) remove( PSA_ITS_STORAGE_TEMP ); return( status ); } psa_status_t psa_its_remove( psa_storage_uid_t uid ) { char filename[PSA_ITS_STORAGE_FILENAME_LENGTH]; FILE *stream; psa_its_fill_filename( uid, filename ); stream = fopen( filename, "rb" ); if( stream == NULL ) return( PSA_ERROR_DOES_NOT_EXIST ); fclose( stream ); if( remove( filename ) != 0 ) return( PSA_ERROR_STORAGE_FAILURE ); return( PSA_SUCCESS ); } #endif /* MBEDTLS_PSA_ITS_FILE_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ripemd160.c
/* * RIPE MD-160 implementation * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The RIPEMD-160 algorithm was designed by RIPE in 1996 * http://homes.esat.kuleuven.be/~bosselae/mbedtls_ripemd160.html * http://ehash.iaik.tugraz.at/wiki/RIPEMD-160 */ #include "common.h" #if defined(MBEDTLS_RIPEMD160_C) #include "mbedtls/ripemd160.h" #include "mbedtls/platform_util.h" #include "mbedtls/error.h" #include <string.h> #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #define mbedtls_printf printf #endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_SELF_TEST */ #if !defined(MBEDTLS_RIPEMD160_ALT) /* * 32-bit integer manipulation macros (little endian) */ #ifndef GET_UINT32_LE #define GET_UINT32_LE(n,b,i) \ { \ (n) = ( (uint32_t) (b)[(i) ] ) \ | ( (uint32_t) (b)[(i) + 1] << 8 ) \ | ( (uint32_t) (b)[(i) + 2] << 16 ) \ | ( (uint32_t) (b)[(i) + 3] << 24 ); \ } #endif #ifndef PUT_UINT32_LE #define PUT_UINT32_LE(n,b,i) \ { \ (b)[(i) ] = (unsigned char) ( ( (n) ) & 0xFF ); \ (b)[(i) + 1] = (unsigned char) ( ( (n) >> 8 ) & 0xFF ); \ (b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF ); \ (b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF ); \ } #endif void mbedtls_ripemd160_init( mbedtls_ripemd160_context *ctx ) { memset( ctx, 0, sizeof( mbedtls_ripemd160_context ) ); } void mbedtls_ripemd160_free( mbedtls_ripemd160_context *ctx ) { if( ctx == NULL ) return; mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ripemd160_context ) ); } void mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst, const mbedtls_ripemd160_context *src ) { *dst = *src; } /* * RIPEMD-160 context setup */ int mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx ) { ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0x67452301; ctx->state[1] = 0xEFCDAB89; ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; ctx->state[4] = 0xC3D2E1F0; return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_ripemd160_starts( mbedtls_ripemd160_context *ctx ) { mbedtls_ripemd160_starts_ret( ctx ); } #endif #if !defined(MBEDTLS_RIPEMD160_PROCESS_ALT) /* * Process one block */ int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx, const unsigned char data[64] ) { struct { uint32_t A, B, C, D, E, Ap, Bp, Cp, Dp, Ep, X[16]; } local; GET_UINT32_LE( local.X[ 0], data, 0 ); GET_UINT32_LE( local.X[ 1], data, 4 ); GET_UINT32_LE( local.X[ 2], data, 8 ); GET_UINT32_LE( local.X[ 3], data, 12 ); GET_UINT32_LE( local.X[ 4], data, 16 ); GET_UINT32_LE( local.X[ 5], data, 20 ); GET_UINT32_LE( local.X[ 6], data, 24 ); GET_UINT32_LE( local.X[ 7], data, 28 ); GET_UINT32_LE( local.X[ 8], data, 32 ); GET_UINT32_LE( local.X[ 9], data, 36 ); GET_UINT32_LE( local.X[10], data, 40 ); GET_UINT32_LE( local.X[11], data, 44 ); GET_UINT32_LE( local.X[12], data, 48 ); GET_UINT32_LE( local.X[13], data, 52 ); GET_UINT32_LE( local.X[14], data, 56 ); GET_UINT32_LE( local.X[15], data, 60 ); local.A = local.Ap = ctx->state[0]; local.B = local.Bp = ctx->state[1]; local.C = local.Cp = ctx->state[2]; local.D = local.Dp = ctx->state[3]; local.E = local.Ep = ctx->state[4]; #define F1( x, y, z ) ( (x) ^ (y) ^ (z) ) #define F2( x, y, z ) ( ( (x) & (y) ) | ( ~(x) & (z) ) ) #define F3( x, y, z ) ( ( (x) | ~(y) ) ^ (z) ) #define F4( x, y, z ) ( ( (x) & (z) ) | ( (y) & ~(z) ) ) #define F5( x, y, z ) ( (x) ^ ( (y) | ~(z) ) ) #define S( x, n ) ( ( (x) << (n) ) | ( (x) >> (32 - (n)) ) ) #define P( a, b, c, d, e, r, s, f, k ) \ do \ { \ (a) += f( (b), (c), (d) ) + local.X[r] + (k); \ (a) = S( (a), (s) ) + (e); \ (c) = S( (c), 10 ); \ } while( 0 ) #define P2( a, b, c, d, e, r, s, rp, sp ) \ do \ { \ P( (a), (b), (c), (d), (e), (r), (s), F, K ); \ P( a ## p, b ## p, c ## p, d ## p, e ## p, \ (rp), (sp), Fp, Kp ); \ } while( 0 ) #define F F1 #define K 0x00000000 #define Fp F5 #define Kp 0x50A28BE6 P2( local.A, local.B, local.C, local.D, local.E, 0, 11, 5, 8 ); P2( local.E, local.A, local.B, local.C, local.D, 1, 14, 14, 9 ); P2( local.D, local.E, local.A, local.B, local.C, 2, 15, 7, 9 ); P2( local.C, local.D, local.E, local.A, local.B, 3, 12, 0, 11 ); P2( local.B, local.C, local.D, local.E, local.A, 4, 5, 9, 13 ); P2( local.A, local.B, local.C, local.D, local.E, 5, 8, 2, 15 ); P2( local.E, local.A, local.B, local.C, local.D, 6, 7, 11, 15 ); P2( local.D, local.E, local.A, local.B, local.C, 7, 9, 4, 5 ); P2( local.C, local.D, local.E, local.A, local.B, 8, 11, 13, 7 ); P2( local.B, local.C, local.D, local.E, local.A, 9, 13, 6, 7 ); P2( local.A, local.B, local.C, local.D, local.E, 10, 14, 15, 8 ); P2( local.E, local.A, local.B, local.C, local.D, 11, 15, 8, 11 ); P2( local.D, local.E, local.A, local.B, local.C, 12, 6, 1, 14 ); P2( local.C, local.D, local.E, local.A, local.B, 13, 7, 10, 14 ); P2( local.B, local.C, local.D, local.E, local.A, 14, 9, 3, 12 ); P2( local.A, local.B, local.C, local.D, local.E, 15, 8, 12, 6 ); #undef F #undef K #undef Fp #undef Kp #define F F2 #define K 0x5A827999 #define Fp F4 #define Kp 0x5C4DD124 P2( local.E, local.A, local.B, local.C, local.D, 7, 7, 6, 9 ); P2( local.D, local.E, local.A, local.B, local.C, 4, 6, 11, 13 ); P2( local.C, local.D, local.E, local.A, local.B, 13, 8, 3, 15 ); P2( local.B, local.C, local.D, local.E, local.A, 1, 13, 7, 7 ); P2( local.A, local.B, local.C, local.D, local.E, 10, 11, 0, 12 ); P2( local.E, local.A, local.B, local.C, local.D, 6, 9, 13, 8 ); P2( local.D, local.E, local.A, local.B, local.C, 15, 7, 5, 9 ); P2( local.C, local.D, local.E, local.A, local.B, 3, 15, 10, 11 ); P2( local.B, local.C, local.D, local.E, local.A, 12, 7, 14, 7 ); P2( local.A, local.B, local.C, local.D, local.E, 0, 12, 15, 7 ); P2( local.E, local.A, local.B, local.C, local.D, 9, 15, 8, 12 ); P2( local.D, local.E, local.A, local.B, local.C, 5, 9, 12, 7 ); P2( local.C, local.D, local.E, local.A, local.B, 2, 11, 4, 6 ); P2( local.B, local.C, local.D, local.E, local.A, 14, 7, 9, 15 ); P2( local.A, local.B, local.C, local.D, local.E, 11, 13, 1, 13 ); P2( local.E, local.A, local.B, local.C, local.D, 8, 12, 2, 11 ); #undef F #undef K #undef Fp #undef Kp #define F F3 #define K 0x6ED9EBA1 #define Fp F3 #define Kp 0x6D703EF3 P2( local.D, local.E, local.A, local.B, local.C, 3, 11, 15, 9 ); P2( local.C, local.D, local.E, local.A, local.B, 10, 13, 5, 7 ); P2( local.B, local.C, local.D, local.E, local.A, 14, 6, 1, 15 ); P2( local.A, local.B, local.C, local.D, local.E, 4, 7, 3, 11 ); P2( local.E, local.A, local.B, local.C, local.D, 9, 14, 7, 8 ); P2( local.D, local.E, local.A, local.B, local.C, 15, 9, 14, 6 ); P2( local.C, local.D, local.E, local.A, local.B, 8, 13, 6, 6 ); P2( local.B, local.C, local.D, local.E, local.A, 1, 15, 9, 14 ); P2( local.A, local.B, local.C, local.D, local.E, 2, 14, 11, 12 ); P2( local.E, local.A, local.B, local.C, local.D, 7, 8, 8, 13 ); P2( local.D, local.E, local.A, local.B, local.C, 0, 13, 12, 5 ); P2( local.C, local.D, local.E, local.A, local.B, 6, 6, 2, 14 ); P2( local.B, local.C, local.D, local.E, local.A, 13, 5, 10, 13 ); P2( local.A, local.B, local.C, local.D, local.E, 11, 12, 0, 13 ); P2( local.E, local.A, local.B, local.C, local.D, 5, 7, 4, 7 ); P2( local.D, local.E, local.A, local.B, local.C, 12, 5, 13, 5 ); #undef F #undef K #undef Fp #undef Kp #define F F4 #define K 0x8F1BBCDC #define Fp F2 #define Kp 0x7A6D76E9 P2( local.C, local.D, local.E, local.A, local.B, 1, 11, 8, 15 ); P2( local.B, local.C, local.D, local.E, local.A, 9, 12, 6, 5 ); P2( local.A, local.B, local.C, local.D, local.E, 11, 14, 4, 8 ); P2( local.E, local.A, local.B, local.C, local.D, 10, 15, 1, 11 ); P2( local.D, local.E, local.A, local.B, local.C, 0, 14, 3, 14 ); P2( local.C, local.D, local.E, local.A, local.B, 8, 15, 11, 14 ); P2( local.B, local.C, local.D, local.E, local.A, 12, 9, 15, 6 ); P2( local.A, local.B, local.C, local.D, local.E, 4, 8, 0, 14 ); P2( local.E, local.A, local.B, local.C, local.D, 13, 9, 5, 6 ); P2( local.D, local.E, local.A, local.B, local.C, 3, 14, 12, 9 ); P2( local.C, local.D, local.E, local.A, local.B, 7, 5, 2, 12 ); P2( local.B, local.C, local.D, local.E, local.A, 15, 6, 13, 9 ); P2( local.A, local.B, local.C, local.D, local.E, 14, 8, 9, 12 ); P2( local.E, local.A, local.B, local.C, local.D, 5, 6, 7, 5 ); P2( local.D, local.E, local.A, local.B, local.C, 6, 5, 10, 15 ); P2( local.C, local.D, local.E, local.A, local.B, 2, 12, 14, 8 ); #undef F #undef K #undef Fp #undef Kp #define F F5 #define K 0xA953FD4E #define Fp F1 #define Kp 0x00000000 P2( local.B, local.C, local.D, local.E, local.A, 4, 9, 12, 8 ); P2( local.A, local.B, local.C, local.D, local.E, 0, 15, 15, 5 ); P2( local.E, local.A, local.B, local.C, local.D, 5, 5, 10, 12 ); P2( local.D, local.E, local.A, local.B, local.C, 9, 11, 4, 9 ); P2( local.C, local.D, local.E, local.A, local.B, 7, 6, 1, 12 ); P2( local.B, local.C, local.D, local.E, local.A, 12, 8, 5, 5 ); P2( local.A, local.B, local.C, local.D, local.E, 2, 13, 8, 14 ); P2( local.E, local.A, local.B, local.C, local.D, 10, 12, 7, 6 ); P2( local.D, local.E, local.A, local.B, local.C, 14, 5, 6, 8 ); P2( local.C, local.D, local.E, local.A, local.B, 1, 12, 2, 13 ); P2( local.B, local.C, local.D, local.E, local.A, 3, 13, 13, 6 ); P2( local.A, local.B, local.C, local.D, local.E, 8, 14, 14, 5 ); P2( local.E, local.A, local.B, local.C, local.D, 11, 11, 0, 15 ); P2( local.D, local.E, local.A, local.B, local.C, 6, 8, 3, 13 ); P2( local.C, local.D, local.E, local.A, local.B, 15, 5, 9, 11 ); P2( local.B, local.C, local.D, local.E, local.A, 13, 6, 11, 11 ); #undef F #undef K #undef Fp #undef Kp local.C = ctx->state[1] + local.C + local.Dp; ctx->state[1] = ctx->state[2] + local.D + local.Ep; ctx->state[2] = ctx->state[3] + local.E + local.Ap; ctx->state[3] = ctx->state[4] + local.A + local.Bp; ctx->state[4] = ctx->state[0] + local.B + local.Cp; ctx->state[0] = local.C; /* Zeroise variables to clear sensitive data from memory. */ mbedtls_platform_zeroize( &local, sizeof( local ) ); return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_ripemd160_process( mbedtls_ripemd160_context *ctx, const unsigned char data[64] ) { mbedtls_internal_ripemd160_process( ctx, data ); } #endif #endif /* !MBEDTLS_RIPEMD160_PROCESS_ALT */ /* * RIPEMD-160 process buffer */ int mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx, const unsigned char *input, size_t ilen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t fill; uint32_t left; if( ilen == 0 ) return( 0 ); left = ctx->total[0] & 0x3F; fill = 64 - left; ctx->total[0] += (uint32_t) ilen; ctx->total[0] &= 0xFFFFFFFF; if( ctx->total[0] < (uint32_t) ilen ) ctx->total[1]++; if( left && ilen >= fill ) { memcpy( (void *) (ctx->buffer + left), input, fill ); if( ( ret = mbedtls_internal_ripemd160_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); input += fill; ilen -= fill; left = 0; } while( ilen >= 64 ) { if( ( ret = mbedtls_internal_ripemd160_process( ctx, input ) ) != 0 ) return( ret ); input += 64; ilen -= 64; } if( ilen > 0 ) { memcpy( (void *) (ctx->buffer + left), input, ilen ); } return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_ripemd160_update( mbedtls_ripemd160_context *ctx, const unsigned char *input, size_t ilen ) { mbedtls_ripemd160_update_ret( ctx, input, ilen ); } #endif static const unsigned char ripemd160_padding[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* * RIPEMD-160 final digest */ int mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx, unsigned char output[20] ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; uint32_t last, padn; uint32_t high, low; unsigned char msglen[8]; high = ( ctx->total[0] >> 29 ) | ( ctx->total[1] << 3 ); low = ( ctx->total[0] << 3 ); PUT_UINT32_LE( low, msglen, 0 ); PUT_UINT32_LE( high, msglen, 4 ); last = ctx->total[0] & 0x3F; padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last ); ret = mbedtls_ripemd160_update_ret( ctx, ripemd160_padding, padn ); if( ret != 0 ) return( ret ); ret = mbedtls_ripemd160_update_ret( ctx, msglen, 8 ); if( ret != 0 ) return( ret ); PUT_UINT32_LE( ctx->state[0], output, 0 ); PUT_UINT32_LE( ctx->state[1], output, 4 ); PUT_UINT32_LE( ctx->state[2], output, 8 ); PUT_UINT32_LE( ctx->state[3], output, 12 ); PUT_UINT32_LE( ctx->state[4], output, 16 ); return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_ripemd160_finish( mbedtls_ripemd160_context *ctx, unsigned char output[20] ) { mbedtls_ripemd160_finish_ret( ctx, output ); } #endif #endif /* ! MBEDTLS_RIPEMD160_ALT */ /* * output = RIPEMD-160( input buffer ) */ int mbedtls_ripemd160_ret( const unsigned char *input, size_t ilen, unsigned char output[20] ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_ripemd160_context ctx; mbedtls_ripemd160_init( &ctx ); if( ( ret = mbedtls_ripemd160_starts_ret( &ctx ) ) != 0 ) goto exit; if( ( ret = mbedtls_ripemd160_update_ret( &ctx, input, ilen ) ) != 0 ) goto exit; if( ( ret = mbedtls_ripemd160_finish_ret( &ctx, output ) ) != 0 ) goto exit; exit: mbedtls_ripemd160_free( &ctx ); return( ret ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_ripemd160( const unsigned char *input, size_t ilen, unsigned char output[20] ) { mbedtls_ripemd160_ret( input, ilen, output ); } #endif #if defined(MBEDTLS_SELF_TEST) /* * Test vectors from the RIPEMD-160 paper and * http://homes.esat.kuleuven.be/~bosselae/mbedtls_ripemd160.html#HMAC */ #define TESTS 8 static const unsigned char ripemd160_test_str[TESTS][81] = { { "" }, { "a" }, { "abc" }, { "message digest" }, { "abcdefghijklmnopqrstuvwxyz" }, { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" }, { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" }, { "12345678901234567890123456789012345678901234567890123456789012345678901234567890" }, }; static const size_t ripemd160_test_strlen[TESTS] = { 0, 1, 3, 14, 26, 56, 62, 80 }; static const unsigned char ripemd160_test_md[TESTS][20] = { { 0x9c, 0x11, 0x85, 0xa5, 0xc5, 0xe9, 0xfc, 0x54, 0x61, 0x28, 0x08, 0x97, 0x7e, 0xe8, 0xf5, 0x48, 0xb2, 0x25, 0x8d, 0x31 }, { 0x0b, 0xdc, 0x9d, 0x2d, 0x25, 0x6b, 0x3e, 0xe9, 0xda, 0xae, 0x34, 0x7b, 0xe6, 0xf4, 0xdc, 0x83, 0x5a, 0x46, 0x7f, 0xfe }, { 0x8e, 0xb2, 0x08, 0xf7, 0xe0, 0x5d, 0x98, 0x7a, 0x9b, 0x04, 0x4a, 0x8e, 0x98, 0xc6, 0xb0, 0x87, 0xf1, 0x5a, 0x0b, 0xfc }, { 0x5d, 0x06, 0x89, 0xef, 0x49, 0xd2, 0xfa, 0xe5, 0x72, 0xb8, 0x81, 0xb1, 0x23, 0xa8, 0x5f, 0xfa, 0x21, 0x59, 0x5f, 0x36 }, { 0xf7, 0x1c, 0x27, 0x10, 0x9c, 0x69, 0x2c, 0x1b, 0x56, 0xbb, 0xdc, 0xeb, 0x5b, 0x9d, 0x28, 0x65, 0xb3, 0x70, 0x8d, 0xbc }, { 0x12, 0xa0, 0x53, 0x38, 0x4a, 0x9c, 0x0c, 0x88, 0xe4, 0x05, 0xa0, 0x6c, 0x27, 0xdc, 0xf4, 0x9a, 0xda, 0x62, 0xeb, 0x2b }, { 0xb0, 0xe2, 0x0b, 0x6e, 0x31, 0x16, 0x64, 0x02, 0x86, 0xed, 0x3a, 0x87, 0xa5, 0x71, 0x30, 0x79, 0xb2, 0x1f, 0x51, 0x89 }, { 0x9b, 0x75, 0x2e, 0x45, 0x57, 0x3d, 0x4b, 0x39, 0xf4, 0xdb, 0xd3, 0x32, 0x3c, 0xab, 0x82, 0xbf, 0x63, 0x32, 0x6b, 0xfb }, }; /* * Checkup routine */ int mbedtls_ripemd160_self_test( int verbose ) { int i, ret = 0; unsigned char output[20]; memset( output, 0, sizeof output ); for( i = 0; i < TESTS; i++ ) { if( verbose != 0 ) mbedtls_printf( " RIPEMD-160 test #%d: ", i + 1 ); ret = mbedtls_ripemd160_ret( ripemd160_test_str[i], ripemd160_test_strlen[i], output ); if( ret != 0 ) goto fail; if( memcmp( output, ripemd160_test_md[i], 20 ) != 0 ) { ret = 1; goto fail; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); return( 0 ); fail: if( verbose != 0 ) mbedtls_printf( "failed\n" ); return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_RIPEMD160_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\rsa.c
/* * The RSA public-key cryptosystem * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The following sources were referenced in the design of this implementation * of the RSA algorithm: * * [1] A method for obtaining digital signatures and public-key cryptosystems * R Rivest, A Shamir, and L Adleman * http://people.csail.mit.edu/rivest/pubs.html#RSA78 * * [2] Handbook of Applied Cryptography - 1997, Chapter 8 * Menezes, van Oorschot and Vanstone * * [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks * Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and * Stefan Mangard * https://arxiv.org/abs/1702.08719v2 * */ #include "common.h" #if defined(MBEDTLS_RSA_C) #include "mbedtls/rsa.h" #include "mbedtls/rsa_internal.h" #include "mbedtls/oid.h" #include "mbedtls/platform_util.h" #include "mbedtls/error.h" #include <string.h> #if defined(MBEDTLS_PKCS1_V21) #include "mbedtls/md.h" #endif #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) && !defined(__NetBSD__) #include <stdlib.h> #endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #define mbedtls_printf printf #define mbedtls_calloc calloc #define mbedtls_free free #endif #if !defined(MBEDTLS_RSA_ALT) /* Parameter validation macros */ #define RSA_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_RSA_BAD_INPUT_DATA ) #define RSA_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) #if defined(MBEDTLS_PKCS1_V15) /* constant-time buffer comparison */ static inline int mbedtls_safer_memcmp( const void *a, const void *b, size_t n ) { size_t i; const unsigned char *A = (const unsigned char *) a; const unsigned char *B = (const unsigned char *) b; unsigned char diff = 0; for( i = 0; i < n; i++ ) diff |= A[i] ^ B[i]; return( diff ); } #endif /* MBEDTLS_PKCS1_V15 */ int mbedtls_rsa_import( mbedtls_rsa_context *ctx, const mbedtls_mpi *N, const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *E ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; RSA_VALIDATE_RET( ctx != NULL ); if( ( N != NULL && ( ret = mbedtls_mpi_copy( &ctx->N, N ) ) != 0 ) || ( P != NULL && ( ret = mbedtls_mpi_copy( &ctx->P, P ) ) != 0 ) || ( Q != NULL && ( ret = mbedtls_mpi_copy( &ctx->Q, Q ) ) != 0 ) || ( D != NULL && ( ret = mbedtls_mpi_copy( &ctx->D, D ) ) != 0 ) || ( E != NULL && ( ret = mbedtls_mpi_copy( &ctx->E, E ) ) != 0 ) ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } if( N != NULL ) ctx->len = mbedtls_mpi_size( &ctx->N ); return( 0 ); } int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx, unsigned char const *N, size_t N_len, unsigned char const *P, size_t P_len, unsigned char const *Q, size_t Q_len, unsigned char const *D, size_t D_len, unsigned char const *E, size_t E_len ) { int ret = 0; RSA_VALIDATE_RET( ctx != NULL ); if( N != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->N, N, N_len ) ); ctx->len = mbedtls_mpi_size( &ctx->N ); } if( P != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->P, P, P_len ) ); if( Q != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->Q, Q, Q_len ) ); if( D != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->D, D, D_len ) ); if( E != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->E, E, E_len ) ); cleanup: if( ret != 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); return( 0 ); } /* * Checks whether the context fields are set in such a way * that the RSA primitives will be able to execute without error. * It does *not* make guarantees for consistency of the parameters. */ static int rsa_check_context( mbedtls_rsa_context const *ctx, int is_priv, int blinding_needed ) { #if !defined(MBEDTLS_RSA_NO_CRT) /* blinding_needed is only used for NO_CRT to decide whether * P,Q need to be present or not. */ ((void) blinding_needed); #endif if( ctx->len != mbedtls_mpi_size( &ctx->N ) || ctx->len > MBEDTLS_MPI_MAX_SIZE ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } /* * 1. Modular exponentiation needs positive, odd moduli. */ /* Modular exponentiation wrt. N is always used for * RSA public key operations. */ if( mbedtls_mpi_cmp_int( &ctx->N, 0 ) <= 0 || mbedtls_mpi_get_bit( &ctx->N, 0 ) == 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #if !defined(MBEDTLS_RSA_NO_CRT) /* Modular exponentiation for P and Q is only * used for private key operations and if CRT * is used. */ if( is_priv && ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) <= 0 || mbedtls_mpi_get_bit( &ctx->P, 0 ) == 0 || mbedtls_mpi_cmp_int( &ctx->Q, 0 ) <= 0 || mbedtls_mpi_get_bit( &ctx->Q, 0 ) == 0 ) ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #endif /* !MBEDTLS_RSA_NO_CRT */ /* * 2. Exponents must be positive */ /* Always need E for public key operations */ if( mbedtls_mpi_cmp_int( &ctx->E, 0 ) <= 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); #if defined(MBEDTLS_RSA_NO_CRT) /* For private key operations, use D or DP & DQ * as (unblinded) exponents. */ if( is_priv && mbedtls_mpi_cmp_int( &ctx->D, 0 ) <= 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); #else if( is_priv && ( mbedtls_mpi_cmp_int( &ctx->DP, 0 ) <= 0 || mbedtls_mpi_cmp_int( &ctx->DQ, 0 ) <= 0 ) ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #endif /* MBEDTLS_RSA_NO_CRT */ /* Blinding shouldn't make exponents negative either, * so check that P, Q >= 1 if that hasn't yet been * done as part of 1. */ #if defined(MBEDTLS_RSA_NO_CRT) if( is_priv && blinding_needed && ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) <= 0 || mbedtls_mpi_cmp_int( &ctx->Q, 0 ) <= 0 ) ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #endif /* It wouldn't lead to an error if it wasn't satisfied, * but check for QP >= 1 nonetheless. */ #if !defined(MBEDTLS_RSA_NO_CRT) if( is_priv && mbedtls_mpi_cmp_int( &ctx->QP, 0 ) <= 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #endif return( 0 ); } int mbedtls_rsa_complete( mbedtls_rsa_context *ctx ) { int ret = 0; int have_N, have_P, have_Q, have_D, have_E; #if !defined(MBEDTLS_RSA_NO_CRT) int have_DP, have_DQ, have_QP; #endif int n_missing, pq_missing, d_missing, is_pub, is_priv; RSA_VALIDATE_RET( ctx != NULL ); have_N = ( mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 ); have_P = ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 ); have_Q = ( mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 ); have_D = ( mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 ); have_E = ( mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0 ); #if !defined(MBEDTLS_RSA_NO_CRT) have_DP = ( mbedtls_mpi_cmp_int( &ctx->DP, 0 ) != 0 ); have_DQ = ( mbedtls_mpi_cmp_int( &ctx->DQ, 0 ) != 0 ); have_QP = ( mbedtls_mpi_cmp_int( &ctx->QP, 0 ) != 0 ); #endif /* * Check whether provided parameters are enough * to deduce all others. The following incomplete * parameter sets for private keys are supported: * * (1) P, Q missing. * (2) D and potentially N missing. * */ n_missing = have_P && have_Q && have_D && have_E; pq_missing = have_N && !have_P && !have_Q && have_D && have_E; d_missing = have_P && have_Q && !have_D && have_E; is_pub = have_N && !have_P && !have_Q && !have_D && have_E; /* These three alternatives are mutually exclusive */ is_priv = n_missing || pq_missing || d_missing; if( !is_priv && !is_pub ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * Step 1: Deduce N if P, Q are provided. */ if( !have_N && have_P && have_Q ) { if( ( ret = mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) ) != 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } ctx->len = mbedtls_mpi_size( &ctx->N ); } /* * Step 2: Deduce and verify all remaining core parameters. */ if( pq_missing ) { ret = mbedtls_rsa_deduce_primes( &ctx->N, &ctx->E, &ctx->D, &ctx->P, &ctx->Q ); if( ret != 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } else if( d_missing ) { if( ( ret = mbedtls_rsa_deduce_private_exponent( &ctx->P, &ctx->Q, &ctx->E, &ctx->D ) ) != 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } } /* * Step 3: Deduce all additional parameters specific * to our current RSA implementation. */ #if !defined(MBEDTLS_RSA_NO_CRT) if( is_priv && ! ( have_DP && have_DQ && have_QP ) ) { ret = mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D, &ctx->DP, &ctx->DQ, &ctx->QP ); if( ret != 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } #endif /* MBEDTLS_RSA_NO_CRT */ /* * Step 3: Basic sanity checks */ return( rsa_check_context( ctx, is_priv, 1 ) ); } int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx, unsigned char *N, size_t N_len, unsigned char *P, size_t P_len, unsigned char *Q, size_t Q_len, unsigned char *D, size_t D_len, unsigned char *E, size_t E_len ) { int ret = 0; int is_priv; RSA_VALIDATE_RET( ctx != NULL ); /* Check if key is private or public */ is_priv = mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0; if( !is_priv ) { /* If we're trying to export private parameters for a public key, * something must be wrong. */ if( P != NULL || Q != NULL || D != NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } if( N != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->N, N, N_len ) ); if( P != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->P, P, P_len ) ); if( Q != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->Q, Q, Q_len ) ); if( D != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->D, D, D_len ) ); if( E != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->E, E, E_len ) ); cleanup: return( ret ); } int mbedtls_rsa_export( const mbedtls_rsa_context *ctx, mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q, mbedtls_mpi *D, mbedtls_mpi *E ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; int is_priv; RSA_VALIDATE_RET( ctx != NULL ); /* Check if key is private or public */ is_priv = mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0; if( !is_priv ) { /* If we're trying to export private parameters for a public key, * something must be wrong. */ if( P != NULL || Q != NULL || D != NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } /* Export all requested core parameters. */ if( ( N != NULL && ( ret = mbedtls_mpi_copy( N, &ctx->N ) ) != 0 ) || ( P != NULL && ( ret = mbedtls_mpi_copy( P, &ctx->P ) ) != 0 ) || ( Q != NULL && ( ret = mbedtls_mpi_copy( Q, &ctx->Q ) ) != 0 ) || ( D != NULL && ( ret = mbedtls_mpi_copy( D, &ctx->D ) ) != 0 ) || ( E != NULL && ( ret = mbedtls_mpi_copy( E, &ctx->E ) ) != 0 ) ) { return( ret ); } return( 0 ); } /* * Export CRT parameters * This must also be implemented if CRT is not used, for being able to * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt * can be used in this case. */ int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx, mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; int is_priv; RSA_VALIDATE_RET( ctx != NULL ); /* Check if key is private or public */ is_priv = mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0; if( !is_priv ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); #if !defined(MBEDTLS_RSA_NO_CRT) /* Export all requested blinding parameters. */ if( ( DP != NULL && ( ret = mbedtls_mpi_copy( DP, &ctx->DP ) ) != 0 ) || ( DQ != NULL && ( ret = mbedtls_mpi_copy( DQ, &ctx->DQ ) ) != 0 ) || ( QP != NULL && ( ret = mbedtls_mpi_copy( QP, &ctx->QP ) ) != 0 ) ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } #else if( ( ret = mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D, DP, DQ, QP ) ) != 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } #endif return( 0 ); } /* * Initialize an RSA context */ void mbedtls_rsa_init( mbedtls_rsa_context *ctx, int padding, int hash_id ) { RSA_VALIDATE( ctx != NULL ); RSA_VALIDATE( padding == MBEDTLS_RSA_PKCS_V15 || padding == MBEDTLS_RSA_PKCS_V21 ); memset( ctx, 0, sizeof( mbedtls_rsa_context ) ); mbedtls_rsa_set_padding( ctx, padding, hash_id ); #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_init( &ctx->mutex ); #endif } /* * Set padding for an existing RSA context */ void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, int hash_id ) { RSA_VALIDATE( ctx != NULL ); RSA_VALIDATE( padding == MBEDTLS_RSA_PKCS_V15 || padding == MBEDTLS_RSA_PKCS_V21 ); ctx->padding = padding; ctx->hash_id = hash_id; } /* * Get length in bytes of RSA modulus */ size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx ) { return( ctx->len ); } #if defined(MBEDTLS_GENPRIME) /* * Generate an RSA keypair * * This generation method follows the RSA key pair generation procedure of * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072. */ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, unsigned int nbits, int exponent ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_mpi H, G, L; int prime_quality = 0; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( f_rng != NULL ); if( nbits < 128 || exponent < 3 || nbits % 2 != 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * If the modulus is 1024 bit long or shorter, then the security strength of * the RSA algorithm is less than or equal to 80 bits and therefore an error * rate of 2^-80 is sufficient. */ if( nbits > 1024 ) prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR; mbedtls_mpi_init( &H ); mbedtls_mpi_init( &G ); mbedtls_mpi_init( &L ); /* * find primes P and Q with Q < P so that: * 1. |P-Q| > 2^( nbits / 2 - 100 ) * 2. GCD( E, (P-1)*(Q-1) ) == 1 * 3. E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 ) */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->E, exponent ) ); do { MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1, prime_quality, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, prime_quality, f_rng, p_rng ) ); /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &H, &ctx->P, &ctx->Q ) ); if( mbedtls_mpi_bitlen( &H ) <= ( ( nbits >= 200 ) ? ( ( nbits >> 1 ) - 99 ) : 0 ) ) continue; /* not required by any standards, but some users rely on the fact that P > Q */ if( H.s < 0 ) mbedtls_mpi_swap( &ctx->P, &ctx->Q ); /* Temporarily replace P,Q by P-1, Q-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->P, &ctx->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->Q, &ctx->Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &ctx->P, &ctx->Q ) ); /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->E, &H ) ); if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 ) continue; /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->P, &ctx->Q ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &L, NULL, &H, &G ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->D, &ctx->E, &L ) ); if( mbedtls_mpi_bitlen( &ctx->D ) <= ( ( nbits + 1 ) / 2 ) ) // (FIPS 186-4 §B.3.1 criterion 3(a)) continue; break; } while( 1 ); /* Restore P,Q */ MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->P, &ctx->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->Q, &ctx->Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) ); ctx->len = mbedtls_mpi_size( &ctx->N ); #if !defined(MBEDTLS_RSA_NO_CRT) /* * DP = D mod (P - 1) * DQ = D mod (Q - 1) * QP = Q^-1 mod P */ MBEDTLS_MPI_CHK( mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D, &ctx->DP, &ctx->DQ, &ctx->QP ) ); #endif /* MBEDTLS_RSA_NO_CRT */ /* Double-check */ MBEDTLS_MPI_CHK( mbedtls_rsa_check_privkey( ctx ) ); cleanup: mbedtls_mpi_free( &H ); mbedtls_mpi_free( &G ); mbedtls_mpi_free( &L ); if( ret != 0 ) { mbedtls_rsa_free( ctx ); return( MBEDTLS_ERR_RSA_KEY_GEN_FAILED + ret ); } return( 0 ); } #endif /* MBEDTLS_GENPRIME */ /* * Check a public RSA key */ int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx ) { RSA_VALIDATE_RET( ctx != NULL ); if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) != 0 ) return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); if( mbedtls_mpi_bitlen( &ctx->N ) < 128 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } if( mbedtls_mpi_get_bit( &ctx->E, 0 ) == 0 || mbedtls_mpi_bitlen( &ctx->E ) < 2 || mbedtls_mpi_cmp_mpi( &ctx->E, &ctx->N ) >= 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } return( 0 ); } /* * Check for the consistency of all fields in an RSA private key context */ int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx ) { RSA_VALIDATE_RET( ctx != NULL ); if( mbedtls_rsa_check_pubkey( ctx ) != 0 || rsa_check_context( ctx, 1 /* private */, 1 /* blinding */ ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } if( mbedtls_rsa_validate_params( &ctx->N, &ctx->P, &ctx->Q, &ctx->D, &ctx->E, NULL, NULL ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } #if !defined(MBEDTLS_RSA_NO_CRT) else if( mbedtls_rsa_validate_crt( &ctx->P, &ctx->Q, &ctx->D, &ctx->DP, &ctx->DQ, &ctx->QP ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } #endif return( 0 ); } /* * Check if contexts holding a public and private key match */ int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, const mbedtls_rsa_context *prv ) { RSA_VALIDATE_RET( pub != NULL ); RSA_VALIDATE_RET( prv != NULL ); if( mbedtls_rsa_check_pubkey( pub ) != 0 || mbedtls_rsa_check_privkey( prv ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } if( mbedtls_mpi_cmp_mpi( &pub->N, &prv->N ) != 0 || mbedtls_mpi_cmp_mpi( &pub->E, &prv->E ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } return( 0 ); } /* * Do an RSA public key operation */ int mbedtls_rsa_public( mbedtls_rsa_context *ctx, const unsigned char *input, unsigned char *output ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t olen; mbedtls_mpi T; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( input != NULL ); RSA_VALIDATE_RET( output != NULL ); if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); mbedtls_mpi_init( &T ); #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( ret ); #endif MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) ); if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 ) { ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; goto cleanup; } olen = ctx->len; MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, &ctx->E, &ctx->N, &ctx->RN ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) ); cleanup: #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif mbedtls_mpi_free( &T ); if( ret != 0 ) return( MBEDTLS_ERR_RSA_PUBLIC_FAILED + ret ); return( 0 ); } /* * Generate or update blinding values, see section 10 of: * KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA, * DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer * Berlin Heidelberg, 1996. p. 104-113. */ static int rsa_prepare_blinding( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret, count = 0; mbedtls_mpi R; mbedtls_mpi_init( &R ); if( ctx->Vf.p != NULL ) { /* We already have blinding values, just update them by squaring */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &ctx->Vi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &ctx->Vf ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->N ) ); goto cleanup; } /* Unblinding value: Vf = random number, invertible mod N */ do { if( count++ > 10 ) { ret = MBEDTLS_ERR_RSA_RNG_FAILED; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vf, ctx->len - 1, f_rng, p_rng ) ); /* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */ MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, ctx->len - 1, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vf, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) ); /* At this point, Vi is invertible mod N if and only if both Vf and R * are invertible mod N. If one of them isn't, we don't need to know * which one, we just loop and choose new values for both of them. * (Each iteration succeeds with overwhelming probability.) */ ret = mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vi, &ctx->N ); if( ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) goto cleanup; } while( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ); /* Finish the computation of Vf^-1 = R * (R Vf)^-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) ); /* Blinding value: Vi = Vf^(-e) mod N * (Vi already contains Vf^-1 at this point) */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN ) ); cleanup: mbedtls_mpi_free( &R ); return( ret ); } /* * Exponent blinding supposed to prevent side-channel attacks using multiple * traces of measurements to recover the RSA key. The more collisions are there, * the more bits of the key can be recovered. See [3]. * * Collecting n collisions with m bit long blinding value requires 2^(m-m/n) * observations on avarage. * * For example with 28 byte blinding to achieve 2 collisions the adversary has * to make 2^112 observations on avarage. * * (With the currently (as of 2017 April) known best algorithms breaking 2048 * bit RSA requires approximately as much time as trying out 2^112 random keys. * Thus in this sense with 28 byte blinding the security is not reduced by * side-channel attacks like the one in [3]) * * This countermeasure does not help if the key recovery is possible with a * single trace. */ #define RSA_EXPONENT_BLINDING 28 /* * Do an RSA private key operation */ int mbedtls_rsa_private( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, const unsigned char *input, unsigned char *output ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t olen; /* Temporary holding the result */ mbedtls_mpi T; /* Temporaries holding P-1, Q-1 and the * exponent blinding factor, respectively. */ mbedtls_mpi P1, Q1, R; #if !defined(MBEDTLS_RSA_NO_CRT) /* Temporaries holding the results mod p resp. mod q. */ mbedtls_mpi TP, TQ; /* Temporaries holding the blinded exponents for * the mod p resp. mod q computation (if used). */ mbedtls_mpi DP_blind, DQ_blind; /* Pointers to actual exponents to be used - either the unblinded * or the blinded ones, depending on the presence of a PRNG. */ mbedtls_mpi *DP = &ctx->DP; mbedtls_mpi *DQ = &ctx->DQ; #else /* Temporary holding the blinded exponent (if used). */ mbedtls_mpi D_blind; /* Pointer to actual exponent to be used - either the unblinded * or the blinded one, depending on the presence of a PRNG. */ mbedtls_mpi *D = &ctx->D; #endif /* MBEDTLS_RSA_NO_CRT */ /* Temporaries holding the initial input and the double * checked result; should be the same in the end. */ mbedtls_mpi I, C; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( input != NULL ); RSA_VALIDATE_RET( output != NULL ); if( rsa_check_context( ctx, 1 /* private key checks */, f_rng != NULL /* blinding y/n */ ) != 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( ret ); #endif /* MPI Initialization */ mbedtls_mpi_init( &T ); mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 ); mbedtls_mpi_init( &R ); if( f_rng != NULL ) { #if defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_init( &D_blind ); #else mbedtls_mpi_init( &DP_blind ); mbedtls_mpi_init( &DQ_blind ); #endif } #if !defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_init( &TP ); mbedtls_mpi_init( &TQ ); #endif mbedtls_mpi_init( &I ); mbedtls_mpi_init( &C ); /* End of MPI initialization */ MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) ); if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 ) { ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &I, &T ) ); if( f_rng != NULL ) { /* * Blinding * T = T * Vi mod N */ MBEDTLS_MPI_CHK( rsa_prepare_blinding( ctx, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) ); /* * Exponent blinding */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx->Q, 1 ) ); #if defined(MBEDTLS_RSA_NO_CRT) /* * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D */ MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &P1, &Q1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &D_blind, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &D_blind, &D_blind, &ctx->D ) ); D = &D_blind; #else /* * DP_blind = ( P - 1 ) * R + DP */ MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DP_blind, &P1, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DP_blind, &DP_blind, &ctx->DP ) ); DP = &DP_blind; /* * DQ_blind = ( Q - 1 ) * R + DQ */ MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DQ_blind, &Q1, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DQ_blind, &DQ_blind, &ctx->DQ ) ); DQ = &DQ_blind; #endif /* MBEDTLS_RSA_NO_CRT */ } #if defined(MBEDTLS_RSA_NO_CRT) MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, D, &ctx->N, &ctx->RN ) ); #else /* * Faster decryption using the CRT * * TP = input ^ dP mod P * TQ = input ^ dQ mod Q */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TP, &T, DP, &ctx->P, &ctx->RP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TQ, &T, DQ, &ctx->Q, &ctx->RQ ) ); /* * T = (TP - TQ) * (Q^-1 mod P) mod P */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T, &TP, &TQ ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->QP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &TP, &ctx->P ) ); /* * T = TQ + T * Q */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->Q ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T, &TQ, &TP ) ); #endif /* MBEDTLS_RSA_NO_CRT */ if( f_rng != NULL ) { /* * Unblind * T = T * Vf mod N */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vf ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) ); } /* Verify the result to prevent glitching attacks. */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &C, &T, &ctx->E, &ctx->N, &ctx->RN ) ); if( mbedtls_mpi_cmp_mpi( &C, &I ) != 0 ) { ret = MBEDTLS_ERR_RSA_VERIFY_FAILED; goto cleanup; } olen = ctx->len; MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) ); cleanup: #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif mbedtls_mpi_free( &P1 ); mbedtls_mpi_free( &Q1 ); mbedtls_mpi_free( &R ); if( f_rng != NULL ) { #if defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_free( &D_blind ); #else mbedtls_mpi_free( &DP_blind ); mbedtls_mpi_free( &DQ_blind ); #endif } mbedtls_mpi_free( &T ); #if !defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_free( &TP ); mbedtls_mpi_free( &TQ ); #endif mbedtls_mpi_free( &C ); mbedtls_mpi_free( &I ); if( ret != 0 && ret >= -0x007f ) return( MBEDTLS_ERR_RSA_PRIVATE_FAILED + ret ); return( ret ); } #if defined(MBEDTLS_PKCS1_V21) /** * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer. * * \param dst buffer to mask * \param dlen length of destination buffer * \param src source of the mask generation * \param slen length of the source buffer * \param md_ctx message digest context to use */ static int mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src, size_t slen, mbedtls_md_context_t *md_ctx ) { unsigned char mask[MBEDTLS_MD_MAX_SIZE]; unsigned char counter[4]; unsigned char *p; unsigned int hlen; size_t i, use_len; int ret = 0; memset( mask, 0, MBEDTLS_MD_MAX_SIZE ); memset( counter, 0, 4 ); hlen = mbedtls_md_get_size( md_ctx->md_info ); /* Generate and apply dbMask */ p = dst; while( dlen > 0 ) { use_len = hlen; if( dlen < hlen ) use_len = dlen; if( ( ret = mbedtls_md_starts( md_ctx ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_update( md_ctx, src, slen ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_update( md_ctx, counter, 4 ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_finish( md_ctx, mask ) ) != 0 ) goto exit; for( i = 0; i < use_len; ++i ) *p++ ^= mask[i]; counter[3]++; dlen -= use_len; } exit: mbedtls_platform_zeroize( mask, sizeof( mask ) ); return( ret ); } #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PKCS1_V21) /* * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function */ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, const unsigned char *label, size_t label_len, size_t ilen, const unsigned char *input, unsigned char *output ) { size_t olen; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = output; unsigned int hlen; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output != NULL ); RSA_VALIDATE_RET( ilen == 0 || input != NULL ); RSA_VALIDATE_RET( label_len == 0 || label != NULL ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); if( f_rng == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id ); if( md_info == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; hlen = mbedtls_md_get_size( md_info ); /* first comparison checks for overflow */ if( ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); memset( output, 0, olen ); *p++ = 0; /* Generate a random octet string seed */ if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 ) return( MBEDTLS_ERR_RSA_RNG_FAILED + ret ); p += hlen; /* Construct DB */ if( ( ret = mbedtls_md( md_info, label, label_len, p ) ) != 0 ) return( ret ); p += hlen; p += olen - 2 * hlen - 2 - ilen; *p++ = 1; if( ilen != 0 ) memcpy( p, input, ilen ); mbedtls_md_init( &md_ctx ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) goto exit; /* maskedDB: Apply dbMask to DB */ if( ( ret = mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen, &md_ctx ) ) != 0 ) goto exit; /* maskedSeed: Apply seedMask to seed */ if( ( ret = mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1, &md_ctx ) ) != 0 ) goto exit; exit: mbedtls_md_free( &md_ctx ); if( ret != 0 ) return( ret ); return( ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, output, output ) : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) ); } #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PKCS1_V15) /* * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function */ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t ilen, const unsigned char *input, unsigned char *output ) { size_t nb_pad, olen; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = output; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output != NULL ); RSA_VALIDATE_RET( ilen == 0 || input != NULL ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; /* first comparison checks for overflow */ if( ilen + 11 < ilen || olen < ilen + 11 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); nb_pad = olen - 3 - ilen; *p++ = 0; if( mode == MBEDTLS_RSA_PUBLIC ) { if( f_rng == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); *p++ = MBEDTLS_RSA_CRYPT; while( nb_pad-- > 0 ) { int rng_dl = 100; do { ret = f_rng( p_rng, p, 1 ); } while( *p == 0 && --rng_dl && ret == 0 ); /* Check if RNG failed to generate data */ if( rng_dl == 0 || ret != 0 ) return( MBEDTLS_ERR_RSA_RNG_FAILED + ret ); p++; } } else { *p++ = MBEDTLS_RSA_SIGN; while( nb_pad-- > 0 ) *p++ = 0xFF; } *p++ = 0; if( ilen != 0 ) memcpy( p, input, ilen ); return( ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, output, output ) : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) ); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Add the message padding, then do an RSA operation */ int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t ilen, const unsigned char *input, unsigned char *output ) { RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output != NULL ); RSA_VALIDATE_RET( ilen == 0 || input != NULL ); switch( ctx->padding ) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsaes_pkcs1_v15_encrypt( ctx, f_rng, p_rng, mode, ilen, input, output ); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsaes_oaep_encrypt( ctx, f_rng, p_rng, mode, NULL, 0, ilen, input, output ); #endif default: return( MBEDTLS_ERR_RSA_INVALID_PADDING ); } } #if defined(MBEDTLS_PKCS1_V21) /* * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function */ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, const unsigned char *label, size_t label_len, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t ilen, i, pad_len; unsigned char *p, bad, pad_done; unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; unsigned char lhash[MBEDTLS_MD_MAX_SIZE]; unsigned int hlen; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output_max_len == 0 || output != NULL ); RSA_VALIDATE_RET( label_len == 0 || label != NULL ); RSA_VALIDATE_RET( input != NULL ); RSA_VALIDATE_RET( olen != NULL ); /* * Parameters sanity checks */ if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); ilen = ctx->len; if( ilen < 16 || ilen > sizeof( buf ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id ); if( md_info == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hlen = mbedtls_md_get_size( md_info ); // checking for integer underflow if( 2 * hlen + 2 > ilen ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * RSA operation */ ret = ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, input, buf ) : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf ); if( ret != 0 ) goto cleanup; /* * Unmask data and generate lHash */ mbedtls_md_init( &md_ctx ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) { mbedtls_md_free( &md_ctx ); goto cleanup; } /* seed: Apply seedMask to maskedSeed */ if( ( ret = mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1, &md_ctx ) ) != 0 || /* DB: Apply dbMask to maskedDB */ ( ret = mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen, &md_ctx ) ) != 0 ) { mbedtls_md_free( &md_ctx ); goto cleanup; } mbedtls_md_free( &md_ctx ); /* Generate lHash */ if( ( ret = mbedtls_md( md_info, label, label_len, lhash ) ) != 0 ) goto cleanup; /* * Check contents, in "constant-time" */ p = buf; bad = 0; bad |= *p++; /* First byte must be 0 */ p += hlen; /* Skip seed */ /* Check lHash */ for( i = 0; i < hlen; i++ ) bad |= lhash[i] ^ *p++; /* Get zero-padding len, but always read till end of buffer * (minus one, for the 01 byte) */ pad_len = 0; pad_done = 0; for( i = 0; i < ilen - 2 * hlen - 2; i++ ) { pad_done |= p[i]; pad_len += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1; } p += pad_len; bad |= *p++ ^ 0x01; /* * The only information "leaked" is whether the padding was correct or not * (eg, no data is copied if it was not correct). This meets the * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between * the different error conditions. */ if( bad != 0 ) { ret = MBEDTLS_ERR_RSA_INVALID_PADDING; goto cleanup; } if( ilen - ( p - buf ) > output_max_len ) { ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE; goto cleanup; } *olen = ilen - (p - buf); if( *olen != 0 ) memcpy( output, p, *olen ); ret = 0; cleanup: mbedtls_platform_zeroize( buf, sizeof( buf ) ); mbedtls_platform_zeroize( lhash, sizeof( lhash ) ); return( ret ); } #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PKCS1_V15) /** Turn zero-or-nonzero into zero-or-all-bits-one, without branches. * * \param value The value to analyze. * \return Zero if \p value is zero, otherwise all-bits-one. */ static unsigned all_or_nothing_int( unsigned value ) { /* MSVC has a warning about unary minus on unsigned, but this is * well-defined and precisely what we want to do here */ #if defined(_MSC_VER) #pragma warning( push ) #pragma warning( disable : 4146 ) #endif return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) ); #if defined(_MSC_VER) #pragma warning( pop ) #endif } /** Check whether a size is out of bounds, without branches. * * This is equivalent to `size > max`, but is likely to be compiled to * to code using bitwise operation rather than a branch. * * \param size Size to check. * \param max Maximum desired value for \p size. * \return \c 0 if `size <= max`. * \return \c 1 if `size > max`. */ static unsigned size_greater_than( size_t size, size_t max ) { /* Return the sign bit (1 for negative) of (max - size). */ return( ( max - size ) >> ( sizeof( size_t ) * 8 - 1 ) ); } /** Choose between two integer values, without branches. * * This is equivalent to `cond ? if1 : if0`, but is likely to be compiled * to code using bitwise operation rather than a branch. * * \param cond Condition to test. * \param if1 Value to use if \p cond is nonzero. * \param if0 Value to use if \p cond is zero. * \return \c if1 if \p cond is nonzero, otherwise \c if0. */ static unsigned if_int( unsigned cond, unsigned if1, unsigned if0 ) { unsigned mask = all_or_nothing_int( cond ); return( ( mask & if1 ) | (~mask & if0 ) ); } /** Shift some data towards the left inside a buffer without leaking * the length of the data through side channels. * * `mem_move_to_left(start, total, offset)` is functionally equivalent to * ``` * memmove(start, start + offset, total - offset); * memset(start + offset, 0, total - offset); * ``` * but it strives to use a memory access pattern (and thus total timing) * that does not depend on \p offset. This timing independence comes at * the expense of performance. * * \param start Pointer to the start of the buffer. * \param total Total size of the buffer. * \param offset Offset from which to copy \p total - \p offset bytes. */ static void mem_move_to_left( void *start, size_t total, size_t offset ) { volatile unsigned char *buf = start; size_t i, n; if( total == 0 ) return; for( i = 0; i < total; i++ ) { unsigned no_op = size_greater_than( total - offset, i ); /* The first `total - offset` passes are a no-op. The last * `offset` passes shift the data one byte to the left and * zero out the last byte. */ for( n = 0; n < total - 1; n++ ) { unsigned char current = buf[n]; unsigned char next = buf[n+1]; buf[n] = if_int( no_op, current, next ); } buf[total-1] = if_int( no_op, buf[total-1], 0 ); } } /* * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function */ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t ilen, i, plaintext_max_size; unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; /* The following variables take sensitive values: their value must * not leak into the observable behavior of the function other than * the designated outputs (output, olen, return value). Otherwise * this would open the execution of the function to * side-channel-based variants of the Bleichenbacher padding oracle * attack. Potential side channels include overall timing, memory * access patterns (especially visible to an adversary who has access * to a shared memory cache), and branches (especially visible to * an adversary who has access to a shared code cache or to a shared * branch predictor). */ size_t pad_count = 0; unsigned bad = 0; unsigned char pad_done = 0; size_t plaintext_size = 0; unsigned output_too_large; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output_max_len == 0 || output != NULL ); RSA_VALIDATE_RET( input != NULL ); RSA_VALIDATE_RET( olen != NULL ); ilen = ctx->len; plaintext_max_size = ( output_max_len > ilen - 11 ? ilen - 11 : output_max_len ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); if( ilen < 16 || ilen > sizeof( buf ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); ret = ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, input, buf ) : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf ); if( ret != 0 ) goto cleanup; /* Check and get padding length in constant time and constant * memory trace. The first byte must be 0. */ bad |= buf[0]; if( mode == MBEDTLS_RSA_PRIVATE ) { /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00 * where PS must be at least 8 nonzero bytes. */ bad |= buf[1] ^ MBEDTLS_RSA_CRYPT; /* Read the whole buffer. Set pad_done to nonzero if we find * the 0x00 byte and remember the padding length in pad_count. */ for( i = 2; i < ilen; i++ ) { pad_done |= ((buf[i] | (unsigned char)-buf[i]) >> 7) ^ 1; pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1; } } else { /* Decode EMSA-PKCS1-v1_5 padding: 0x00 || 0x01 || PS || 0x00 * where PS must be at least 8 bytes with the value 0xFF. */ bad |= buf[1] ^ MBEDTLS_RSA_SIGN; /* Read the whole buffer. Set pad_done to nonzero if we find * the 0x00 byte and remember the padding length in pad_count. * If there's a non-0xff byte in the padding, the padding is bad. */ for( i = 2; i < ilen; i++ ) { pad_done |= if_int( buf[i], 0, 1 ); pad_count += if_int( pad_done, 0, 1 ); bad |= if_int( pad_done, 0, buf[i] ^ 0xFF ); } } /* If pad_done is still zero, there's no data, only unfinished padding. */ bad |= if_int( pad_done, 0, 1 ); /* There must be at least 8 bytes of padding. */ bad |= size_greater_than( 8, pad_count ); /* If the padding is valid, set plaintext_size to the number of * remaining bytes after stripping the padding. If the padding * is invalid, avoid leaking this fact through the size of the * output: use the maximum message size that fits in the output * buffer. Do it without branches to avoid leaking the padding * validity through timing. RSA keys are small enough that all the * size_t values involved fit in unsigned int. */ plaintext_size = if_int( bad, (unsigned) plaintext_max_size, (unsigned) ( ilen - pad_count - 3 ) ); /* Set output_too_large to 0 if the plaintext fits in the output * buffer and to 1 otherwise. */ output_too_large = size_greater_than( plaintext_size, plaintext_max_size ); /* Set ret without branches to avoid timing attacks. Return: * - INVALID_PADDING if the padding is bad (bad != 0). * - OUTPUT_TOO_LARGE if the padding is good but the decrypted * plaintext does not fit in the output buffer. * - 0 if the padding is correct. */ ret = - (int) if_int( bad, - MBEDTLS_ERR_RSA_INVALID_PADDING, if_int( output_too_large, - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE, 0 ) ); /* If the padding is bad or the plaintext is too large, zero the * data that we're about to copy to the output buffer. * We need to copy the same amount of data * from the same buffer whether the padding is good or not to * avoid leaking the padding validity through overall timing or * through memory or cache access patterns. */ bad = all_or_nothing_int( bad | output_too_large ); for( i = 11; i < ilen; i++ ) buf[i] &= ~bad; /* If the plaintext is too large, truncate it to the buffer size. * Copy anyway to avoid revealing the length through timing, because * revealing the length is as bad as revealing the padding validity * for a Bleichenbacher attack. */ plaintext_size = if_int( output_too_large, (unsigned) plaintext_max_size, (unsigned) plaintext_size ); /* Move the plaintext to the leftmost position where it can start in * the working buffer, i.e. make it start plaintext_max_size from * the end of the buffer. Do this with a memory access trace that * does not depend on the plaintext size. After this move, the * starting location of the plaintext is no longer sensitive * information. */ mem_move_to_left( buf + ilen - plaintext_max_size, plaintext_max_size, plaintext_max_size - plaintext_size ); /* Finally copy the decrypted plaintext plus trailing zeros into the output * buffer. If output_max_len is 0, then output may be an invalid pointer * and the result of memcpy() would be undefined; prevent undefined * behavior making sure to depend only on output_max_len (the size of the * user-provided output buffer), which is independent from plaintext * length, validity of padding, success of the decryption, and other * secrets. */ if( output_max_len != 0 ) memcpy( output, buf + ilen - plaintext_max_size, plaintext_max_size ); /* Report the amount of data we copied to the output buffer. In case * of errors (bad padding or output too large), the value of *olen * when this function returns is not specified. Making it equivalent * to the good case limits the risks of leaking the padding validity. */ *olen = plaintext_size; cleanup: mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Do an RSA operation, then remove the message padding */ int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len) { RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output_max_len == 0 || output != NULL ); RSA_VALIDATE_RET( input != NULL ); RSA_VALIDATE_RET( olen != NULL ); switch( ctx->padding ) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsaes_pkcs1_v15_decrypt( ctx, f_rng, p_rng, mode, olen, input, output, output_max_len ); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsaes_oaep_decrypt( ctx, f_rng, p_rng, mode, NULL, 0, olen, input, output, output_max_len ); #endif default: return( MBEDTLS_ERR_RSA_INVALID_PADDING ); } } #if defined(MBEDTLS_PKCS1_V21) /* * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function */ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { size_t olen; unsigned char *p = sig; unsigned char salt[MBEDTLS_MD_MAX_SIZE]; size_t slen, min_slen, hlen, offset = 0; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t msb; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hashlen == 0 ) || hash != NULL ); RSA_VALIDATE_RET( sig != NULL ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); if( f_rng == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; if( md_alg != MBEDTLS_MD_NONE ) { /* Gather length of hash to sign */ md_info = mbedtls_md_info_from_type( md_alg ); if( md_info == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hashlen = mbedtls_md_get_size( md_info ); } md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id ); if( md_info == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hlen = mbedtls_md_get_size( md_info ); /* Calculate the largest possible salt length. Normally this is the hash * length, which is the maximum length the salt can have. If there is not * enough room, use the maximum salt length that fits. The constraint is * that the hash length plus the salt length plus 2 bytes must be at most * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017 * (PKCS#1 v2.2) §9.1.1 step 3. */ min_slen = hlen - 2; if( olen < hlen + min_slen + 2 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); else if( olen >= hlen + hlen + 2 ) slen = hlen; else slen = olen - hlen - 2; memset( sig, 0, olen ); /* Generate salt of length slen */ if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 ) return( MBEDTLS_ERR_RSA_RNG_FAILED + ret ); /* Note: EMSA-PSS encoding is over the length of N - 1 bits */ msb = mbedtls_mpi_bitlen( &ctx->N ) - 1; p += olen - hlen - slen - 2; *p++ = 0x01; memcpy( p, salt, slen ); p += slen; mbedtls_md_init( &md_ctx ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) goto exit; /* Generate H = Hash( M' ) */ if( ( ret = mbedtls_md_starts( &md_ctx ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_update( &md_ctx, p, 8 ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_update( &md_ctx, hash, hashlen ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_update( &md_ctx, salt, slen ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_finish( &md_ctx, p ) ) != 0 ) goto exit; /* Compensate for boundary condition when applying mask */ if( msb % 8 == 0 ) offset = 1; /* maskedDB: Apply dbMask to DB */ if( ( ret = mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen, &md_ctx ) ) != 0 ) goto exit; msb = mbedtls_mpi_bitlen( &ctx->N ) - 1; sig[0] &= 0xFF >> ( olen * 8 - msb ); p += hlen; *p++ = 0xBC; mbedtls_platform_zeroize( salt, sizeof( salt ) ); exit: mbedtls_md_free( &md_ctx ); if( ret != 0 ) return( ret ); return( ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, sig, sig ) : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig ) ); } #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PKCS1_V15) /* * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function */ /* Construct a PKCS v1.5 encoding of a hashed message * * This is used both for signature generation and verification. * * Parameters: * - md_alg: Identifies the hash algorithm used to generate the given hash; * MBEDTLS_MD_NONE if raw data is signed. * - hashlen: Length of hash in case hashlen is MBEDTLS_MD_NONE. * - hash: Buffer containing the hashed message or the raw data. * - dst_len: Length of the encoded message. * - dst: Buffer to hold the encoded message. * * Assumptions: * - hash has size hashlen if md_alg == MBEDTLS_MD_NONE. * - hash has size corresponding to md_alg if md_alg != MBEDTLS_MD_NONE. * - dst points to a buffer of size at least dst_len. * */ static int rsa_rsassa_pkcs1_v15_encode( mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, size_t dst_len, unsigned char *dst ) { size_t oid_size = 0; size_t nb_pad = dst_len; unsigned char *p = dst; const char *oid = NULL; /* Are we signing hashed or raw data? */ if( md_alg != MBEDTLS_MD_NONE ) { const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg ); if( md_info == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); if( mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hashlen = mbedtls_md_get_size( md_info ); /* Double-check that 8 + hashlen + oid_size can be used as a * 1-byte ASN.1 length encoding and that there's no overflow. */ if( 8 + hashlen + oid_size >= 0x80 || 10 + hashlen < hashlen || 10 + hashlen + oid_size < 10 + hashlen ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * Static bounds check: * - Need 10 bytes for five tag-length pairs. * (Insist on 1-byte length encodings to protect against variants of * Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification) * - Need hashlen bytes for hash * - Need oid_size bytes for hash alg OID. */ if( nb_pad < 10 + hashlen + oid_size ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); nb_pad -= 10 + hashlen + oid_size; } else { if( nb_pad < hashlen ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); nb_pad -= hashlen; } /* Need space for signature header and padding delimiter (3 bytes), * and 8 bytes for the minimal padding */ if( nb_pad < 3 + 8 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); nb_pad -= 3; /* Now nb_pad is the amount of memory to be filled * with padding, and at least 8 bytes long. */ /* Write signature header and padding */ *p++ = 0; *p++ = MBEDTLS_RSA_SIGN; memset( p, 0xFF, nb_pad ); p += nb_pad; *p++ = 0; /* Are we signing raw data? */ if( md_alg == MBEDTLS_MD_NONE ) { memcpy( p, hash, hashlen ); return( 0 ); } /* Signing hashed data, add corresponding ASN.1 structure * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithmIdentifier, * digest Digest } * DigestAlgorithmIdentifier ::= AlgorithmIdentifier * Digest ::= OCTET STRING * * Schematic: * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID + LEN [ OID ] * TAG-NULL + LEN [ NULL ] ] * TAG-OCTET + LEN [ HASH ] ] */ *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED; *p++ = (unsigned char)( 0x08 + oid_size + hashlen ); *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED; *p++ = (unsigned char)( 0x04 + oid_size ); *p++ = MBEDTLS_ASN1_OID; *p++ = (unsigned char) oid_size; memcpy( p, oid, oid_size ); p += oid_size; *p++ = MBEDTLS_ASN1_NULL; *p++ = 0x00; *p++ = MBEDTLS_ASN1_OCTET_STRING; *p++ = (unsigned char) hashlen; memcpy( p, hash, hashlen ); p += hashlen; /* Just a sanity-check, should be automatic * after the initial bounds check. */ if( p != dst + dst_len ) { mbedtls_platform_zeroize( dst, dst_len ); return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } return( 0 ); } /* * Do an RSA operation to sign the message digest */ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *sig_try = NULL, *verif = NULL; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hashlen == 0 ) || hash != NULL ); RSA_VALIDATE_RET( sig != NULL ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * Prepare PKCS1-v1.5 encoding (padding and hash identifier) */ if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash, ctx->len, sig ) ) != 0 ) return( ret ); /* * Call respective RSA primitive */ if( mode == MBEDTLS_RSA_PUBLIC ) { /* Skip verification on a public key operation */ return( mbedtls_rsa_public( ctx, sig, sig ) ); } /* Private key operation * * In order to prevent Lenstra's attack, make the signature in a * temporary buffer and check it before returning it. */ sig_try = mbedtls_calloc( 1, ctx->len ); if( sig_try == NULL ) return( MBEDTLS_ERR_MPI_ALLOC_FAILED ); verif = mbedtls_calloc( 1, ctx->len ); if( verif == NULL ) { mbedtls_free( sig_try ); return( MBEDTLS_ERR_MPI_ALLOC_FAILED ); } MBEDTLS_MPI_CHK( mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig_try ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_public( ctx, sig_try, verif ) ); if( mbedtls_safer_memcmp( verif, sig, ctx->len ) != 0 ) { ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED; goto cleanup; } memcpy( sig, sig_try, ctx->len ); cleanup: mbedtls_free( sig_try ); mbedtls_free( verif ); return( ret ); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Do an RSA operation to sign the message digest */ int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hashlen == 0 ) || hash != NULL ); RSA_VALIDATE_RET( sig != NULL ); switch( ctx->padding ) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsassa_pkcs1_v15_sign( ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig ); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig ); #endif default: return( MBEDTLS_ERR_RSA_INVALID_PADDING ); } } #if defined(MBEDTLS_PKCS1_V21) /* * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function */ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, mbedtls_md_type_t mgf1_hash_id, int expected_salt_len, const unsigned char *sig ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t siglen; unsigned char *p; unsigned char *hash_start; unsigned char result[MBEDTLS_MD_MAX_SIZE]; unsigned char zeros[8]; unsigned int hlen; size_t observed_salt_len, msb; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( sig != NULL ); RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hashlen == 0 ) || hash != NULL ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); siglen = ctx->len; if( siglen < 16 || siglen > sizeof( buf ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); ret = ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, sig, buf ) : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, buf ); if( ret != 0 ) return( ret ); p = buf; if( buf[siglen - 1] != 0xBC ) return( MBEDTLS_ERR_RSA_INVALID_PADDING ); if( md_alg != MBEDTLS_MD_NONE ) { /* Gather length of hash to sign */ md_info = mbedtls_md_info_from_type( md_alg ); if( md_info == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hashlen = mbedtls_md_get_size( md_info ); } md_info = mbedtls_md_info_from_type( mgf1_hash_id ); if( md_info == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hlen = mbedtls_md_get_size( md_info ); memset( zeros, 0, 8 ); /* * Note: EMSA-PSS verification is over the length of N - 1 bits */ msb = mbedtls_mpi_bitlen( &ctx->N ) - 1; if( buf[0] >> ( 8 - siglen * 8 + msb ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* Compensate for boundary condition when applying mask */ if( msb % 8 == 0 ) { p++; siglen -= 1; } if( siglen < hlen + 2 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hash_start = p + siglen - hlen - 1; mbedtls_md_init( &md_ctx ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) goto exit; ret = mgf_mask( p, siglen - hlen - 1, hash_start, hlen, &md_ctx ); if( ret != 0 ) goto exit; buf[0] &= 0xFF >> ( siglen * 8 - msb ); while( p < hash_start - 1 && *p == 0 ) p++; if( *p++ != 0x01 ) { ret = MBEDTLS_ERR_RSA_INVALID_PADDING; goto exit; } observed_salt_len = hash_start - p; if( expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY && observed_salt_len != (size_t) expected_salt_len ) { ret = MBEDTLS_ERR_RSA_INVALID_PADDING; goto exit; } /* * Generate H = Hash( M' ) */ ret = mbedtls_md_starts( &md_ctx ); if ( ret != 0 ) goto exit; ret = mbedtls_md_update( &md_ctx, zeros, 8 ); if ( ret != 0 ) goto exit; ret = mbedtls_md_update( &md_ctx, hash, hashlen ); if ( ret != 0 ) goto exit; ret = mbedtls_md_update( &md_ctx, p, observed_salt_len ); if ( ret != 0 ) goto exit; ret = mbedtls_md_finish( &md_ctx, result ); if ( ret != 0 ) goto exit; if( memcmp( hash_start, result, hlen ) != 0 ) { ret = MBEDTLS_ERR_RSA_VERIFY_FAILED; goto exit; } exit: mbedtls_md_free( &md_ctx ); return( ret ); } /* * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function */ int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig ) { mbedtls_md_type_t mgf1_hash_id; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( sig != NULL ); RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hashlen == 0 ) || hash != NULL ); mgf1_hash_id = ( ctx->hash_id != MBEDTLS_MD_NONE ) ? (mbedtls_md_type_t) ctx->hash_id : md_alg; return( mbedtls_rsa_rsassa_pss_verify_ext( ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, mgf1_hash_id, MBEDTLS_RSA_SALT_LEN_ANY, sig ) ); } #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PKCS1_V15) /* * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function */ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig ) { int ret = 0; size_t sig_len; unsigned char *encoded = NULL, *encoded_expected = NULL; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( sig != NULL ); RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hashlen == 0 ) || hash != NULL ); sig_len = ctx->len; if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * Prepare expected PKCS1 v1.5 encoding of hash. */ if( ( encoded = mbedtls_calloc( 1, sig_len ) ) == NULL || ( encoded_expected = mbedtls_calloc( 1, sig_len ) ) == NULL ) { ret = MBEDTLS_ERR_MPI_ALLOC_FAILED; goto cleanup; } if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash, sig_len, encoded_expected ) ) != 0 ) goto cleanup; /* * Apply RSA primitive to get what should be PKCS1 encoded hash. */ ret = ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, sig, encoded ) : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, encoded ); if( ret != 0 ) goto cleanup; /* * Compare */ if( ( ret = mbedtls_safer_memcmp( encoded, encoded_expected, sig_len ) ) != 0 ) { ret = MBEDTLS_ERR_RSA_VERIFY_FAILED; goto cleanup; } cleanup: if( encoded != NULL ) { mbedtls_platform_zeroize( encoded, sig_len ); mbedtls_free( encoded ); } if( encoded_expected != NULL ) { mbedtls_platform_zeroize( encoded_expected, sig_len ); mbedtls_free( encoded_expected ); } return( ret ); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Do an RSA operation and check the message digest */ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig ) { RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( sig != NULL ); RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hashlen == 0 ) || hash != NULL ); switch( ctx->padding ) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsassa_pkcs1_v15_verify( ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig ); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsassa_pss_verify( ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig ); #endif default: return( MBEDTLS_ERR_RSA_INVALID_PADDING ); } } /* * Copy the components of an RSA key */ int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; RSA_VALIDATE_RET( dst != NULL ); RSA_VALIDATE_RET( src != NULL ); dst->ver = src->ver; dst->len = src->len; MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->N, &src->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->E, &src->E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->D, &src->D ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->P, &src->P ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Q, &src->Q ) ); #if !defined(MBEDTLS_RSA_NO_CRT) MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DP, &src->DP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DQ, &src->DQ ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->QP, &src->QP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RP, &src->RP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RQ, &src->RQ ) ); #endif MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RN, &src->RN ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vi, &src->Vi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vf, &src->Vf ) ); dst->padding = src->padding; dst->hash_id = src->hash_id; cleanup: if( ret != 0 ) mbedtls_rsa_free( dst ); return( ret ); } /* * Free the components of an RSA key */ void mbedtls_rsa_free( mbedtls_rsa_context *ctx ) { if( ctx == NULL ) return; mbedtls_mpi_free( &ctx->Vi ); mbedtls_mpi_free( &ctx->Vf ); mbedtls_mpi_free( &ctx->RN ); mbedtls_mpi_free( &ctx->D ); mbedtls_mpi_free( &ctx->Q ); mbedtls_mpi_free( &ctx->P ); mbedtls_mpi_free( &ctx->E ); mbedtls_mpi_free( &ctx->N ); #if !defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_free( &ctx->RQ ); mbedtls_mpi_free( &ctx->RP ); mbedtls_mpi_free( &ctx->QP ); mbedtls_mpi_free( &ctx->DQ ); mbedtls_mpi_free( &ctx->DP ); #endif /* MBEDTLS_RSA_NO_CRT */ #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_free( &ctx->mutex ); #endif } #endif /* !MBEDTLS_RSA_ALT */ #if defined(MBEDTLS_SELF_TEST) #include "mbedtls/sha1.h" /* * Example RSA-1024 keypair, for test purposes */ #define KEY_LEN 128 #define RSA_N "9292758453063D803DD603D5E777D788" \ "8ED1D5BF35786190FA2F23EBC0848AEA" \ "DDA92CA6C3D80B32C4D109BE0F36D6AE" \ "7130B9CED7ACDF54CFC7555AC14EEBAB" \ "93A89813FBF3C4F8066D2D800F7C38A8" \ "1AE31942917403FF4946B0A83D3D3E05" \ "EE57C6F5F5606FB5D4BC6CD34EE0801A" \ "5E94BB77B07507233A0BC7BAC8F90F79" #define RSA_E "10001" #define RSA_D "24BF6185468786FDD303083D25E64EFC" \ "66CA472BC44D253102F8B4A9D3BFA750" \ "91386C0077937FE33FA3252D28855837" \ "AE1B484A8A9A45F7EE8C0C634F99E8CD" \ "DF79C5CE07EE72C7F123142198164234" \ "CABB724CF78B8173B9F880FC86322407" \ "AF1FEDFDDE2BEB674CA15F3E81A1521E" \ "071513A1E85B5DFA031F21ECAE91A34D" #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \ "2C01CAD19EA484A87EA4377637E75500" \ "FCB2005C5C7DD6EC4AC023CDA285D796" \ "C3D9E75E1EFC42488BB4F1D13AC30A57" #define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \ "E211C2B9E5DB1ED0BF61D0D9899620F4" \ "910E4168387E3C30AA1E00C339A79508" \ "8452DD96A9A5EA5D9DCA68DA636032AF" #define PT_LEN 24 #define RSA_PT "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \ "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD" #if defined(MBEDTLS_PKCS1_V15) static int myrand( void *rng_state, unsigned char *output, size_t len ) { #if !defined(__OpenBSD__) && !defined(__NetBSD__) size_t i; if( rng_state != NULL ) rng_state = NULL; for( i = 0; i < len; ++i ) output[i] = rand(); #else if( rng_state != NULL ) rng_state = NULL; arc4random_buf( output, len ); #endif /* !OpenBSD && !NetBSD */ return( 0 ); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Checkup routine */ int mbedtls_rsa_self_test( int verbose ) { int ret = 0; #if defined(MBEDTLS_PKCS1_V15) size_t len; mbedtls_rsa_context rsa; unsigned char rsa_plaintext[PT_LEN]; unsigned char rsa_decrypted[PT_LEN]; unsigned char rsa_ciphertext[KEY_LEN]; #if defined(MBEDTLS_SHA1_C) unsigned char sha1sum[20]; #endif mbedtls_mpi K; mbedtls_mpi_init( &K ); mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_N ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, &K, NULL, NULL, NULL, NULL ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_P ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, &K, NULL, NULL, NULL ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_Q ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, &K, NULL, NULL ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_D ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, &K, NULL ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_E ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, NULL, &K ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_complete( &rsa ) ); if( verbose != 0 ) mbedtls_printf( " RSA key validation: " ); if( mbedtls_rsa_check_pubkey( &rsa ) != 0 || mbedtls_rsa_check_privkey( &rsa ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n PKCS#1 encryption : " ); memcpy( rsa_plaintext, RSA_PT, PT_LEN ); if( mbedtls_rsa_pkcs1_encrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PUBLIC, PT_LEN, rsa_plaintext, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n PKCS#1 decryption : " ); if( mbedtls_rsa_pkcs1_decrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE, &len, rsa_ciphertext, rsa_decrypted, sizeof(rsa_decrypted) ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); #if defined(MBEDTLS_SHA1_C) if( verbose != 0 ) mbedtls_printf( " PKCS#1 data sign : " ); if( mbedtls_sha1_ret( rsa_plaintext, PT_LEN, sha1sum ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); return( 1 ); } if( mbedtls_rsa_pkcs1_sign( &rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 0, sha1sum, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n PKCS#1 sig. verify: " ); if( mbedtls_rsa_pkcs1_verify( &rsa, NULL, NULL, MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 0, sha1sum, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); #endif /* MBEDTLS_SHA1_C */ if( verbose != 0 ) mbedtls_printf( "\n" ); cleanup: mbedtls_mpi_free( &K ); mbedtls_rsa_free( &rsa ); #else /* MBEDTLS_PKCS1_V15 */ ((void) verbose); #endif /* MBEDTLS_PKCS1_V15 */ return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_RSA_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\rsa_internal.c
/* * Helper functions for the RSA module * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "common.h" #if defined(MBEDTLS_RSA_C) #include "mbedtls/rsa.h" #include "mbedtls/bignum.h" #include "mbedtls/rsa_internal.h" /* * Compute RSA prime factors from public and private exponents * * Summary of algorithm: * Setting F := lcm(P-1,Q-1), the idea is as follows: * * (a) For any 1 <= X < N with gcd(X,N)=1, we have X^F = 1 modulo N, so X^(F/2) * is a square root of 1 in Z/NZ. Since Z/NZ ~= Z/PZ x Z/QZ by CRT and the * square roots of 1 in Z/PZ and Z/QZ are +1 and -1, this leaves the four * possibilities X^(F/2) = (+-1, +-1). If it happens that X^(F/2) = (-1,+1) * or (+1,-1), then gcd(X^(F/2) + 1, N) will be equal to one of the prime * factors of N. * * (b) If we don't know F/2 but (F/2) * K for some odd (!) K, then the same * construction still applies since (-)^K is the identity on the set of * roots of 1 in Z/NZ. * * The public and private key primitives (-)^E and (-)^D are mutually inverse * bijections on Z/NZ if and only if (-)^(DE) is the identity on Z/NZ, i.e. * if and only if DE - 1 is a multiple of F, say DE - 1 = F * L. * Splitting L = 2^t * K with K odd, we have * * DE - 1 = FL = (F/2) * (2^(t+1)) * K, * * so (F / 2) * K is among the numbers * * (DE - 1) >> 1, (DE - 1) >> 2, ..., (DE - 1) >> ord * * where ord is the order of 2 in (DE - 1). * We can therefore iterate through these numbers apply the construction * of (a) and (b) above to attempt to factor N. * */ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E, mbedtls_mpi const *D, mbedtls_mpi *P, mbedtls_mpi *Q ) { int ret = 0; uint16_t attempt; /* Number of current attempt */ uint16_t iter; /* Number of squares computed in the current attempt */ uint16_t order; /* Order of 2 in DE - 1 */ mbedtls_mpi T; /* Holds largest odd divisor of DE - 1 */ mbedtls_mpi K; /* Temporary holding the current candidate */ const unsigned char primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 }; const size_t num_primes = sizeof( primes ) / sizeof( *primes ); if( P == NULL || Q == NULL || P->p != NULL || Q->p != NULL ) return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 || mbedtls_mpi_cmp_int( D, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( D, N ) >= 0 || mbedtls_mpi_cmp_int( E, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( E, N ) >= 0 ) { return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); } /* * Initializations and temporary changes */ mbedtls_mpi_init( &K ); mbedtls_mpi_init( &T ); /* T := DE - 1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, D, E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &T, &T, 1 ) ); if( ( order = (uint16_t) mbedtls_mpi_lsb( &T ) ) == 0 ) { ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; goto cleanup; } /* After this operation, T holds the largest odd divisor of DE - 1. */ MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &T, order ) ); /* * Actual work */ /* Skip trying 2 if N == 1 mod 8 */ attempt = 0; if( N->p[0] % 8 == 1 ) attempt = 1; for( ; attempt < num_primes; ++attempt ) { mbedtls_mpi_lset( &K, primes[attempt] ); /* Check if gcd(K,N) = 1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) ); if( mbedtls_mpi_cmp_int( P, 1 ) != 0 ) continue; /* Go through K^T + 1, K^(2T) + 1, K^(4T) + 1, ... * and check whether they have nontrivial GCD with N. */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &K, &K, &T, N, Q /* temporarily use Q for storing Montgomery * multiplication helper values */ ) ); for( iter = 1; iter <= order; ++iter ) { /* If we reach 1 prematurely, there's no point * in continuing to square K */ if( mbedtls_mpi_cmp_int( &K, 1 ) == 0 ) break; MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) ); if( mbedtls_mpi_cmp_int( P, 1 ) == 1 && mbedtls_mpi_cmp_mpi( P, N ) == -1 ) { /* * Have found a nontrivial divisor P of N. * Set Q := N / P. */ MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( Q, NULL, N, P ) ); goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &K ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, N ) ); } /* * If we get here, then either we prematurely aborted the loop because * we reached 1, or K holds primes[attempt]^(DE - 1) mod N, which must * be 1 if D,E,N were consistent. * Check if that's the case and abort if not, to avoid very long, * yet eventually failing, computations if N,D,E were not sane. */ if( mbedtls_mpi_cmp_int( &K, 1 ) != 0 ) { break; } } ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; cleanup: mbedtls_mpi_free( &K ); mbedtls_mpi_free( &T ); return( ret ); } /* * Given P, Q and the public exponent E, deduce D. * This is essentially a modular inversion. */ int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P, mbedtls_mpi const *Q, mbedtls_mpi const *E, mbedtls_mpi *D ) { int ret = 0; mbedtls_mpi K, L; if( D == NULL || mbedtls_mpi_cmp_int( D, 0 ) != 0 ) return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 || mbedtls_mpi_cmp_int( Q, 1 ) <= 0 || mbedtls_mpi_cmp_int( E, 0 ) == 0 ) { return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); } mbedtls_mpi_init( &K ); mbedtls_mpi_init( &L ); /* Temporarily put K := P-1 and L := Q-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) ); /* Temporarily put D := gcd(P-1, Q-1) */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( D, &K, &L ) ); /* K := LCM(P-1, Q-1) */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &L ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &K, NULL, &K, D ) ); /* Compute modular inverse of E in LCM(P-1, Q-1) */ MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( D, E, &K ) ); cleanup: mbedtls_mpi_free( &K ); mbedtls_mpi_free( &L ); return( ret ); } /* * Check that RSA CRT parameters are in accordance with core parameters. */ int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *DP, const mbedtls_mpi *DQ, const mbedtls_mpi *QP ) { int ret = 0; mbedtls_mpi K, L; mbedtls_mpi_init( &K ); mbedtls_mpi_init( &L ); /* Check that DP - D == 0 mod P - 1 */ if( DP != NULL ) { if( P == NULL ) { ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DP, D ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) ); if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* Check that DQ - D == 0 mod Q - 1 */ if( DQ != NULL ) { if( Q == NULL ) { ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DQ, D ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) ); if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* Check that QP * Q - 1 == 0 mod P */ if( QP != NULL ) { if( P == NULL || Q == NULL ) { ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, QP, Q ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, P ) ); if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } cleanup: /* Wrap MPI error codes by RSA check failure error code */ if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED && ret != MBEDTLS_ERR_RSA_BAD_INPUT_DATA ) { ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; } mbedtls_mpi_free( &K ); mbedtls_mpi_free( &L ); return( ret ); } /* * Check that core RSA parameters are sane. */ int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *E, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = 0; mbedtls_mpi K, L; mbedtls_mpi_init( &K ); mbedtls_mpi_init( &L ); /* * Step 1: If PRNG provided, check that P and Q are prime */ #if defined(MBEDTLS_GENPRIME) /* * When generating keys, the strongest security we support aims for an error * rate of at most 2^-100 and we are aiming for the same certainty here as * well. */ if( f_rng != NULL && P != NULL && ( ret = mbedtls_mpi_is_prime_ext( P, 50, f_rng, p_rng ) ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } if( f_rng != NULL && Q != NULL && ( ret = mbedtls_mpi_is_prime_ext( Q, 50, f_rng, p_rng ) ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } #else ((void) f_rng); ((void) p_rng); #endif /* MBEDTLS_GENPRIME */ /* * Step 2: Check that 1 < N = P * Q */ if( P != NULL && Q != NULL && N != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, P, Q ) ); if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( &K, N ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* * Step 3: Check and 1 < D, E < N if present. */ if( N != NULL && D != NULL && E != NULL ) { if ( mbedtls_mpi_cmp_int( D, 1 ) <= 0 || mbedtls_mpi_cmp_int( E, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( D, N ) >= 0 || mbedtls_mpi_cmp_mpi( E, N ) >= 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* * Step 4: Check that D, E are inverse modulo P-1 and Q-1 */ if( P != NULL && Q != NULL && D != NULL && E != NULL ) { if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 || mbedtls_mpi_cmp_int( Q, 1 ) <= 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } /* Compute DE-1 mod P-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) ); if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } /* Compute DE-1 mod Q-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) ); if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } cleanup: mbedtls_mpi_free( &K ); mbedtls_mpi_free( &L ); /* Wrap MPI error codes by RSA check failure error code */ if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ) { ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; } return( ret ); } int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP ) { int ret = 0; mbedtls_mpi K; mbedtls_mpi_init( &K ); /* DP = D mod P-1 */ if( DP != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DP, D, &K ) ); } /* DQ = D mod Q-1 */ if( DQ != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DQ, D, &K ) ); } /* QP = Q^{-1} mod P */ if( QP != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( QP, Q, P ) ); } cleanup: mbedtls_mpi_free( &K ); return( ret ); } #endif /* MBEDTLS_RSA_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\sha1.c
/* * FIPS-180-1 compliant SHA-1 implementation * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The SHA-1 standard was published by NIST in 1993. * * http://www.itl.nist.gov/fipspubs/fip180-1.htm */ #include "common.h" #if defined(MBEDTLS_SHA1_C) #include "mbedtls/sha1.h" #include "mbedtls/platform_util.h" #include "mbedtls/error.h" #include <string.h> #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #define mbedtls_printf printf #endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_SELF_TEST */ #define SHA1_VALIDATE_RET(cond) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA1_BAD_INPUT_DATA ) #define SHA1_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond ) #if !defined(MBEDTLS_SHA1_ALT) /* * 32-bit integer manipulation macros (big endian) */ #ifndef GET_UINT32_BE #define GET_UINT32_BE(n,b,i) \ { \ (n) = ( (uint32_t) (b)[(i) ] << 24 ) \ | ( (uint32_t) (b)[(i) + 1] << 16 ) \ | ( (uint32_t) (b)[(i) + 2] << 8 ) \ | ( (uint32_t) (b)[(i) + 3] ); \ } #endif #ifndef PUT_UINT32_BE #define PUT_UINT32_BE(n,b,i) \ { \ (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ (b)[(i) + 3] = (unsigned char) ( (n) ); \ } #endif void mbedtls_sha1_init( mbedtls_sha1_context *ctx ) { SHA1_VALIDATE( ctx != NULL ); memset( ctx, 0, sizeof( mbedtls_sha1_context ) ); } void mbedtls_sha1_free( mbedtls_sha1_context *ctx ) { if( ctx == NULL ) return; mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha1_context ) ); } void mbedtls_sha1_clone( mbedtls_sha1_context *dst, const mbedtls_sha1_context *src ) { SHA1_VALIDATE( dst != NULL ); SHA1_VALIDATE( src != NULL ); *dst = *src; } /* * SHA-1 context setup */ int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx ) { SHA1_VALIDATE_RET( ctx != NULL ); ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0x67452301; ctx->state[1] = 0xEFCDAB89; ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; ctx->state[4] = 0xC3D2E1F0; return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha1_starts( mbedtls_sha1_context *ctx ) { mbedtls_sha1_starts_ret( ctx ); } #endif #if !defined(MBEDTLS_SHA1_PROCESS_ALT) int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[64] ) { struct { uint32_t temp, W[16], A, B, C, D, E; } local; SHA1_VALIDATE_RET( ctx != NULL ); SHA1_VALIDATE_RET( (const unsigned char *)data != NULL ); GET_UINT32_BE( local.W[ 0], data, 0 ); GET_UINT32_BE( local.W[ 1], data, 4 ); GET_UINT32_BE( local.W[ 2], data, 8 ); GET_UINT32_BE( local.W[ 3], data, 12 ); GET_UINT32_BE( local.W[ 4], data, 16 ); GET_UINT32_BE( local.W[ 5], data, 20 ); GET_UINT32_BE( local.W[ 6], data, 24 ); GET_UINT32_BE( local.W[ 7], data, 28 ); GET_UINT32_BE( local.W[ 8], data, 32 ); GET_UINT32_BE( local.W[ 9], data, 36 ); GET_UINT32_BE( local.W[10], data, 40 ); GET_UINT32_BE( local.W[11], data, 44 ); GET_UINT32_BE( local.W[12], data, 48 ); GET_UINT32_BE( local.W[13], data, 52 ); GET_UINT32_BE( local.W[14], data, 56 ); GET_UINT32_BE( local.W[15], data, 60 ); #define S(x,n) (((x) << (n)) | (((x) & 0xFFFFFFFF) >> (32 - (n)))) #define R(t) \ ( \ local.temp = local.W[( (t) - 3 ) & 0x0F] ^ \ local.W[( (t) - 8 ) & 0x0F] ^ \ local.W[( (t) - 14 ) & 0x0F] ^ \ local.W[ (t) & 0x0F], \ ( local.W[(t) & 0x0F] = S(local.temp,1) ) \ ) #define P(a,b,c,d,e,x) \ do \ { \ (e) += S((a),5) + F((b),(c),(d)) + K + (x); \ (b) = S((b),30); \ } while( 0 ) local.A = ctx->state[0]; local.B = ctx->state[1]; local.C = ctx->state[2]; local.D = ctx->state[3]; local.E = ctx->state[4]; #define F(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) #define K 0x5A827999 P( local.A, local.B, local.C, local.D, local.E, local.W[0] ); P( local.E, local.A, local.B, local.C, local.D, local.W[1] ); P( local.D, local.E, local.A, local.B, local.C, local.W[2] ); P( local.C, local.D, local.E, local.A, local.B, local.W[3] ); P( local.B, local.C, local.D, local.E, local.A, local.W[4] ); P( local.A, local.B, local.C, local.D, local.E, local.W[5] ); P( local.E, local.A, local.B, local.C, local.D, local.W[6] ); P( local.D, local.E, local.A, local.B, local.C, local.W[7] ); P( local.C, local.D, local.E, local.A, local.B, local.W[8] ); P( local.B, local.C, local.D, local.E, local.A, local.W[9] ); P( local.A, local.B, local.C, local.D, local.E, local.W[10] ); P( local.E, local.A, local.B, local.C, local.D, local.W[11] ); P( local.D, local.E, local.A, local.B, local.C, local.W[12] ); P( local.C, local.D, local.E, local.A, local.B, local.W[13] ); P( local.B, local.C, local.D, local.E, local.A, local.W[14] ); P( local.A, local.B, local.C, local.D, local.E, local.W[15] ); P( local.E, local.A, local.B, local.C, local.D, R(16) ); P( local.D, local.E, local.A, local.B, local.C, R(17) ); P( local.C, local.D, local.E, local.A, local.B, R(18) ); P( local.B, local.C, local.D, local.E, local.A, R(19) ); #undef K #undef F #define F(x,y,z) ((x) ^ (y) ^ (z)) #define K 0x6ED9EBA1 P( local.A, local.B, local.C, local.D, local.E, R(20) ); P( local.E, local.A, local.B, local.C, local.D, R(21) ); P( local.D, local.E, local.A, local.B, local.C, R(22) ); P( local.C, local.D, local.E, local.A, local.B, R(23) ); P( local.B, local.C, local.D, local.E, local.A, R(24) ); P( local.A, local.B, local.C, local.D, local.E, R(25) ); P( local.E, local.A, local.B, local.C, local.D, R(26) ); P( local.D, local.E, local.A, local.B, local.C, R(27) ); P( local.C, local.D, local.E, local.A, local.B, R(28) ); P( local.B, local.C, local.D, local.E, local.A, R(29) ); P( local.A, local.B, local.C, local.D, local.E, R(30) ); P( local.E, local.A, local.B, local.C, local.D, R(31) ); P( local.D, local.E, local.A, local.B, local.C, R(32) ); P( local.C, local.D, local.E, local.A, local.B, R(33) ); P( local.B, local.C, local.D, local.E, local.A, R(34) ); P( local.A, local.B, local.C, local.D, local.E, R(35) ); P( local.E, local.A, local.B, local.C, local.D, R(36) ); P( local.D, local.E, local.A, local.B, local.C, R(37) ); P( local.C, local.D, local.E, local.A, local.B, R(38) ); P( local.B, local.C, local.D, local.E, local.A, R(39) ); #undef K #undef F #define F(x,y,z) (((x) & (y)) | ((z) & ((x) | (y)))) #define K 0x8F1BBCDC P( local.A, local.B, local.C, local.D, local.E, R(40) ); P( local.E, local.A, local.B, local.C, local.D, R(41) ); P( local.D, local.E, local.A, local.B, local.C, R(42) ); P( local.C, local.D, local.E, local.A, local.B, R(43) ); P( local.B, local.C, local.D, local.E, local.A, R(44) ); P( local.A, local.B, local.C, local.D, local.E, R(45) ); P( local.E, local.A, local.B, local.C, local.D, R(46) ); P( local.D, local.E, local.A, local.B, local.C, R(47) ); P( local.C, local.D, local.E, local.A, local.B, R(48) ); P( local.B, local.C, local.D, local.E, local.A, R(49) ); P( local.A, local.B, local.C, local.D, local.E, R(50) ); P( local.E, local.A, local.B, local.C, local.D, R(51) ); P( local.D, local.E, local.A, local.B, local.C, R(52) ); P( local.C, local.D, local.E, local.A, local.B, R(53) ); P( local.B, local.C, local.D, local.E, local.A, R(54) ); P( local.A, local.B, local.C, local.D, local.E, R(55) ); P( local.E, local.A, local.B, local.C, local.D, R(56) ); P( local.D, local.E, local.A, local.B, local.C, R(57) ); P( local.C, local.D, local.E, local.A, local.B, R(58) ); P( local.B, local.C, local.D, local.E, local.A, R(59) ); #undef K #undef F #define F(x,y,z) ((x) ^ (y) ^ (z)) #define K 0xCA62C1D6 P( local.A, local.B, local.C, local.D, local.E, R(60) ); P( local.E, local.A, local.B, local.C, local.D, R(61) ); P( local.D, local.E, local.A, local.B, local.C, R(62) ); P( local.C, local.D, local.E, local.A, local.B, R(63) ); P( local.B, local.C, local.D, local.E, local.A, R(64) ); P( local.A, local.B, local.C, local.D, local.E, R(65) ); P( local.E, local.A, local.B, local.C, local.D, R(66) ); P( local.D, local.E, local.A, local.B, local.C, R(67) ); P( local.C, local.D, local.E, local.A, local.B, R(68) ); P( local.B, local.C, local.D, local.E, local.A, R(69) ); P( local.A, local.B, local.C, local.D, local.E, R(70) ); P( local.E, local.A, local.B, local.C, local.D, R(71) ); P( local.D, local.E, local.A, local.B, local.C, R(72) ); P( local.C, local.D, local.E, local.A, local.B, R(73) ); P( local.B, local.C, local.D, local.E, local.A, R(74) ); P( local.A, local.B, local.C, local.D, local.E, R(75) ); P( local.E, local.A, local.B, local.C, local.D, R(76) ); P( local.D, local.E, local.A, local.B, local.C, R(77) ); P( local.C, local.D, local.E, local.A, local.B, R(78) ); P( local.B, local.C, local.D, local.E, local.A, R(79) ); #undef K #undef F ctx->state[0] += local.A; ctx->state[1] += local.B; ctx->state[2] += local.C; ctx->state[3] += local.D; ctx->state[4] += local.E; /* Zeroise buffers and variables to clear sensitive data from memory. */ mbedtls_platform_zeroize( &local, sizeof( local ) ); return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[64] ) { mbedtls_internal_sha1_process( ctx, data ); } #endif #endif /* !MBEDTLS_SHA1_PROCESS_ALT */ /* * SHA-1 process buffer */ int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx, const unsigned char *input, size_t ilen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t fill; uint32_t left; SHA1_VALIDATE_RET( ctx != NULL ); SHA1_VALIDATE_RET( ilen == 0 || input != NULL ); if( ilen == 0 ) return( 0 ); left = ctx->total[0] & 0x3F; fill = 64 - left; ctx->total[0] += (uint32_t) ilen; ctx->total[0] &= 0xFFFFFFFF; if( ctx->total[0] < (uint32_t) ilen ) ctx->total[1]++; if( left && ilen >= fill ) { memcpy( (void *) (ctx->buffer + left), input, fill ); if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); input += fill; ilen -= fill; left = 0; } while( ilen >= 64 ) { if( ( ret = mbedtls_internal_sha1_process( ctx, input ) ) != 0 ) return( ret ); input += 64; ilen -= 64; } if( ilen > 0 ) memcpy( (void *) (ctx->buffer + left), input, ilen ); return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha1_update( mbedtls_sha1_context *ctx, const unsigned char *input, size_t ilen ) { mbedtls_sha1_update_ret( ctx, input, ilen ); } #endif /* * SHA-1 final digest */ int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx, unsigned char output[20] ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; uint32_t used; uint32_t high, low; SHA1_VALIDATE_RET( ctx != NULL ); SHA1_VALIDATE_RET( (unsigned char *)output != NULL ); /* * Add padding: 0x80 then 0x00 until 8 bytes remain for the length */ used = ctx->total[0] & 0x3F; ctx->buffer[used++] = 0x80; if( used <= 56 ) { /* Enough room for padding + length in current block */ memset( ctx->buffer + used, 0, 56 - used ); } else { /* We'll need an extra block */ memset( ctx->buffer + used, 0, 64 - used ); if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); memset( ctx->buffer, 0, 56 ); } /* * Add message length */ high = ( ctx->total[0] >> 29 ) | ( ctx->total[1] << 3 ); low = ( ctx->total[0] << 3 ); PUT_UINT32_BE( high, ctx->buffer, 56 ); PUT_UINT32_BE( low, ctx->buffer, 60 ); if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); /* * Output final state */ PUT_UINT32_BE( ctx->state[0], output, 0 ); PUT_UINT32_BE( ctx->state[1], output, 4 ); PUT_UINT32_BE( ctx->state[2], output, 8 ); PUT_UINT32_BE( ctx->state[3], output, 12 ); PUT_UINT32_BE( ctx->state[4], output, 16 ); return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha1_finish( mbedtls_sha1_context *ctx, unsigned char output[20] ) { mbedtls_sha1_finish_ret( ctx, output ); } #endif #endif /* !MBEDTLS_SHA1_ALT */ /* * output = SHA-1( input buffer ) */ int mbedtls_sha1_ret( const unsigned char *input, size_t ilen, unsigned char output[20] ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_sha1_context ctx; SHA1_VALIDATE_RET( ilen == 0 || input != NULL ); SHA1_VALIDATE_RET( (unsigned char *)output != NULL ); mbedtls_sha1_init( &ctx ); if( ( ret = mbedtls_sha1_starts_ret( &ctx ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha1_update_ret( &ctx, input, ilen ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha1_finish_ret( &ctx, output ) ) != 0 ) goto exit; exit: mbedtls_sha1_free( &ctx ); return( ret ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha1( const unsigned char *input, size_t ilen, unsigned char output[20] ) { mbedtls_sha1_ret( input, ilen, output ); } #endif #if defined(MBEDTLS_SELF_TEST) /* * FIPS-180-1 test vectors */ static const unsigned char sha1_test_buf[3][57] = { { "abc" }, { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" }, { "" } }; static const size_t sha1_test_buflen[3] = { 3, 56, 1000 }; static const unsigned char sha1_test_sum[3][20] = { { 0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D }, { 0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE, 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1 }, { 0x34, 0xAA, 0x97, 0x3C, 0xD4, 0xC4, 0xDA, 0xA4, 0xF6, 0x1E, 0xEB, 0x2B, 0xDB, 0xAD, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6F } }; /* * Checkup routine */ int mbedtls_sha1_self_test( int verbose ) { int i, j, buflen, ret = 0; unsigned char buf[1024]; unsigned char sha1sum[20]; mbedtls_sha1_context ctx; mbedtls_sha1_init( &ctx ); /* * SHA-1 */ for( i = 0; i < 3; i++ ) { if( verbose != 0 ) mbedtls_printf( " SHA-1 test #%d: ", i + 1 ); if( ( ret = mbedtls_sha1_starts_ret( &ctx ) ) != 0 ) goto fail; if( i == 2 ) { memset( buf, 'a', buflen = 1000 ); for( j = 0; j < 1000; j++ ) { ret = mbedtls_sha1_update_ret( &ctx, buf, buflen ); if( ret != 0 ) goto fail; } } else { ret = mbedtls_sha1_update_ret( &ctx, sha1_test_buf[i], sha1_test_buflen[i] ); if( ret != 0 ) goto fail; } if( ( ret = mbedtls_sha1_finish_ret( &ctx, sha1sum ) ) != 0 ) goto fail; if( memcmp( sha1sum, sha1_test_sum[i], 20 ) != 0 ) { ret = 1; goto fail; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); goto exit; fail: if( verbose != 0 ) mbedtls_printf( "failed\n" ); exit: mbedtls_sha1_free( &ctx ); return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_SHA1_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\sha256.c
/* * FIPS-180-2 compliant SHA-256 implementation * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The SHA-256 Secure Hash Standard was published by NIST in 2002. * * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf */ #include "common.h" #if defined(MBEDTLS_SHA256_C) #include "mbedtls/sha256.h" #include "mbedtls/platform_util.h" #include "mbedtls/error.h" #include <string.h> #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #include <stdlib.h> #define mbedtls_printf printf #define mbedtls_calloc calloc #define mbedtls_free free #endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_SELF_TEST */ #define SHA256_VALIDATE_RET(cond) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA256_BAD_INPUT_DATA ) #define SHA256_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond ) #if !defined(MBEDTLS_SHA256_ALT) /* * 32-bit integer manipulation macros (big endian) */ #ifndef GET_UINT32_BE #define GET_UINT32_BE(n,b,i) \ do { \ (n) = ( (uint32_t) (b)[(i) ] << 24 ) \ | ( (uint32_t) (b)[(i) + 1] << 16 ) \ | ( (uint32_t) (b)[(i) + 2] << 8 ) \ | ( (uint32_t) (b)[(i) + 3] ); \ } while( 0 ) #endif #ifndef PUT_UINT32_BE #define PUT_UINT32_BE(n,b,i) \ do { \ (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ (b)[(i) + 3] = (unsigned char) ( (n) ); \ } while( 0 ) #endif void mbedtls_sha256_init( mbedtls_sha256_context *ctx ) { SHA256_VALIDATE( ctx != NULL ); memset( ctx, 0, sizeof( mbedtls_sha256_context ) ); } void mbedtls_sha256_free( mbedtls_sha256_context *ctx ) { if( ctx == NULL ) return; mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha256_context ) ); } void mbedtls_sha256_clone( mbedtls_sha256_context *dst, const mbedtls_sha256_context *src ) { SHA256_VALIDATE( dst != NULL ); SHA256_VALIDATE( src != NULL ); *dst = *src; } /* * SHA-256 context setup */ int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 ) { SHA256_VALIDATE_RET( ctx != NULL ); SHA256_VALIDATE_RET( is224 == 0 || is224 == 1 ); ctx->total[0] = 0; ctx->total[1] = 0; if( is224 == 0 ) { /* SHA-256 */ ctx->state[0] = 0x6A09E667; ctx->state[1] = 0xBB67AE85; ctx->state[2] = 0x3C6EF372; ctx->state[3] = 0xA54FF53A; ctx->state[4] = 0x510E527F; ctx->state[5] = 0x9B05688C; ctx->state[6] = 0x1F83D9AB; ctx->state[7] = 0x5BE0CD19; } else { /* SHA-224 */ ctx->state[0] = 0xC1059ED8; ctx->state[1] = 0x367CD507; ctx->state[2] = 0x3070DD17; ctx->state[3] = 0xF70E5939; ctx->state[4] = 0xFFC00B31; ctx->state[5] = 0x68581511; ctx->state[6] = 0x64F98FA7; ctx->state[7] = 0xBEFA4FA4; } ctx->is224 = is224; return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, int is224 ) { mbedtls_sha256_starts_ret( ctx, is224 ); } #endif #if !defined(MBEDTLS_SHA256_PROCESS_ALT) static const uint32_t K[] = { 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2, }; #define SHR(x,n) (((x) & 0xFFFFFFFF) >> (n)) #define ROTR(x,n) (SHR(x,n) | ((x) << (32 - (n)))) #define S0(x) (ROTR(x, 7) ^ ROTR(x,18) ^ SHR(x, 3)) #define S1(x) (ROTR(x,17) ^ ROTR(x,19) ^ SHR(x,10)) #define S2(x) (ROTR(x, 2) ^ ROTR(x,13) ^ ROTR(x,22)) #define S3(x) (ROTR(x, 6) ^ ROTR(x,11) ^ ROTR(x,25)) #define F0(x,y,z) (((x) & (y)) | ((z) & ((x) | (y)))) #define F1(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) #define R(t) \ ( \ local.W[t] = S1(local.W[(t) - 2]) + local.W[(t) - 7] + \ S0(local.W[(t) - 15]) + local.W[(t) - 16] \ ) #define P(a,b,c,d,e,f,g,h,x,K) \ do \ { \ local.temp1 = (h) + S3(e) + F1((e),(f),(g)) + (K) + (x); \ local.temp2 = S2(a) + F0((a),(b),(c)); \ (d) += local.temp1; (h) = local.temp1 + local.temp2; \ } while( 0 ) int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx, const unsigned char data[64] ) { struct { uint32_t temp1, temp2, W[64]; uint32_t A[8]; } local; unsigned int i; SHA256_VALIDATE_RET( ctx != NULL ); SHA256_VALIDATE_RET( (const unsigned char *)data != NULL ); for( i = 0; i < 8; i++ ) local.A[i] = ctx->state[i]; #if defined(MBEDTLS_SHA256_SMALLER) for( i = 0; i < 64; i++ ) { if( i < 16 ) GET_UINT32_BE( local.W[i], data, 4 * i ); else R( i ); P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.W[i], K[i] ); local.temp1 = local.A[7]; local.A[7] = local.A[6]; local.A[6] = local.A[5]; local.A[5] = local.A[4]; local.A[4] = local.A[3]; local.A[3] = local.A[2]; local.A[2] = local.A[1]; local.A[1] = local.A[0]; local.A[0] = local.temp1; } #else /* MBEDTLS_SHA256_SMALLER */ for( i = 0; i < 16; i++ ) GET_UINT32_BE( local.W[i], data, 4 * i ); for( i = 0; i < 16; i += 8 ) { P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.W[i+0], K[i+0] ); P( local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.W[i+1], K[i+1] ); P( local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.W[i+2], K[i+2] ); P( local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.W[i+3], K[i+3] ); P( local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.W[i+4], K[i+4] ); P( local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.W[i+5], K[i+5] ); P( local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.W[i+6], K[i+6] ); P( local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.W[i+7], K[i+7] ); } for( i = 16; i < 64; i += 8 ) { P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], R(i+0), K[i+0] ); P( local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], R(i+1), K[i+1] ); P( local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], R(i+2), K[i+2] ); P( local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], R(i+3), K[i+3] ); P( local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], R(i+4), K[i+4] ); P( local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], R(i+5), K[i+5] ); P( local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], R(i+6), K[i+6] ); P( local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], R(i+7), K[i+7] ); } #endif /* MBEDTLS_SHA256_SMALLER */ for( i = 0; i < 8; i++ ) ctx->state[i] += local.A[i]; /* Zeroise buffers and variables to clear sensitive data from memory. */ mbedtls_platform_zeroize( &local, sizeof( local ) ); return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha256_process( mbedtls_sha256_context *ctx, const unsigned char data[64] ) { mbedtls_internal_sha256_process( ctx, data ); } #endif #endif /* !MBEDTLS_SHA256_PROCESS_ALT */ /* * SHA-256 process buffer */ int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx, const unsigned char *input, size_t ilen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t fill; uint32_t left; SHA256_VALIDATE_RET( ctx != NULL ); SHA256_VALIDATE_RET( ilen == 0 || input != NULL ); if( ilen == 0 ) return( 0 ); left = ctx->total[0] & 0x3F; fill = 64 - left; ctx->total[0] += (uint32_t) ilen; ctx->total[0] &= 0xFFFFFFFF; if( ctx->total[0] < (uint32_t) ilen ) ctx->total[1]++; if( left && ilen >= fill ) { memcpy( (void *) (ctx->buffer + left), input, fill ); if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); input += fill; ilen -= fill; left = 0; } while( ilen >= 64 ) { if( ( ret = mbedtls_internal_sha256_process( ctx, input ) ) != 0 ) return( ret ); input += 64; ilen -= 64; } if( ilen > 0 ) memcpy( (void *) (ctx->buffer + left), input, ilen ); return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha256_update( mbedtls_sha256_context *ctx, const unsigned char *input, size_t ilen ) { mbedtls_sha256_update_ret( ctx, input, ilen ); } #endif /* * SHA-256 final digest */ int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx, unsigned char output[32] ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; uint32_t used; uint32_t high, low; SHA256_VALIDATE_RET( ctx != NULL ); SHA256_VALIDATE_RET( (unsigned char *)output != NULL ); /* * Add padding: 0x80 then 0x00 until 8 bytes remain for the length */ used = ctx->total[0] & 0x3F; ctx->buffer[used++] = 0x80; if( used <= 56 ) { /* Enough room for padding + length in current block */ memset( ctx->buffer + used, 0, 56 - used ); } else { /* We'll need an extra block */ memset( ctx->buffer + used, 0, 64 - used ); if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); memset( ctx->buffer, 0, 56 ); } /* * Add message length */ high = ( ctx->total[0] >> 29 ) | ( ctx->total[1] << 3 ); low = ( ctx->total[0] << 3 ); PUT_UINT32_BE( high, ctx->buffer, 56 ); PUT_UINT32_BE( low, ctx->buffer, 60 ); if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); /* * Output final state */ PUT_UINT32_BE( ctx->state[0], output, 0 ); PUT_UINT32_BE( ctx->state[1], output, 4 ); PUT_UINT32_BE( ctx->state[2], output, 8 ); PUT_UINT32_BE( ctx->state[3], output, 12 ); PUT_UINT32_BE( ctx->state[4], output, 16 ); PUT_UINT32_BE( ctx->state[5], output, 20 ); PUT_UINT32_BE( ctx->state[6], output, 24 ); if( ctx->is224 == 0 ) PUT_UINT32_BE( ctx->state[7], output, 28 ); return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha256_finish( mbedtls_sha256_context *ctx, unsigned char output[32] ) { mbedtls_sha256_finish_ret( ctx, output ); } #endif #endif /* !MBEDTLS_SHA256_ALT */ /* * output = SHA-256( input buffer ) */ int mbedtls_sha256_ret( const unsigned char *input, size_t ilen, unsigned char output[32], int is224 ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_sha256_context ctx; SHA256_VALIDATE_RET( is224 == 0 || is224 == 1 ); SHA256_VALIDATE_RET( ilen == 0 || input != NULL ); SHA256_VALIDATE_RET( (unsigned char *)output != NULL ); mbedtls_sha256_init( &ctx ); if( ( ret = mbedtls_sha256_starts_ret( &ctx, is224 ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha256_update_ret( &ctx, input, ilen ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha256_finish_ret( &ctx, output ) ) != 0 ) goto exit; exit: mbedtls_sha256_free( &ctx ); return( ret ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha256( const unsigned char *input, size_t ilen, unsigned char output[32], int is224 ) { mbedtls_sha256_ret( input, ilen, output, is224 ); } #endif #if defined(MBEDTLS_SELF_TEST) /* * FIPS-180-2 test vectors */ static const unsigned char sha256_test_buf[3][57] = { { "abc" }, { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" }, { "" } }; static const size_t sha256_test_buflen[3] = { 3, 56, 1000 }; static const unsigned char sha256_test_sum[6][32] = { /* * SHA-224 test vectors */ { 0x23, 0x09, 0x7D, 0x22, 0x34, 0x05, 0xD8, 0x22, 0x86, 0x42, 0xA4, 0x77, 0xBD, 0xA2, 0x55, 0xB3, 0x2A, 0xAD, 0xBC, 0xE4, 0xBD, 0xA0, 0xB3, 0xF7, 0xE3, 0x6C, 0x9D, 0xA7 }, { 0x75, 0x38, 0x8B, 0x16, 0x51, 0x27, 0x76, 0xCC, 0x5D, 0xBA, 0x5D, 0xA1, 0xFD, 0x89, 0x01, 0x50, 0xB0, 0xC6, 0x45, 0x5C, 0xB4, 0xF5, 0x8B, 0x19, 0x52, 0x52, 0x25, 0x25 }, { 0x20, 0x79, 0x46, 0x55, 0x98, 0x0C, 0x91, 0xD8, 0xBB, 0xB4, 0xC1, 0xEA, 0x97, 0x61, 0x8A, 0x4B, 0xF0, 0x3F, 0x42, 0x58, 0x19, 0x48, 0xB2, 0xEE, 0x4E, 0xE7, 0xAD, 0x67 }, /* * SHA-256 test vectors */ { 0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x01, 0xCF, 0xEA, 0x41, 0x41, 0x40, 0xDE, 0x5D, 0xAE, 0x22, 0x23, 0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C, 0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x00, 0x15, 0xAD }, { 0x24, 0x8D, 0x6A, 0x61, 0xD2, 0x06, 0x38, 0xB8, 0xE5, 0xC0, 0x26, 0x93, 0x0C, 0x3E, 0x60, 0x39, 0xA3, 0x3C, 0xE4, 0x59, 0x64, 0xFF, 0x21, 0x67, 0xF6, 0xEC, 0xED, 0xD4, 0x19, 0xDB, 0x06, 0xC1 }, { 0xCD, 0xC7, 0x6E, 0x5C, 0x99, 0x14, 0xFB, 0x92, 0x81, 0xA1, 0xC7, 0xE2, 0x84, 0xD7, 0x3E, 0x67, 0xF1, 0x80, 0x9A, 0x48, 0xA4, 0x97, 0x20, 0x0E, 0x04, 0x6D, 0x39, 0xCC, 0xC7, 0x11, 0x2C, 0xD0 } }; /* * Checkup routine */ int mbedtls_sha256_self_test( int verbose ) { int i, j, k, buflen, ret = 0; unsigned char *buf; unsigned char sha256sum[32]; mbedtls_sha256_context ctx; buf = mbedtls_calloc( 1024, sizeof(unsigned char) ); if( NULL == buf ) { if( verbose != 0 ) mbedtls_printf( "Buffer allocation failed\n" ); return( 1 ); } mbedtls_sha256_init( &ctx ); for( i = 0; i < 6; i++ ) { j = i % 3; k = i < 3; if( verbose != 0 ) mbedtls_printf( " SHA-%d test #%d: ", 256 - k * 32, j + 1 ); if( ( ret = mbedtls_sha256_starts_ret( &ctx, k ) ) != 0 ) goto fail; if( j == 2 ) { memset( buf, 'a', buflen = 1000 ); for( j = 0; j < 1000; j++ ) { ret = mbedtls_sha256_update_ret( &ctx, buf, buflen ); if( ret != 0 ) goto fail; } } else { ret = mbedtls_sha256_update_ret( &ctx, sha256_test_buf[j], sha256_test_buflen[j] ); if( ret != 0 ) goto fail; } if( ( ret = mbedtls_sha256_finish_ret( &ctx, sha256sum ) ) != 0 ) goto fail; if( memcmp( sha256sum, sha256_test_sum[i], 32 - k * 4 ) != 0 ) { ret = 1; goto fail; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); goto exit; fail: if( verbose != 0 ) mbedtls_printf( "failed\n" ); exit: mbedtls_sha256_free( &ctx ); mbedtls_free( buf ); return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_SHA256_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\sha512.c
/* * FIPS-180-2 compliant SHA-384/512 implementation * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The SHA-512 Secure Hash Standard was published by NIST in 2002. * * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf */ #include "common.h" #if defined(MBEDTLS_SHA512_C) #include "mbedtls/sha512.h" #include "mbedtls/platform_util.h" #include "mbedtls/error.h" #if defined(_MSC_VER) || defined(__WATCOMC__) #define UL64(x) x##ui64 #else #define UL64(x) x##ULL #endif #include <string.h> #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #include <stdlib.h> #define mbedtls_printf printf #define mbedtls_calloc calloc #define mbedtls_free free #endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_SELF_TEST */ #define SHA512_VALIDATE_RET(cond) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA512_BAD_INPUT_DATA ) #define SHA512_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond ) #if !defined(MBEDTLS_SHA512_ALT) /* * 64-bit integer manipulation macros (big endian) */ #ifndef GET_UINT64_BE #define GET_UINT64_BE(n,b,i) \ { \ (n) = ( (uint64_t) (b)[(i) ] << 56 ) \ | ( (uint64_t) (b)[(i) + 1] << 48 ) \ | ( (uint64_t) (b)[(i) + 2] << 40 ) \ | ( (uint64_t) (b)[(i) + 3] << 32 ) \ | ( (uint64_t) (b)[(i) + 4] << 24 ) \ | ( (uint64_t) (b)[(i) + 5] << 16 ) \ | ( (uint64_t) (b)[(i) + 6] << 8 ) \ | ( (uint64_t) (b)[(i) + 7] ); \ } #endif /* GET_UINT64_BE */ #ifndef PUT_UINT64_BE #define PUT_UINT64_BE(n,b,i) \ { \ (b)[(i) ] = (unsigned char) ( (n) >> 56 ); \ (b)[(i) + 1] = (unsigned char) ( (n) >> 48 ); \ (b)[(i) + 2] = (unsigned char) ( (n) >> 40 ); \ (b)[(i) + 3] = (unsigned char) ( (n) >> 32 ); \ (b)[(i) + 4] = (unsigned char) ( (n) >> 24 ); \ (b)[(i) + 5] = (unsigned char) ( (n) >> 16 ); \ (b)[(i) + 6] = (unsigned char) ( (n) >> 8 ); \ (b)[(i) + 7] = (unsigned char) ( (n) ); \ } #endif /* PUT_UINT64_BE */ #if defined(MBEDTLS_SHA512_SMALLER) static void sha512_put_uint64_be( uint64_t n, unsigned char *b, uint8_t i ) { PUT_UINT64_BE(n, b, i); } #else #define sha512_put_uint64_be PUT_UINT64_BE #endif /* MBEDTLS_SHA512_SMALLER */ void mbedtls_sha512_init( mbedtls_sha512_context *ctx ) { SHA512_VALIDATE( ctx != NULL ); memset( ctx, 0, sizeof( mbedtls_sha512_context ) ); } void mbedtls_sha512_free( mbedtls_sha512_context *ctx ) { if( ctx == NULL ) return; mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha512_context ) ); } void mbedtls_sha512_clone( mbedtls_sha512_context *dst, const mbedtls_sha512_context *src ) { SHA512_VALIDATE( dst != NULL ); SHA512_VALIDATE( src != NULL ); *dst = *src; } /* * SHA-512 context setup */ int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 ) { SHA512_VALIDATE_RET( ctx != NULL ); #if !defined(MBEDTLS_SHA512_NO_SHA384) SHA512_VALIDATE_RET( is384 == 0 || is384 == 1 ); #else SHA512_VALIDATE_RET( is384 == 0 ); #endif ctx->total[0] = 0; ctx->total[1] = 0; if( is384 == 0 ) { /* SHA-512 */ ctx->state[0] = UL64(0x6A09E667F3BCC908); ctx->state[1] = UL64(0xBB67AE8584CAA73B); ctx->state[2] = UL64(0x3C6EF372FE94F82B); ctx->state[3] = UL64(0xA54FF53A5F1D36F1); ctx->state[4] = UL64(0x510E527FADE682D1); ctx->state[5] = UL64(0x9B05688C2B3E6C1F); ctx->state[6] = UL64(0x1F83D9ABFB41BD6B); ctx->state[7] = UL64(0x5BE0CD19137E2179); } else { #if defined(MBEDTLS_SHA512_NO_SHA384) return( MBEDTLS_ERR_SHA512_BAD_INPUT_DATA ); #else /* SHA-384 */ ctx->state[0] = UL64(0xCBBB9D5DC1059ED8); ctx->state[1] = UL64(0x629A292A367CD507); ctx->state[2] = UL64(0x9159015A3070DD17); ctx->state[3] = UL64(0x152FECD8F70E5939); ctx->state[4] = UL64(0x67332667FFC00B31); ctx->state[5] = UL64(0x8EB44A8768581511); ctx->state[6] = UL64(0xDB0C2E0D64F98FA7); ctx->state[7] = UL64(0x47B5481DBEFA4FA4); #endif /* MBEDTLS_SHA512_NO_SHA384 */ } #if !defined(MBEDTLS_SHA512_NO_SHA384) ctx->is384 = is384; #endif return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, int is384 ) { mbedtls_sha512_starts_ret( ctx, is384 ); } #endif #if !defined(MBEDTLS_SHA512_PROCESS_ALT) /* * Round constants */ static const uint64_t K[80] = { UL64(0x428A2F98D728AE22), UL64(0x7137449123EF65CD), UL64(0xB5C0FBCFEC4D3B2F), UL64(0xE9B5DBA58189DBBC), UL64(0x3956C25BF348B538), UL64(0x59F111F1B605D019), UL64(0x923F82A4AF194F9B), UL64(0xAB1C5ED5DA6D8118), UL64(0xD807AA98A3030242), UL64(0x12835B0145706FBE), UL64(0x243185BE4EE4B28C), UL64(0x550C7DC3D5FFB4E2), UL64(0x72BE5D74F27B896F), UL64(0x80DEB1FE3B1696B1), UL64(0x9BDC06A725C71235), UL64(0xC19BF174CF692694), UL64(0xE49B69C19EF14AD2), UL64(0xEFBE4786384F25E3), UL64(0x0FC19DC68B8CD5B5), UL64(0x240CA1CC77AC9C65), UL64(0x2DE92C6F592B0275), UL64(0x4A7484AA6EA6E483), UL64(0x5CB0A9DCBD41FBD4), UL64(0x76F988DA831153B5), UL64(0x983E5152EE66DFAB), UL64(0xA831C66D2DB43210), UL64(0xB00327C898FB213F), UL64(0xBF597FC7BEEF0EE4), UL64(0xC6E00BF33DA88FC2), UL64(0xD5A79147930AA725), UL64(0x06CA6351E003826F), UL64(0x142929670A0E6E70), UL64(0x27B70A8546D22FFC), UL64(0x2E1B21385C26C926), UL64(0x4D2C6DFC5AC42AED), UL64(0x53380D139D95B3DF), UL64(0x650A73548BAF63DE), UL64(0x766A0ABB3C77B2A8), UL64(0x81C2C92E47EDAEE6), UL64(0x92722C851482353B), UL64(0xA2BFE8A14CF10364), UL64(0xA81A664BBC423001), UL64(0xC24B8B70D0F89791), UL64(0xC76C51A30654BE30), UL64(0xD192E819D6EF5218), UL64(0xD69906245565A910), UL64(0xF40E35855771202A), UL64(0x106AA07032BBD1B8), UL64(0x19A4C116B8D2D0C8), UL64(0x1E376C085141AB53), UL64(0x2748774CDF8EEB99), UL64(0x34B0BCB5E19B48A8), UL64(0x391C0CB3C5C95A63), UL64(0x4ED8AA4AE3418ACB), UL64(0x5B9CCA4F7763E373), UL64(0x682E6FF3D6B2B8A3), UL64(0x748F82EE5DEFB2FC), UL64(0x78A5636F43172F60), UL64(0x84C87814A1F0AB72), UL64(0x8CC702081A6439EC), UL64(0x90BEFFFA23631E28), UL64(0xA4506CEBDE82BDE9), UL64(0xBEF9A3F7B2C67915), UL64(0xC67178F2E372532B), UL64(0xCA273ECEEA26619C), UL64(0xD186B8C721C0C207), UL64(0xEADA7DD6CDE0EB1E), UL64(0xF57D4F7FEE6ED178), UL64(0x06F067AA72176FBA), UL64(0x0A637DC5A2C898A6), UL64(0x113F9804BEF90DAE), UL64(0x1B710B35131C471B), UL64(0x28DB77F523047D84), UL64(0x32CAAB7B40C72493), UL64(0x3C9EBE0A15C9BEBC), UL64(0x431D67C49C100D4C), UL64(0x4CC5D4BECB3E42B6), UL64(0x597F299CFC657E2A), UL64(0x5FCB6FAB3AD6FAEC), UL64(0x6C44198C4A475817) }; int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx, const unsigned char data[128] ) { int i; struct { uint64_t temp1, temp2, W[80]; uint64_t A[8]; } local; SHA512_VALIDATE_RET( ctx != NULL ); SHA512_VALIDATE_RET( (const unsigned char *)data != NULL ); #define SHR(x,n) ((x) >> (n)) #define ROTR(x,n) (SHR((x),(n)) | ((x) << (64 - (n)))) #define S0(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHR(x, 7)) #define S1(x) (ROTR(x,19) ^ ROTR(x,61) ^ SHR(x, 6)) #define S2(x) (ROTR(x,28) ^ ROTR(x,34) ^ ROTR(x,39)) #define S3(x) (ROTR(x,14) ^ ROTR(x,18) ^ ROTR(x,41)) #define F0(x,y,z) (((x) & (y)) | ((z) & ((x) | (y)))) #define F1(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) #define P(a,b,c,d,e,f,g,h,x,K) \ do \ { \ local.temp1 = (h) + S3(e) + F1((e),(f),(g)) + (K) + (x); \ local.temp2 = S2(a) + F0((a),(b),(c)); \ (d) += local.temp1; (h) = local.temp1 + local.temp2; \ } while( 0 ) for( i = 0; i < 8; i++ ) local.A[i] = ctx->state[i]; #if defined(MBEDTLS_SHA512_SMALLER) for( i = 0; i < 80; i++ ) { if( i < 16 ) { GET_UINT64_BE( local.W[i], data, i << 3 ); } else { local.W[i] = S1(local.W[i - 2]) + local.W[i - 7] + S0(local.W[i - 15]) + local.W[i - 16]; } P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.W[i], K[i] ); local.temp1 = local.A[7]; local.A[7] = local.A[6]; local.A[6] = local.A[5]; local.A[5] = local.A[4]; local.A[4] = local.A[3]; local.A[3] = local.A[2]; local.A[2] = local.A[1]; local.A[1] = local.A[0]; local.A[0] = local.temp1; } #else /* MBEDTLS_SHA512_SMALLER */ for( i = 0; i < 16; i++ ) { GET_UINT64_BE( local.W[i], data, i << 3 ); } for( ; i < 80; i++ ) { local.W[i] = S1(local.W[i - 2]) + local.W[i - 7] + S0(local.W[i - 15]) + local.W[i - 16]; } i = 0; do { P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.W[i], K[i] ); i++; P( local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.W[i], K[i] ); i++; P( local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.W[i], K[i] ); i++; P( local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.W[i], K[i] ); i++; P( local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.W[i], K[i] ); i++; P( local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.W[i], K[i] ); i++; P( local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.W[i], K[i] ); i++; P( local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.W[i], K[i] ); i++; } while( i < 80 ); #endif /* MBEDTLS_SHA512_SMALLER */ for( i = 0; i < 8; i++ ) ctx->state[i] += local.A[i]; /* Zeroise buffers and variables to clear sensitive data from memory. */ mbedtls_platform_zeroize( &local, sizeof( local ) ); return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha512_process( mbedtls_sha512_context *ctx, const unsigned char data[128] ) { mbedtls_internal_sha512_process( ctx, data ); } #endif #endif /* !MBEDTLS_SHA512_PROCESS_ALT */ /* * SHA-512 process buffer */ int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx, const unsigned char *input, size_t ilen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t fill; unsigned int left; SHA512_VALIDATE_RET( ctx != NULL ); SHA512_VALIDATE_RET( ilen == 0 || input != NULL ); if( ilen == 0 ) return( 0 ); left = (unsigned int) (ctx->total[0] & 0x7F); fill = 128 - left; ctx->total[0] += (uint64_t) ilen; if( ctx->total[0] < (uint64_t) ilen ) ctx->total[1]++; if( left && ilen >= fill ) { memcpy( (void *) (ctx->buffer + left), input, fill ); if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); input += fill; ilen -= fill; left = 0; } while( ilen >= 128 ) { if( ( ret = mbedtls_internal_sha512_process( ctx, input ) ) != 0 ) return( ret ); input += 128; ilen -= 128; } if( ilen > 0 ) memcpy( (void *) (ctx->buffer + left), input, ilen ); return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha512_update( mbedtls_sha512_context *ctx, const unsigned char *input, size_t ilen ) { mbedtls_sha512_update_ret( ctx, input, ilen ); } #endif /* * SHA-512 final digest */ int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx, unsigned char output[64] ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned used; uint64_t high, low; SHA512_VALIDATE_RET( ctx != NULL ); SHA512_VALIDATE_RET( (unsigned char *)output != NULL ); /* * Add padding: 0x80 then 0x00 until 16 bytes remain for the length */ used = ctx->total[0] & 0x7F; ctx->buffer[used++] = 0x80; if( used <= 112 ) { /* Enough room for padding + length in current block */ memset( ctx->buffer + used, 0, 112 - used ); } else { /* We'll need an extra block */ memset( ctx->buffer + used, 0, 128 - used ); if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); memset( ctx->buffer, 0, 112 ); } /* * Add message length */ high = ( ctx->total[0] >> 61 ) | ( ctx->total[1] << 3 ); low = ( ctx->total[0] << 3 ); sha512_put_uint64_be( high, ctx->buffer, 112 ); sha512_put_uint64_be( low, ctx->buffer, 120 ); if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); /* * Output final state */ sha512_put_uint64_be( ctx->state[0], output, 0 ); sha512_put_uint64_be( ctx->state[1], output, 8 ); sha512_put_uint64_be( ctx->state[2], output, 16 ); sha512_put_uint64_be( ctx->state[3], output, 24 ); sha512_put_uint64_be( ctx->state[4], output, 32 ); sha512_put_uint64_be( ctx->state[5], output, 40 ); #if !defined(MBEDTLS_SHA512_NO_SHA384) if( ctx->is384 == 0 ) #endif { sha512_put_uint64_be( ctx->state[6], output, 48 ); sha512_put_uint64_be( ctx->state[7], output, 56 ); } return( 0 ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha512_finish( mbedtls_sha512_context *ctx, unsigned char output[64] ) { mbedtls_sha512_finish_ret( ctx, output ); } #endif #endif /* !MBEDTLS_SHA512_ALT */ /* * output = SHA-512( input buffer ) */ int mbedtls_sha512_ret( const unsigned char *input, size_t ilen, unsigned char output[64], int is384 ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_sha512_context ctx; #if !defined(MBEDTLS_SHA512_NO_SHA384) SHA512_VALIDATE_RET( is384 == 0 || is384 == 1 ); #else SHA512_VALIDATE_RET( is384 == 0 ); #endif SHA512_VALIDATE_RET( ilen == 0 || input != NULL ); SHA512_VALIDATE_RET( (unsigned char *)output != NULL ); mbedtls_sha512_init( &ctx ); if( ( ret = mbedtls_sha512_starts_ret( &ctx, is384 ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha512_update_ret( &ctx, input, ilen ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha512_finish_ret( &ctx, output ) ) != 0 ) goto exit; exit: mbedtls_sha512_free( &ctx ); return( ret ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_sha512( const unsigned char *input, size_t ilen, unsigned char output[64], int is384 ) { mbedtls_sha512_ret( input, ilen, output, is384 ); } #endif #if defined(MBEDTLS_SELF_TEST) /* * FIPS-180-2 test vectors */ static const unsigned char sha512_test_buf[3][113] = { { "abc" }, { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu" }, { "" } }; static const size_t sha512_test_buflen[3] = { 3, 112, 1000 }; static const unsigned char sha512_test_sum[][64] = { #if !defined(MBEDTLS_SHA512_NO_SHA384) /* * SHA-384 test vectors */ { 0xCB, 0x00, 0x75, 0x3F, 0x45, 0xA3, 0x5E, 0x8B, 0xB5, 0xA0, 0x3D, 0x69, 0x9A, 0xC6, 0x50, 0x07, 0x27, 0x2C, 0x32, 0xAB, 0x0E, 0xDE, 0xD1, 0x63, 0x1A, 0x8B, 0x60, 0x5A, 0x43, 0xFF, 0x5B, 0xED, 0x80, 0x86, 0x07, 0x2B, 0xA1, 0xE7, 0xCC, 0x23, 0x58, 0xBA, 0xEC, 0xA1, 0x34, 0xC8, 0x25, 0xA7 }, { 0x09, 0x33, 0x0C, 0x33, 0xF7, 0x11, 0x47, 0xE8, 0x3D, 0x19, 0x2F, 0xC7, 0x82, 0xCD, 0x1B, 0x47, 0x53, 0x11, 0x1B, 0x17, 0x3B, 0x3B, 0x05, 0xD2, 0x2F, 0xA0, 0x80, 0x86, 0xE3, 0xB0, 0xF7, 0x12, 0xFC, 0xC7, 0xC7, 0x1A, 0x55, 0x7E, 0x2D, 0xB9, 0x66, 0xC3, 0xE9, 0xFA, 0x91, 0x74, 0x60, 0x39 }, { 0x9D, 0x0E, 0x18, 0x09, 0x71, 0x64, 0x74, 0xCB, 0x08, 0x6E, 0x83, 0x4E, 0x31, 0x0A, 0x4A, 0x1C, 0xED, 0x14, 0x9E, 0x9C, 0x00, 0xF2, 0x48, 0x52, 0x79, 0x72, 0xCE, 0xC5, 0x70, 0x4C, 0x2A, 0x5B, 0x07, 0xB8, 0xB3, 0xDC, 0x38, 0xEC, 0xC4, 0xEB, 0xAE, 0x97, 0xDD, 0xD8, 0x7F, 0x3D, 0x89, 0x85 }, #endif /* !MBEDTLS_SHA512_NO_SHA384 */ /* * SHA-512 test vectors */ { 0xDD, 0xAF, 0x35, 0xA1, 0x93, 0x61, 0x7A, 0xBA, 0xCC, 0x41, 0x73, 0x49, 0xAE, 0x20, 0x41, 0x31, 0x12, 0xE6, 0xFA, 0x4E, 0x89, 0xA9, 0x7E, 0xA2, 0x0A, 0x9E, 0xEE, 0xE6, 0x4B, 0x55, 0xD3, 0x9A, 0x21, 0x92, 0x99, 0x2A, 0x27, 0x4F, 0xC1, 0xA8, 0x36, 0xBA, 0x3C, 0x23, 0xA3, 0xFE, 0xEB, 0xBD, 0x45, 0x4D, 0x44, 0x23, 0x64, 0x3C, 0xE8, 0x0E, 0x2A, 0x9A, 0xC9, 0x4F, 0xA5, 0x4C, 0xA4, 0x9F }, { 0x8E, 0x95, 0x9B, 0x75, 0xDA, 0xE3, 0x13, 0xDA, 0x8C, 0xF4, 0xF7, 0x28, 0x14, 0xFC, 0x14, 0x3F, 0x8F, 0x77, 0x79, 0xC6, 0xEB, 0x9F, 0x7F, 0xA1, 0x72, 0x99, 0xAE, 0xAD, 0xB6, 0x88, 0x90, 0x18, 0x50, 0x1D, 0x28, 0x9E, 0x49, 0x00, 0xF7, 0xE4, 0x33, 0x1B, 0x99, 0xDE, 0xC4, 0xB5, 0x43, 0x3A, 0xC7, 0xD3, 0x29, 0xEE, 0xB6, 0xDD, 0x26, 0x54, 0x5E, 0x96, 0xE5, 0x5B, 0x87, 0x4B, 0xE9, 0x09 }, { 0xE7, 0x18, 0x48, 0x3D, 0x0C, 0xE7, 0x69, 0x64, 0x4E, 0x2E, 0x42, 0xC7, 0xBC, 0x15, 0xB4, 0x63, 0x8E, 0x1F, 0x98, 0xB1, 0x3B, 0x20, 0x44, 0x28, 0x56, 0x32, 0xA8, 0x03, 0xAF, 0xA9, 0x73, 0xEB, 0xDE, 0x0F, 0xF2, 0x44, 0x87, 0x7E, 0xA6, 0x0A, 0x4C, 0xB0, 0x43, 0x2C, 0xE5, 0x77, 0xC3, 0x1B, 0xEB, 0x00, 0x9C, 0x5C, 0x2C, 0x49, 0xAA, 0x2E, 0x4E, 0xAD, 0xB2, 0x17, 0xAD, 0x8C, 0xC0, 0x9B } }; #define ARRAY_LENGTH( a ) ( sizeof( a ) / sizeof( ( a )[0] ) ) /* * Checkup routine */ int mbedtls_sha512_self_test( int verbose ) { int i, j, k, buflen, ret = 0; unsigned char *buf; unsigned char sha512sum[64]; mbedtls_sha512_context ctx; buf = mbedtls_calloc( 1024, sizeof(unsigned char) ); if( NULL == buf ) { if( verbose != 0 ) mbedtls_printf( "Buffer allocation failed\n" ); return( 1 ); } mbedtls_sha512_init( &ctx ); for( i = 0; i < (int) ARRAY_LENGTH(sha512_test_sum); i++ ) { j = i % 3; #if !defined(MBEDTLS_SHA512_NO_SHA384) k = i < 3; #else k = 0; #endif if( verbose != 0 ) mbedtls_printf( " SHA-%d test #%d: ", 512 - k * 128, j + 1 ); if( ( ret = mbedtls_sha512_starts_ret( &ctx, k ) ) != 0 ) goto fail; if( j == 2 ) { memset( buf, 'a', buflen = 1000 ); for( j = 0; j < 1000; j++ ) { ret = mbedtls_sha512_update_ret( &ctx, buf, buflen ); if( ret != 0 ) goto fail; } } else { ret = mbedtls_sha512_update_ret( &ctx, sha512_test_buf[j], sha512_test_buflen[j] ); if( ret != 0 ) goto fail; } if( ( ret = mbedtls_sha512_finish_ret( &ctx, sha512sum ) ) != 0 ) goto fail; if( memcmp( sha512sum, sha512_test_sum[i], 64 - k * 16 ) != 0 ) { ret = 1; goto fail; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); goto exit; fail: if( verbose != 0 ) mbedtls_printf( "failed\n" ); exit: mbedtls_sha512_free( &ctx ); mbedtls_free( buf ); return( ret ); } #undef ARRAY_LENGTH #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_SHA512_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_cache.c
/* * SSL session cache implementation * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These session callbacks use a simple chained list * to store and retrieve the session information. */ #include "common.h" #if defined(MBEDTLS_SSL_CACHE_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/ssl_cache.h" #include "mbedtls/ssl_internal.h" #include <string.h> void mbedtls_ssl_cache_init( mbedtls_ssl_cache_context *cache ) { memset( cache, 0, sizeof( mbedtls_ssl_cache_context ) ); cache->timeout = MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT; cache->max_entries = MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES; #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_init( &cache->mutex ); #endif } int mbedtls_ssl_cache_get( void *data, mbedtls_ssl_session *session ) { int ret = 1; #if defined(MBEDTLS_HAVE_TIME) mbedtls_time_t t = mbedtls_time( NULL ); #endif mbedtls_ssl_cache_context *cache = (mbedtls_ssl_cache_context *) data; mbedtls_ssl_cache_entry *cur, *entry; #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_lock( &cache->mutex ) != 0 ) return( 1 ); #endif cur = cache->chain; entry = NULL; while( cur != NULL ) { entry = cur; cur = cur->next; #if defined(MBEDTLS_HAVE_TIME) if( cache->timeout != 0 && (int) ( t - entry->timestamp ) > cache->timeout ) continue; #endif if( session->ciphersuite != entry->session.ciphersuite || session->compression != entry->session.compression || session->id_len != entry->session.id_len ) continue; if( memcmp( session->id, entry->session.id, entry->session.id_len ) != 0 ) continue; ret = mbedtls_ssl_session_copy( session, &entry->session ); if( ret != 0 ) { ret = 1; goto exit; } #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* * Restore peer certificate (without rest of the original chain) */ if( entry->peer_cert.p != NULL ) { /* `session->peer_cert` is NULL after the call to * mbedtls_ssl_session_copy(), because cache entries * have the `peer_cert` field set to NULL. */ if( ( session->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) ) ) == NULL ) { ret = 1; goto exit; } mbedtls_x509_crt_init( session->peer_cert ); if( mbedtls_x509_crt_parse( session->peer_cert, entry->peer_cert.p, entry->peer_cert.len ) != 0 ) { mbedtls_free( session->peer_cert ); session->peer_cert = NULL; ret = 1; goto exit; } } #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ ret = 0; goto exit; } exit: #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &cache->mutex ) != 0 ) ret = 1; #endif return( ret ); } int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session ) { int ret = 1; #if defined(MBEDTLS_HAVE_TIME) mbedtls_time_t t = mbedtls_time( NULL ), oldest = 0; mbedtls_ssl_cache_entry *old = NULL; #endif mbedtls_ssl_cache_context *cache = (mbedtls_ssl_cache_context *) data; mbedtls_ssl_cache_entry *cur, *prv; int count = 0; #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &cache->mutex ) ) != 0 ) return( ret ); #endif cur = cache->chain; prv = NULL; while( cur != NULL ) { count++; #if defined(MBEDTLS_HAVE_TIME) if( cache->timeout != 0 && (int) ( t - cur->timestamp ) > cache->timeout ) { cur->timestamp = t; break; /* expired, reuse this slot, update timestamp */ } #endif if( memcmp( session->id, cur->session.id, cur->session.id_len ) == 0 ) break; /* client reconnected, keep timestamp for session id */ #if defined(MBEDTLS_HAVE_TIME) if( oldest == 0 || cur->timestamp < oldest ) { oldest = cur->timestamp; old = cur; } #endif prv = cur; cur = cur->next; } if( cur == NULL ) { #if defined(MBEDTLS_HAVE_TIME) /* * Reuse oldest entry if max_entries reached */ if( count >= cache->max_entries ) { if( old == NULL ) { ret = 1; goto exit; } cur = old; } #else /* MBEDTLS_HAVE_TIME */ /* * Reuse first entry in chain if max_entries reached, * but move to last place */ if( count >= cache->max_entries ) { if( cache->chain == NULL ) { ret = 1; goto exit; } cur = cache->chain; cache->chain = cur->next; cur->next = NULL; prv->next = cur; } #endif /* MBEDTLS_HAVE_TIME */ else { /* * max_entries not reached, create new entry */ cur = mbedtls_calloc( 1, sizeof(mbedtls_ssl_cache_entry) ); if( cur == NULL ) { ret = 1; goto exit; } if( prv == NULL ) cache->chain = cur; else prv->next = cur; } #if defined(MBEDTLS_HAVE_TIME) cur->timestamp = t; #endif } #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* * If we're reusing an entry, free its certificate first */ if( cur->peer_cert.p != NULL ) { mbedtls_free( cur->peer_cert.p ); memset( &cur->peer_cert, 0, sizeof(mbedtls_x509_buf) ); } #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* Copy the entire session; this temporarily makes a copy of the * X.509 CRT structure even though we only want to store the raw CRT. * This inefficiency will go away as soon as we implement on-demand * parsing of CRTs, in which case there's no need for the `peer_cert` * field anymore in the first place, and we're done after this call. */ ret = mbedtls_ssl_session_copy( &cur->session, session ); if( ret != 0 ) { ret = 1; goto exit; } #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* If present, free the X.509 structure and only store the raw CRT data. */ if( cur->session.peer_cert != NULL ) { cur->peer_cert.p = mbedtls_calloc( 1, cur->session.peer_cert->raw.len ); if( cur->peer_cert.p == NULL ) { ret = 1; goto exit; } memcpy( cur->peer_cert.p, cur->session.peer_cert->raw.p, cur->session.peer_cert->raw.len ); cur->peer_cert.len = session->peer_cert->raw.len; mbedtls_x509_crt_free( cur->session.peer_cert ); mbedtls_free( cur->session.peer_cert ); cur->session.peer_cert = NULL; } #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ ret = 0; exit: #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &cache->mutex ) != 0 ) ret = 1; #endif return( ret ); } #if defined(MBEDTLS_HAVE_TIME) void mbedtls_ssl_cache_set_timeout( mbedtls_ssl_cache_context *cache, int timeout ) { if( timeout < 0 ) timeout = 0; cache->timeout = timeout; } #endif /* MBEDTLS_HAVE_TIME */ void mbedtls_ssl_cache_set_max_entries( mbedtls_ssl_cache_context *cache, int max ) { if( max < 0 ) max = 0; cache->max_entries = max; } void mbedtls_ssl_cache_free( mbedtls_ssl_cache_context *cache ) { mbedtls_ssl_cache_entry *cur, *prv; cur = cache->chain; while( cur != NULL ) { prv = cur; cur = cur->next; mbedtls_ssl_session_free( &prv->session ); #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) mbedtls_free( prv->peer_cert.p ); #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ mbedtls_free( prv ); } #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_free( &cache->mutex ); #endif cache->chain = NULL; } #endif /* MBEDTLS_SSL_CACHE_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_ciphersuites.c
/** * \file ssl_ciphersuites.c * * \brief SSL ciphersuites for mbed TLS * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #if defined(MBEDTLS_SSL_TLS_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #endif #include "mbedtls/ssl_ciphersuites.h" #include "mbedtls/ssl.h" #include <string.h> /* * Ordered from most preferred to least preferred in terms of security. * * Current rule (except RC4 and 3DES, weak and null which come last): * 1. By key exchange: * Forward-secure non-PSK > forward-secure PSK > ECJPAKE > other non-PSK > other PSK * 2. By key length and cipher: * ChaCha > AES-256 > Camellia-256 > ARIA-256 > AES-128 > Camellia-128 > ARIA-128 * 3. By cipher mode when relevant GCM > CCM > CBC > CCM_8 * 4. By hash function used when relevant * 5. By key exchange/auth again: EC > non-EC */ static const int ciphersuite_preference[] = { #if defined(MBEDTLS_SSL_CIPHERSUITES) MBEDTLS_SSL_CIPHERSUITES, #else /* Chacha-Poly ephemeral suites */ MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, /* All AES-256 ephemeral suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM, MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8, MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8, /* All CAMELLIA-256 ephemeral suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384, MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, /* All ARIA-256 ephemeral suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384, MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384, /* All AES-128 ephemeral suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8, /* All CAMELLIA-128 ephemeral suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, /* All ARIA-128 ephemeral suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256, /* The PSK ephemeral suites */ MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256, MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256, MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM, MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8, MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM, MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8, MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256, MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256, /* The ECJPAKE suite */ MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8, /* All AES-256 suites */ MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_RSA_WITH_AES_256_CCM, MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256, MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8, /* All CAMELLIA-256 suites */ MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256, MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384, MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, /* All ARIA-256 suites */ MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384, MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384, MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384, MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384, /* All AES-128 suites */ MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_RSA_WITH_AES_128_CCM, MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8, /* All CAMELLIA-128 suites */ MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, /* All ARIA-128 suites */ MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256, MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256, MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256, /* The RSA PSK suites */ MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384, MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256, /* The PSK suites */ MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256, MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_PSK_WITH_AES_256_CCM, MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384, MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8, MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384, MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_PSK_WITH_AES_128_CCM, MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8, MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256, MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256, /* 3DES suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA, /* RC4 suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA, MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA, MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA, MBEDTLS_TLS_RSA_WITH_RC4_128_SHA, MBEDTLS_TLS_RSA_WITH_RC4_128_MD5, MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA, MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA, MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA, MBEDTLS_TLS_PSK_WITH_RC4_128_SHA, /* Weak suites */ MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA, MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA, /* NULL suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA, MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA, MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384, MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256, MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA, MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384, MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256, MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA, MBEDTLS_TLS_RSA_WITH_NULL_SHA256, MBEDTLS_TLS_RSA_WITH_NULL_SHA, MBEDTLS_TLS_RSA_WITH_NULL_MD5, MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA, MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA, MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384, MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA, MBEDTLS_TLS_PSK_WITH_NULL_SHA384, MBEDTLS_TLS_PSK_WITH_NULL_SHA256, MBEDTLS_TLS_PSK_WITH_NULL_SHA, #endif /* MBEDTLS_SSL_CIPHERSUITES */ 0 }; static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] = { #if defined(MBEDTLS_CHACHAPOLY_C) && \ defined(MBEDTLS_SHA256_C) && \ defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) { MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, "TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256", MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, "TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1305-SHA256", MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) { MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, "TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA256", MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) { MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256, "TLS-PSK-WITH-CHACHA20-POLY1305-SHA256", MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) { MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256, "TLS-ECDHE-PSK-WITH-CHACHA20-POLY1305-SHA256", MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) { MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256, "TLS-DHE-PSK-WITH-CHACHA20-POLY1305-SHA256", MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) { MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256, "TLS-RSA-PSK-WITH-CHACHA20-POLY1305-SHA256", MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_CHACHAPOLY_C && MBEDTLS_SHA256_C && MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_SHA1_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, "TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256", MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA384", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, "TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384", MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_SHA512_C */ #if defined(MBEDTLS_CCM_C) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM, "TLS-ECDHE-ECDSA-WITH-AES-256-CCM", MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8, "TLS-ECDHE-ECDSA-WITH-AES-256-CCM-8", MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, "TLS-ECDHE-ECDSA-WITH-AES-128-CCM", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, "TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, #endif /* MBEDTLS_CCM_C */ #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_CAMELLIA_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-GCM-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-GCM-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, "TLS-ECDHE-ECDSA-WITH-3DES-EDE-CBC-SHA", MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ARC4_C) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, "TLS-ECDHE-ECDSA-WITH-RC4-128-SHA", MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_NODTLS }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_ARC4_C */ #if defined(MBEDTLS_CIPHER_NULL_CIPHER) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA, "TLS-ECDHE-ECDSA-WITH-NULL-SHA", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_NULL_CIPHER */ #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_SHA1_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, "TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256", MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA384", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, "TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384", MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_CAMELLIA_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, "TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384, "TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256, "TLS-ECDHE-RSA-WITH-CAMELLIA-128-GCM-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384, "TLS-ECDHE-RSA-WITH-CAMELLIA-256-GCM-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, "TLS-ECDHE-RSA-WITH-3DES-EDE-CBC-SHA", MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ARC4_C) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA, "TLS-ECDHE-RSA-WITH-RC4-128-SHA", MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_NODTLS }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_ARC4_C */ #if defined(MBEDTLS_CIPHER_NULL_CIPHER) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA, "TLS-ECDHE-RSA-WITH-NULL-SHA", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_NULL_CIPHER */ #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_SHA512_C) && defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, "TLS-DHE-RSA-WITH-AES-256-GCM-SHA384", MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C && MBEDTLS_GCM_C */ #if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, "TLS-DHE-RSA-WITH-AES-128-GCM-SHA256", MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, "TLS-DHE-RSA-WITH-AES-128-CBC-SHA256", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA, "TLS-DHE-RSA-WITH-AES-128-CBC-SHA", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA, "TLS-DHE-RSA-WITH-AES-256-CBC-SHA", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CCM_C) { MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM, "TLS-DHE-RSA-WITH-AES-256-CCM", MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8, "TLS-DHE-RSA-WITH-AES-256-CCM-8", MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, { MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM, "TLS-DHE-RSA-WITH-AES-128-CCM", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8, "TLS-DHE-RSA-WITH-AES-128-CCM-8", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, #endif /* MBEDTLS_CCM_C */ #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_CAMELLIA_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256, "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256, "TLS-DHE-RSA-WITH-CAMELLIA-128-GCM-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384, "TLS-DHE-RSA-WITH-CAMELLIA-256-GCM-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, "TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA", MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_SHA512_C) && defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384, "TLS-RSA-WITH-AES-256-GCM-SHA384", MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C && MBEDTLS_GCM_C */ #if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, "TLS-RSA-WITH-AES-128-GCM-SHA256", MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, "TLS-RSA-WITH-AES-128-CBC-SHA256", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256, "TLS-RSA-WITH-AES-256-CBC-SHA256", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA1_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, "TLS-RSA-WITH-AES-128-CBC-SHA", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA, "TLS-RSA-WITH-AES-256-CBC-SHA", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_CCM_C) { MBEDTLS_TLS_RSA_WITH_AES_256_CCM, "TLS-RSA-WITH-AES-256-CCM", MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8, "TLS-RSA-WITH-AES-256-CCM-8", MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, { MBEDTLS_TLS_RSA_WITH_AES_128_CCM, "TLS-RSA-WITH-AES-128-CCM", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8, "TLS-RSA-WITH-AES-128-CCM-8", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, #endif /* MBEDTLS_CCM_C */ #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_CAMELLIA_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256, "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256, "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256, "TLS-RSA-WITH-CAMELLIA-128-GCM-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384, "TLS-RSA-WITH-CAMELLIA-256-GCM-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA, "TLS-RSA-WITH-3DES-EDE-CBC-SHA", MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ARC4_C) #if defined(MBEDTLS_MD5_C) { MBEDTLS_TLS_RSA_WITH_RC4_128_MD5, "TLS-RSA-WITH-RC4-128-MD5", MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_MD5, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_NODTLS }, #endif #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_RSA_WITH_RC4_128_SHA, "TLS-RSA-WITH-RC4-128-SHA", MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_NODTLS }, #endif #endif /* MBEDTLS_ARC4_C */ #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_SHA1_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA256", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, "TLS-ECDH-RSA-WITH-AES-128-GCM-SHA256", MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA384", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, "TLS-ECDH-RSA-WITH-AES-256-GCM-SHA384", MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_CAMELLIA_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256, "TLS-ECDH-RSA-WITH-CAMELLIA-128-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384, "TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256, "TLS-ECDH-RSA-WITH-CAMELLIA-128-GCM-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384, "TLS-ECDH-RSA-WITH-CAMELLIA-256-GCM-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, "TLS-ECDH-RSA-WITH-3DES-EDE-CBC-SHA", MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ARC4_C) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA, "TLS-ECDH-RSA-WITH-RC4-128-SHA", MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_NODTLS }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_ARC4_C */ #if defined(MBEDTLS_CIPHER_NULL_CIPHER) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA, "TLS-ECDH-RSA-WITH-NULL-SHA", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_NULL_CIPHER */ #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_SHA1_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, "TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, "TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA256", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, "TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256", MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA384", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, "TLS-ECDH-ECDSA-WITH-AES-256-GCM-SHA384", MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_CAMELLIA_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-GCM-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-GCM-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, "TLS-ECDH-ECDSA-WITH-3DES-EDE-CBC-SHA", MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ARC4_C) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA, "TLS-ECDH-ECDSA-WITH-RC4-128-SHA", MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_NODTLS }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_ARC4_C */ #if defined(MBEDTLS_CIPHER_NULL_CIPHER) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA, "TLS-ECDH-ECDSA-WITH-NULL-SHA", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_NULL_CIPHER */ #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256, "TLS-PSK-WITH-AES-128-GCM-SHA256", MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384, "TLS-PSK-WITH-AES-256-GCM-SHA384", MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256, "TLS-PSK-WITH-AES-128-CBC-SHA256", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384, "TLS-PSK-WITH-AES-256-CBC-SHA384", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA, "TLS-PSK-WITH-AES-128-CBC-SHA", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA, "TLS-PSK-WITH-AES-256-CBC-SHA", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CCM_C) { MBEDTLS_TLS_PSK_WITH_AES_256_CCM, "TLS-PSK-WITH-AES-256-CCM", MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8, "TLS-PSK-WITH-AES-256-CCM-8", MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, { MBEDTLS_TLS_PSK_WITH_AES_128_CCM, "TLS-PSK-WITH-AES-128-CCM", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8, "TLS-PSK-WITH-AES-128-CCM-8", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, #endif /* MBEDTLS_CCM_C */ #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_CAMELLIA_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-PSK-WITH-CAMELLIA-128-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-PSK-WITH-CAMELLIA-256-CBC-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256, "TLS-PSK-WITH-CAMELLIA-128-GCM-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384, "TLS-PSK-WITH-CAMELLIA-256-GCM-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA, "TLS-PSK-WITH-3DES-EDE-CBC-SHA", MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ARC4_C) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_PSK_WITH_RC4_128_SHA, "TLS-PSK-WITH-RC4-128-SHA", MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_NODTLS }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_ARC4_C */ #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256, "TLS-DHE-PSK-WITH-AES-128-GCM-SHA256", MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384, "TLS-DHE-PSK-WITH-AES-256-GCM-SHA384", MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, "TLS-DHE-PSK-WITH-AES-128-CBC-SHA256", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, "TLS-DHE-PSK-WITH-AES-256-CBC-SHA384", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA, "TLS-DHE-PSK-WITH-AES-128-CBC-SHA", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA, "TLS-DHE-PSK-WITH-AES-256-CBC-SHA", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CCM_C) { MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM, "TLS-DHE-PSK-WITH-AES-256-CCM", MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8, "TLS-DHE-PSK-WITH-AES-256-CCM-8", MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, { MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM, "TLS-DHE-PSK-WITH-AES-128-CCM", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8, "TLS-DHE-PSK-WITH-AES-128-CCM-8", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, #endif /* MBEDTLS_CCM_C */ #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_CAMELLIA_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-DHE-PSK-WITH-CAMELLIA-128-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-DHE-PSK-WITH-CAMELLIA-256-CBC-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256, "TLS-DHE-PSK-WITH-CAMELLIA-128-GCM-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384, "TLS-DHE-PSK-WITH-CAMELLIA-256-GCM-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, "TLS-DHE-PSK-WITH-3DES-EDE-CBC-SHA", MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ARC4_C) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA, "TLS-DHE-PSK-WITH-RC4-128-SHA", MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_NODTLS }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_ARC4_C */ #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, "TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, "TLS-ECDHE-PSK-WITH-AES-256-CBC-SHA384", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, "TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, "TLS-ECDHE-PSK-WITH-AES-256-CBC-SHA", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_CAMELLIA_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-ECDHE-PSK-WITH-CAMELLIA-128-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-ECDHE-PSK-WITH-CAMELLIA-256-CBC-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA, "TLS-ECDHE-PSK-WITH-3DES-EDE-CBC-SHA", MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ARC4_C) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA, "TLS-ECDHE-PSK-WITH-RC4-128-SHA", MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_NODTLS }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_ARC4_C */ #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, "TLS-RSA-PSK-WITH-AES-128-GCM-SHA256", MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, "TLS-RSA-PSK-WITH-AES-256-GCM-SHA384", MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, "TLS-RSA-PSK-WITH-AES-128-CBC-SHA256", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, "TLS-RSA-PSK-WITH-AES-256-CBC-SHA384", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA, "TLS-RSA-PSK-WITH-AES-128-CBC-SHA", MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, { MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA, "TLS-RSA-PSK-WITH-AES-256-CBC-SHA", MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_CAMELLIA_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-RSA-PSK-WITH-CAMELLIA-128-CBC-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-RSA-PSK-WITH-CAMELLIA-256-CBC-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256, "TLS-RSA-PSK-WITH-CAMELLIA-128-GCM-SHA256", MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384, "TLS-RSA-PSK-WITH-CAMELLIA-256-GCM-SHA384", MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_GCM_C */ #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, "TLS-RSA-PSK-WITH-3DES-EDE-CBC-SHA", MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ARC4_C) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA, "TLS-RSA-PSK-WITH-RC4-128-SHA", MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_NODTLS }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_ARC4_C */ #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) #if defined(MBEDTLS_AES_C) #if defined(MBEDTLS_CCM_C) { MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8, "TLS-ECJPAKE-WITH-AES-128-CCM-8", MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECJPAKE, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_SHORT_TAG }, #endif /* MBEDTLS_CCM_C */ #endif /* MBEDTLS_AES_C */ #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_ENABLE_WEAK_CIPHERSUITES) #if defined(MBEDTLS_CIPHER_NULL_CIPHER) #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) #if defined(MBEDTLS_MD5_C) { MBEDTLS_TLS_RSA_WITH_NULL_MD5, "TLS-RSA-WITH-NULL-MD5", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_MD5, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_RSA_WITH_NULL_SHA, "TLS-RSA-WITH-NULL-SHA", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_RSA_WITH_NULL_SHA256, "TLS-RSA-WITH-NULL-SHA256", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_PSK_WITH_NULL_SHA, "TLS-PSK-WITH-NULL-SHA", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_PSK_WITH_NULL_SHA256, "TLS-PSK-WITH-NULL-SHA256", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_PSK_WITH_NULL_SHA384, "TLS-PSK-WITH-NULL-SHA384", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA, "TLS-DHE-PSK-WITH-NULL-SHA", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256, "TLS-DHE-PSK-WITH-NULL-SHA256", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384, "TLS-DHE-PSK-WITH-NULL-SHA384", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA, "TLS-ECDHE-PSK-WITH-NULL-SHA", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256, "TLS-ECDHE-PSK-WITH-NULL-SHA256", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384, "TLS-ECDHE-PSK-WITH-NULL-SHA384", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA, "TLS-RSA-PSK-WITH-NULL-SHA", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) { MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256, "TLS-RSA-PSK-WITH-NULL-SHA256", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #if defined(MBEDTLS_SHA512_C) { MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384, "TLS-RSA-PSK-WITH-NULL-SHA384", MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #endif /* MBEDTLS_CIPHER_NULL_CIPHER */ #if defined(MBEDTLS_DES_C) #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA, "TLS-DHE-RSA-WITH-DES-CBC-SHA", MBEDTLS_CIPHER_DES_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) #if defined(MBEDTLS_SHA1_C) { MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA, "TLS-RSA-WITH-DES-CBC-SHA", MBEDTLS_CIPHER_DES_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_CIPHERSUITE_WEAK }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_DES_C */ #endif /* MBEDTLS_ENABLE_WEAK_CIPHERSUITES */ #if defined(MBEDTLS_ARIA_C) #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384, "TLS-RSA-WITH-ARIA-256-GCM-SHA384", MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384, "TLS-RSA-WITH-ARIA-256-CBC-SHA384", MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256, "TLS-RSA-WITH-ARIA-128-GCM-SHA256", MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256, "TLS-RSA-WITH-ARIA-128-CBC-SHA256", MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384, "TLS-RSA-PSK-WITH-ARIA-256-GCM-SHA384", MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384, "TLS-RSA-PSK-WITH-ARIA-256-CBC-SHA384", MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256, "TLS-RSA-PSK-WITH-ARIA-128-GCM-SHA256", MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256, "TLS-RSA-PSK-WITH-ARIA-128-CBC-SHA256", MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384, "TLS-PSK-WITH-ARIA-256-GCM-SHA384", MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384,MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384, "TLS-PSK-WITH-ARIA-256-CBC-SHA384", MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256, "TLS-PSK-WITH-ARIA-128-GCM-SHA256", MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256, "TLS-PSK-WITH-ARIA-128-CBC-SHA256", MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384, "TLS-ECDH-RSA-WITH-ARIA-256-GCM-SHA384", MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384, "TLS-ECDH-RSA-WITH-ARIA-256-CBC-SHA384", MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256, "TLS-ECDH-RSA-WITH-ARIA-128-GCM-SHA256", MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256, "TLS-ECDH-RSA-WITH-ARIA-128-CBC-SHA256", MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384, "TLS-ECDHE-RSA-WITH-ARIA-256-GCM-SHA384", MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384, "TLS-ECDHE-RSA-WITH-ARIA-256-CBC-SHA384", MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256, "TLS-ECDHE-RSA-WITH-ARIA-128-GCM-SHA256", MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256, "TLS-ECDHE-RSA-WITH-ARIA-128-CBC-SHA256", MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384, "TLS-ECDHE-PSK-WITH-ARIA-256-CBC-SHA384", MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256, "TLS-ECDHE-PSK-WITH-ARIA-128-CBC-SHA256", MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384, "TLS-ECDHE-ECDSA-WITH-ARIA-256-GCM-SHA384", MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384, "TLS-ECDHE-ECDSA-WITH-ARIA-256-CBC-SHA384", MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256, "TLS-ECDHE-ECDSA-WITH-ARIA-128-GCM-SHA256", MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256, "TLS-ECDHE-ECDSA-WITH-ARIA-128-CBC-SHA256", MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384, "TLS-ECDH-ECDSA-WITH-ARIA-256-GCM-SHA384", MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384, "TLS-ECDH-ECDSA-WITH-ARIA-256-CBC-SHA384", MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256, "TLS-ECDH-ECDSA-WITH-ARIA-128-GCM-SHA256", MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256, "TLS-ECDH-ECDSA-WITH-ARIA-128-CBC-SHA256", MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384, "TLS-DHE-RSA-WITH-ARIA-256-GCM-SHA384", MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384, "TLS-DHE-RSA-WITH-ARIA-256-CBC-SHA384", MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256, "TLS-DHE-RSA-WITH-ARIA-128-GCM-SHA256", MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256, "TLS-DHE-RSA-WITH-ARIA-128-CBC-SHA256", MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384, "TLS-DHE-PSK-WITH-ARIA-256-GCM-SHA384", MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384, "TLS-DHE-PSK-WITH-ARIA-256-CBC-SHA384", MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256, "TLS-DHE-PSK-WITH-ARIA-128-GCM-SHA256", MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256, "TLS-DHE-PSK-WITH-ARIA-128-CBC-SHA256", MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, 0 }, #endif #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #endif /* MBEDTLS_ARIA_C */ { 0, "", MBEDTLS_CIPHER_NONE, MBEDTLS_MD_NONE, MBEDTLS_KEY_EXCHANGE_NONE, 0, 0, 0, 0, 0 } }; #if defined(MBEDTLS_SSL_CIPHERSUITES) const int *mbedtls_ssl_list_ciphersuites( void ) { return( ciphersuite_preference ); } #else #define MAX_CIPHERSUITES sizeof( ciphersuite_definitions ) / \ sizeof( ciphersuite_definitions[0] ) static int supported_ciphersuites[MAX_CIPHERSUITES]; static int supported_init = 0; static int ciphersuite_is_removed( const mbedtls_ssl_ciphersuite_t *cs_info ) { (void)cs_info; #if defined(MBEDTLS_REMOVE_ARC4_CIPHERSUITES) if( cs_info->cipher == MBEDTLS_CIPHER_ARC4_128 ) return( 1 ); #endif /* MBEDTLS_REMOVE_ARC4_CIPHERSUITES */ #if defined(MBEDTLS_REMOVE_3DES_CIPHERSUITES) if( cs_info->cipher == MBEDTLS_CIPHER_DES_EDE3_ECB || cs_info->cipher == MBEDTLS_CIPHER_DES_EDE3_CBC ) { return( 1 ); } #endif /* MBEDTLS_REMOVE_3DES_CIPHERSUITES */ return( 0 ); } const int *mbedtls_ssl_list_ciphersuites( void ) { /* * On initial call filter out all ciphersuites not supported by current * build based on presence in the ciphersuite_definitions. */ if( supported_init == 0 ) { const int *p; int *q; for( p = ciphersuite_preference, q = supported_ciphersuites; *p != 0 && q < supported_ciphersuites + MAX_CIPHERSUITES - 1; p++ ) { const mbedtls_ssl_ciphersuite_t *cs_info; if( ( cs_info = mbedtls_ssl_ciphersuite_from_id( *p ) ) != NULL && !ciphersuite_is_removed( cs_info ) ) { *(q++) = *p; } } *q = 0; supported_init = 1; } return( supported_ciphersuites ); } #endif /* MBEDTLS_SSL_CIPHERSUITES */ const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_string( const char *ciphersuite_name ) { const mbedtls_ssl_ciphersuite_t *cur = ciphersuite_definitions; if( NULL == ciphersuite_name ) return( NULL ); while( cur->id != 0 ) { if( 0 == strcmp( cur->name, ciphersuite_name ) ) return( cur ); cur++; } return( NULL ); } const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_id( int ciphersuite ) { const mbedtls_ssl_ciphersuite_t *cur = ciphersuite_definitions; while( cur->id != 0 ) { if( cur->id == ciphersuite ) return( cur ); cur++; } return( NULL ); } const char *mbedtls_ssl_get_ciphersuite_name( const int ciphersuite_id ) { const mbedtls_ssl_ciphersuite_t *cur; cur = mbedtls_ssl_ciphersuite_from_id( ciphersuite_id ); if( cur == NULL ) return( "unknown" ); return( cur->name ); } int mbedtls_ssl_get_ciphersuite_id( const char *ciphersuite_name ) { const mbedtls_ssl_ciphersuite_t *cur; cur = mbedtls_ssl_ciphersuite_from_string( ciphersuite_name ); if( cur == NULL ) return( 0 ); return( cur->id ); } #if defined(MBEDTLS_PK_C) mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg( const mbedtls_ssl_ciphersuite_t *info ) { switch( info->key_exchange ) { case MBEDTLS_KEY_EXCHANGE_RSA: case MBEDTLS_KEY_EXCHANGE_DHE_RSA: case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: case MBEDTLS_KEY_EXCHANGE_RSA_PSK: return( MBEDTLS_PK_RSA ); case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: return( MBEDTLS_PK_ECDSA ); case MBEDTLS_KEY_EXCHANGE_ECDH_RSA: case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA: return( MBEDTLS_PK_ECKEY ); default: return( MBEDTLS_PK_NONE ); } } mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphersuite_t *info ) { switch( info->key_exchange ) { case MBEDTLS_KEY_EXCHANGE_RSA: case MBEDTLS_KEY_EXCHANGE_DHE_RSA: case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: return( MBEDTLS_PK_RSA ); case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: return( MBEDTLS_PK_ECDSA ); default: return( MBEDTLS_PK_NONE ); } } #endif /* MBEDTLS_PK_C */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info ) { switch( info->key_exchange ) { case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK: case MBEDTLS_KEY_EXCHANGE_ECDH_RSA: case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA: case MBEDTLS_KEY_EXCHANGE_ECJPAKE: return( 1 ); default: return( 0 ); } } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED*/ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) int mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info ) { switch( info->key_exchange ) { case MBEDTLS_KEY_EXCHANGE_PSK: case MBEDTLS_KEY_EXCHANGE_RSA_PSK: case MBEDTLS_KEY_EXCHANGE_DHE_PSK: case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK: return( 1 ); default: return( 0 ); } } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #endif /* MBEDTLS_SSL_TLS_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_cli.c
/* * SSLv3/TLSv1 client-side functions * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #if defined(MBEDTLS_SSL_CLI_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/ssl.h" #include "mbedtls/ssl_internal.h" #include "mbedtls/debug.h" #include "mbedtls/error.h" #if defined(MBEDTLS_USE_PSA_CRYPTO) #include "mbedtls/psa_util.h" #endif /* MBEDTLS_USE_PSA_CRYPTO */ #include <string.h> #include <stdint.h> #if defined(MBEDTLS_HAVE_TIME) #include "mbedtls/platform_time.h" #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) #include "mbedtls/platform_util.h" #endif #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static int ssl_conf_has_static_psk( mbedtls_ssl_config const *conf ) { if( conf->psk_identity == NULL || conf->psk_identity_len == 0 ) { return( 0 ); } if( conf->psk != NULL && conf->psk_len != 0 ) return( 1 ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ! mbedtls_svc_key_id_is_null( conf->psk_opaque ) ) return( 1 ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ return( 0 ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) static int ssl_conf_has_static_raw_psk( mbedtls_ssl_config const *conf ) { if( conf->psk_identity == NULL || conf->psk_identity_len == 0 ) { return( 0 ); } if( conf->psk != NULL && conf->psk_len != 0 ) return( 1 ); return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) static int ssl_write_hostname_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t hostname_len; *olen = 0; if( ssl->hostname == NULL ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s", ssl->hostname ) ); hostname_len = strlen( ssl->hostname ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, hostname_len + 9 ); /* * Sect. 3, RFC 6066 (TLS Extensions Definitions) * * In order to provide any of the server names, clients MAY include an * extension of type "server_name" in the (extended) client hello. The * "extension_data" field of this extension SHALL contain * "ServerNameList" where: * * struct { * NameType name_type; * select (name_type) { * case host_name: HostName; * } name; * } ServerName; * * enum { * host_name(0), (255) * } NameType; * * opaque HostName<1..2^16-1>; * * struct { * ServerName server_name_list<1..2^16-1> * } ServerNameList; * */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME ) & 0xFF ); *p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( (hostname_len + 5) ) & 0xFF ); *p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( (hostname_len + 3) ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF ); *p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( hostname_len ) & 0xFF ); memcpy( p, ssl->hostname, hostname_len ); *olen = hostname_len + 9; return( 0 ); } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_RENEGOTIATION) static int ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; *olen = 0; /* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the * initial ClientHello, in which case also adding the renegotiation * info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */ if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 5 + ssl->verify_data_len ); /* * Secure renegotiation */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF ); *p++ = 0x00; *p++ = ( ssl->verify_data_len + 1 ) & 0xFF; *p++ = ssl->verify_data_len & 0xFF; memcpy( p, ssl->own_verify_data, ssl->verify_data_len ); *olen = 5 + ssl->verify_data_len; return( 0 ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /* * Only if we handle at least one key exchange that needs signatures. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) static int ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t sig_alg_len = 0; const int *md; #if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) unsigned char *sig_alg_list = buf + 6; #endif *olen = 0; if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) ); if( ssl->conf->sig_hashes == NULL ) return( MBEDTLS_ERR_SSL_BAD_CONFIG ); for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ ) { #if defined(MBEDTLS_ECDSA_C) sig_alg_len += 2; #endif #if defined(MBEDTLS_RSA_C) sig_alg_len += 2; #endif if( sig_alg_len > MBEDTLS_SSL_MAX_SIG_HASH_ALG_LIST_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "length in bytes of sig-hash-alg extension too big" ) ); return( MBEDTLS_ERR_SSL_BAD_CONFIG ); } } /* Empty signature algorithms list, this is a configuration error. */ if( sig_alg_len == 0 ) return( MBEDTLS_ERR_SSL_BAD_CONFIG ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, sig_alg_len + 6 ); /* * Prepare signature_algorithms extension (TLS 1.2) */ sig_alg_len = 0; for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ ) { #if defined(MBEDTLS_ECDSA_C) sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md ); sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA; #endif #if defined(MBEDTLS_RSA_C) sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md ); sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA; #endif } /* * enum { * none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5), * sha512(6), (255) * } HashAlgorithm; * * enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) } * SignatureAlgorithm; * * struct { * HashAlgorithm hash; * SignatureAlgorithm signature; * } SignatureAndHashAlgorithm; * * SignatureAndHashAlgorithm * supported_signature_algorithms<2..2^16-2>; */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG ) & 0xFF ); *p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ( sig_alg_len + 2 ) ) & 0xFF ); *p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( sig_alg_len ) & 0xFF ); *olen = 6 + sig_alg_len; return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; unsigned char *elliptic_curve_list = p + 6; size_t elliptic_curve_len = 0; const mbedtls_ecp_curve_info *info; const mbedtls_ecp_group_id *grp_id; *olen = 0; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_elliptic_curves extension" ) ); if( ssl->conf->curve_list == NULL ) return( MBEDTLS_ERR_SSL_BAD_CONFIG ); for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ ) { info = mbedtls_ecp_curve_info_from_grp_id( *grp_id ); if( info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid curve in ssl configuration" ) ); return( MBEDTLS_ERR_SSL_BAD_CONFIG ); } elliptic_curve_len += 2; if( elliptic_curve_len > MBEDTLS_SSL_MAX_CURVE_LIST_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "malformed supported_elliptic_curves extension in config" ) ); return( MBEDTLS_ERR_SSL_BAD_CONFIG ); } } /* Empty elliptic curve list, this is a configuration error. */ if( elliptic_curve_len == 0 ) return( MBEDTLS_ERR_SSL_BAD_CONFIG ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 + elliptic_curve_len ); elliptic_curve_len = 0; for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ ) { info = mbedtls_ecp_curve_info_from_grp_id( *grp_id ); elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8; elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF; } *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES ) & 0xFF ); *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) ) & 0xFF ); *p++ = (unsigned char)( ( ( elliptic_curve_len ) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ( elliptic_curve_len ) ) & 0xFF ); *olen = 6 + elliptic_curve_len; return( 0 ); } static int ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; (void) ssl; /* ssl used for debugging only */ *olen = 0; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF ); *p++ = 0x00; *p++ = 2; *p++ = 1; *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED; *olen = 6; return( 0 ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = buf; size_t kkpp_len; *olen = 0; /* Skip costly extension if we can't use EC J-PAKE anyway */ if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding ecjpake_kkpp extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF ); /* * We may need to send ClientHello multiple times for Hello verification. * We don't want to compute fresh values every time (both for performance * and consistency reasons), so cache the extension content. */ if( ssl->handshake->ecjpake_cache == NULL || ssl->handshake->ecjpake_cache_len == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) ); ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx, p + 2, end - p - 2, &kkpp_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret ); return( ret ); } ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len ); if( ssl->handshake->ecjpake_cache == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len ); ssl->handshake->ecjpake_cache_len = kkpp_len; } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) ); kkpp_len = ssl->handshake->ecjpake_cache_len; MBEDTLS_SSL_CHK_BUF_PTR( p + 2, end, kkpp_len ); memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len ); } *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( kkpp_len ) & 0xFF ); *olen = kkpp_len + 4; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) static int ssl_write_cid_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t ext_len; /* * Quoting draft-ietf-tls-dtls-connection-id-05 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05 * * struct { * opaque cid<0..2^8-1>; * } ConnectionId; */ *olen = 0; if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM || ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED ) { return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding CID extension" ) ); /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX * which is at most 255, so the increment cannot overflow. */ MBEDTLS_SSL_CHK_BUF_PTR( p, end, (unsigned)( ssl->own_cid_len + 5 ) ); /* Add extension ID + size */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID ) & 0xFF ); ext_len = (size_t) ssl->own_cid_len + 1; *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); *p++ = (uint8_t) ssl->own_cid_len; memcpy( p, ssl->own_cid, ssl->own_cid_len ); *olen = ssl->own_cid_len + 5; return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static int ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 5 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF ); *p++ = 0x00; *p++ = 1; *p++ = ssl->conf->mfl_code; *olen = 5; return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) static int ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding truncated_hmac extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; return( 0 ); } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) static int ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED || ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; return( 0 ); } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) static int ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED || ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; return( 0 ); } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t tlen = ssl->session_negotiate->ticket_len; *olen = 0; if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) ); /* The addition is safe here since the ticket length is 16 bit. */ MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 + tlen ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF ); *p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( tlen ) & 0xFF ); *olen = 4; if( ssl->session_negotiate->ticket == NULL || tlen == 0 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "sending session ticket of length %d", tlen ) ); memcpy( p, ssl->session_negotiate->ticket, tlen ); *olen += tlen; return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_ALPN) static int ssl_write_alpn_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t alpnlen = 0; const char **cur; *olen = 0; if( ssl->conf->alpn_list == NULL ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) ); for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ ) alpnlen += strlen( *cur ) + 1; MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 + alpnlen ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF ); /* * opaque ProtocolName<1..2^8-1>; * * struct { * ProtocolName protocol_name_list<2..2^16-1> * } ProtocolNameList; */ /* Skip writing extension and list length for now */ p += 4; for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ ) { /* * mbedtls_ssl_conf_set_alpn_protocols() checked that the length of * protocol names is less than 255. */ *p = (unsigned char)strlen( *cur ); memcpy( p + 1, *cur, *p ); p += 1 + *p; } *olen = p - buf; /* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */ buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF ); buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF ); /* Extension length = olen - 2 (ext_type) - 2 (ext_len) */ buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF ); buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF ); return( 0 ); } #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_DTLS_SRTP) static int ssl_write_use_srtp_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t protection_profiles_index = 0, ext_len = 0; uint16_t mki_len = 0, profile_value = 0; *olen = 0; if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) || ( ssl->conf->dtls_srtp_profile_list == NULL ) || ( ssl->conf->dtls_srtp_profile_list_len == 0 ) ) { return( 0 ); } /* RFC 5764 section 4.1.1 * uint8 SRTPProtectionProfile[2]; * * struct { * SRTPProtectionProfiles SRTPProtectionProfiles; * opaque srtp_mki<0..255>; * } UseSRTPData; * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>; */ if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED ) { mki_len = ssl->dtls_srtp_info.mki_len; } /* Extension length = 2 bytes for profiles length, * ssl->conf->dtls_srtp_profile_list_len * 2 (each profile is 2 bytes length ), * 1 byte for srtp_mki vector length and the mki_len value */ ext_len = 2 + 2 * ( ssl->conf->dtls_srtp_profile_list_len ) + 1 + mki_len; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding use_srtp extension" ) ); /* Check there is room in the buffer for the extension + 4 bytes * - the extension tag (2 bytes) * - the extension length (2 bytes) */ MBEDTLS_SSL_CHK_BUF_PTR( p, end, ext_len + 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_USE_SRTP >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_USE_SRTP ) & 0xFF ); *p++ = (unsigned char)( ( ( ext_len & 0xFF00 ) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ext_len & 0xFF ); /* protection profile length: 2*(ssl->conf->dtls_srtp_profile_list_len) */ /* micro-optimization: * the list size is limited to MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH * which is lower than 127, so the upper byte of the length is always 0 * For the documentation, the more generic code is left in comments * *p++ = (unsigned char)( ( ( 2 * ssl->conf->dtls_srtp_profile_list_len ) * >> 8 ) & 0xFF ); */ *p++ = 0; *p++ = (unsigned char)( ( 2 * ssl->conf->dtls_srtp_profile_list_len ) & 0xFF ); for( protection_profiles_index=0; protection_profiles_index < ssl->conf->dtls_srtp_profile_list_len; protection_profiles_index++ ) { profile_value = mbedtls_ssl_check_srtp_profile_value ( ssl->conf->dtls_srtp_profile_list[protection_profiles_index] ); if( profile_value != MBEDTLS_TLS_SRTP_UNSET ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_write_use_srtp_ext, add profile: %04x", profile_value ) ); *p++ = ( ( profile_value >> 8 ) & 0xFF ); *p++ = ( profile_value & 0xFF ); } else { /* * Note: we shall never arrive here as protection profiles * is checked by mbedtls_ssl_conf_dtls_srtp_protection_profiles function */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, " "illegal DTLS-SRTP protection profile %d", ssl->conf->dtls_srtp_profile_list[protection_profiles_index] ) ); return( MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED ); } } *p++ = mki_len & 0xFF; if( mki_len != 0 ) { memcpy( p, ssl->dtls_srtp_info.mki_value, mki_len ); /* * Increment p to point to the current position. */ p += mki_len; MBEDTLS_SSL_DEBUG_BUF( 3, "sending mki", ssl->dtls_srtp_info.mki_value, ssl->dtls_srtp_info.mki_len ); } /* * total extension length: extension type (2 bytes) * + extension length (2 bytes) * + protection profile length (2 bytes) * + 2 * number of protection profiles * + srtp_mki vector length(1 byte) * + mki value */ *olen = p - buf; return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_SRTP */ /* * Generate random bytes for ClientHello */ static int ssl_generate_random( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = ssl->handshake->randbytes; #if defined(MBEDTLS_HAVE_TIME) mbedtls_time_t t; #endif /* * When responding to a verify request, MUST reuse random (RFC 6347 4.2.1) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->verify_cookie != NULL ) { return( 0 ); } #endif #if defined(MBEDTLS_HAVE_TIME) t = mbedtls_time( NULL ); *p++ = (unsigned char)( t >> 24 ); *p++ = (unsigned char)( t >> 16 ); *p++ = (unsigned char)( t >> 8 ); *p++ = (unsigned char)( t ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, current time: %lu", t ) ); #else if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 ) return( ret ); p += 4; #endif /* MBEDTLS_HAVE_TIME */ if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 ) return( ret ); return( 0 ); } /** * \brief Validate cipher suite against config in SSL context. * * \param suite_info cipher suite to validate * \param ssl SSL context * \param min_minor_ver Minimal minor version to accept a cipher suite * \param max_minor_ver Maximal minor version to accept a cipher suite * * \return 0 if valid, else 1 */ static int ssl_validate_ciphersuite( const mbedtls_ssl_ciphersuite_t * suite_info, const mbedtls_ssl_context * ssl, int min_minor_ver, int max_minor_ver ) { (void) ssl; if( suite_info == NULL ) return( 1 ); if( suite_info->min_minor_ver > max_minor_ver || suite_info->max_minor_ver < min_minor_ver ) return( 1 ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) ) return( 1 ); #endif #if defined(MBEDTLS_ARC4_C) if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED && suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 ) return( 1 ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE && mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 ) return( 1 ); #endif /* Don't suggest PSK-based ciphersuite if no PSK is available. */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) && ssl_conf_has_static_psk( ssl->conf ) == 0 ) { return( 1 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ return( 0 ); } static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t i, n, olen, ext_len = 0; unsigned char *buf; unsigned char *p, *q; const unsigned char *end; unsigned char offer_compress; const int *ciphersuites; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) int uses_ec = 0; #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) ); if( ssl->conf->f_rng == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") ); return( MBEDTLS_ERR_SSL_NO_RNG ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) #endif { ssl->major_ver = ssl->conf->min_major_ver; ssl->minor_ver = ssl->conf->min_minor_ver; } if( ssl->conf->max_major_ver == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "configured max major version is invalid, consider using mbedtls_ssl_config_defaults()" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } buf = ssl->out_msg; end = buf + MBEDTLS_SSL_OUT_CONTENT_LEN; /* * Check if there's enough space for the first part of the ClientHello * consisting of the 38 bytes described below, the session identifier (at * most 32 bytes) and its length (1 byte). * * Use static upper bounds instead of the actual values * to allow the compiler to optimize this away. */ MBEDTLS_SSL_CHK_BUF_PTR( buf, end, 38 + 1 + 32 ); /* * The 38 first bytes of the ClientHello: * 0 . 0 handshake type (written later) * 1 . 3 handshake length (written later) * 4 . 5 highest version supported * 6 . 9 current UNIX time * 10 . 37 random bytes * * The current UNIX time (4 bytes) and following 28 random bytes are written * by ssl_generate_random() into ssl->handshake->randbytes buffer and then * copied from there into the output buffer. */ p = buf + 4; mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver, ssl->conf->transport, p ); p += 2; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]", buf[4], buf[5] ) ); if( ( ret = ssl_generate_random( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_generate_random", ret ); return( ret ); } memcpy( p, ssl->handshake->randbytes, 32 ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", p, 32 ); p += 32; /* * 38 . 38 session id length * 39 . 39+n session id * 39+n . 39+n DTLS only: cookie length (1 byte) * 40+n . .. DTLS only: cookie * .. . .. ciphersuitelist length (2 bytes) * .. . .. ciphersuitelist * .. . .. compression methods length (1 byte) * .. . .. compression methods * .. . .. extensions length (2 bytes) * .. . .. extensions */ n = ssl->session_negotiate->id_len; if( n < 16 || n > 32 || #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE || #endif ssl->handshake->resume == 0 ) { n = 0; } #if defined(MBEDTLS_SSL_SESSION_TICKETS) /* * RFC 5077 section 3.4: "When presenting a ticket, the client MAY * generate and include a Session ID in the TLS ClientHello." */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) #endif { if( ssl->session_negotiate->ticket != NULL && ssl->session_negotiate->ticket_len != 0 ) { ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 ); if( ret != 0 ) return( ret ); ssl->session_negotiate->id_len = n = 32; } } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ /* * The first check of the output buffer size above ( * MBEDTLS_SSL_CHK_BUF_PTR( buf, end, 38 + 1 + 32 );) * has checked that there is enough space in the output buffer for the * session identifier length byte and the session identifier (n <= 32). */ *p++ = (unsigned char) n; for( i = 0; i < n; i++ ) *p++ = ssl->session_negotiate->id[i]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %d", n ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 39, n ); /* * With 'n' being the length of the session identifier * * 39+n . 39+n DTLS only: cookie length (1 byte) * 40+n . .. DTLS only: cookie * .. . .. ciphersuitelist length (2 bytes) * .. . .. ciphersuitelist * .. . .. compression methods length (1 byte) * .. . .. compression methods * .. . .. extensions length (2 bytes) * .. . .. extensions */ /* * DTLS cookie */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { MBEDTLS_SSL_CHK_BUF_PTR( p, end, 1 ); if( ssl->handshake->verify_cookie == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) ); *p++ = 0; } else { MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie", ssl->handshake->verify_cookie, ssl->handshake->verify_cookie_len ); *p++ = ssl->handshake->verify_cookie_len; MBEDTLS_SSL_CHK_BUF_PTR( p, end, ssl->handshake->verify_cookie_len ); memcpy( p, ssl->handshake->verify_cookie, ssl->handshake->verify_cookie_len ); p += ssl->handshake->verify_cookie_len; } } #endif /* * Ciphersuite list */ ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; /* Skip writing ciphersuite length for now */ n = 0; q = p; MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); p += 2; for( i = 0; ciphersuites[i] != 0; i++ ) { ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] ); if( ssl_validate_ciphersuite( ciphersuite_info, ssl, ssl->conf->min_minor_ver, ssl->conf->max_minor_ver ) != 0 ) continue; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %#04x (%s)", ciphersuites[i], ciphersuite_info->name ) ); #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) uses_ec |= mbedtls_ssl_ciphersuite_uses_ec( ciphersuite_info ); #endif MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); n++; *p++ = (unsigned char)( ciphersuites[i] >> 8 ); *p++ = (unsigned char)( ciphersuites[i] ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites (excluding SCSVs)", n ) ); /* * Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) #endif { MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding EMPTY_RENEGOTIATION_INFO_SCSV" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 ); *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ); n++; } /* Some versions of OpenSSL don't handle it correctly if not at end */ #if defined(MBEDTLS_SSL_FALLBACK_SCSV) if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ); *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ); n++; } #endif *q++ = (unsigned char)( n >> 7 ); *q++ = (unsigned char)( n << 1 ); #if defined(MBEDTLS_ZLIB_SUPPORT) offer_compress = 1; #else offer_compress = 0; #endif /* * We don't support compression with DTLS right now: if many records come * in the same datagram, uncompressing one could overwrite the next one. * We don't want to add complexity for handling that case unless there is * an actual need for it. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) offer_compress = 0; #endif if( offer_compress ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d", MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 3 ); *p++ = 2; *p++ = MBEDTLS_SSL_COMPRESS_DEFLATE; *p++ = MBEDTLS_SSL_COMPRESS_NULL; } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 1 ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d", MBEDTLS_SSL_COMPRESS_NULL ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); *p++ = 1; *p++ = MBEDTLS_SSL_COMPRESS_NULL; } /* First write extensions, then the total length */ MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ( ret = ssl_write_hostname_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_hostname_ext", ret ); return( ret ); } ext_len += olen; #endif /* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added * even if MBEDTLS_SSL_RENEGOTIATION is not defined. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ( ret = ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_renegotiation_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) if( ( ret = ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_signature_algorithms_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( uses_ec ) { if( ( ret = ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_supported_elliptic_curves_ext", ret ); return( ret ); } ext_len += olen; if( ( ret = ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_supported_point_formats_ext", ret ); return( ret ); } ext_len += olen; } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ( ret = ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_ecjpake_kkpp_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( ( ret = ssl_write_cid_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_cid_ext", ret ); return( ret ); } ext_len += olen; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) if( ( ret = ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_max_fragment_length_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) if( ( ret = ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_truncated_hmac_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( ( ret = ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_encrypt_then_mac_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) if( ( ret = ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_extended_ms_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_ALPN) if( ( ret = ssl_write_alpn_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_alpn_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_DTLS_SRTP) if( ( ret = ssl_write_use_srtp_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_use_srtp_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) if( ( ret = ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_session_ticket_ext", ret ); return( ret ); } ext_len += olen; #endif /* olen unused if all extensions are disabled */ ((void) olen); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %d", ext_len ) ); if( ext_len > 0 ) { /* No need to check for space here, because the extension * writing functions already took care of that. */ *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); p += ext_len; } ssl->out_msglen = p - buf; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_HELLO; ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_send_flight_completed( ssl ); #endif if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client hello" ) ); return( 0 ); } static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { /* Check verify-data in constant-time. The length OTOH is no secret */ if( len != 1 + ssl->verify_data_len * 2 || buf[0] != ssl->verify_data_len * 2 || mbedtls_ssl_safer_memcmp( buf + 1, ssl->own_verify_data, ssl->verify_data_len ) != 0 || mbedtls_ssl_safer_memcmp( buf + 1 + ssl->verify_data_len, ssl->peer_verify_data, ssl->verify_data_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { if( len != 1 || buf[0] != 0x00 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; } return( 0 ); } #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { /* * server should use the extension only if we did, * and if so the server's value should match ours (and len is always 1) */ if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE || len != 1 || buf[0] != ssl->conf->mfl_code ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching max fragment length extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED || len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching truncated HMAC extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ((void) buf); ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED; return( 0 ); } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) static int ssl_parse_cid_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t peer_cid_len; if( /* CID extension only makes sense in DTLS */ ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM || /* The server must only send the CID extension if we have offered it. */ ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension unexpected" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } if( len == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } peer_cid_len = *buf++; len--; if( peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } if( len != peer_cid_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED; ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len; memcpy( ssl->handshake->peer_cid, buf, peer_cid_len ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use of CID extension negotiated" ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Server CID", buf, peer_cid_len ); return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 || len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching encrypt-then-MAC extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ((void) buf); ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED; return( 0 ); } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 || len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching extended master secret extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ((void) buf); ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED; return( 0 ); } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED || len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching session ticket extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ((void) buf); ssl->handshake->new_session_ticket = 1; return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_size; const unsigned char *p; if( len == 0 || (size_t)( buf[0] + 1 ) != len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } list_size = buf[0]; p = buf + 1; while( list_size > 0 ) { if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED || p[0] == MBEDTLS_ECP_PF_COMPRESSED ) { #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ssl->handshake->ecdh_ctx.point_format = p[0]; #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ssl->handshake->ecjpake_ctx.point_format = p[0]; #endif MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) ); return( 0 ); } list_size--; p++; } MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ssl->handshake->ciphersuite_info->key_exchange != MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) ); return( 0 ); } /* If we got here, we no longer need our cached extension */ mbedtls_free( ssl->handshake->ecjpake_cache ); ssl->handshake->ecjpake_cache = NULL; ssl->handshake->ecjpake_cache_len = 0; if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx, buf, len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( ret ); } return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_ALPN) static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_len, name_len; const char **p; /* If we didn't send it, the server shouldn't send it */ if( ssl->conf->alpn_list == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* * opaque ProtocolName<1..2^8-1>; * * struct { * ProtocolName protocol_name_list<2..2^16-1> * } ProtocolNameList; * * the "ProtocolNameList" MUST contain exactly one "ProtocolName" */ /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */ if( len < 4 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } list_len = ( buf[0] << 8 ) | buf[1]; if( list_len != len - 2 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } name_len = buf[2]; if( name_len != list_len - 1 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* Check that the server chosen protocol was in our list and save it */ for( p = ssl->conf->alpn_list; *p != NULL; p++ ) { if( name_len == strlen( *p ) && memcmp( buf + 3, *p, name_len ) == 0 ) { ssl->alpn_chosen = *p; return( 0 ); } } MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_DTLS_SRTP) static int ssl_parse_use_srtp_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { mbedtls_ssl_srtp_profile server_protection = MBEDTLS_TLS_SRTP_UNSET; size_t i, mki_len = 0; uint16_t server_protection_profile_value = 0; /* If use_srtp is not configured, just ignore the extension */ if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) || ( ssl->conf->dtls_srtp_profile_list == NULL ) || ( ssl->conf->dtls_srtp_profile_list_len == 0 ) ) return( 0 ); /* RFC 5764 section 4.1.1 * uint8 SRTPProtectionProfile[2]; * * struct { * SRTPProtectionProfiles SRTPProtectionProfiles; * opaque srtp_mki<0..255>; * } UseSRTPData; * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>; * */ if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED ) { mki_len = ssl->dtls_srtp_info.mki_len; } /* * Length is 5 + optional mki_value : one protection profile length (2 bytes) * + protection profile (2 bytes) * + mki_len(1 byte) * and optional srtp_mki */ if( ( len < 5 ) || ( len != ( buf[4] + 5u ) ) ) return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); /* * get the server protection profile */ /* * protection profile length must be 0x0002 as we must have only * one protection profile in server Hello */ if( ( buf[0] != 0 ) || ( buf[1] != 2 ) ) return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); server_protection_profile_value = ( buf[2] << 8 ) | buf[3]; server_protection = mbedtls_ssl_check_srtp_profile_value( server_protection_profile_value ); if( server_protection != MBEDTLS_TLS_SRTP_UNSET ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "found srtp profile: %s", mbedtls_ssl_get_srtp_profile_as_string( server_protection ) ) ); } ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET; /* * Check we have the server profile in our list */ for( i=0; i < ssl->conf->dtls_srtp_profile_list_len; i++) { if( server_protection == ssl->conf->dtls_srtp_profile_list[i] ) { ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "selected srtp profile: %s", mbedtls_ssl_get_srtp_profile_as_string( server_protection ) ) ); break; } } /* If no match was found : server problem, it shall never answer with incompatible profile */ if( ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* If server does not use mki in its reply, make sure the client won't keep * one as negotiated */ if( len == 5 ) { ssl->dtls_srtp_info.mki_len = 0; } /* * RFC5764: * If the client detects a nonzero-length MKI in the server's response * that is different than the one the client offered, then the client * MUST abort the handshake and SHOULD send an invalid_parameter alert. */ if( len > 5 && ( buf[4] != mki_len || ( memcmp( ssl->dtls_srtp_info.mki_value, &buf[5], mki_len ) ) ) ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } #if defined (MBEDTLS_DEBUG_C) if( len > 5 ) { MBEDTLS_SSL_DEBUG_BUF( 3, "received mki", ssl->dtls_srtp_info.mki_value, ssl->dtls_srtp_info.mki_len ); } #endif return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_SRTP */ /* * Parse HelloVerifyRequest. Only called after verifying the HS type. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl ) { const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); int major_ver, minor_ver; unsigned char cookie_len; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) ); /* Check that there is enough room for: * - 2 bytes of version * - 1 byte of cookie_len */ if( mbedtls_ssl_hs_hdr_len( ssl ) + 3 > ssl->in_msglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming HelloVerifyRequest message is too short" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* * struct { * ProtocolVersion server_version; * opaque cookie<0..2^8-1>; * } HelloVerifyRequest; */ MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 ); mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p ); p += 2; /* * Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1) * even is lower than our min version. */ if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 || minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 || major_ver > ssl->conf->max_major_ver || minor_ver > ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); } cookie_len = *p++; if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "cookie length does not match incoming message size" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len ); mbedtls_free( ssl->handshake->verify_cookie ); ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len ); if( ssl->handshake->verify_cookie == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } memcpy( ssl->handshake->verify_cookie, p, cookie_len ); ssl->handshake->verify_cookie_len = cookie_len; /* Start over at ClientHello */ ssl->state = MBEDTLS_SSL_CLIENT_HELLO; mbedtls_ssl_reset_checksum( ssl ); mbedtls_ssl_recv_flight_completed( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) { int ret, i; size_t n; size_t ext_len; unsigned char *buf, *ext; unsigned char comp; #if defined(MBEDTLS_ZLIB_SUPPORT) int accept_comp; #endif #if defined(MBEDTLS_SSL_RENEGOTIATION) int renegotiation_info_seen = 0; #endif int handshake_failure = 0; const mbedtls_ssl_ciphersuite_t *suite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) ); if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { /* No alert on a read error. */ MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } buf = ssl->in_msg; if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { ssl->renego_records_seen++; if( ssl->conf->renego_max_records >= 0 && ssl->renego_records_seen > ssl->conf->renego_max_records ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, but not honored by server" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-handshake message during renegotiation" ) ); ssl->keep_current_message = 1; return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) ); return( ssl_parse_hello_verify_request( ssl ) ); } else { /* We made it through the verification process */ mbedtls_free( ssl->handshake->verify_cookie ); ssl->handshake->verify_cookie = NULL; ssl->handshake->verify_cookie_len = 0; } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) || buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* * 0 . 1 server_version * 2 . 33 random (maybe including 4 bytes of Unix time) * 34 . 34 session_id length = n * 35 . 34+n session_id * 35+n . 36+n cipher_suite * 37+n . 37+n compression_method * * 38+n . 39+n extensions length (optional) * 40+n . .. extensions */ buf += mbedtls_ssl_hs_hdr_len( ssl ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf + 0, 2 ); mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver, ssl->conf->transport, buf + 0 ); if( ssl->major_ver < ssl->conf->min_major_ver || ssl->minor_ver < ssl->conf->min_minor_ver || ssl->major_ver > ssl->conf->max_major_ver || ssl->minor_ver > ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server version out of bounds - min: [%d:%d], server: [%d:%d], max: [%d:%d]", ssl->conf->min_major_ver, ssl->conf->min_minor_ver, ssl->major_ver, ssl->minor_ver, ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu", ( (uint32_t) buf[2] << 24 ) | ( (uint32_t) buf[3] << 16 ) | ( (uint32_t) buf[4] << 8 ) | ( (uint32_t) buf[5] ) ) ); memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 ); n = buf[34]; MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 2, 32 ); if( n > 32 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n ) { ext_len = ( ( buf[38 + n] << 8 ) | ( buf[39 + n] ) ); if( ( ext_len > 0 && ext_len < 4 ) || ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } } else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n ) { ext_len = 0; } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* ciphersuite (used later) */ i = ( buf[35 + n] << 8 ) | buf[36 + n]; /* * Read and check compression */ comp = buf[37 + n]; #if defined(MBEDTLS_ZLIB_SUPPORT) /* See comments in ssl_write_client_hello() */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) accept_comp = 0; else #endif accept_comp = 1; if( comp != MBEDTLS_SSL_COMPRESS_NULL && ( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) ) #else /* MBEDTLS_ZLIB_SUPPORT */ if( comp != MBEDTLS_SSL_COMPRESS_NULL ) #endif/* MBEDTLS_ZLIB_SUPPORT */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server hello, bad compression: %d", comp ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } /* * Initialize update checksum functions */ ssl->handshake->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i ); if( ssl->handshake->ciphersuite_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", i ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } mbedtls_ssl_optimize_checksum( ssl, ssl->handshake->ciphersuite_info ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 35, n ); /* * Check if the session can be resumed */ if( ssl->handshake->resume == 0 || n == 0 || #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE || #endif ssl->session_negotiate->ciphersuite != i || ssl->session_negotiate->compression != comp || ssl->session_negotiate->id_len != n || memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 ) { ssl->state++; ssl->handshake->resume = 0; #if defined(MBEDTLS_HAVE_TIME) ssl->session_negotiate->start = mbedtls_time( NULL ); #endif ssl->session_negotiate->ciphersuite = i; ssl->session_negotiate->compression = comp; ssl->session_negotiate->id_len = n; memcpy( ssl->session_negotiate->id, buf + 35, n ); } else { ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC; if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( ret ); } } MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed", ssl->handshake->resume ? "a" : "no" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) ); /* * Perform cipher suite validation in same way as in ssl_write_client_hello. */ i = 0; while( 1 ) { if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] == ssl->session_negotiate->ciphersuite ) { break; } } suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ); if( ssl_validate_ciphersuite( suite_info, ssl, ssl->minor_ver, ssl->minor_ver ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA && ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { ssl->handshake->ecrs_enabled = 1; } #endif if( comp != MBEDTLS_SSL_COMPRESS_NULL #if defined(MBEDTLS_ZLIB_SUPPORT) && comp != MBEDTLS_SSL_COMPRESS_DEFLATE #endif ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ssl->session_negotiate->compression = comp; ext = buf + 40 + n; MBEDTLS_SSL_DEBUG_MSG( 2, ( "server hello, total extension length: %d", ext_len ) ); while( ext_len ) { unsigned int ext_id = ( ( ext[0] << 8 ) | ( ext[1] ) ); unsigned int ext_size = ( ( ext[2] << 8 ) | ( ext[3] ) ); if( ext_size + 4 > ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } switch( ext_id ) { case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) renegotiation_info_seen = 1; #endif if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size ) ) != 0 ) return( ret ); break; #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max_fragment_length extension" ) ); if( ( ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) case MBEDTLS_TLS_EXT_TRUNCATED_HMAC: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated_hmac extension" ) ); if( ( ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) case MBEDTLS_TLS_EXT_CID: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found CID extension" ) ); if( ( ret = ssl_parse_cid_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) ); if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended_master_secret extension" ) ); if( ( ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) case MBEDTLS_TLS_EXT_SESSION_TICKET: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) ); if( ( ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported_point_formats extension" ) ); if( ( ret = ssl_parse_supported_point_formats_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_ECJPAKE_KKPP: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) ); if( ( ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_ALPN) case MBEDTLS_TLS_EXT_ALPN: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) ); if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_DTLS_SRTP) case MBEDTLS_TLS_EXT_USE_SRTP: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found use_srtp extension" ) ); if( ( ret = ssl_parse_use_srtp_ext( ssl, ext + 4, ext_size ) ) != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_DTLS_SRTP */ default: MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)", ext_id ) ); } ext_len -= 4 + ext_size; ext += 4 + ext_size; if( ext_len > 0 && ext_len < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } } /* * Renegotiation security checks */ if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) ); handshake_failure = 1; } #if defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION && renegotiation_info_seen == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && renegotiation_info_seen == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) ); handshake_failure = 1; } #endif /* MBEDTLS_SSL_RENEGOTIATION */ if( handshake_failure == 1 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) ); return( 0 ); } #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; /* * Ephemeral DH parameters: * * struct { * opaque dh_p<1..2^16-1>; * opaque dh_g<1..2^16-1>; * opaque dh_Ys<1..2^16-1>; * } ServerDHParams; */ if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret ); return( ret ); } if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %d < %d", ssl->handshake->dhm_ctx.len * 8, ssl->conf->dhm_min_bitlen ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl ) { const mbedtls_ecp_curve_info *curve_info; mbedtls_ecp_group_id grp_id; #if defined(MBEDTLS_ECDH_LEGACY_CONTEXT) grp_id = ssl->handshake->ecdh_ctx.grp.id; #else grp_id = ssl->handshake->ecdh_ctx.grp_id; #endif curve_info = mbedtls_ecp_curve_info_from_grp_id( grp_id ); if( curve_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) ); #if defined(MBEDTLS_ECP_C) if( mbedtls_ssl_check_curve( ssl, grp_id ) != 0 ) #else if( ssl->handshake->ecdh_ctx.grp.nbits < 163 || ssl->handshake->ecdh_ctx.grp.nbits > 521 ) #endif return( -1 ); MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_QP ); return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_USE_PSA_CRYPTO) && \ ( defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ) static int ssl_parse_server_ecdh_params_psa( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { uint16_t tls_id; size_t ecdh_bits = 0; uint8_t ecpoint_len; mbedtls_ssl_handshake_params *handshake = ssl->handshake; /* * Parse ECC group */ if( end - *p < 4 ) return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); /* First byte is curve_type; only named_curve is handled */ if( *(*p)++ != MBEDTLS_ECP_TLS_NAMED_CURVE ) return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); /* Next two bytes are the namedcurve value */ tls_id = *(*p)++; tls_id <<= 8; tls_id |= *(*p)++; /* Convert EC group to PSA key type. */ if( ( handshake->ecdh_psa_type = mbedtls_psa_parse_tls_ecc_group( tls_id, &ecdh_bits ) ) == 0 ) { return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } if( ecdh_bits > 0xffff ) return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); handshake->ecdh_bits = (uint16_t) ecdh_bits; /* * Put peer's ECDH public key in the format understood by PSA. */ ecpoint_len = *(*p)++; if( (size_t)( end - *p ) < ecpoint_len ) return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); if( mbedtls_psa_tls_ecpoint_to_psa_ec( *p, ecpoint_len, handshake->ecdh_psa_peerkey, sizeof( handshake->ecdh_psa_peerkey ), &handshake->ecdh_psa_peerkey_len ) != 0 ) { return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } *p += ecpoint_len; return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO && ( MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ) */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; /* * Ephemeral ECDH parameters: * * struct { * ECParameters curve_params; * ECPoint public; * } ServerECDHParams; */ if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx, (const unsigned char **) p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; #endif return( ret ); } if( ssl_check_server_ecdh_params( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (ECDHE curve)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; uint16_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( end - (*p) < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( end - (*p) < len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) /* * Generate a pre-master secret and encrypt it with the server's RSA key */ static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl, size_t offset, size_t *olen, size_t pms_offset ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2; unsigned char *p = ssl->handshake->premaster + pms_offset; mbedtls_pk_context * peer_pk; if( offset + len_bytes > MBEDTLS_SSL_OUT_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* * Generate (part of) the pre-master as * struct { * ProtocolVersion client_version; * opaque random[46]; * } PreMasterSecret; */ mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver, ssl->conf->transport, p ); if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret ); return( ret ); } ssl->handshake->pmslen = 48; #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) peer_pk = &ssl->handshake->peer_pubkey; #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert == NULL ) { /* Should never happen */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } peer_pk = &ssl->session_negotiate->peer_cert->pk; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* * Now write it out, encrypted */ if( ! mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_RSA ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } if( ( ret = mbedtls_pk_encrypt( peer_pk, p, ssl->handshake->pmslen, ssl->out_msg + offset + len_bytes, olen, MBEDTLS_SSL_OUT_CONTENT_LEN - offset - len_bytes, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( len_bytes == 2 ) { ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 ); ssl->out_msg[offset+1] = (unsigned char)( *olen ); *olen += 2; } #endif #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* We don't need the peer's public key anymore. Free it. */ mbedtls_pk_free( peer_pk ); #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end, mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg ) { ((void) ssl); *md_alg = MBEDTLS_MD_NONE; *pk_alg = MBEDTLS_PK_NONE; /* Only in TLS 1.2 */ if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) { return( 0 ); } if( (*p) + 2 > end ) return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); /* * Get hash algorithm */ if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported HashAlgorithm %d", *(p)[0] ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Get signature algorithm */ if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported SignatureAlgorithm %d", (*p)[1] ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Check if the hash is acceptable */ if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm %d that was not offered", *(p)[0] ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) ); *p += 2; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const mbedtls_ecp_keypair *peer_key; mbedtls_pk_context * peer_pk; #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) peer_pk = &ssl->handshake->peer_pubkey; #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert == NULL ) { /* Should never happen */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } peer_pk = &ssl->session_negotiate->peer_cert->pk; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ! mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_ECKEY ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } peer_key = mbedtls_pk_ec( *peer_pk ); if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key, MBEDTLS_ECDH_THEIRS ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret ); return( ret ); } if( ssl_check_server_ecdh_params( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* We don't need the peer's public key anymore. Free it, * so that more RAM is available for upcoming expensive * operations like ECDHE. */ mbedtls_pk_free( peer_pk ); #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; unsigned char *p = NULL, *end = NULL; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) ); #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) ); ssl->state++; return( 0 ); } ((void) p); ((void) end); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ) { if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) ); ssl->state++; return( 0 ); } ((void) p); ((void) end); #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled && ssl->handshake->ecrs_state == ssl_ecrs_ske_start_processing ) { goto start_processing; } #endif if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server * doesn't use a psk_identity_hint */ if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE ) { if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { /* Current message is probably either * CertificateRequest or ServerHelloDone */ ssl->keep_current_message = 1; goto exit; } MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must not be skipped" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) ssl->handshake->ecrs_state = ssl_ecrs_ske_start_processing; start_processing: #endif p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); end = ssl->in_msg + ssl->in_hslen; MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p ); #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } /* FALLTROUGH */ #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) ; /* nothing more to do */ else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_USE_PSA_CRYPTO) && \ ( defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) { if( ssl_parse_server_ecdh_params_psa( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_USE_PSA_CRYPTO && ( MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ) */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) { if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx, p, end - p ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) ) { size_t sig_len, hashlen; unsigned char hash[64]; mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE; mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE; unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); size_t params_len = p - params; void *rs_ctx = NULL; mbedtls_pk_context * peer_pk; /* * Handle the digitally-signed structure */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { if( ssl_parse_signature_algorithm( ssl, &p, end, &md_alg, &pk_alg ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) { pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); /* Default hash for ECDSA is SHA-1 */ if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE ) md_alg = MBEDTLS_MD_SHA1; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Read signature */ if( p > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } sig_len = ( p[0] << 8 ) | p[1]; p += 2; if( p != end - sig_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len ); /* * Compute the hash that has been signed */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( md_alg == MBEDTLS_MD_NONE ) { hashlen = 36; ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params, params_len ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( md_alg != MBEDTLS_MD_NONE ) { ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen, params, params_len, md_alg ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen ); #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) peer_pk = &ssl->handshake->peer_pubkey; #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert == NULL ) { /* Should never happen */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } peer_pk = &ssl->session_negotiate->peer_cert->pk; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* * Verify signature */ if( !mbedtls_pk_can_do( peer_pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) rs_ctx = &ssl->handshake->ecrs_ctx.pk; #endif if( ( ret = mbedtls_pk_verify_restartable( peer_pk, md_alg, hash, hashlen, p, sig_len, rs_ctx ) ) != 0 ) { #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) #endif mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR ); MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; #endif return( ret ); } #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* We don't need the peer's public key anymore. Free it, * so that more RAM is available for upcoming expensive * operations like ECDHE. */ mbedtls_pk_free( peer_pk ); #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ exit: ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) ); return( 0 ); } #if ! defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) ); if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *buf; size_t n = 0; size_t cert_type_len = 0, dn_len = 0; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) ); if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) ); ssl->state++; return( 0 ); } if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } ssl->state++; ssl->client_auth = ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request", ssl->client_auth ? "a" : "no" ) ); if( ssl->client_auth == 0 ) { /* Current message is probably the ServerHelloDone */ ssl->keep_current_message = 1; goto exit; } /* * struct { * ClientCertificateType certificate_types<1..2^8-1>; * SignatureAndHashAlgorithm * supported_signature_algorithms<2^16-1>; -- TLS 1.2 only * DistinguishedName certificate_authorities<0..2^16-1>; * } CertificateRequest; * * Since we only support a single certificate on clients, let's just * ignore all the information that's supposed to help us pick a * certificate. * * We could check that our certificate matches the request, and bail out * if it doesn't, but it's simpler to just send the certificate anyway, * and give the server the opportunity to decide if it should terminate * the connection when it doesn't like our certificate. * * Same goes for the hash in TLS 1.2's signature_algorithms: at this * point we only have one hash available (see comments in * write_certificate_verify), so let's just use what we have. * * However, we still minimally parse the message to check it is at least * superficially sane. */ buf = ssl->in_msg; /* certificate_types */ if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); } cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )]; n = cert_type_len; /* * In the subsequent code there are two paths that read from buf: * * the length of the signature algorithms field (if minor version of * SSL is 3), * * distinguished name length otherwise. * Both reach at most the index: * ...hdr_len + 2 + n, * therefore the buffer length at this point must be greater than that * regardless of the actual code path. */ if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); } /* supported_signature_algorithms */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 ) | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) ); #if defined(MBEDTLS_DEBUG_C) unsigned char* sig_alg; size_t i; #endif /* * The furthest access in buf is in the loop few lines below: * sig_alg[i + 1], * where: * sig_alg = buf + ...hdr_len + 3 + n, * max(i) = sig_alg_len - 1. * Therefore the furthest access is: * buf[...hdr_len + 3 + n + sig_alg_len - 1 + 1], * which reduces to: * buf[...hdr_len + 3 + n + sig_alg_len], * which is one less than we need the buf to be. */ if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n + sig_alg_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); } #if defined(MBEDTLS_DEBUG_C) sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n; for( i = 0; i < sig_alg_len; i += 2 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d,%d", sig_alg[i], sig_alg[i + 1] ) ); } #endif n += 2 + sig_alg_len; } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ /* certificate_authorities */ dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 ) | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) ); n += dn_len; if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); } exit: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) ); return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) ); if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) || ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE ); } ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_recv_flight_completed( ssl ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) ); return( 0 ); } static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t header_len; size_t content_len; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) ); #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ) { /* * DHM key exchange -- send G^X mod P */ content_len = ssl->handshake->dhm_ctx.len; ssl->out_msg[4] = (unsigned char)( content_len >> 8 ); ssl->out_msg[5] = (unsigned char)( content_len ); header_len = 6; ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx, (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ), &ssl->out_msg[header_len], content_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX ); if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx, ssl->handshake->premaster, MBEDTLS_PREMASTER_SIZE, &ssl->handshake->pmslen, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K ); } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */ #if defined(MBEDTLS_USE_PSA_CRYPTO) && \ ( defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) { psa_status_t status; psa_key_attributes_t key_attributes; mbedtls_ssl_handshake_params *handshake = ssl->handshake; unsigned char own_pubkey[MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH]; size_t own_pubkey_len; unsigned char *own_pubkey_ecpoint; size_t own_pubkey_ecpoint_len; header_len = 4; MBEDTLS_SSL_DEBUG_MSG( 1, ( "Perform PSA-based ECDH computation." ) ); /* * Generate EC private key for ECDHE exchange. */ /* The master secret is obtained from the shared ECDH secret by * applying the TLS 1.2 PRF with a specific salt and label. While * the PSA Crypto API encourages combining key agreement schemes * such as ECDH with fixed KDFs such as TLS 1.2 PRF, it does not * yet support the provisioning of salt + label to the KDF. * For the time being, we therefore need to split the computation * of the ECDH secret and the application of the TLS 1.2 PRF. */ key_attributes = psa_key_attributes_init(); psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE ); psa_set_key_algorithm( &key_attributes, PSA_ALG_ECDH ); psa_set_key_type( &key_attributes, handshake->ecdh_psa_type ); psa_set_key_bits( &key_attributes, handshake->ecdh_bits ); /* Generate ECDH private key. */ status = psa_generate_key( &key_attributes, &handshake->ecdh_psa_privkey ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); /* Export the public part of the ECDH private key from PSA * and convert it to ECPoint format used in ClientKeyExchange. */ status = psa_export_public_key( handshake->ecdh_psa_privkey, own_pubkey, sizeof( own_pubkey ), &own_pubkey_len ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); if( mbedtls_psa_tls_psa_ec_to_ecpoint( own_pubkey, own_pubkey_len, &own_pubkey_ecpoint, &own_pubkey_ecpoint_len ) != 0 ) { return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } /* Copy ECPoint structure to outgoing message buffer. */ ssl->out_msg[header_len] = (unsigned char) own_pubkey_ecpoint_len; memcpy( ssl->out_msg + header_len + 1, own_pubkey_ecpoint, own_pubkey_ecpoint_len ); content_len = own_pubkey_ecpoint_len + 1; /* The ECDH secret is the premaster secret used for key derivation. */ /* Compute ECDH shared secret. */ status = psa_raw_key_agreement( PSA_ALG_ECDH, handshake->ecdh_psa_privkey, handshake->ecdh_psa_peerkey, handshake->ecdh_psa_peerkey_len, ssl->handshake->premaster, sizeof( ssl->handshake->premaster ), &ssl->handshake->pmslen ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); status = psa_destroy_key( handshake->ecdh_psa_privkey ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT; } else #endif /* MBEDTLS_USE_PSA_CRYPTO && ( MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ) */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ) { /* * ECDH key exchange -- send client public value */ header_len = 4; #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) { if( ssl->handshake->ecrs_state == ssl_ecrs_cke_ecdh_calc_secret ) goto ecdh_calc_secret; mbedtls_ecdh_enable_restart( &ssl->handshake->ecdh_ctx ); } #endif ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &content_len, &ssl->out_msg[header_len], 1000, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; #endif return( ret ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Q ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) { ssl->handshake->ecrs_n = content_len; ssl->handshake->ecrs_state = ssl_ecrs_cke_ecdh_calc_secret; } ecdh_calc_secret: if( ssl->handshake->ecrs_enabled ) content_len = ssl->handshake->ecrs_n; #endif if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &ssl->handshake->pmslen, ssl->handshake->premaster, MBEDTLS_MPI_MAX_SIZE, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; #endif return( ret ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Z ); } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) ) { /* * opaque psk_identity<0..2^16-1>; */ if( ssl_conf_has_static_psk( ssl->conf ) == 0 ) { /* We don't offer PSK suites if we don't have a PSK, * and we check that the server's choice is among the * ciphersuites we offered, so this should never happen. */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } header_len = 4; content_len = ssl->conf->psk_identity_len; if( header_len + 2 + content_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or SSL buffer too short" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } ssl->out_msg[header_len++] = (unsigned char)( content_len >> 8 ); ssl->out_msg[header_len++] = (unsigned char)( content_len ); memcpy( ssl->out_msg + header_len, ssl->conf->psk_identity, ssl->conf->psk_identity_len ); header_len += ssl->conf->psk_identity_len; #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ) { content_len = 0; } else #endif #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only suites. */ if( ssl_conf_has_static_raw_psk( ssl->conf ) == 0 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = ssl_write_encrypted_pms( ssl, header_len, &content_len, 2 ) ) != 0 ) return( ret ); } else #endif #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only suites. */ if( ssl_conf_has_static_raw_psk( ssl->conf ) == 0 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ /* * ClientDiffieHellmanPublic public (DHM send G^X mod P) */ content_len = ssl->handshake->dhm_ctx.len; if( header_len + 2 + content_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long or SSL buffer too short" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } ssl->out_msg[header_len++] = (unsigned char)( content_len >> 8 ); ssl->out_msg[header_len++] = (unsigned char)( content_len ); ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx, (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ), &ssl->out_msg[header_len], content_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only suites. */ if( ssl_conf_has_static_raw_psk( ssl->conf ) == 0 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ /* * ClientECDiffieHellmanPublic public; */ ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &content_len, &ssl->out_msg[header_len], MBEDTLS_SSL_OUT_CONTENT_LEN - header_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Q ); } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) && \ defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK && ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 && ssl_conf_has_static_raw_psk( ssl->conf ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "skip PMS generation for opaque PSK" ) ); } else #endif /* MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) { header_len = 4; if( ( ret = ssl_write_encrypted_pms( ssl, header_len, &content_len, 0 ) ) != 0 ) return( ret ); } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { header_len = 4; ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx, ssl->out_msg + header_len, MBEDTLS_SSL_OUT_CONTENT_LEN - header_len, &content_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret ); return( ret ); } ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx, ssl->handshake->premaster, 32, &ssl->handshake->pmslen, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ { ((void) ciphersuite_info); MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->out_msglen = header_len + content_len; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE; ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) ); return( 0 ); } #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) ); if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); return( ret ); } if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; size_t n = 0, offset = 0; unsigned char hash[48]; unsigned char *hash_start = hash; mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE; size_t hashlen; void *rs_ctx = NULL; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled && ssl->handshake->ecrs_state == ssl_ecrs_crt_vrfy_sign ) { goto sign; } #endif if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); return( ret ); } if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) ); ssl->state++; return( 0 ); } if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) ); ssl->state++; return( 0 ); } if( mbedtls_ssl_own_key( ssl ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* * Make a signature of the handshake digests */ #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) ssl->handshake->ecrs_state = ssl_ecrs_crt_vrfy_sign; sign: #endif ssl->handshake->calc_verify( ssl, hash, &hashlen ); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) { /* * digitally-signed struct { * opaque md5_hash[16]; * opaque sha_hash[20]; * }; * * md5_hash * MD5(handshake_messages); * * sha_hash * SHA(handshake_messages); */ md_alg = MBEDTLS_MD_NONE; /* * For ECDSA, default hash is SHA-1 only */ if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) ) { hash_start += 16; hashlen -= 16; md_alg = MBEDTLS_MD_SHA1; } } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { /* * digitally-signed struct { * opaque handshake_messages[handshake_messages_length]; * }; * * Taking shortcut here. We assume that the server always allows the * PRF Hash function and has sent it in the allowed signature * algorithms list received in the Certificate Request message. * * Until we encounter a server that does not, we will take this * shortcut. * * Reason: Otherwise we should have running hashes for SHA512 and * SHA224 in order to satisfy 'weird' needs from the server * side. */ if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) { md_alg = MBEDTLS_MD_SHA384; ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384; } else { md_alg = MBEDTLS_MD_SHA256; ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256; } ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) ); /* Info from md_alg will be used instead */ hashlen = 0; offset = 2; } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) rs_ctx = &ssl->handshake->ecrs_ctx.pk; #endif if( ( ret = mbedtls_pk_sign_restartable( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen, ssl->out_msg + 6 + offset, &n, ssl->conf->f_rng, ssl->conf->p_rng, rs_ctx ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; #endif return( ret ); } ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 ); ssl->out_msg[5 + offset] = (unsigned char)( n ); ssl->out_msglen = 6 + n + offset; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY; ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; uint32_t lifetime; size_t ticket_len; unsigned char *ticket; const unsigned char *msg; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) ); if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* * struct { * uint32 ticket_lifetime_hint; * opaque ticket<0..2^16-1>; * } NewSessionTicket; * * 0 . 3 ticket_lifetime_hint * 4 . 5 ticket_len (n) * 6 . 5+n ticket content */ if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET || ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET ); } msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); lifetime = ( ((uint32_t) msg[0]) << 24 ) | ( msg[1] << 16 ) | ( msg[2] << 8 ) | ( msg[3] ); ticket_len = ( msg[4] << 8 ) | ( msg[5] ); if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", ticket_len ) ); /* We're not waiting for a NewSessionTicket message any more */ ssl->handshake->new_session_ticket = 0; ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC; /* * Zero-length ticket means the server changed his mind and doesn't want * to send a ticket after all, so just forget it */ if( ticket_len == 0 ) return( 0 ); if( ssl->session != NULL && ssl->session->ticket != NULL ) { mbedtls_platform_zeroize( ssl->session->ticket, ssl->session->ticket_len ); mbedtls_free( ssl->session->ticket ); ssl->session->ticket = NULL; ssl->session->ticket_len = 0; } mbedtls_platform_zeroize( ssl->session_negotiate->ticket, ssl->session_negotiate->ticket_len ); mbedtls_free( ssl->session_negotiate->ticket ); ssl->session_negotiate->ticket = NULL; ssl->session_negotiate->ticket_len = 0; if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } memcpy( ticket, msg + 6, ticket_len ); ssl->session_negotiate->ticket = ticket; ssl->session_negotiate->ticket_len = ticket_len; ssl->session_negotiate->ticket_lifetime = lifetime; /* * RFC 5077 section 3.4: * "If the client receives a session ticket from the server, then it * discards any Session ID that was sent in the ServerHello." */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) ); ssl->session_negotiate->id_len = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ /* * SSL handshake -- client side -- single step */ int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl ) { int ret = 0; if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) ); if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* Change state now, so that it is right in mbedtls_ssl_read_record(), used * by DTLS for dropping out-of-sequence ChangeCipherSpec records */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC && ssl->handshake->new_session_ticket != 0 ) { ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET; } #endif switch( ssl->state ) { case MBEDTLS_SSL_HELLO_REQUEST: ssl->state = MBEDTLS_SSL_CLIENT_HELLO; break; /* * ==> ClientHello */ case MBEDTLS_SSL_CLIENT_HELLO: ret = ssl_write_client_hello( ssl ); break; /* * <== ServerHello * Certificate * ( ServerKeyExchange ) * ( CertificateRequest ) * ServerHelloDone */ case MBEDTLS_SSL_SERVER_HELLO: ret = ssl_parse_server_hello( ssl ); break; case MBEDTLS_SSL_SERVER_CERTIFICATE: ret = mbedtls_ssl_parse_certificate( ssl ); break; case MBEDTLS_SSL_SERVER_KEY_EXCHANGE: ret = ssl_parse_server_key_exchange( ssl ); break; case MBEDTLS_SSL_CERTIFICATE_REQUEST: ret = ssl_parse_certificate_request( ssl ); break; case MBEDTLS_SSL_SERVER_HELLO_DONE: ret = ssl_parse_server_hello_done( ssl ); break; /* * ==> ( Certificate/Alert ) * ClientKeyExchange * ( CertificateVerify ) * ChangeCipherSpec * Finished */ case MBEDTLS_SSL_CLIENT_CERTIFICATE: ret = mbedtls_ssl_write_certificate( ssl ); break; case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE: ret = ssl_write_client_key_exchange( ssl ); break; case MBEDTLS_SSL_CERTIFICATE_VERIFY: ret = ssl_write_certificate_verify( ssl ); break; case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC: ret = mbedtls_ssl_write_change_cipher_spec( ssl ); break; case MBEDTLS_SSL_CLIENT_FINISHED: ret = mbedtls_ssl_write_finished( ssl ); break; /* * <== ( NewSessionTicket ) * ChangeCipherSpec * Finished */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET: ret = ssl_parse_new_session_ticket( ssl ); break; #endif case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC: ret = mbedtls_ssl_parse_change_cipher_spec( ssl ); break; case MBEDTLS_SSL_SERVER_FINISHED: ret = mbedtls_ssl_parse_finished( ssl ); break; case MBEDTLS_SSL_FLUSH_BUFFERS: MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) ); ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; break; case MBEDTLS_SSL_HANDSHAKE_WRAPUP: mbedtls_ssl_handshake_wrapup( ssl ); break; default: MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } return( ret ); } #endif /* MBEDTLS_SSL_CLI_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_cookie.c
/* * DTLS cookie callbacks implementation * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These session callbacks use a simple chained list * to store and retrieve the session information. */ #include "common.h" #if defined(MBEDTLS_SSL_COOKIE_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/ssl_cookie.h" #include "mbedtls/ssl_internal.h" #include "mbedtls/error.h" #include "mbedtls/platform_util.h" #include <string.h> /* * If DTLS is in use, then at least one of SHA-1, SHA-256, SHA-512 is * available. Try SHA-256 first, 512 wastes resources since we need to stay * with max 32 bytes of cookie for DTLS 1.0 */ #if defined(MBEDTLS_SHA256_C) #define COOKIE_MD MBEDTLS_MD_SHA224 #define COOKIE_MD_OUTLEN 32 #define COOKIE_HMAC_LEN 28 #elif defined(MBEDTLS_SHA512_C) #define COOKIE_MD MBEDTLS_MD_SHA384 #define COOKIE_MD_OUTLEN 48 #define COOKIE_HMAC_LEN 28 #elif defined(MBEDTLS_SHA1_C) #define COOKIE_MD MBEDTLS_MD_SHA1 #define COOKIE_MD_OUTLEN 20 #define COOKIE_HMAC_LEN 20 #else #error "DTLS hello verify needs SHA-1 or SHA-2" #endif /* * Cookies are formed of a 4-bytes timestamp (or serial number) and * an HMAC of timestemp and client ID. */ #define COOKIE_LEN ( 4 + COOKIE_HMAC_LEN ) void mbedtls_ssl_cookie_init( mbedtls_ssl_cookie_ctx *ctx ) { mbedtls_md_init( &ctx->hmac_ctx ); #if !defined(MBEDTLS_HAVE_TIME) ctx->serial = 0; #endif ctx->timeout = MBEDTLS_SSL_COOKIE_TIMEOUT; #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_init( &ctx->mutex ); #endif } void mbedtls_ssl_cookie_set_timeout( mbedtls_ssl_cookie_ctx *ctx, unsigned long delay ) { ctx->timeout = delay; } void mbedtls_ssl_cookie_free( mbedtls_ssl_cookie_ctx *ctx ) { mbedtls_md_free( &ctx->hmac_ctx ); #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_free( &ctx->mutex ); #endif mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ssl_cookie_ctx ) ); } int mbedtls_ssl_cookie_setup( mbedtls_ssl_cookie_ctx *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char key[COOKIE_MD_OUTLEN]; if( ( ret = f_rng( p_rng, key, sizeof( key ) ) ) != 0 ) return( ret ); ret = mbedtls_md_setup( &ctx->hmac_ctx, mbedtls_md_info_from_type( COOKIE_MD ), 1 ); if( ret != 0 ) return( ret ); ret = mbedtls_md_hmac_starts( &ctx->hmac_ctx, key, sizeof( key ) ); if( ret != 0 ) return( ret ); mbedtls_platform_zeroize( key, sizeof( key ) ); return( 0 ); } /* * Generate the HMAC part of a cookie */ static int ssl_cookie_hmac( mbedtls_md_context_t *hmac_ctx, const unsigned char time[4], unsigned char **p, unsigned char *end, const unsigned char *cli_id, size_t cli_id_len ) { unsigned char hmac_out[COOKIE_MD_OUTLEN]; MBEDTLS_SSL_CHK_BUF_PTR( *p, end, COOKIE_HMAC_LEN ); if( mbedtls_md_hmac_reset( hmac_ctx ) != 0 || mbedtls_md_hmac_update( hmac_ctx, time, 4 ) != 0 || mbedtls_md_hmac_update( hmac_ctx, cli_id, cli_id_len ) != 0 || mbedtls_md_hmac_finish( hmac_ctx, hmac_out ) != 0 ) { return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } memcpy( *p, hmac_out, COOKIE_HMAC_LEN ); *p += COOKIE_HMAC_LEN; return( 0 ); } /* * Generate cookie for DTLS ClientHello verification */ int mbedtls_ssl_cookie_write( void *p_ctx, unsigned char **p, unsigned char *end, const unsigned char *cli_id, size_t cli_id_len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_ssl_cookie_ctx *ctx = (mbedtls_ssl_cookie_ctx *) p_ctx; unsigned long t; if( ctx == NULL || cli_id == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_CHK_BUF_PTR( *p, end, COOKIE_LEN ); #if defined(MBEDTLS_HAVE_TIME) t = (unsigned long) mbedtls_time( NULL ); #else t = ctx->serial++; #endif (*p)[0] = (unsigned char)( t >> 24 ); (*p)[1] = (unsigned char)( t >> 16 ); (*p)[2] = (unsigned char)( t >> 8 ); (*p)[3] = (unsigned char)( t ); *p += 4; #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR + ret ); #endif ret = ssl_cookie_hmac( &ctx->hmac_ctx, *p - 4, p, end, cli_id, cli_id_len ); #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR + MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif return( ret ); } /* * Check a cookie */ int mbedtls_ssl_cookie_check( void *p_ctx, const unsigned char *cookie, size_t cookie_len, const unsigned char *cli_id, size_t cli_id_len ) { unsigned char ref_hmac[COOKIE_HMAC_LEN]; int ret = 0; unsigned char *p = ref_hmac; mbedtls_ssl_cookie_ctx *ctx = (mbedtls_ssl_cookie_ctx *) p_ctx; unsigned long cur_time, cookie_time; if( ctx == NULL || cli_id == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( cookie_len != COOKIE_LEN ) return( -1 ); #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR + ret ); #endif if( ssl_cookie_hmac( &ctx->hmac_ctx, cookie, &p, p + sizeof( ref_hmac ), cli_id, cli_id_len ) != 0 ) ret = -1; #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR + MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif if( ret != 0 ) return( ret ); if( mbedtls_ssl_safer_memcmp( cookie + 4, ref_hmac, sizeof( ref_hmac ) ) != 0 ) return( -1 ); #if defined(MBEDTLS_HAVE_TIME) cur_time = (unsigned long) mbedtls_time( NULL ); #else cur_time = ctx->serial; #endif cookie_time = ( (unsigned long) cookie[0] << 24 ) | ( (unsigned long) cookie[1] << 16 ) | ( (unsigned long) cookie[2] << 8 ) | ( (unsigned long) cookie[3] ); if( ctx->timeout != 0 && cur_time - cookie_time > ctx->timeout ) return( -1 ); return( 0 ); } #endif /* MBEDTLS_SSL_COOKIE_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_invasive.h
/** * \file ssl_invasive.h * * \brief SSL module: interfaces for invasive testing only. * * The interfaces in this file are intended for testing purposes only. * They SHOULD NOT be made available in library integrations except when * building the library for testing. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_SSL_INVASIVE_H #define MBEDTLS_SSL_INVASIVE_H #include "common.h" #include "mbedtls/md.h" #if defined(MBEDTLS_TEST_HOOKS) && \ defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC) /** \brief Compute the HMAC of variable-length data with constant flow. * * This function computes the HMAC of the concatenation of \p add_data and \p * data, and does with a code flow and memory access pattern that does not * depend on \p data_len_secret, but only on \p min_data_len and \p * max_data_len. In particular, this function always reads exactly \p * max_data_len bytes from \p data. * * \param ctx The HMAC context. It must have keys configured * with mbedtls_md_hmac_starts() and use one of the * following hashes: SHA-384, SHA-256, SHA-1 or MD-5. * It is reset using mbedtls_md_hmac_reset() after * the computation is complete to prepare for the * next computation. * \param add_data The additional data prepended to \p data. This * must point to a readable buffer of \p add_data_len * bytes. * \param add_data_len The length of \p add_data in bytes. * \param data The data appended to \p add_data. This must point * to a readable buffer of \p max_data_len bytes. * \param data_len_secret The length of the data to process in \p data. * This must be no less than \p min_data_len and no * greater than \p max_data_len. * \param min_data_len The minimal length of \p data in bytes. * \param max_data_len The maximal length of \p data in bytes. * \param output The HMAC will be written here. This must point to * a writable buffer of sufficient size to hold the * HMAC value. * * \retval 0 * Success. * \retval MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED * The hardware accelerator failed. */ int mbedtls_ssl_cf_hmac( mbedtls_md_context_t *ctx, const unsigned char *add_data, size_t add_data_len, const unsigned char *data, size_t data_len_secret, size_t min_data_len, size_t max_data_len, unsigned char *output ); /** \brief Copy data from a secret position with constant flow. * * This function copies \p len bytes from \p src_base + \p offset_secret to \p * dst, with a code flow and memory access pattern that does not depend on \p * offset_secret, but only on \p offset_min, \p offset_max and \p len. * * \param dst The destination buffer. This must point to a writable * buffer of at least \p len bytes. * \param src_base The base of the source buffer. This must point to a * readable buffer of at least \p offset_max + \p len * bytes. * \param offset_secret The offset in the source buffer from which to copy. * This must be no less than \p offset_min and no greater * than \p offset_max. * \param offset_min The minimal value of \p offset_secret. * \param offset_max The maximal value of \p offset_secret. * \param len The number of bytes to copy. */ void mbedtls_ssl_cf_memcpy_offset( unsigned char *dst, const unsigned char *src_base, size_t offset_secret, size_t offset_min, size_t offset_max, size_t len ); #endif /* MBEDTLS_TEST_HOOKS && MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */ #endif /* MBEDTLS_SSL_INVASIVE_H */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_msg.c
/* * Generic SSL/TLS messaging layer functions * (record layer + retransmission state machine) * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The SSL 3.0 specification was drafted by Netscape in 1996, * and became an IETF standard in 1999. * * http://wp.netscape.com/eng/ssl3/ * http://www.ietf.org/rfc/rfc2246.txt * http://www.ietf.org/rfc/rfc4346.txt */ #include "common.h" #if defined(MBEDTLS_SSL_TLS_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/ssl.h" #include "mbedtls/ssl_internal.h" #include "mbedtls/debug.h" #include "mbedtls/error.h" #include "mbedtls/platform_util.h" #include "mbedtls/version.h" #include "ssl_invasive.h" #include <string.h> #if defined(MBEDTLS_USE_PSA_CRYPTO) #include "mbedtls/psa_util.h" #include "psa/crypto.h" #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) #include "mbedtls/oid.h" #endif static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl ); /* * Start a timer. * Passing millisecs = 0 cancels a running timer. */ void mbedtls_ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs ) { if( ssl->f_set_timer == NULL ) return; MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) ); ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs ); } /* * Return -1 is timer is expired, 0 if it isn't. */ int mbedtls_ssl_check_timer( mbedtls_ssl_context *ssl ) { if( ssl->f_get_timer == NULL ) return( 0 ); if( ssl->f_get_timer( ssl->p_timer ) == 2 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) ); return( -1 ); } return( 0 ); } #if defined(MBEDTLS_SSL_RECORD_CHECKING) static int ssl_parse_record_header( mbedtls_ssl_context const *ssl, unsigned char *buf, size_t len, mbedtls_record *rec ); int mbedtls_ssl_check_record( mbedtls_ssl_context const *ssl, unsigned char *buf, size_t buflen ) { int ret = 0; MBEDTLS_SSL_DEBUG_MSG( 1, ( "=> mbedtls_ssl_check_record" ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "record buffer", buf, buflen ); /* We don't support record checking in TLS because * (a) there doesn't seem to be a usecase for it, and * (b) In SSLv3 and TLS 1.0, CBC record decryption has state * and we'd need to backup the transform here. */ if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM ) { ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; goto exit; } #if defined(MBEDTLS_SSL_PROTO_DTLS) else { mbedtls_record rec; ret = ssl_parse_record_header( ssl, buf, buflen, &rec ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 3, "ssl_parse_record_header", ret ); goto exit; } if( ssl->transform_in != NULL ) { ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in, &rec ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 3, "mbedtls_ssl_decrypt_buf", ret ); goto exit; } } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ exit: /* On success, we have decrypted the buffer in-place, so make * sure we don't leak any plaintext data. */ mbedtls_platform_zeroize( buf, buflen ); /* For the purpose of this API, treat messages with unexpected CID * as well as such from future epochs as unexpected. */ if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID || ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE ) { ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD; } MBEDTLS_SSL_DEBUG_MSG( 1, ( "<= mbedtls_ssl_check_record" ) ); return( ret ); } #endif /* MBEDTLS_SSL_RECORD_CHECKING */ #define SSL_DONT_FORCE_FLUSH 0 #define SSL_FORCE_FLUSH 1 #if defined(MBEDTLS_SSL_PROTO_DTLS) /* Forward declarations for functions related to message buffering. */ static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl, uint8_t slot ); static void ssl_free_buffered_record( mbedtls_ssl_context *ssl ); static int ssl_load_buffered_message( mbedtls_ssl_context *ssl ); static int ssl_load_buffered_record( mbedtls_ssl_context *ssl ); static int ssl_buffer_message( mbedtls_ssl_context *ssl ); static int ssl_buffer_future_record( mbedtls_ssl_context *ssl, mbedtls_record const *rec ); static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl ); static size_t ssl_get_maximum_datagram_size( mbedtls_ssl_context const *ssl ) { size_t mtu = mbedtls_ssl_get_current_mtu( ssl ); #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t out_buf_len = ssl->out_buf_len; #else size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; #endif if( mtu != 0 && mtu < out_buf_len ) return( mtu ); return( out_buf_len ); } static int ssl_get_remaining_space_in_datagram( mbedtls_ssl_context const *ssl ) { size_t const bytes_written = ssl->out_left; size_t const mtu = ssl_get_maximum_datagram_size( ssl ); /* Double-check that the write-index hasn't gone * past what we can transmit in a single datagram. */ if( bytes_written > mtu ) { /* Should never happen... */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } return( (int) ( mtu - bytes_written ) ); } static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t remaining, expansion; size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN; #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) const size_t mfl = mbedtls_ssl_get_output_max_frag_len( ssl ); if( max_len > mfl ) max_len = mfl; /* By the standard (RFC 6066 Sect. 4), the MFL extension * only limits the maximum record payload size, so in theory * we would be allowed to pack multiple records of payload size * MFL into a single datagram. However, this would mean that there's * no way to explicitly communicate MTU restrictions to the peer. * * The following reduction of max_len makes sure that we never * write datagrams larger than MFL + Record Expansion Overhead. */ if( max_len <= ssl->out_left ) return( 0 ); max_len -= ssl->out_left; #endif ret = ssl_get_remaining_space_in_datagram( ssl ); if( ret < 0 ) return( ret ); remaining = (size_t) ret; ret = mbedtls_ssl_get_record_expansion( ssl ); if( ret < 0 ) return( ret ); expansion = (size_t) ret; if( remaining <= expansion ) return( 0 ); remaining -= expansion; if( remaining >= max_len ) remaining = max_len; return( (int) remaining ); } /* * Double the retransmit timeout value, within the allowed range, * returning -1 if the maximum value has already been reached. */ static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl ) { uint32_t new_timeout; if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max ) return( -1 ); /* Implement the final paragraph of RFC 6347 section 4.1.1.1 * in the following way: after the initial transmission and a first * retransmission, back off to a temporary estimated MTU of 508 bytes. * This value is guaranteed to be deliverable (if not guaranteed to be * delivered) of any compliant IPv4 (and IPv6) network, and should work * on most non-IP stacks too. */ if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min ) { ssl->handshake->mtu = 508; MBEDTLS_SSL_DEBUG_MSG( 2, ( "mtu autoreduction to %d bytes", ssl->handshake->mtu ) ); } new_timeout = 2 * ssl->handshake->retransmit_timeout; /* Avoid arithmetic overflow and range overflow */ if( new_timeout < ssl->handshake->retransmit_timeout || new_timeout > ssl->conf->hs_timeout_max ) { new_timeout = ssl->conf->hs_timeout_max; } ssl->handshake->retransmit_timeout = new_timeout; MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs", ssl->handshake->retransmit_timeout ) ); return( 0 ); } static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl ) { ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min; MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs", ssl->handshake->retransmit_timeout ) ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl, const unsigned char *key_enc, const unsigned char *key_dec, size_t keylen, const unsigned char *iv_enc, const unsigned char *iv_dec, size_t ivlen, const unsigned char *mac_enc, const unsigned char *mac_dec, size_t maclen ) = NULL; int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL; int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL; int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL; int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL; int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL; #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ /* * Encryption/decryption functions */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || \ defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) static size_t ssl_compute_padding_length( size_t len, size_t granularity ) { return( ( granularity - ( len + 1 ) % granularity ) % granularity ); } /* This functions transforms a (D)TLS plaintext fragment and a record content * type into an instance of the (D)TLSInnerPlaintext structure. This is used * in DTLS 1.2 + CID and within TLS 1.3 to allow flexible padding and to protect * a record's content type. * * struct { * opaque content[DTLSPlaintext.length]; * ContentType real_type; * uint8 zeros[length_of_padding]; * } (D)TLSInnerPlaintext; * * Input: * - `content`: The beginning of the buffer holding the * plaintext to be wrapped. * - `*content_size`: The length of the plaintext in Bytes. * - `max_len`: The number of Bytes available starting from * `content`. This must be `>= *content_size`. * - `rec_type`: The desired record content type. * * Output: * - `content`: The beginning of the resulting (D)TLSInnerPlaintext structure. * - `*content_size`: The length of the resulting (D)TLSInnerPlaintext structure. * * Returns: * - `0` on success. * - A negative error code if `max_len` didn't offer enough space * for the expansion. */ static int ssl_build_inner_plaintext( unsigned char *content, size_t *content_size, size_t remaining, uint8_t rec_type, size_t pad ) { size_t len = *content_size; /* Write real content type */ if( remaining == 0 ) return( -1 ); content[ len ] = rec_type; len++; remaining--; if( remaining < pad ) return( -1 ); memset( content + len, 0, pad ); len += pad; remaining -= pad; *content_size = len; return( 0 ); } /* This function parses a (D)TLSInnerPlaintext structure. * See ssl_build_inner_plaintext() for details. */ static int ssl_parse_inner_plaintext( unsigned char const *content, size_t *content_size, uint8_t *rec_type ) { size_t remaining = *content_size; /* Determine length of padding by skipping zeroes from the back. */ do { if( remaining == 0 ) return( -1 ); remaining--; } while( content[ remaining ] == 0 ); *content_size = remaining; *rec_type = content[ remaining ]; return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID || MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ /* `add_data` must have size 13 Bytes if the CID extension is disabled, * and 13 + 1 + CID-length Bytes if the CID extension is enabled. */ static void ssl_extract_add_data_from_record( unsigned char* add_data, size_t *add_data_len, mbedtls_record *rec, unsigned minor_ver ) { /* Quoting RFC 5246 (TLS 1.2): * * additional_data = seq_num + TLSCompressed.type + * TLSCompressed.version + TLSCompressed.length; * * For the CID extension, this is extended as follows * (quoting draft-ietf-tls-dtls-connection-id-05, * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05): * * additional_data = seq_num + DTLSPlaintext.type + * DTLSPlaintext.version + * cid + * cid_length + * length_of_DTLSInnerPlaintext; * * For TLS 1.3, the record sequence number is dropped from the AAD * and encoded within the nonce of the AEAD operation instead. */ unsigned char *cur = add_data; #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) if( minor_ver != MBEDTLS_SSL_MINOR_VERSION_4 ) #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ { ((void) minor_ver); memcpy( cur, rec->ctr, sizeof( rec->ctr ) ); cur += sizeof( rec->ctr ); } *cur = rec->type; cur++; memcpy( cur, rec->ver, sizeof( rec->ver ) ); cur += sizeof( rec->ver ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( rec->cid_len != 0 ) { memcpy( cur, rec->cid, rec->cid_len ); cur += rec->cid_len; *cur = rec->cid_len; cur++; cur[0] = ( rec->data_len >> 8 ) & 0xFF; cur[1] = ( rec->data_len >> 0 ) & 0xFF; cur += 2; } else #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ { cur[0] = ( rec->data_len >> 8 ) & 0xFF; cur[1] = ( rec->data_len >> 0 ) & 0xFF; cur += 2; } *add_data_len = cur - add_data; } #if defined(MBEDTLS_SSL_PROTO_SSL3) #define SSL3_MAC_MAX_BYTES 20 /* MD-5 or SHA-1 */ /* * SSLv3.0 MAC functions */ static void ssl_mac( mbedtls_md_context_t *md_ctx, const unsigned char *secret, const unsigned char *buf, size_t len, const unsigned char *ctr, int type, unsigned char out[SSL3_MAC_MAX_BYTES] ) { unsigned char header[11]; unsigned char padding[48]; int padlen; int md_size = mbedtls_md_get_size( md_ctx->md_info ); int md_type = mbedtls_md_get_type( md_ctx->md_info ); /* Only MD5 and SHA-1 supported */ if( md_type == MBEDTLS_MD_MD5 ) padlen = 48; else padlen = 40; memcpy( header, ctr, 8 ); header[ 8] = (unsigned char) type; header[ 9] = (unsigned char)( len >> 8 ); header[10] = (unsigned char)( len ); memset( padding, 0x36, padlen ); mbedtls_md_starts( md_ctx ); mbedtls_md_update( md_ctx, secret, md_size ); mbedtls_md_update( md_ctx, padding, padlen ); mbedtls_md_update( md_ctx, header, 11 ); mbedtls_md_update( md_ctx, buf, len ); mbedtls_md_finish( md_ctx, out ); memset( padding, 0x5C, padlen ); mbedtls_md_starts( md_ctx ); mbedtls_md_update( md_ctx, secret, md_size ); mbedtls_md_update( md_ctx, padding, padlen ); mbedtls_md_update( md_ctx, out, md_size ); mbedtls_md_finish( md_ctx, out ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_GCM_C) || \ defined(MBEDTLS_CCM_C) || \ defined(MBEDTLS_CHACHAPOLY_C) static int ssl_transform_aead_dynamic_iv_is_explicit( mbedtls_ssl_transform const *transform ) { return( transform->ivlen != transform->fixed_ivlen ); } /* Compute IV := ( fixed_iv || 0 ) XOR ( 0 || dynamic_IV ) * * Concretely, this occurs in two variants: * * a) Fixed and dynamic IV lengths add up to total IV length, giving * IV = fixed_iv || dynamic_iv * * This variant is used in TLS 1.2 when used with GCM or CCM. * * b) Fixed IV lengths matches total IV length, giving * IV = fixed_iv XOR ( 0 || dynamic_iv ) * * This variant occurs in TLS 1.3 and for TLS 1.2 when using ChaChaPoly. * * See also the documentation of mbedtls_ssl_transform. * * This function has the precondition that * * dst_iv_len >= max( fixed_iv_len, dynamic_iv_len ) * * which has to be ensured by the caller. If this precondition * violated, the behavior of this function is undefined. */ static void ssl_build_record_nonce( unsigned char *dst_iv, size_t dst_iv_len, unsigned char const *fixed_iv, size_t fixed_iv_len, unsigned char const *dynamic_iv, size_t dynamic_iv_len ) { size_t i; /* Start with Fixed IV || 0 */ memset( dst_iv, 0, dst_iv_len ); memcpy( dst_iv, fixed_iv, fixed_iv_len ); dst_iv += dst_iv_len - dynamic_iv_len; for( i = 0; i < dynamic_iv_len; i++ ) dst_iv[i] ^= dynamic_iv[i]; } #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, mbedtls_ssl_transform *transform, mbedtls_record *rec, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { mbedtls_cipher_mode_t mode; int auth_done = 0; unsigned char * data; unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_OUT_LEN_MAX ]; size_t add_data_len; size_t post_avail; /* The SSL context is only used for debugging purposes! */ #if !defined(MBEDTLS_DEBUG_C) ssl = NULL; /* make sure we don't use it except for debug */ ((void) ssl); #endif /* The PRNG is used for dynamic IV generation that's used * for CBC transformations in TLS 1.1 and TLS 1.2. */ #if !( defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \ ( defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) ) ) ((void) f_rng); ((void) p_rng); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) ); if( transform == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no transform provided to encrypt_buf" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( rec == NULL || rec->buf == NULL || rec->buf_len < rec->data_offset || rec->buf_len - rec->data_offset < rec->data_len #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || rec->cid_len != 0 #endif ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to encrypt_buf" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } data = rec->buf + rec->data_offset; post_avail = rec->buf_len - ( rec->data_len + rec->data_offset ); MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload", data, rec->data_len ); mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ); if( rec->data_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record content %u too large, maximum %d", (unsigned) rec->data_len, MBEDTLS_SSL_OUT_CONTENT_LEN ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* The following two code paths implement the (D)TLSInnerPlaintext * structure present in TLS 1.3 and DTLS 1.2 + CID. * * See ssl_build_inner_plaintext() for more information. * * Note that this changes `rec->data_len`, and hence * `post_avail` needs to be recalculated afterwards. * * Note also that the two code paths cannot occur simultaneously * since they apply to different versions of the protocol. There * is hence no risk of double-addition of the inner plaintext. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) { size_t padding = ssl_compute_padding_length( rec->data_len, MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY ); if( ssl_build_inner_plaintext( data, &rec->data_len, post_avail, rec->type, padding ) != 0 ) { return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } rec->type = MBEDTLS_SSL_MSG_APPLICATION_DATA; } #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* * Add CID information */ rec->cid_len = transform->out_cid_len; memcpy( rec->cid, transform->out_cid, transform->out_cid_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "CID", rec->cid, rec->cid_len ); if( rec->cid_len != 0 ) { size_t padding = ssl_compute_padding_length( rec->data_len, MBEDTLS_SSL_CID_PADDING_GRANULARITY ); /* * Wrap plaintext into DTLSInnerPlaintext structure. * See ssl_build_inner_plaintext() for more information. * * Note that this changes `rec->data_len`, and hence * `post_avail` needs to be recalculated afterwards. */ if( ssl_build_inner_plaintext( data, &rec->data_len, post_avail, rec->type, padding ) != 0 ) { return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } rec->type = MBEDTLS_SSL_MSG_CID; } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ post_avail = rec->buf_len - ( rec->data_len + rec->data_offset ); /* * Add MAC before if needed */ #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) if( mode == MBEDTLS_MODE_STREAM || ( mode == MBEDTLS_MODE_CBC #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && transform->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED #endif ) ) { if( post_avail < transform->maclen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { unsigned char mac[SSL3_MAC_MAX_BYTES]; ssl_mac( &transform->md_ctx_enc, transform->mac_enc, data, rec->data_len, rec->ctr, rec->type, mac ); memcpy( data + rec->data_len, mac, transform->maclen ); } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) { unsigned char mac[MBEDTLS_SSL_MAC_ADD]; ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data, add_data_len ); mbedtls_md_hmac_update( &transform->md_ctx_enc, data, rec->data_len ); mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac ); mbedtls_md_hmac_reset( &transform->md_ctx_enc ); memcpy( data + rec->data_len, mac, transform->maclen ); } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", data + rec->data_len, transform->maclen ); rec->data_len += transform->maclen; post_avail -= transform->maclen; auth_done++; } #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ /* * Encrypt */ #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) if( mode == MBEDTLS_MODE_STREAM ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t olen; MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " "including %d bytes of padding", rec->data_len, 0 ) ); if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc, transform->iv_enc, transform->ivlen, data, rec->data_len, data, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } if( rec->data_len != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */ #if defined(MBEDTLS_GCM_C) || \ defined(MBEDTLS_CCM_C) || \ defined(MBEDTLS_CHACHAPOLY_C) if( mode == MBEDTLS_MODE_GCM || mode == MBEDTLS_MODE_CCM || mode == MBEDTLS_MODE_CHACHAPOLY ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char iv[12]; unsigned char *dynamic_iv; size_t dynamic_iv_len; int dynamic_iv_is_explicit = ssl_transform_aead_dynamic_iv_is_explicit( transform ); /* Check that there's space for the authentication tag. */ if( post_avail < transform->taglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* * Build nonce for AEAD encryption. * * Note: In the case of CCM and GCM in TLS 1.2, the dynamic * part of the IV is prepended to the ciphertext and * can be chosen freely - in particular, it need not * agree with the record sequence number. * However, since ChaChaPoly as well as all AEAD modes * in TLS 1.3 use the record sequence number as the * dynamic part of the nonce, we uniformly use the * record sequence number here in all cases. */ dynamic_iv = rec->ctr; dynamic_iv_len = sizeof( rec->ctr ); ssl_build_record_nonce( iv, sizeof( iv ), transform->iv_enc, transform->fixed_ivlen, dynamic_iv, dynamic_iv_len ); /* * Build additional data for AEAD encryption. * This depends on the TLS version. */ ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)", iv, transform->ivlen ); MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)", dynamic_iv, dynamic_iv_is_explicit ? dynamic_iv_len : 0 ); MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", add_data, add_data_len ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " "including 0 bytes of padding", rec->data_len ) ); /* * Encrypt and authenticate */ if( ( ret = mbedtls_cipher_auth_encrypt_ext( &transform->cipher_ctx_enc, iv, transform->ivlen, add_data, add_data_len, data, rec->data_len, /* src */ data, rec->buf_len - (data - rec->buf), /* dst */ &rec->data_len, transform->taglen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", data + rec->data_len - transform->taglen, transform->taglen ); /* Account for authentication tag. */ post_avail -= transform->taglen; /* * Prefix record content with dynamic IV in case it is explicit. */ if( dynamic_iv_is_explicit != 0 ) { if( rec->data_offset < dynamic_iv_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } memcpy( data - dynamic_iv_len, dynamic_iv, dynamic_iv_len ); rec->data_offset -= dynamic_iv_len; rec->data_len += dynamic_iv_len; } auth_done++; } else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */ #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) if( mode == MBEDTLS_MODE_CBC ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t padlen, i; size_t olen; /* Currently we're always using minimal padding * (up to 255 bytes would be allowed). */ padlen = transform->ivlen - ( rec->data_len + 1 ) % transform->ivlen; if( padlen == transform->ivlen ) padlen = 0; /* Check there's enough space in the buffer for the padding. */ if( post_avail < padlen + 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } for( i = 0; i <= padlen; i++ ) data[rec->data_len + i] = (unsigned char) padlen; rec->data_len += padlen + 1; post_avail -= padlen + 1; #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) /* * Prepend per-record IV for block cipher in TLS v1.1 and up as per * Method 1 (6.2.3.2. in RFC4346 and RFC5246) */ if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { if( f_rng == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "No PRNG provided to encrypt_record routine" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( rec->data_offset < transform->ivlen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* * Generate IV */ ret = f_rng( p_rng, transform->iv_enc, transform->ivlen ); if( ret != 0 ) return( ret ); memcpy( data - transform->ivlen, transform->iv_enc, transform->ivlen ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " "including %d bytes of IV and %d bytes of padding", rec->data_len, transform->ivlen, padlen + 1 ) ); if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc, transform->iv_enc, transform->ivlen, data, rec->data_len, data, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } if( rec->data_len != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) { /* * Save IV in SSL3 and TLS1 */ memcpy( transform->iv_enc, transform->cipher_ctx_enc.iv, transform->ivlen ); } else #endif { data -= transform->ivlen; rec->data_offset -= transform->ivlen; rec->data_len += transform->ivlen; } #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( auth_done == 0 ) { unsigned char mac[MBEDTLS_SSL_MAC_ADD]; /* * MAC(MAC_write_key, seq_num + * TLSCipherText.type + * TLSCipherText.version + * length_of( (IV +) ENC(...) ) + * IV + // except for TLS 1.0 * ENC(content + padding + padding_length)); */ if( post_avail < transform->maclen) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data, add_data_len ); mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data, add_data_len ); mbedtls_md_hmac_update( &transform->md_ctx_enc, data, rec->data_len ); mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac ); mbedtls_md_hmac_reset( &transform->md_ctx_enc ); memcpy( data + rec->data_len, mac, transform->maclen ); rec->data_len += transform->maclen; post_avail -= transform->maclen; auth_done++; } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ } else #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC) */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* Make extra sure authentication was performed, exactly once */ if( auth_done != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC) /* * Turn a bit into a mask: * - if bit == 1, return the all-bits 1 mask, aka (size_t) -1 * - if bit == 0, return the all-bits 0 mask, aka 0 * * This function can be used to write constant-time code by replacing branches * with bit operations using masks. * * This function is implemented without using comparison operators, as those * might be translated to branches by some compilers on some platforms. */ static size_t mbedtls_ssl_cf_mask_from_bit( size_t bit ) { /* MSVC has a warning about unary minus on unsigned integer types, * but this is well-defined and precisely what we want to do here. */ #if defined(_MSC_VER) #pragma warning( push ) #pragma warning( disable : 4146 ) #endif return -bit; #if defined(_MSC_VER) #pragma warning( pop ) #endif } /* * Constant-flow mask generation for "less than" comparison: * - if x < y, return all bits 1, that is (size_t) -1 * - otherwise, return all bits 0, that is 0 * * This function can be used to write constant-time code by replacing branches * with bit operations using masks. * * This function is implemented without using comparison operators, as those * might be translated to branches by some compilers on some platforms. */ static size_t mbedtls_ssl_cf_mask_lt( size_t x, size_t y ) { /* This has the most significant bit set if and only if x < y */ const size_t sub = x - y; /* sub1 = (x < y) ? 1 : 0 */ const size_t sub1 = sub >> ( sizeof( sub ) * 8 - 1 ); /* mask = (x < y) ? 0xff... : 0x00... */ const size_t mask = mbedtls_ssl_cf_mask_from_bit( sub1 ); return( mask ); } /* * Constant-flow mask generation for "greater or equal" comparison: * - if x >= y, return all bits 1, that is (size_t) -1 * - otherwise, return all bits 0, that is 0 * * This function can be used to write constant-time code by replacing branches * with bit operations using masks. * * This function is implemented without using comparison operators, as those * might be translated to branches by some compilers on some platforms. */ static size_t mbedtls_ssl_cf_mask_ge( size_t x, size_t y ) { return( ~mbedtls_ssl_cf_mask_lt( x, y ) ); } /* * Constant-flow boolean "equal" comparison: * return x == y * * This function can be used to write constant-time code by replacing branches * with bit operations - it can be used in conjunction with * mbedtls_ssl_cf_mask_from_bit(). * * This function is implemented without using comparison operators, as those * might be translated to branches by some compilers on some platforms. */ static size_t mbedtls_ssl_cf_bool_eq( size_t x, size_t y ) { /* diff = 0 if x == y, non-zero otherwise */ const size_t diff = x ^ y; /* MSVC has a warning about unary minus on unsigned integer types, * but this is well-defined and precisely what we want to do here. */ #if defined(_MSC_VER) #pragma warning( push ) #pragma warning( disable : 4146 ) #endif /* diff_msb's most significant bit is equal to x != y */ const size_t diff_msb = ( diff | -diff ); #if defined(_MSC_VER) #pragma warning( pop ) #endif /* diff1 = (x != y) ? 1 : 0 */ const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 ); return( 1 ^ diff1 ); } /* * Constant-flow conditional memcpy: * - if c1 == c2, equivalent to memcpy(dst, src, len), * - otherwise, a no-op, * but with execution flow independent of the values of c1 and c2. * * This function is implemented without using comparison operators, as those * might be translated to branches by some compilers on some platforms. */ static void mbedtls_ssl_cf_memcpy_if_eq( unsigned char *dst, const unsigned char *src, size_t len, size_t c1, size_t c2 ) { /* mask = c1 == c2 ? 0xff : 0x00 */ const size_t equal = mbedtls_ssl_cf_bool_eq( c1, c2 ); const unsigned char mask = (unsigned char) mbedtls_ssl_cf_mask_from_bit( equal ); /* dst[i] = c1 == c2 ? src[i] : dst[i] */ for( size_t i = 0; i < len; i++ ) dst[i] = ( src[i] & mask ) | ( dst[i] & ~mask ); } /* * Compute HMAC of variable-length data with constant flow. * * Only works with MD-5, SHA-1, SHA-256 and SHA-384. * (Otherwise, computation of block_size needs to be adapted.) */ MBEDTLS_STATIC_TESTABLE int mbedtls_ssl_cf_hmac( mbedtls_md_context_t *ctx, const unsigned char *add_data, size_t add_data_len, const unsigned char *data, size_t data_len_secret, size_t min_data_len, size_t max_data_len, unsigned char *output ) { /* * This function breaks the HMAC abstraction and uses the md_clone() * extension to the MD API in order to get constant-flow behaviour. * * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means * concatenation, and okey/ikey are the XOR of the key with some fixed bit * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx. * * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to * minlen, then cloning the context, and for each byte up to maxlen * finishing up the hash computation, keeping only the correct result. * * Then we only need to compute HASH(okey + inner_hash) and we're done. */ const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info ); /* TLS 1.0-1.2 only support SHA-384, SHA-256, SHA-1, MD-5, * all of which have the same block size except SHA-384. */ const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64; const unsigned char * const ikey = ctx->hmac_ctx; const unsigned char * const okey = ikey + block_size; const size_t hash_size = mbedtls_md_get_size( ctx->md_info ); unsigned char aux_out[MBEDTLS_MD_MAX_SIZE]; mbedtls_md_context_t aux; size_t offset; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_md_init( &aux ); #define MD_CHK( func_call ) \ do { \ ret = (func_call); \ if( ret != 0 ) \ goto cleanup; \ } while( 0 ) MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) ); /* After hmac_start() of hmac_reset(), ikey has already been hashed, * so we can start directly with the message */ MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) ); MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) ); /* For each possible length, compute the hash up to that point */ for( offset = min_data_len; offset <= max_data_len; offset++ ) { MD_CHK( mbedtls_md_clone( &aux, ctx ) ); MD_CHK( mbedtls_md_finish( &aux, aux_out ) ); /* Keep only the correct inner_hash in the output buffer */ mbedtls_ssl_cf_memcpy_if_eq( output, aux_out, hash_size, offset, data_len_secret ); if( offset < max_data_len ) MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) ); } /* Now compute HASH(okey + inner_hash) */ MD_CHK( mbedtls_md_starts( ctx ) ); MD_CHK( mbedtls_md_update( ctx, okey, block_size ) ); MD_CHK( mbedtls_md_update( ctx, output, hash_size ) ); MD_CHK( mbedtls_md_finish( ctx, output ) ); /* Done, get ready for next time */ MD_CHK( mbedtls_md_hmac_reset( ctx ) ); #undef MD_CHK cleanup: mbedtls_md_free( &aux ); return( ret ); } /* * Constant-flow memcpy from variable position in buffer. * - functionally equivalent to memcpy(dst, src + offset_secret, len) * - but with execution flow independent from the value of offset_secret. */ MBEDTLS_STATIC_TESTABLE void mbedtls_ssl_cf_memcpy_offset( unsigned char *dst, const unsigned char *src_base, size_t offset_secret, size_t offset_min, size_t offset_max, size_t len ) { size_t offset; for( offset = offset_min; offset <= offset_max; offset++ ) { mbedtls_ssl_cf_memcpy_if_eq( dst, src_base + offset, len, offset, offset_secret ); } } #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, mbedtls_ssl_transform *transform, mbedtls_record *rec ) { size_t olen; mbedtls_cipher_mode_t mode; int ret, auth_done = 0; #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) size_t padlen = 0, correct = 1; #endif unsigned char* data; unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_IN_LEN_MAX ]; size_t add_data_len; #if !defined(MBEDTLS_DEBUG_C) ssl = NULL; /* make sure we don't use it except for debug */ ((void) ssl); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) ); if( rec == NULL || rec->buf == NULL || rec->buf_len < rec->data_offset || rec->buf_len - rec->data_offset < rec->data_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to decrypt_buf" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } data = rec->buf + rec->data_offset; mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_dec ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* * Match record's CID with incoming CID. */ if( rec->cid_len != transform->in_cid_len || memcmp( rec->cid, transform->in_cid, rec->cid_len ) != 0 ) { return( MBEDTLS_ERR_SSL_UNEXPECTED_CID ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) if( mode == MBEDTLS_MODE_STREAM ) { padlen = 0; if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_dec, transform->iv_dec, transform->ivlen, data, rec->data_len, data, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } if( rec->data_len != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */ #if defined(MBEDTLS_GCM_C) || \ defined(MBEDTLS_CCM_C) || \ defined(MBEDTLS_CHACHAPOLY_C) if( mode == MBEDTLS_MODE_GCM || mode == MBEDTLS_MODE_CCM || mode == MBEDTLS_MODE_CHACHAPOLY ) { unsigned char iv[12]; unsigned char *dynamic_iv; size_t dynamic_iv_len; /* * Extract dynamic part of nonce for AEAD decryption. * * Note: In the case of CCM and GCM in TLS 1.2, the dynamic * part of the IV is prepended to the ciphertext and * can be chosen freely - in particular, it need not * agree with the record sequence number. */ dynamic_iv_len = sizeof( rec->ctr ); if( ssl_transform_aead_dynamic_iv_is_explicit( transform ) == 1 ) { if( rec->data_len < dynamic_iv_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) ", rec->data_len, dynamic_iv_len ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } dynamic_iv = data; data += dynamic_iv_len; rec->data_offset += dynamic_iv_len; rec->data_len -= dynamic_iv_len; } else { dynamic_iv = rec->ctr; } /* Check that there's space for the authentication tag. */ if( rec->data_len < transform->taglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < taglen (%d) ", rec->data_len, transform->taglen ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } rec->data_len -= transform->taglen; /* * Prepare nonce from dynamic and static parts. */ ssl_build_record_nonce( iv, sizeof( iv ), transform->iv_dec, transform->fixed_ivlen, dynamic_iv, dynamic_iv_len ); /* * Build additional data for AEAD encryption. * This depends on the TLS version. */ ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", add_data, add_data_len ); /* Because of the check above, we know that there are * explicit_iv_len Bytes preceeding data, and taglen * bytes following data + data_len. This justifies * the debug message and the invocation of * mbedtls_cipher_auth_decrypt() below. */ MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", iv, transform->ivlen ); MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", data + rec->data_len, transform->taglen ); /* * Decrypt and authenticate */ if( ( ret = mbedtls_cipher_auth_decrypt_ext( &transform->cipher_ctx_dec, iv, transform->ivlen, add_data, add_data_len, data, rec->data_len + transform->taglen, /* src */ data, rec->buf_len - (data - rec->buf), &olen, /* dst */ transform->taglen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret ); if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED ) return( MBEDTLS_ERR_SSL_INVALID_MAC ); return( ret ); } auth_done++; /* Double-check that AEAD decryption doesn't change content length. */ if( olen != rec->data_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) if( mode == MBEDTLS_MODE_CBC ) { size_t minlen = 0; /* * Check immediate ciphertext sanity */ #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { /* The ciphertext is prefixed with the CBC IV. */ minlen += transform->ivlen; } #endif /* Size considerations: * * - The CBC cipher text must not be empty and hence * at least of size transform->ivlen. * * Together with the potential IV-prefix, this explains * the first of the two checks below. * * - The record must contain a MAC, either in plain or * encrypted, depending on whether Encrypt-then-MAC * is used or not. * - If it is, the message contains the IV-prefix, * the CBC ciphertext, and the MAC. * - If it is not, the padded plaintext, and hence * the CBC ciphertext, has at least length maclen + 1 * because there is at least the padding length byte. * * As the CBC ciphertext is not empty, both cases give the * lower bound minlen + maclen + 1 on the record size, which * we test for in the second check below. */ if( rec->data_len < minlen + transform->ivlen || rec->data_len < minlen + transform->maclen + 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) " "+ 1 ) ( + expl IV )", rec->data_len, transform->ivlen, transform->maclen ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } /* * Authenticate before decrypt if enabled */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( transform->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED ) { unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); /* Update data_len in tandem with add_data. * * The subtraction is safe because of the previous check * data_len >= minlen + maclen + 1. * * Afterwards, we know that data + data_len is followed by at * least maclen Bytes, which justifies the call to * mbedtls_ssl_safer_memcmp() below. * * Further, we still know that data_len > minlen */ rec->data_len -= transform->maclen; ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); /* Calculate expected MAC. */ MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data, add_data_len ); mbedtls_md_hmac_update( &transform->md_ctx_dec, add_data, add_data_len ); mbedtls_md_hmac_update( &transform->md_ctx_dec, data, rec->data_len ); mbedtls_md_hmac_finish( &transform->md_ctx_dec, mac_expect ); mbedtls_md_hmac_reset( &transform->md_ctx_dec ); MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", data + rec->data_len, transform->maclen ); MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, transform->maclen ); /* Compare expected MAC with MAC at the end of the record. */ if( mbedtls_ssl_safer_memcmp( data + rec->data_len, mac_expect, transform->maclen ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } auth_done++; } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ /* * Check length sanity */ /* We know from above that data_len > minlen >= 0, * so the following check in particular implies that * data_len >= minlen + ivlen ( = minlen or 2 * minlen ). */ if( rec->data_len % transform->ivlen != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0", rec->data_len, transform->ivlen ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) /* * Initialize for prepended IV for block cipher in TLS v1.1 and up */ if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { /* Safe because data_len >= minlen + ivlen = 2 * ivlen. */ memcpy( transform->iv_dec, data, transform->ivlen ); data += transform->ivlen; rec->data_offset += transform->ivlen; rec->data_len -= transform->ivlen; } #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ /* We still have data_len % ivlen == 0 and data_len >= ivlen here. */ if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_dec, transform->iv_dec, transform->ivlen, data, rec->data_len, data, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } /* Double-check that length hasn't changed during decryption. */ if( rec->data_len != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) { /* * Save IV in SSL3 and TLS1, where CBC decryption of consecutive * records is equivalent to CBC decryption of the concatenation * of the records; in other words, IVs are maintained across * record decryptions. */ memcpy( transform->iv_dec, transform->cipher_ctx_dec.iv, transform->ivlen ); } #endif /* Safe since data_len >= minlen + maclen + 1, so after having * subtracted at most minlen and maclen up to this point, * data_len > 0 (because of data_len % ivlen == 0, it's actually * >= ivlen ). */ padlen = data[rec->data_len - 1]; if( auth_done == 1 ) { const size_t mask = mbedtls_ssl_cf_mask_ge( rec->data_len, padlen + 1 ); correct &= mask; padlen &= mask; } else { #if defined(MBEDTLS_SSL_DEBUG_ALL) if( rec->data_len < transform->maclen + padlen + 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)", rec->data_len, transform->maclen, padlen + 1 ) ); } #endif const size_t mask = mbedtls_ssl_cf_mask_ge( rec->data_len, transform->maclen + padlen + 1 ); correct &= mask; padlen &= mask; } padlen++; /* Regardless of the validity of the padding, * we have data_len >= padlen here. */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { /* This is the SSL 3.0 path, we don't have to worry about Lucky * 13, because there's a strictly worse padding attack built in * the protocol (known as part of POODLE), so we don't care if the * code is not constant-time, in particular branches are OK. */ if( padlen > transform->ivlen ) { #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, " "should be no more than %d", padlen, transform->ivlen ) ); #endif correct = 0; } } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) { /* The padding check involves a series of up to 256 * consecutive memory reads at the end of the record * plaintext buffer. In order to hide the length and * validity of the padding, always perform exactly * `min(256,plaintext_len)` reads (but take into account * only the last `padlen` bytes for the padding check). */ size_t pad_count = 0; volatile unsigned char* const check = data; /* Index of first padding byte; it has been ensured above * that the subtraction is safe. */ size_t const padding_idx = rec->data_len - padlen; size_t const num_checks = rec->data_len <= 256 ? rec->data_len : 256; size_t const start_idx = rec->data_len - num_checks; size_t idx; for( idx = start_idx; idx < rec->data_len; idx++ ) { /* pad_count += (idx >= padding_idx) && * (check[idx] == padlen - 1); */ const size_t mask = mbedtls_ssl_cf_mask_ge( idx, padding_idx ); const size_t equal = mbedtls_ssl_cf_bool_eq( check[idx], padlen - 1 ); pad_count += mask & equal; } correct &= mbedtls_ssl_cf_bool_eq( pad_count, padlen ); #if defined(MBEDTLS_SSL_DEBUG_ALL) if( padlen > 0 && correct == 0 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) ); #endif padlen &= mbedtls_ssl_cf_mask_from_bit( correct ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* If the padding was found to be invalid, padlen == 0 * and the subtraction is safe. If the padding was found valid, * padlen hasn't been changed and the previous assertion * data_len >= padlen still holds. */ rec->data_len -= padlen; } else #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption", data, rec->data_len ); #endif /* * Authenticate if not done yet. * Compute the MAC regardless of the padding result (RFC4346, CBCTIME). */ #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) if( auth_done == 0 ) { unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD]; unsigned char mac_peer[MBEDTLS_SSL_MAC_ADD]; /* If the initial value of padlen was such that * data_len < maclen + padlen + 1, then padlen * got reset to 1, and the initial check * data_len >= minlen + maclen + 1 * guarantees that at this point we still * have at least data_len >= maclen. * * If the initial value of padlen was such that * data_len >= maclen + padlen + 1, then we have * subtracted either padlen + 1 (if the padding was correct) * or 0 (if the padding was incorrect) since then, * hence data_len >= maclen in any case. */ rec->data_len -= transform->maclen; ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); #if defined(MBEDTLS_SSL_PROTO_SSL3) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl_mac( &transform->md_ctx_dec, transform->mac_dec, data, rec->data_len, rec->ctr, rec->type, mac_expect ); memcpy( mac_peer, data + rec->data_len, transform->maclen ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) { /* * The next two sizes are the minimum and maximum values of * data_len over all padlen values. * * They're independent of padlen, since we previously did * data_len -= padlen. * * Note that max_len + maclen is never more than the buffer * length, as we previously did in_msglen -= maclen too. */ const size_t max_len = rec->data_len + padlen; const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0; ret = mbedtls_ssl_cf_hmac( &transform->md_ctx_dec, add_data, add_data_len, data, rec->data_len, min_len, max_len, mac_expect ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_cf_hmac", ret ); return( ret ); } mbedtls_ssl_cf_memcpy_offset( mac_peer, data, rec->data_len, min_len, max_len, transform->maclen ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, transform->maclen ); MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", mac_peer, transform->maclen ); #endif if( mbedtls_ssl_safer_memcmp( mac_peer, mac_expect, transform->maclen ) != 0 ) { #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); #endif correct = 0; } auth_done++; } /* * Finally check the correct flag */ if( correct == 0 ) return( MBEDTLS_ERR_SSL_INVALID_MAC ); #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ /* Make extra sure authentication was performed, exactly once */ if( auth_done != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) { /* Remove inner padding and infer true content type. */ ret = ssl_parse_inner_plaintext( data, &rec->data_len, &rec->type ); if( ret != 0 ) return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( rec->cid_len != 0 ) { ret = ssl_parse_inner_plaintext( data, &rec->data_len, &rec->type ); if( ret != 0 ) return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) ); return( 0 ); } #undef MAC_NONE #undef MAC_PLAINTEXT #undef MAC_CIPHERTEXT #if defined(MBEDTLS_ZLIB_SUPPORT) /* * Compression/decompression functions */ static int ssl_compress_buf( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *msg_post = ssl->out_msg; ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf; size_t len_pre = ssl->out_msglen; unsigned char *msg_pre = ssl->compress_buf; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t out_buf_len = ssl->out_buf_len; #else size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) ); if( len_pre == 0 ) return( 0 ); memcpy( msg_pre, ssl->out_msg, len_pre ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ", ssl->out_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload", ssl->out_msg, ssl->out_msglen ); ssl->transform_out->ctx_deflate.next_in = msg_pre; ssl->transform_out->ctx_deflate.avail_in = len_pre; ssl->transform_out->ctx_deflate.next_out = msg_post; ssl->transform_out->ctx_deflate.avail_out = out_buf_len - bytes_written; ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH ); if( ret != Z_OK ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) ); return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); } ssl->out_msglen = out_buf_len - ssl->transform_out->ctx_deflate.avail_out - bytes_written; MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ", ssl->out_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload", ssl->out_msg, ssl->out_msglen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) ); return( 0 ); } static int ssl_decompress_buf( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *msg_post = ssl->in_msg; ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf; size_t len_pre = ssl->in_msglen; unsigned char *msg_pre = ssl->compress_buf; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t in_buf_len = ssl->in_buf_len; #else size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) ); if( len_pre == 0 ) return( 0 ); memcpy( msg_pre, ssl->in_msg, len_pre ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ", ssl->in_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload", ssl->in_msg, ssl->in_msglen ); ssl->transform_in->ctx_inflate.next_in = msg_pre; ssl->transform_in->ctx_inflate.avail_in = len_pre; ssl->transform_in->ctx_inflate.next_out = msg_post; ssl->transform_in->ctx_inflate.avail_out = in_buf_len - header_bytes; ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH ); if( ret != Z_OK ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) ); return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); } ssl->in_msglen = in_buf_len - ssl->transform_in->ctx_inflate.avail_out - header_bytes; MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ", ssl->in_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload", ssl->in_msg, ssl->in_msglen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) ); return( 0 ); } #endif /* MBEDTLS_ZLIB_SUPPORT */ /* * Fill the input message buffer by appending data to it. * The amount of data already fetched is in ssl->in_left. * * If we return 0, is it guaranteed that (at least) nb_want bytes are * available (from this read and/or a previous one). Otherwise, an error code * is returned (possibly EOF or WANT_READ). * * With stream transport (TLS) on success ssl->in_left == nb_want, but * with datagram transport (DTLS) on success ssl->in_left >= nb_want, * since we always read a whole datagram at once. * * For DTLS, it is up to the caller to set ssl->next_record_offset when * they're done reading a record. */ int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t in_buf_len = ssl->in_buf_len; #else size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) ); if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " "or mbedtls_ssl_set_bio()" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( nb_want > in_buf_len - (size_t)( ssl->in_hdr - ssl->in_buf ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { uint32_t timeout; /* * The point is, we need to always read a full datagram at once, so we * sometimes read more then requested, and handle the additional data. * It could be the rest of the current record (while fetching the * header) and/or some other records in the same datagram. */ /* * Move to the next record in the already read datagram if applicable */ if( ssl->next_record_offset != 0 ) { if( ssl->in_left < ssl->next_record_offset ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->in_left -= ssl->next_record_offset; if( ssl->in_left != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d", ssl->next_record_offset ) ); memmove( ssl->in_hdr, ssl->in_hdr + ssl->next_record_offset, ssl->in_left ); } ssl->next_record_offset = 0; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d", ssl->in_left, nb_want ) ); /* * Done if we already have enough data. */ if( nb_want <= ssl->in_left) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); return( 0 ); } /* * A record can't be split across datagrams. If we need to read but * are not at the beginning of a new record, the caller did something * wrong. */ if( ssl->in_left != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Don't even try to read if time's out already. * This avoids by-passing the timer when repeatedly receiving messages * that will end up being dropped. */ if( mbedtls_ssl_check_timer( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) ); ret = MBEDTLS_ERR_SSL_TIMEOUT; } else { len = in_buf_len - ( ssl->in_hdr - ssl->in_buf ); if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) timeout = ssl->handshake->retransmit_timeout; else timeout = ssl->conf->read_timeout; MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) ); if( ssl->f_recv_timeout != NULL ) ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len, timeout ); else ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret ); if( ret == 0 ) return( MBEDTLS_ERR_SSL_CONN_EOF ); } if( ret == MBEDTLS_ERR_SSL_TIMEOUT ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) ); mbedtls_ssl_set_timer( ssl, 0 ); if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { if( ssl_double_retransmit_timeout( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) ); return( MBEDTLS_ERR_SSL_TIMEOUT ); } if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); return( ret ); } return( MBEDTLS_ERR_SSL_WANT_READ ); } #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ( ret = mbedtls_ssl_resend_hello_request( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend_hello_request", ret ); return( ret ); } return( MBEDTLS_ERR_SSL_WANT_READ ); } #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ } if( ret < 0 ) return( ret ); ssl->in_left = ret; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d", ssl->in_left, nb_want ) ); while( ssl->in_left < nb_want ) { len = nb_want - ssl->in_left; if( mbedtls_ssl_check_timer( ssl ) != 0 ) ret = MBEDTLS_ERR_SSL_TIMEOUT; else { if( ssl->f_recv_timeout != NULL ) { ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr + ssl->in_left, len, ssl->conf->read_timeout ); } else { ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr + ssl->in_left, len ); } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d", ssl->in_left, nb_want ) ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret ); if( ret == 0 ) return( MBEDTLS_ERR_SSL_CONN_EOF ); if( ret < 0 ) return( ret ); if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "f_recv returned %d bytes but only %lu were requested", ret, (unsigned long)len ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->in_left += ret; } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); return( 0 ); } /* * Flush any data not yet written */ int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *buf; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) ); if( ssl->f_send == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " "or mbedtls_ssl_set_bio()" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Avoid incrementing counter if data is flushed */ if( ssl->out_left == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); return( 0 ); } while( ssl->out_left > 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d", mbedtls_ssl_out_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) ); buf = ssl->out_hdr - ssl->out_left; ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret ); if( ret <= 0 ) return( ret ); if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "f_send returned %d bytes but only %lu bytes were sent", ret, (unsigned long)ssl->out_left ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->out_left -= ret; } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->out_hdr = ssl->out_buf; } else #endif { ssl->out_hdr = ssl->out_buf + 8; } mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); return( 0 ); } /* * Functions to handle the DTLS retransmission state machine */ #if defined(MBEDTLS_SSL_PROTO_DTLS) /* * Append current handshake message to current outgoing flight */ static int ssl_flight_append( mbedtls_ssl_context *ssl ) { mbedtls_ssl_flight_item *msg; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_flight_append" ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "message appended to flight", ssl->out_msg, ssl->out_msglen ); /* Allocate space for current message */ if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", sizeof( mbedtls_ssl_flight_item ) ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) ); mbedtls_free( msg ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } /* Copy current handshake message with headers */ memcpy( msg->p, ssl->out_msg, ssl->out_msglen ); msg->len = ssl->out_msglen; msg->type = ssl->out_msgtype; msg->next = NULL; /* Append to the current flight */ if( ssl->handshake->flight == NULL ) ssl->handshake->flight = msg; else { mbedtls_ssl_flight_item *cur = ssl->handshake->flight; while( cur->next != NULL ) cur = cur->next; cur->next = msg; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_flight_append" ) ); return( 0 ); } /* * Free the current flight of handshake messages */ void mbedtls_ssl_flight_free( mbedtls_ssl_flight_item *flight ) { mbedtls_ssl_flight_item *cur = flight; mbedtls_ssl_flight_item *next; while( cur != NULL ) { next = cur->next; mbedtls_free( cur->p ); mbedtls_free( cur ); cur = next; } } /* * Swap transform_out and out_ctr with the alternative ones */ static int ssl_swap_epochs( mbedtls_ssl_context *ssl ) { mbedtls_ssl_transform *tmp_transform; unsigned char tmp_out_ctr[8]; if( ssl->transform_out == ssl->handshake->alt_transform_out ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) ); return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) ); /* Swap transforms */ tmp_transform = ssl->transform_out; ssl->transform_out = ssl->handshake->alt_transform_out; ssl->handshake->alt_transform_out = tmp_transform; /* Swap epoch + sequence_number */ memcpy( tmp_out_ctr, ssl->cur_out_ctr, 8 ); memcpy( ssl->cur_out_ctr, ssl->handshake->alt_out_ctr, 8 ); memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 ); /* Adjust to the newly activated transform */ mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out ); #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_activate != NULL ) { int ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif return( 0 ); } /* * Retransmit the current flight of messages. */ int mbedtls_ssl_resend( mbedtls_ssl_context *ssl ) { int ret = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) ); ret = mbedtls_ssl_flight_transmit( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) ); return( ret ); } /* * Transmit or retransmit the current flight of messages. * * Need to remember the current message in case flush_output returns * WANT_WRITE, causing us to exit this function and come back later. * This function must be called until state is no longer SENDING. */ int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_flight_transmit" ) ); if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise flight transmission" ) ); ssl->handshake->cur_msg = ssl->handshake->flight; ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12; ret = ssl_swap_epochs( ssl ); if( ret != 0 ) return( ret ); ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING; } while( ssl->handshake->cur_msg != NULL ) { size_t max_frag_len; const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg; int const is_finished = ( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE && cur->p[0] == MBEDTLS_SSL_HS_FINISHED ); uint8_t const force_flush = ssl->disable_datagram_packing == 1 ? SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH; /* Swap epochs before sending Finished: we can't do it after * sending ChangeCipherSpec, in case write returns WANT_READ. * Must be done before copying, may change out_msg pointer */ if( is_finished && ssl->handshake->cur_msg_p == ( cur->p + 12 ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "swap epochs to send finished message" ) ); ret = ssl_swap_epochs( ssl ); if( ret != 0 ) return( ret ); } ret = ssl_get_remaining_payload_in_datagram( ssl ); if( ret < 0 ) return( ret ); max_frag_len = (size_t) ret; /* CCS is copied as is, while HS messages may need fragmentation */ if( cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) { if( max_frag_len == 0 ) { if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); continue; } memcpy( ssl->out_msg, cur->p, cur->len ); ssl->out_msglen = cur->len; ssl->out_msgtype = cur->type; /* Update position inside current message */ ssl->handshake->cur_msg_p += cur->len; } else { const unsigned char * const p = ssl->handshake->cur_msg_p; const size_t hs_len = cur->len - 12; const size_t frag_off = p - ( cur->p + 12 ); const size_t rem_len = hs_len - frag_off; size_t cur_hs_frag_len, max_hs_frag_len; if( ( max_frag_len < 12 ) || ( max_frag_len == 12 && hs_len != 0 ) ) { if( is_finished ) { ret = ssl_swap_epochs( ssl ); if( ret != 0 ) return( ret ); } if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); continue; } max_hs_frag_len = max_frag_len - 12; cur_hs_frag_len = rem_len > max_hs_frag_len ? max_hs_frag_len : rem_len; if( frag_off == 0 && cur_hs_frag_len != hs_len ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "fragmenting handshake message (%u > %u)", (unsigned) cur_hs_frag_len, (unsigned) max_hs_frag_len ) ); } /* Messages are stored with handshake headers as if not fragmented, * copy beginning of headers then fill fragmentation fields. * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */ memcpy( ssl->out_msg, cur->p, 6 ); ssl->out_msg[6] = ( ( frag_off >> 16 ) & 0xff ); ssl->out_msg[7] = ( ( frag_off >> 8 ) & 0xff ); ssl->out_msg[8] = ( ( frag_off ) & 0xff ); ssl->out_msg[ 9] = ( ( cur_hs_frag_len >> 16 ) & 0xff ); ssl->out_msg[10] = ( ( cur_hs_frag_len >> 8 ) & 0xff ); ssl->out_msg[11] = ( ( cur_hs_frag_len ) & 0xff ); MBEDTLS_SSL_DEBUG_BUF( 3, "handshake header", ssl->out_msg, 12 ); /* Copy the handshake message content and set records fields */ memcpy( ssl->out_msg + 12, p, cur_hs_frag_len ); ssl->out_msglen = cur_hs_frag_len + 12; ssl->out_msgtype = cur->type; /* Update position inside current message */ ssl->handshake->cur_msg_p += cur_hs_frag_len; } /* If done with the current message move to the next one if any */ if( ssl->handshake->cur_msg_p >= cur->p + cur->len ) { if( cur->next != NULL ) { ssl->handshake->cur_msg = cur->next; ssl->handshake->cur_msg_p = cur->next->p + 12; } else { ssl->handshake->cur_msg = NULL; ssl->handshake->cur_msg_p = NULL; } } /* Actually send the message out */ if( ( ret = mbedtls_ssl_write_record( ssl, force_flush ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } } if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); /* Update state and set timer */ if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; else { ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; mbedtls_ssl_set_timer( ssl, ssl->handshake->retransmit_timeout ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_flight_transmit" ) ); return( 0 ); } /* * To be called when the last message of an incoming flight is received. */ void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl ) { /* We won't need to resend that one any more */ mbedtls_ssl_flight_free( ssl->handshake->flight ); ssl->handshake->flight = NULL; ssl->handshake->cur_msg = NULL; /* The next incoming flight will start with this msg_seq */ ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq; /* We don't want to remember CCS's across flight boundaries. */ ssl->handshake->buffering.seen_ccs = 0; /* Clear future message buffering structure. */ mbedtls_ssl_buffering_free( ssl ); /* Cancel timer */ mbedtls_ssl_set_timer( ssl, 0 ); if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) { ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; } else ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING; } /* * To be called when the last message of an outgoing flight is send. */ void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl ) { ssl_reset_retransmit_timeout( ssl ); mbedtls_ssl_set_timer( ssl, ssl->handshake->retransmit_timeout ); if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) { ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; } else ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* * Handshake layer functions */ /* * Write (DTLS: or queue) current handshake (including CCS) message. * * - fill in handshake headers * - update handshake checksum * - DTLS: save message for resending * - then pass to the record layer * * DTLS: except for HelloRequest, messages are only queued, and will only be * actually sent when calling flight_transmit() or resend(). * * Inputs: * - ssl->out_msglen: 4 + actual handshake message len * (4 is the size of handshake headers for TLS) * - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc) * - ssl->out_msg + 4: the handshake message body * * Outputs, ie state before passing to flight_append() or write_record(): * - ssl->out_msglen: the length of the record contents * (including handshake headers but excluding record headers) * - ssl->out_msg: the record contents (handshake headers + content) */ int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const size_t hs_len = ssl->out_msglen - 4; const unsigned char hs_type = ssl->out_msg[0]; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write handshake message" ) ); /* * Sanity checks */ if( ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE && ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) { /* In SSLv3, the client might send a NoCertificate alert. */ #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C) if( ! ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && ssl->out_msgtype == MBEDTLS_SSL_MSG_ALERT && ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ) #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } /* Whenever we send anything different from a * HelloRequest we should be in a handshake - double check. */ if( ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) && ssl->handshake == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake != NULL && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #endif /* Double-check that we did not exceed the bounds * of the outgoing record buffer. * This should never fail as the various message * writing functions must obey the bounds of the * outgoing record buffer, but better be safe. * * Note: We deliberately do not check for the MTU or MFL here. */ if( ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record too large: " "size %u, maximum %u", (unsigned) ssl->out_msglen, (unsigned) MBEDTLS_SSL_OUT_CONTENT_LEN ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Fill handshake headers */ if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) { ssl->out_msg[1] = (unsigned char)( hs_len >> 16 ); ssl->out_msg[2] = (unsigned char)( hs_len >> 8 ); ssl->out_msg[3] = (unsigned char)( hs_len ); /* * DTLS has additional fields in the Handshake layer, * between the length field and the actual payload: * uint16 message_seq; * uint24 fragment_offset; * uint24 fragment_length; */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Make room for the additional DTLS fields */ if( MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS handshake message too large: " "size %u, maximum %u", (unsigned) ( hs_len ), (unsigned) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } memmove( ssl->out_msg + 12, ssl->out_msg + 4, hs_len ); ssl->out_msglen += 8; /* Write message_seq and update it, except for HelloRequest */ if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) { ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF; ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF; ++( ssl->handshake->out_msg_seq ); } else { ssl->out_msg[4] = 0; ssl->out_msg[5] = 0; } /* Handshake hashes are computed without fragmentation, * so set frag_offset = 0 and frag_len = hs_len for now */ memset( ssl->out_msg + 6, 0x00, 3 ); memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* Update running hashes of handshake messages seen */ if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) ssl->handshake->update_checksum( ssl, ssl->out_msg, ssl->out_msglen ); } /* Either send now, or just save to be sent (and resent) later */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) ) { if( ( ret = ssl_flight_append( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret ); return( ret ); } } else #endif { if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_record", ret ); return( ret ); } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write handshake message" ) ); return( 0 ); } /* * Record layer functions */ /* * Write current record. * * Uses: * - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS) * - ssl->out_msglen: length of the record content (excl headers) * - ssl->out_msg: record content */ int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush ) { int ret, done = 0; size_t len = ssl->out_msglen; uint8_t flush = force_flush; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) ); #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->transform_out != NULL && ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) { if( ( ret = ssl_compress_buf( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret ); return( ret ); } len = ssl->out_msglen; } #endif /*MBEDTLS_ZLIB_SUPPORT */ #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_write != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) ); ret = mbedtls_ssl_hw_record_write( ssl ); if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } if( ret == 0 ) done = 1; } #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ if( !done ) { unsigned i; size_t protected_record_size; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t out_buf_len = ssl->out_buf_len; #else size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; #endif /* Skip writing the record content type to after the encryption, * as it may change when using the CID extension. */ mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, ssl->out_hdr + 1 ); memcpy( ssl->out_ctr, ssl->cur_out_ctr, 8 ); ssl->out_len[0] = (unsigned char)( len >> 8 ); ssl->out_len[1] = (unsigned char)( len ); if( ssl->transform_out != NULL ) { mbedtls_record rec; rec.buf = ssl->out_iv; rec.buf_len = out_buf_len - ( ssl->out_iv - ssl->out_buf ); rec.data_len = ssl->out_msglen; rec.data_offset = ssl->out_msg - rec.buf; memcpy( &rec.ctr[0], ssl->out_ctr, 8 ); mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, rec.ver ); rec.type = ssl->out_msgtype; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* The CID is set by mbedtls_ssl_encrypt_buf(). */ rec.cid_len = 0; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ if( ( ret = mbedtls_ssl_encrypt_buf( ssl, ssl->transform_out, &rec, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret ); return( ret ); } if( rec.data_offset != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* Update the record content type and CID. */ ssl->out_msgtype = rec.type; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID ) memcpy( ssl->out_cid, rec.cid, rec.cid_len ); #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->out_msglen = len = rec.data_len; ssl->out_len[0] = (unsigned char)( rec.data_len >> 8 ); ssl->out_len[1] = (unsigned char)( rec.data_len ); } protected_record_size = len + mbedtls_ssl_out_hdr_len( ssl ); #if defined(MBEDTLS_SSL_PROTO_DTLS) /* In case of DTLS, double-check that we don't exceed * the remaining space in the datagram. */ if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ret = ssl_get_remaining_space_in_datagram( ssl ); if( ret < 0 ) return( ret ); if( protected_record_size > (size_t) ret ) { /* Should never happen */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* Now write the potentially updated record content type. */ ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype; MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, " "version = [%d:%d], msglen = %d", ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2], len ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network", ssl->out_hdr, protected_record_size ); ssl->out_left += protected_record_size; ssl->out_hdr += protected_record_size; mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out ); for( i = 8; i > mbedtls_ssl_ep_len( ssl ); i-- ) if( ++ssl->cur_out_ctr[i - 1] != 0 ) break; /* The loop goes to its end iff the counter is wrapping */ if( i == mbedtls_ssl_ep_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && flush == SSL_DONT_FORCE_FLUSH ) { size_t remaining; ret = ssl_get_remaining_payload_in_datagram( ssl ); if( ret < 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_remaining_payload_in_datagram", ret ); return( ret ); } remaining = (size_t) ret; if( remaining == 0 ) { flush = SSL_FORCE_FLUSH; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Still %u bytes available in current datagram", (unsigned) remaining ) ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ if( ( flush == SSL_FORCE_FLUSH ) && ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) static int ssl_hs_is_proper_fragment( mbedtls_ssl_context *ssl ) { if( ssl->in_msglen < ssl->in_hslen || memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 || memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 ) { return( 1 ); } return( 0 ); } static uint32_t ssl_get_hs_frag_len( mbedtls_ssl_context const *ssl ) { return( ( ssl->in_msg[9] << 16 ) | ( ssl->in_msg[10] << 8 ) | ssl->in_msg[11] ); } static uint32_t ssl_get_hs_frag_off( mbedtls_ssl_context const *ssl ) { return( ( ssl->in_msg[6] << 16 ) | ( ssl->in_msg[7] << 8 ) | ssl->in_msg[8] ); } static int ssl_check_hs_header( mbedtls_ssl_context const *ssl ) { uint32_t msg_len, frag_off, frag_len; msg_len = ssl_get_hs_total_len( ssl ); frag_off = ssl_get_hs_frag_off( ssl ); frag_len = ssl_get_hs_frag_len( ssl ); if( frag_off > msg_len ) return( -1 ); if( frag_len > msg_len - frag_off ) return( -1 ); if( frag_len + 12 > ssl->in_msglen ) return( -1 ); return( 0 ); } /* * Mark bits in bitmask (used for DTLS HS reassembly) */ static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len ) { unsigned int start_bits, end_bits; start_bits = 8 - ( offset % 8 ); if( start_bits != 8 ) { size_t first_byte_idx = offset / 8; /* Special case */ if( len <= start_bits ) { for( ; len != 0; len-- ) mask[first_byte_idx] |= 1 << ( start_bits - len ); /* Avoid potential issues with offset or len becoming invalid */ return; } offset += start_bits; /* Now offset % 8 == 0 */ len -= start_bits; for( ; start_bits != 0; start_bits-- ) mask[first_byte_idx] |= 1 << ( start_bits - 1 ); } end_bits = len % 8; if( end_bits != 0 ) { size_t last_byte_idx = ( offset + len ) / 8; len -= end_bits; /* Now len % 8 == 0 */ for( ; end_bits != 0; end_bits-- ) mask[last_byte_idx] |= 1 << ( 8 - end_bits ); } memset( mask + offset / 8, 0xFF, len / 8 ); } /* * Check that bitmask is full */ static int ssl_bitmask_check( unsigned char *mask, size_t len ) { size_t i; for( i = 0; i < len / 8; i++ ) if( mask[i] != 0xFF ) return( -1 ); for( i = 0; i < len % 8; i++ ) if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 ) return( -1 ); return( 0 ); } /* msg_len does not include the handshake header */ static size_t ssl_get_reassembly_buffer_size( size_t msg_len, unsigned add_bitmap ) { size_t alloc_len; alloc_len = 12; /* Handshake header */ alloc_len += msg_len; /* Content buffer */ if( add_bitmap ) alloc_len += msg_len / 8 + ( msg_len % 8 != 0 ); /* Bitmap */ return( alloc_len ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl ) { return( ( ssl->in_msg[1] << 16 ) | ( ssl->in_msg[2] << 8 ) | ssl->in_msg[3] ); } int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl ) { if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d", ssl->in_msglen ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ssl_get_hs_total_len( ssl ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen =" " %d, type = %d, hslen = %d", ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; if( ssl_check_hs_header( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid handshake header" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } if( ssl->handshake != NULL && ( ( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && recv_msg_seq != ssl->handshake->in_msg_seq ) || ( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER && ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) ) { if( recv_msg_seq > ssl->handshake->in_msg_seq ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received future handshake message of sequence number %u (next %u)", recv_msg_seq, ssl->handshake->in_msg_seq ) ); return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); } /* Retransmit only on last message from previous flight, to avoid * too many retransmissions. * Besides, No sane server ever retransmits HelloVerifyRequest */ if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 && ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, " "message_seq = %d, start_of_flight = %d", recv_msg_seq, ssl->handshake->in_flight_start_seq ) ); if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); return( ret ); } } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: " "message_seq = %d, expected = %d", recv_msg_seq, ssl->handshake->in_msg_seq ) ); } return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); } /* Wait until message completion to increment in_msg_seq */ /* Message reassembly is handled alongside buffering of future * messages; the commonality is that both handshake fragments and * future messages cannot be forwarded immediately to the * handshake logic layer. */ if( ssl_hs_is_proper_fragment( ssl ) == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) ); return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); } } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* With TLS we don't handle fragmentation (for now) */ if( ssl->in_msglen < ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } return( 0 ); } void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && hs != NULL ) { ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen ); } /* Handshake message is complete, increment counter */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake != NULL ) { unsigned offset; mbedtls_ssl_hs_buffer *hs_buf; /* Increment handshake sequence number */ hs->in_msg_seq++; /* * Clear up handshake buffering and reassembly structure. */ /* Free first entry */ ssl_buffering_free_slot( ssl, 0 ); /* Shift all other entries */ for( offset = 0, hs_buf = &hs->buffering.hs[0]; offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++, hs_buf++ ) { *hs_buf = *(hs_buf + 1); } /* Create a fresh last entry */ memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) ); } #endif } /* * DTLS anti-replay: RFC 6347 4.1.2.6 * * in_window is a field of bits numbered from 0 (lsb) to 63 (msb). * Bit n is set iff record number in_window_top - n has been seen. * * Usually, in_window_top is the last record number seen and the lsb of * in_window is set. The only exception is the initial state (record number 0 * not seen yet). */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) void mbedtls_ssl_dtls_replay_reset( mbedtls_ssl_context *ssl ) { ssl->in_window_top = 0; ssl->in_window = 0; } static inline uint64_t ssl_load_six_bytes( unsigned char *buf ) { return( ( (uint64_t) buf[0] << 40 ) | ( (uint64_t) buf[1] << 32 ) | ( (uint64_t) buf[2] << 24 ) | ( (uint64_t) buf[3] << 16 ) | ( (uint64_t) buf[4] << 8 ) | ( (uint64_t) buf[5] ) ); } static int mbedtls_ssl_dtls_record_replay_check( mbedtls_ssl_context *ssl, uint8_t *record_in_ctr ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *original_in_ctr; // save original in_ctr original_in_ctr = ssl->in_ctr; // use counter from record ssl->in_ctr = record_in_ctr; ret = mbedtls_ssl_dtls_replay_check( (mbedtls_ssl_context const *) ssl ); // restore the counter ssl->in_ctr = original_in_ctr; return ret; } /* * Return 0 if sequence number is acceptable, -1 otherwise */ int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context const *ssl ) { uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 ); uint64_t bit; if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED ) return( 0 ); if( rec_seqnum > ssl->in_window_top ) return( 0 ); bit = ssl->in_window_top - rec_seqnum; if( bit >= 64 ) return( -1 ); if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 ) return( -1 ); return( 0 ); } /* * Update replay window on new validated record */ void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl ) { uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 ); if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED ) return; if( rec_seqnum > ssl->in_window_top ) { /* Update window_top and the contents of the window */ uint64_t shift = rec_seqnum - ssl->in_window_top; if( shift >= 64 ) ssl->in_window = 1; else { ssl->in_window <<= shift; ssl->in_window |= 1; } ssl->in_window_top = rec_seqnum; } else { /* Mark that number as seen in the current window */ uint64_t bit = ssl->in_window_top - rec_seqnum; if( bit < 64 ) /* Always true, but be extra sure */ ssl->in_window |= (uint64_t) 1 << bit; } } #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) /* * Without any SSL context, check if a datagram looks like a ClientHello with * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message. * Both input and output include full DTLS headers. * * - if cookie is valid, return 0 * - if ClientHello looks superficially valid but cookie is not, * fill obuf and set olen, then * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED * - otherwise return a specific error code */ static int ssl_check_dtls_clihlo_cookie( mbedtls_ssl_cookie_write_t *f_cookie_write, mbedtls_ssl_cookie_check_t *f_cookie_check, void *p_cookie, const unsigned char *cli_id, size_t cli_id_len, const unsigned char *in, size_t in_len, unsigned char *obuf, size_t buf_len, size_t *olen ) { size_t sid_len, cookie_len; unsigned char *p; /* * Structure of ClientHello with record and handshake headers, * and expected values. We don't need to check a lot, more checks will be * done when actually parsing the ClientHello - skipping those checks * avoids code duplication and does not make cookie forging any easier. * * 0-0 ContentType type; copied, must be handshake * 1-2 ProtocolVersion version; copied * 3-4 uint16 epoch; copied, must be 0 * 5-10 uint48 sequence_number; copied * 11-12 uint16 length; (ignored) * * 13-13 HandshakeType msg_type; (ignored) * 14-16 uint24 length; (ignored) * 17-18 uint16 message_seq; copied * 19-21 uint24 fragment_offset; copied, must be 0 * 22-24 uint24 fragment_length; (ignored) * * 25-26 ProtocolVersion client_version; (ignored) * 27-58 Random random; (ignored) * 59-xx SessionID session_id; 1 byte len + sid_len content * 60+ opaque cookie<0..2^8-1>; 1 byte len + content * ... * * Minimum length is 61 bytes. */ if( in_len < 61 || in[0] != MBEDTLS_SSL_MSG_HANDSHAKE || in[3] != 0 || in[4] != 0 || in[19] != 0 || in[20] != 0 || in[21] != 0 ) { return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } sid_len = in[59]; if( sid_len > in_len - 61 ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); cookie_len = in[60 + sid_len]; if( cookie_len > in_len - 60 ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len, cli_id, cli_id_len ) == 0 ) { /* Valid cookie */ return( 0 ); } /* * If we get here, we've got an invalid cookie, let's prepare HVR. * * 0-0 ContentType type; copied * 1-2 ProtocolVersion version; copied * 3-4 uint16 epoch; copied * 5-10 uint48 sequence_number; copied * 11-12 uint16 length; olen - 13 * * 13-13 HandshakeType msg_type; hello_verify_request * 14-16 uint24 length; olen - 25 * 17-18 uint16 message_seq; copied * 19-21 uint24 fragment_offset; copied * 22-24 uint24 fragment_length; olen - 25 * * 25-26 ProtocolVersion server_version; 0xfe 0xff * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie * * Minimum length is 28. */ if( buf_len < 28 ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); /* Copy most fields and adapt others */ memcpy( obuf, in, 25 ); obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST; obuf[25] = 0xfe; obuf[26] = 0xff; /* Generate and write actual cookie */ p = obuf + 28; if( f_cookie_write( p_cookie, &p, obuf + buf_len, cli_id, cli_id_len ) != 0 ) { return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } *olen = p - obuf; /* Go back and fill length fields */ obuf[27] = (unsigned char)( *olen - 28 ); obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 ); obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 ); obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) ); obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 ); obuf[12] = (unsigned char)( ( *olen - 13 ) ); return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ); } /* * Handle possible client reconnect with the same UDP quadruplet * (RFC 6347 Section 4.2.8). * * Called by ssl_parse_record_header() in case we receive an epoch 0 record * that looks like a ClientHello. * * - if the input looks like a ClientHello without cookies, * send back HelloVerifyRequest, then return 0 * - if the input looks like a ClientHello with a valid cookie, * reset the session of the current context, and * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT * - if anything goes wrong, return a specific error code * * This function is called (through ssl_check_client_reconnect()) when an * unexpected record is found in ssl_get_next_record(), which will discard the * record if we return 0, and bubble up the return value otherwise (this * includes the case of MBEDTLS_ERR_SSL_CLIENT_RECONNECT and of unexpected * errors, and is the right thing to do in both cases). */ static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; if( ssl->conf->f_cookie_write == NULL || ssl->conf->f_cookie_check == NULL ) { /* If we can't use cookies to verify reachability of the peer, * drop the record. */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "no cookie callbacks, " "can't check reconnect validity" ) ); return( 0 ); } ret = ssl_check_dtls_clihlo_cookie( ssl->conf->f_cookie_write, ssl->conf->f_cookie_check, ssl->conf->p_cookie, ssl->cli_id, ssl->cli_id_len, ssl->in_buf, ssl->in_left, ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret ); if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ) { int send_ret; MBEDTLS_SSL_DEBUG_MSG( 1, ( "sending HelloVerifyRequest" ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network", ssl->out_buf, len ); /* Don't check write errors as we can't do anything here. * If the error is permanent we'll catch it later, * if it's not, then hopefully it'll work next time. */ send_ret = ssl->f_send( ssl->p_bio, ssl->out_buf, len ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", send_ret ); (void) send_ret; return( 0 ); } if( ret == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "cookie is valid, resetting context" ) ); if( ( ret = mbedtls_ssl_session_reset_int( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret ); return( ret ); } return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT ); } return( ret ); } #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ static int ssl_check_record_type( uint8_t record_type ) { if( record_type != MBEDTLS_SSL_MSG_HANDSHAKE && record_type != MBEDTLS_SSL_MSG_ALERT && record_type != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC && record_type != MBEDTLS_SSL_MSG_APPLICATION_DATA ) { return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } return( 0 ); } /* * ContentType type; * ProtocolVersion version; * uint16 epoch; // DTLS only * uint48 sequence_number; // DTLS only * uint16 length; * * Return 0 if header looks sane (and, for DTLS, the record is expected) * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad, * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected. * * With DTLS, mbedtls_ssl_read_record() will: * 1. proceed with the record if this function returns 0 * 2. drop only the current record if this function returns UNEXPECTED_RECORD * 3. return CLIENT_RECONNECT if this function return that value * 4. drop the whole datagram if this function returns anything else. * Point 2 is needed when the peer is resending, and we have already received * the first record from a datagram but are still waiting for the others. */ static int ssl_parse_record_header( mbedtls_ssl_context const *ssl, unsigned char *buf, size_t len, mbedtls_record *rec ) { int major_ver, minor_ver; size_t const rec_hdr_type_offset = 0; size_t const rec_hdr_type_len = 1; size_t const rec_hdr_version_offset = rec_hdr_type_offset + rec_hdr_type_len; size_t const rec_hdr_version_len = 2; size_t const rec_hdr_ctr_len = 8; #if defined(MBEDTLS_SSL_PROTO_DTLS) uint32_t rec_epoch; size_t const rec_hdr_ctr_offset = rec_hdr_version_offset + rec_hdr_version_len; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) size_t const rec_hdr_cid_offset = rec_hdr_ctr_offset + rec_hdr_ctr_len; size_t rec_hdr_cid_len = 0; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #endif /* MBEDTLS_SSL_PROTO_DTLS */ size_t rec_hdr_len_offset; /* To be determined */ size_t const rec_hdr_len_len = 2; /* * Check minimum lengths for record header. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { rec_hdr_len_offset = rec_hdr_ctr_offset + rec_hdr_ctr_len; } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { rec_hdr_len_offset = rec_hdr_version_offset + rec_hdr_version_len; } if( len < rec_hdr_len_offset + rec_hdr_len_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "datagram of length %u too small to hold DTLS record header of length %u", (unsigned) len, (unsigned)( rec_hdr_len_len + rec_hdr_len_len ) ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* * Parse and validate record content type */ rec->type = buf[ rec_hdr_type_offset ]; /* Check record content type */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) rec->cid_len = 0; if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->conf->cid_len != 0 && rec->type == MBEDTLS_SSL_MSG_CID ) { /* Shift pointers to account for record header including CID * struct { * ContentType special_type = tls12_cid; * ProtocolVersion version; * uint16 epoch; * uint48 sequence_number; * opaque cid[cid_length]; // Additional field compared to * // default DTLS record format * uint16 length; * opaque enc_content[DTLSCiphertext.length]; * } DTLSCiphertext; */ /* So far, we only support static CID lengths * fixed in the configuration. */ rec_hdr_cid_len = ssl->conf->cid_len; rec_hdr_len_offset += rec_hdr_cid_len; if( len < rec_hdr_len_offset + rec_hdr_len_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "datagram of length %u too small to hold DTLS record header including CID, length %u", (unsigned) len, (unsigned)( rec_hdr_len_offset + rec_hdr_len_len ) ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* configured CID len is guaranteed at most 255, see * MBEDTLS_SSL_CID_OUT_LEN_MAX in check_config.h */ rec->cid_len = (uint8_t) rec_hdr_cid_len; memcpy( rec->cid, buf + rec_hdr_cid_offset, rec_hdr_cid_len ); } else #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ { if( ssl_check_record_type( rec->type ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type %u", (unsigned) rec->type ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } } /* * Parse and validate record version */ rec->ver[0] = buf[ rec_hdr_version_offset + 0 ]; rec->ver[1] = buf[ rec_hdr_version_offset + 1 ]; mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, &rec->ver[0] ); if( major_ver != ssl->major_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } if( minor_ver > ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* * Parse/Copy record sequence number. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Copy explicit record sequence number from input buffer. */ memcpy( &rec->ctr[0], buf + rec_hdr_ctr_offset, rec_hdr_ctr_len ); } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { /* Copy implicit record sequence number from SSL context structure. */ memcpy( &rec->ctr[0], ssl->in_ctr, rec_hdr_ctr_len ); } /* * Parse record length. */ rec->data_offset = rec_hdr_len_offset + rec_hdr_len_len; rec->data_len = ( (size_t) buf[ rec_hdr_len_offset + 0 ] << 8 ) | ( (size_t) buf[ rec_hdr_len_offset + 1 ] << 0 ); MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", buf, rec->data_offset ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, " "version = [%d:%d], msglen = %d", rec->type, major_ver, minor_ver, rec->data_len ) ); rec->buf = buf; rec->buf_len = rec->data_offset + rec->data_len; if( rec->data_len == 0 ) return( MBEDTLS_ERR_SSL_INVALID_RECORD ); /* * DTLS-related tests. * Check epoch before checking length constraint because * the latter varies with the epoch. E.g., if a ChangeCipherSpec * message gets duplicated before the corresponding Finished message, * the second ChangeCipherSpec should be discarded because it belongs * to an old epoch, but not because its length is shorter than * the minimum record length for packets using the new record transform. * Note that these two kinds of failures are handled differently, * as an unexpected record is silently skipped but an invalid * record leads to the entire datagram being dropped. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { rec_epoch = ( rec->ctr[0] << 8 ) | rec->ctr[1]; /* Check that the datagram is large enough to contain a record * of the advertised length. */ if( len < rec->data_offset + rec->data_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Datagram of length %u too small to contain record of advertised length %u.", (unsigned) len, (unsigned)( rec->data_offset + rec->data_len ) ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* Records from other, non-matching epochs are silently discarded. * (The case of same-port Client reconnects must be considered in * the caller). */ if( rec_epoch != ssl->in_epoch ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: " "expected %d, received %d", ssl->in_epoch, rec_epoch ) ); /* Records from the next epoch are considered for buffering * (concretely: early Finished messages). */ if( rec_epoch == (unsigned) ssl->in_epoch + 1 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Consider record for buffering" ) ); return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); } return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) /* For records from the correct epoch, check whether their * sequence number has been seen before. */ else if( mbedtls_ssl_dtls_record_replay_check( (mbedtls_ssl_context *) ssl, &rec->ctr[0] ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } #endif } #endif /* MBEDTLS_SSL_PROTO_DTLS */ return( 0 ); } #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) static int ssl_check_client_reconnect( mbedtls_ssl_context *ssl ) { unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1]; /* * Check for an epoch 0 ClientHello. We can't use in_msg here to * access the first byte of record content (handshake type), as we * have an active transform (possibly iv_len != 0), so use the * fact that the record header len is 13 instead. */ if( rec_epoch == 0 && ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER && ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_left > 13 && ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect " "from the same port" ) ); return( ssl_handle_possible_reconnect( ssl ) ); } return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ /* * If applicable, decrypt record content */ static int ssl_prepare_record_content( mbedtls_ssl_context *ssl, mbedtls_record *rec ) { int ret, done = 0; MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network", rec->buf, rec->buf_len ); #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_read != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) ); ret = mbedtls_ssl_hw_record_read( ssl ); if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } if( ret == 0 ) done = 1; } #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ if( !done && ssl->transform_in != NULL ) { unsigned char const old_msg_type = rec->type; if( ( ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in, rec ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID && ssl->conf->ignore_unexpected_cid == MBEDTLS_SSL_UNEXPECTED_CID_IGNORE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ignoring unexpected CID" ) ); ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING; } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ return( ret ); } if( old_msg_type != rec->type ) { MBEDTLS_SSL_DEBUG_MSG( 4, ( "record type after decrypt (before %d): %d", old_msg_type, rec->type ) ); } MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt", rec->buf + rec->data_offset, rec->data_len ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* We have already checked the record content type * in ssl_parse_record_header(), failing or silently * dropping the record in the case of an unknown type. * * Since with the use of CIDs, the record content type * might change during decryption, re-check the record * content type, but treat a failure as fatal this time. */ if( ssl_check_record_type( rec->type ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ if( rec->data_len == 0 ) { #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 && rec->type != MBEDTLS_SSL_MSG_APPLICATION_DATA ) { /* TLS v1.2 explicitly disallows zero-length messages which are not application data */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ ssl->nb_zero++; /* * Three or more empty messages may be a DoS attack * (excessive CPU consumption). */ if( ssl->nb_zero > 3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty " "messages, possible DoS attack" ) ); /* Treat the records as if they were not properly authenticated, * thereby failing the connection if we see more than allowed * by the configured bad MAC threshold. */ return( MBEDTLS_ERR_SSL_INVALID_MAC ); } } else ssl->nb_zero = 0; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ; /* in_ctr read from peer, not maintained internally */ } else #endif { unsigned i; for( i = 8; i > mbedtls_ssl_ep_len( ssl ); i-- ) if( ++ssl->in_ctr[i - 1] != 0 ) break; /* The loop goes to its end iff the counter is wrapping */ if( i == mbedtls_ssl_ep_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } } #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { mbedtls_ssl_dtls_replay_update( ssl ); } #endif /* Check actual (decrypted) record content length against * configured maximum. */ if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } return( 0 ); } /* * Read a record. * * Silently ignore non-fatal alert (and for DTLS, invalid records as well, * RFC 6347 4.1.2.7) and continue reading until a valid record is found. * */ /* Helper functions for mbedtls_ssl_read_record(). */ static int ssl_consume_current_message( mbedtls_ssl_context *ssl ); static int ssl_get_next_record( mbedtls_ssl_context *ssl ); static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl ); int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl, unsigned update_hs_digest ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) ); if( ssl->keep_current_message == 0 ) { do { ret = ssl_consume_current_message( ssl ); if( ret != 0 ) return( ret ); if( ssl_record_is_in_progress( ssl ) == 0 ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) int have_buffered = 0; /* We only check for buffered messages if the * current datagram is fully consumed. */ if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl_next_record_is_in_datagram( ssl ) == 0 ) { if( ssl_load_buffered_message( ssl ) == 0 ) have_buffered = 1; } if( have_buffered == 0 ) #endif /* MBEDTLS_SSL_PROTO_DTLS */ { ret = ssl_get_next_record( ssl ); if( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ) continue; if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_get_next_record" ), ret ); return( ret ); } } } ret = mbedtls_ssl_handle_message_type( ssl ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE ) { /* Buffer future message */ ret = ssl_buffer_message( ssl ); if( ret != 0 ) return( ret ); ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ } while( MBEDTLS_ERR_SSL_NON_FATAL == ret || MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret ); if( 0 != ret ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret ); return( ret ); } if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && update_hs_digest == 1 ) { mbedtls_ssl_update_handshake_status( ssl ); } } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "reuse previously read message" ) ); ssl->keep_current_message = 0; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl ) { if( ssl->in_left > ssl->next_record_offset ) return( 1 ); return( 0 ); } static int ssl_load_buffered_message( mbedtls_ssl_context *ssl ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; mbedtls_ssl_hs_buffer * hs_buf; int ret = 0; if( hs == NULL ) return( -1 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_messsage" ) ); if( ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC || ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC ) { /* Check if we have seen a ChangeCipherSpec before. * If yes, synthesize a CCS record. */ if( !hs->buffering.seen_ccs ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "CCS not seen in the current flight" ) ); ret = -1; goto exit; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "Injecting buffered CCS message" ) ); ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC; ssl->in_msglen = 1; ssl->in_msg[0] = 1; /* As long as they are equal, the exact value doesn't matter. */ ssl->in_left = 0; ssl->next_record_offset = 0; hs->buffering.seen_ccs = 0; goto exit; } #if defined(MBEDTLS_DEBUG_C) /* Debug only */ { unsigned offset; for( offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ ) { hs_buf = &hs->buffering.hs[offset]; if( hs_buf->is_valid == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Future message with sequence number %u %s buffered.", hs->in_msg_seq + offset, hs_buf->is_complete ? "fully" : "partially" ) ); } } } #endif /* MBEDTLS_DEBUG_C */ /* Check if we have buffered and/or fully reassembled the * next handshake message. */ hs_buf = &hs->buffering.hs[0]; if( ( hs_buf->is_valid == 1 ) && ( hs_buf->is_complete == 1 ) ) { /* Synthesize a record containing the buffered HS message. */ size_t msg_len = ( hs_buf->data[1] << 16 ) | ( hs_buf->data[2] << 8 ) | hs_buf->data[3]; /* Double-check that we haven't accidentally buffered * a message that doesn't fit into the input buffer. */ if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message has been buffered - load" ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered handshake message (incl. header)", hs_buf->data, msg_len + 12 ); ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->in_hslen = msg_len + 12; ssl->in_msglen = msg_len + 12; memcpy( ssl->in_msg, hs_buf->data, ssl->in_hslen ); ret = 0; goto exit; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message %u not or only partially bufffered", hs->in_msg_seq ) ); } ret = -1; exit: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_message" ) ); return( ret ); } static int ssl_buffer_make_space( mbedtls_ssl_context *ssl, size_t desired ) { int offset; mbedtls_ssl_handshake_params * const hs = ssl->handshake; MBEDTLS_SSL_DEBUG_MSG( 2, ( "Attempt to free buffered messages to have %u bytes available", (unsigned) desired ) ); /* Get rid of future records epoch first, if such exist. */ ssl_free_buffered_record( ssl ); /* Check if we have enough space available now. */ if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - hs->buffering.total_bytes_buffered ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing future epoch record" ) ); return( 0 ); } /* We don't have enough space to buffer the next expected handshake * message. Remove buffers used for future messages to gain space, * starting with the most distant one. */ for( offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1; offset >= 0; offset-- ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Free buffering slot %d to make space for reassembly of next handshake message", offset ) ); ssl_buffering_free_slot( ssl, (uint8_t) offset ); /* Check if we have enough space available now. */ if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - hs->buffering.total_bytes_buffered ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing buffered HS messages" ) ); return( 0 ); } } return( -1 ); } static int ssl_buffer_message( mbedtls_ssl_context *ssl ) { int ret = 0; mbedtls_ssl_handshake_params * const hs = ssl->handshake; if( hs == NULL ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_buffer_message" ) ); switch( ssl->in_msgtype ) { case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC: MBEDTLS_SSL_DEBUG_MSG( 2, ( "Remember CCS message" ) ); hs->buffering.seen_ccs = 1; break; case MBEDTLS_SSL_MSG_HANDSHAKE: { unsigned recv_msg_seq_offset; unsigned recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; mbedtls_ssl_hs_buffer *hs_buf; size_t msg_len = ssl->in_hslen - 12; /* We should never receive an old handshake * message - double-check nonetheless. */ if( recv_msg_seq < ssl->handshake->in_msg_seq ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq; if( recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS ) { /* Silently ignore -- message too far in the future */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "Ignore future HS message with sequence number %u, " "buffering window %u - %u", recv_msg_seq, ssl->handshake->in_msg_seq, ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1 ) ); goto exit; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering HS message with sequence number %u, offset %u ", recv_msg_seq, recv_msg_seq_offset ) ); hs_buf = &hs->buffering.hs[ recv_msg_seq_offset ]; /* Check if the buffering for this seq nr has already commenced. */ if( !hs_buf->is_valid ) { size_t reassembly_buf_sz; hs_buf->is_fragmented = ( ssl_hs_is_proper_fragment( ssl ) == 1 ); /* We copy the message back into the input buffer * after reassembly, so check that it's not too large. * This is an implementation-specific limitation * and not one from the standard, hence it is not * checked in ssl_check_hs_header(). */ if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN ) { /* Ignore message */ goto exit; } /* Check if we have enough space to buffer the message. */ if( hs->buffering.total_bytes_buffered > MBEDTLS_SSL_DTLS_MAX_BUFFERING ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } reassembly_buf_sz = ssl_get_reassembly_buffer_size( msg_len, hs_buf->is_fragmented ); if( reassembly_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - hs->buffering.total_bytes_buffered ) ) { if( recv_msg_seq_offset > 0 ) { /* If we can't buffer a future message because * of space limitations -- ignore. */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- ignore\n", (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING, (unsigned) hs->buffering.total_bytes_buffered ) ); goto exit; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- attempt to make space by freeing buffered future messages\n", (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING, (unsigned) hs->buffering.total_bytes_buffered ) ); } if( ssl_buffer_make_space( ssl, reassembly_buf_sz ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reassembly of next message of size %u (%u with bitmap) would exceed the compile-time limit %u (already %u bytes buffered) -- fail\n", (unsigned) msg_len, (unsigned) reassembly_buf_sz, MBEDTLS_SSL_DTLS_MAX_BUFFERING, (unsigned) hs->buffering.total_bytes_buffered ) ); ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL; goto exit; } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d", msg_len ) ); hs_buf->data = mbedtls_calloc( 1, reassembly_buf_sz ); if( hs_buf->data == NULL ) { ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto exit; } hs_buf->data_len = reassembly_buf_sz; /* Prepare final header: copy msg_type, length and message_seq, * then add standardised fragment_offset and fragment_length */ memcpy( hs_buf->data, ssl->in_msg, 6 ); memset( hs_buf->data + 6, 0, 3 ); memcpy( hs_buf->data + 9, hs_buf->data + 1, 3 ); hs_buf->is_valid = 1; hs->buffering.total_bytes_buffered += reassembly_buf_sz; } else { /* Make sure msg_type and length are consistent */ if( memcmp( hs_buf->data, ssl->in_msg, 4 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Fragment header mismatch - ignore" ) ); /* Ignore */ goto exit; } } if( !hs_buf->is_complete ) { size_t frag_len, frag_off; unsigned char * const msg = hs_buf->data + 12; /* * Check and copy current fragment */ /* Validation of header fields already done in * mbedtls_ssl_prepare_handshake_record(). */ frag_off = ssl_get_hs_frag_off( ssl ); frag_len = ssl_get_hs_frag_len( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d", frag_off, frag_len ) ); memcpy( msg + frag_off, ssl->in_msg + 12, frag_len ); if( hs_buf->is_fragmented ) { unsigned char * const bitmask = msg + msg_len; ssl_bitmask_set( bitmask, frag_off, frag_len ); hs_buf->is_complete = ( ssl_bitmask_check( bitmask, msg_len ) == 0 ); } else { hs_buf->is_complete = 1; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "message %scomplete", hs_buf->is_complete ? "" : "not yet " ) ); } break; } default: /* We don't buffer other types of messages. */ break; } exit: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_buffer_message" ) ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ static int ssl_consume_current_message( mbedtls_ssl_context *ssl ) { /* * Consume last content-layer message and potentially * update in_msglen which keeps track of the contents' * consumption state. * * (1) Handshake messages: * Remove last handshake message, move content * and adapt in_msglen. * * (2) Alert messages: * Consume whole record content, in_msglen = 0. * * (3) Change cipher spec: * Consume whole record content, in_msglen = 0. * * (4) Application data: * Don't do anything - the record layer provides * the application data as a stream transport * and consumes through mbedtls_ssl_read only. * */ /* Case (1): Handshake messages */ if( ssl->in_hslen != 0 ) { /* Hard assertion to be sure that no application data * is in flight, as corrupting ssl->in_msglen during * ssl->in_offt != NULL is fatal. */ if( ssl->in_offt != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Get next Handshake message in the current record */ /* Notes: * (1) in_hslen is not necessarily the size of the * current handshake content: If DTLS handshake * fragmentation is used, that's the fragment * size instead. Using the total handshake message * size here is faulty and should be changed at * some point. * (2) While it doesn't seem to cause problems, one * has to be very careful not to assume that in_hslen * is always <= in_msglen in a sensible communication. * Again, it's wrong for DTLS handshake fragmentation. * The following check is therefore mandatory, and * should not be treated as a silently corrected assertion. * Additionally, ssl->in_hslen might be arbitrarily out of * bounds after handling a DTLS message with an unexpected * sequence number, see mbedtls_ssl_prepare_handshake_record. */ if( ssl->in_hslen < ssl->in_msglen ) { ssl->in_msglen -= ssl->in_hslen; memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen, ssl->in_msglen ); MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record", ssl->in_msg, ssl->in_msglen ); } else { ssl->in_msglen = 0; } ssl->in_hslen = 0; } /* Case (4): Application data */ else if( ssl->in_offt != NULL ) { return( 0 ); } /* Everything else (CCS & Alerts) */ else { ssl->in_msglen = 0; } return( 0 ); } static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl ) { if( ssl->in_msglen > 0 ) return( 1 ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) static void ssl_free_buffered_record( mbedtls_ssl_context *ssl ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; if( hs == NULL ) return; if( hs->buffering.future_record.data != NULL ) { hs->buffering.total_bytes_buffered -= hs->buffering.future_record.len; mbedtls_free( hs->buffering.future_record.data ); hs->buffering.future_record.data = NULL; } } static int ssl_load_buffered_record( mbedtls_ssl_context *ssl ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; unsigned char * rec; size_t rec_len; unsigned rec_epoch; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t in_buf_len = ssl->in_buf_len; #else size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; #endif if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) return( 0 ); if( hs == NULL ) return( 0 ); rec = hs->buffering.future_record.data; rec_len = hs->buffering.future_record.len; rec_epoch = hs->buffering.future_record.epoch; if( rec == NULL ) return( 0 ); /* Only consider loading future records if the * input buffer is empty. */ if( ssl_next_record_is_in_datagram( ssl ) == 1 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_record" ) ); if( rec_epoch != ssl->in_epoch ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffered record not from current epoch." ) ); goto exit; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "Found buffered record from current epoch - load" ) ); /* Double-check that the record is not too large */ if( rec_len > in_buf_len - (size_t)( ssl->in_hdr - ssl->in_buf ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } memcpy( ssl->in_hdr, rec, rec_len ); ssl->in_left = rec_len; ssl->next_record_offset = 0; ssl_free_buffered_record( ssl ); exit: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_record" ) ); return( 0 ); } static int ssl_buffer_future_record( mbedtls_ssl_context *ssl, mbedtls_record const *rec ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; /* Don't buffer future records outside handshakes. */ if( hs == NULL ) return( 0 ); /* Only buffer handshake records (we are only interested * in Finished messages). */ if( rec->type != MBEDTLS_SSL_MSG_HANDSHAKE ) return( 0 ); /* Don't buffer more than one future epoch record. */ if( hs->buffering.future_record.data != NULL ) return( 0 ); /* Don't buffer record if there's not enough buffering space remaining. */ if( rec->buf_len > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - hs->buffering.total_bytes_buffered ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future epoch record of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- ignore\n", (unsigned) rec->buf_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING, (unsigned) hs->buffering.total_bytes_buffered ) ); return( 0 ); } /* Buffer record */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffer record from epoch %u", ssl->in_epoch + 1 ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered record", rec->buf, rec->buf_len ); /* ssl_parse_record_header() only considers records * of the next epoch as candidates for buffering. */ hs->buffering.future_record.epoch = ssl->in_epoch + 1; hs->buffering.future_record.len = rec->buf_len; hs->buffering.future_record.data = mbedtls_calloc( 1, hs->buffering.future_record.len ); if( hs->buffering.future_record.data == NULL ) { /* If we run out of RAM trying to buffer a * record from the next epoch, just ignore. */ return( 0 ); } memcpy( hs->buffering.future_record.data, rec->buf, rec->buf_len ); hs->buffering.total_bytes_buffered += rec->buf_len; return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ static int ssl_get_next_record( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_record rec; #if defined(MBEDTLS_SSL_PROTO_DTLS) /* We might have buffered a future record; if so, * and if the epoch matches now, load it. * On success, this call will set ssl->in_left to * the length of the buffered record, so that * the calls to ssl_fetch_input() below will * essentially be no-ops. */ ret = ssl_load_buffered_record( ssl ); if( ret != 0 ) return( ret ); #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* Ensure that we have enough space available for the default form * of TLS / DTLS record headers (5 Bytes for TLS, 13 Bytes for DTLS, * with no space for CIDs counted in). */ ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_in_hdr_len( ssl ) ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } ret = ssl_parse_record_header( ssl, ssl->in_hdr, ssl->in_left, &rec ); if( ret != 0 ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE ) { ret = ssl_buffer_future_record( ssl, &rec ); if( ret != 0 ) return( ret ); /* Fall through to handling of unexpected records */ ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD; } if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ) { #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) /* Reset in pointers to default state for TLS/DTLS records, * assuming no CID and no offset between record content and * record plaintext. */ mbedtls_ssl_update_in_pointers( ssl ); /* Setup internal message pointers from record structure. */ ssl->in_msgtype = rec.type; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->in_len = ssl->in_cid + rec.cid_len; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->in_iv = ssl->in_msg = ssl->in_len + 2; ssl->in_msglen = rec.data_len; ret = ssl_check_client_reconnect( ssl ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_client_reconnect", ret ); if( ret != 0 ) return( ret ); #endif /* Skip unexpected record (but not whole datagram) */ ssl->next_record_offset = rec.buf_len; MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record " "(header)" ) ); } else { /* Skip invalid record and the rest of the datagram */ ssl->next_record_offset = 0; ssl->in_left = 0; MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record " "(header)" ) ); } /* Get next record */ return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); } else #endif { return( ret ); } } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Remember offset of next record within datagram. */ ssl->next_record_offset = rec.buf_len; if( ssl->next_record_offset < ssl->in_left ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "more than one record within datagram" ) ); } } else #endif { /* * Fetch record contents from underlying transport. */ ret = mbedtls_ssl_fetch_input( ssl, rec.buf_len ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } ssl->in_left = 0; } /* * Decrypt record contents. */ if( ( ret = ssl_prepare_record_content( ssl, &rec ) ) != 0 ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Silently discard invalid records */ if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) { /* Except when waiting for Finished as a bad mac here * probably means something went wrong in the handshake * (eg wrong psk used, mitm downgrade attempt, etc.) */ if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED || ssl->state == MBEDTLS_SSL_SERVER_FINISHED ) { #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC ); } #endif return( ret ); } #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) if( ssl->conf->badmac_limit != 0 && ++ssl->badmac_seen >= ssl->conf->badmac_limit ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } #endif /* As above, invalid records cause * dismissal of the whole datagram. */ ssl->next_record_offset = 0; ssl->in_left = 0; MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) ); return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); } return( ret ); } else #endif { /* Error out (and send alert) on invalid records */ #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC ); } #endif return( ret ); } } /* Reset in pointers to default state for TLS/DTLS records, * assuming no CID and no offset between record content and * record plaintext. */ mbedtls_ssl_update_in_pointers( ssl ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->in_len = ssl->in_cid + rec.cid_len; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->in_iv = ssl->in_len + 2; /* The record content type may change during decryption, * so re-read it. */ ssl->in_msgtype = rec.type; /* Also update the input buffer, because unfortunately * the server-side ssl_parse_client_hello() reparses the * record header when receiving a ClientHello initiating * a renegotiation. */ ssl->in_hdr[0] = rec.type; ssl->in_msg = rec.buf + rec.data_offset; ssl->in_msglen = rec.data_len; ssl->in_len[0] = (unsigned char)( rec.data_len >> 8 ); ssl->in_len[1] = (unsigned char)( rec.data_len ); #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->transform_in != NULL && ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) { if( ( ret = ssl_decompress_buf( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret ); return( ret ); } /* Check actual (decompress) record content length against * configured maximum. */ if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } } #endif /* MBEDTLS_ZLIB_SUPPORT */ return( 0 ); } int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* * Handle particular types of records */ if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) { if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 ) { return( ret ); } } if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) { if( ssl->in_msglen != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, len: %d", ssl->in_msglen ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } if( ssl->in_msg[0] != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, content: %02x", ssl->in_msg[0] ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC && ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC ) { if( ssl->handshake == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping ChangeCipherSpec outside handshake" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "received out-of-order ChangeCipherSpec - remember" ) ); return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); } #endif } if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT ) { if( ssl->in_msglen != 2 ) { /* Note: Standard allows for more than one 2 byte alert to be packed in a single message, but Mbed TLS doesn't currently support this. */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %d", ssl->in_msglen ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]", ssl->in_msg[0], ssl->in_msg[1] ) ); /* * Ignore non-fatal alerts, except close_notify and no_renegotiation */ if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)", ssl->in_msg[1] ) ); return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE ); } if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) ); return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ); } #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED) if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no renegotiation alert" ) ); /* Will be handled when trying to parse ServerHello */ return( 0 ); } #endif #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) ); /* Will be handled in mbedtls_ssl_parse_certificate() */ return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */ /* Silently ignore: fetch new message */ return MBEDTLS_ERR_SSL_NON_FATAL; } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Drop unexpected ApplicationData records, * except at the beginning of renegotiations */ if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA && ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER #if defined(MBEDTLS_SSL_RENEGOTIATION) && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->state == MBEDTLS_SSL_SERVER_HELLO ) #endif ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) ); return( MBEDTLS_ERR_SSL_NON_FATAL ); } if( ssl->handshake != NULL && ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) { mbedtls_ssl_handshake_wrapup_free_hs_transform( ssl ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ return( 0 ); } int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl ) { return( mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ); } int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl, unsigned char level, unsigned char message ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message )); ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT; ssl->out_msglen = 2; ssl->out_msg[0] = level; ssl->out_msg[1] = message; if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) ); return( 0 ); } int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC; ssl->out_msglen = 1; ssl->out_msg[0] = 1; ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) ); return( 0 ); } int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) ); if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* CCS records are only accepted if they have length 1 and content '1', * so we don't need to check this here. */ /* * Switch to our negotiated transform and session parameters for inbound * data. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) ); ssl->transform_in = ssl->transform_negotiate; ssl->session_in = ssl->session_negotiate; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) mbedtls_ssl_dtls_replay_reset( ssl ); #endif /* Increment epoch */ if( ++ssl->in_epoch == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) ); /* This is highly unlikely to happen for legitimate reasons, so treat it as an attack and don't send an alert. */ return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ memset( ssl->in_ctr, 0, 8 ); mbedtls_ssl_update_in_pointers( ssl ); #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_activate != NULL ) { if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) ); return( 0 ); } /* Once ssl->out_hdr as the address of the beginning of the * next outgoing record is set, deduce the other pointers. * * Note: For TLS, we save the implicit record sequence number * (entering MAC computation) in the 8 bytes before ssl->out_hdr, * and the caller has to make sure there's space for this. */ static size_t ssl_transform_get_explicit_iv_len( mbedtls_ssl_transform const *transform ) { if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) return( 0 ); return( transform->ivlen - transform->fixed_ivlen ); } void mbedtls_ssl_update_out_pointers( mbedtls_ssl_context *ssl, mbedtls_ssl_transform *transform ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->out_ctr = ssl->out_hdr + 3; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->out_cid = ssl->out_ctr + 8; ssl->out_len = ssl->out_cid; if( transform != NULL ) ssl->out_len += transform->out_cid_len; #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->out_len = ssl->out_ctr + 8; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->out_iv = ssl->out_len + 2; } else #endif { ssl->out_ctr = ssl->out_hdr - 8; ssl->out_len = ssl->out_hdr + 3; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->out_cid = ssl->out_len; #endif ssl->out_iv = ssl->out_hdr + 5; } ssl->out_msg = ssl->out_iv; /* Adjust out_msg to make space for explicit IV, if used. */ if( transform != NULL ) ssl->out_msg += ssl_transform_get_explicit_iv_len( transform ); } /* Once ssl->in_hdr as the address of the beginning of the * next incoming record is set, deduce the other pointers. * * Note: For TLS, we save the implicit record sequence number * (entering MAC computation) in the 8 bytes before ssl->in_hdr, * and the caller has to make sure there's space for this. */ void mbedtls_ssl_update_in_pointers( mbedtls_ssl_context *ssl ) { /* This function sets the pointers to match the case * of unprotected TLS/DTLS records, with both ssl->in_iv * and ssl->in_msg pointing to the beginning of the record * content. * * When decrypting a protected record, ssl->in_msg * will be shifted to point to the beginning of the * record plaintext. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* This sets the header pointers to match records * without CID. When we receive a record containing * a CID, the fields are shifted accordingly in * ssl_parse_record_header(). */ ssl->in_ctr = ssl->in_hdr + 3; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->in_cid = ssl->in_ctr + 8; ssl->in_len = ssl->in_cid; /* Default: no CID */ #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->in_len = ssl->in_ctr + 8; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->in_iv = ssl->in_len + 2; } else #endif { ssl->in_ctr = ssl->in_hdr - 8; ssl->in_len = ssl->in_hdr + 3; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->in_cid = ssl->in_len; #endif ssl->in_iv = ssl->in_hdr + 5; } /* This will be adjusted at record decryption time. */ ssl->in_msg = ssl->in_iv; } /* * Setup an SSL context */ void mbedtls_ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl ) { /* Set the incoming and outgoing record pointers. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->out_hdr = ssl->out_buf; ssl->in_hdr = ssl->in_buf; } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { ssl->out_hdr = ssl->out_buf + 8; ssl->in_hdr = ssl->in_buf + 8; } /* Derive other internal pointers. */ mbedtls_ssl_update_out_pointers( ssl, NULL /* no transform enabled */ ); mbedtls_ssl_update_in_pointers ( ssl ); } /* * SSL get accessors */ size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl ) { return( ssl->in_offt == NULL ? 0 : ssl->in_msglen ); } int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl ) { /* * Case A: We're currently holding back * a message for further processing. */ if( ssl->keep_current_message == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: record held back for processing" ) ); return( 1 ); } /* * Case B: Further records are pending in the current datagram. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->in_left > ssl->next_record_offset ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more records within current datagram" ) ); return( 1 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* * Case C: A handshake message is being processed. */ if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more handshake messages within current record" ) ); return( 1 ); } /* * Case D: An application data message is being processed */ if( ssl->in_offt != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: application data record is being processed" ) ); return( 1 ); } /* * In all other cases, the rest of the message can be dropped. * As in ssl_get_next_record, this needs to be adapted if * we implement support for multiple alerts in single records. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: nothing pending" ) ); return( 0 ); } int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl ) { size_t transform_expansion = 0; const mbedtls_ssl_transform *transform = ssl->transform_out; unsigned block_size; size_t out_hdr_len = mbedtls_ssl_out_hdr_len( ssl ); if( transform == NULL ) return( (int) out_hdr_len ); #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) ) { case MBEDTLS_MODE_GCM: case MBEDTLS_MODE_CCM: case MBEDTLS_MODE_CHACHAPOLY: case MBEDTLS_MODE_STREAM: transform_expansion = transform->minlen; break; case MBEDTLS_MODE_CBC: block_size = mbedtls_cipher_get_block_size( &transform->cipher_ctx_enc ); /* Expansion due to the addition of the MAC. */ transform_expansion += transform->maclen; /* Expansion due to the addition of CBC padding; * Theoretically up to 256 bytes, but we never use * more than the block size of the underlying cipher. */ transform_expansion += block_size; /* For TLS 1.1 or higher, an explicit IV is added * after the record header. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) transform_expansion += block_size; #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ break; default: MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( transform->out_cid_len != 0 ) transform_expansion += MBEDTLS_SSL_MAX_CID_EXPANSION; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ return( (int)( out_hdr_len + transform_expansion ) ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) /* * Check record counters and renegotiate if they're above the limit. */ static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl ) { size_t ep_len = mbedtls_ssl_ep_len( ssl ); int in_ctr_cmp; int out_ctr_cmp; if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER || ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING || ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ) { return( 0 ); } in_ctr_cmp = memcmp( ssl->in_ctr + ep_len, ssl->conf->renego_period + ep_len, 8 - ep_len ); out_ctr_cmp = memcmp( ssl->cur_out_ctr + ep_len, ssl->conf->renego_period + ep_len, 8 - ep_len ); if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 ) { return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) ); return( mbedtls_ssl_renegotiate( ssl ) ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /* * Receive application data decrypted from the SSL layer */ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); if( ssl->handshake != NULL && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) return( ret ); } } #endif /* * Check if renegotiation is necessary and/or handshake is * in process. If yes, perform/continue, and fall through * if an unexpected packet is received while the client * is waiting for the ServerHello. * * (There is no equivalent to the last condition on * the server-side as it is not treated as within * a handshake while waiting for the ClientHello * after a renegotiation request.) */ #if defined(MBEDTLS_SSL_RENEGOTIATION) ret = ssl_check_ctr_renegotiate( ssl ); if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO && ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret ); return( ret ); } #endif if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { ret = mbedtls_ssl_handshake( ssl ); if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO && ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } } /* Loop as long as no application data record is available */ while( ssl->in_offt == NULL ) { /* Start timer if not already running */ if( ssl->f_get_timer != NULL && ssl->f_get_timer( ssl->p_timer ) == -1 ) { mbedtls_ssl_set_timer( ssl, ssl->conf->read_timeout ); } if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { if( ret == MBEDTLS_ERR_SSL_CONN_EOF ) return( 0 ); MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msglen == 0 && ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA ) { /* * OpenSSL sends empty messages to randomize the IV */ if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { if( ret == MBEDTLS_ERR_SSL_CONN_EOF ) return( 0 ); MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } } if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) ); /* * - For client-side, expect SERVER_HELLO_REQUEST. * - For server-side, expect CLIENT_HELLO. * - Fail (TLS) or silently drop record (DTLS) in other cases. */ #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST || ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) ); /* With DTLS, drop the packet (probably from last handshake) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { continue; } #endif return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } #endif /* MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) ); /* With DTLS, drop the packet (probably from last handshake) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { continue; } #endif return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } #endif /* MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_SSL_RENEGOTIATION) /* Determine whether renegotiation attempt should be accepted */ if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED || ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) ) { /* * Accept renegotiation request */ /* DTLS clients need to know renego is server-initiated */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) { ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING; } #endif ret = mbedtls_ssl_start_renegotiation( ssl ); if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO && ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_start_renegotiation", ret ); return( ret ); } } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { /* * Refuse renegotiation */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) ); #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { /* SSLv3 does not have a "no_renegotiation" warning, so we send a fatal alert and abort the connection. */ mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) { if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_WARNING, MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 ) { return( ret ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } /* At this point, we don't know whether the renegotiation has been * completed or not. The cases to consider are the following: * 1) The renegotiation is complete. In this case, no new record * has been read yet. * 2) The renegotiation is incomplete because the client received * an application data record while awaiting the ServerHello. * 3) The renegotiation is incomplete because the client received * a non-handshake, non-application data message while awaiting * the ServerHello. * In each of these case, looping will be the proper action: * - For 1), the next iteration will read a new record and check * if it's application data. * - For 2), the loop condition isn't satisfied as application data * is present, hence continue is the same as break * - For 3), the loop condition is satisfied and read_record * will re-deliver the message that was held back by the client * when expecting the ServerHello. */ continue; } #if defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ssl->conf->renego_max_records >= 0 ) { if( ++ssl->renego_records_seen > ssl->conf->renego_max_records ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, " "but not honored by client" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } } } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */ if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) ); return( MBEDTLS_ERR_SSL_WANT_READ ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } ssl->in_offt = ssl->in_msg; /* We're going to return something now, cancel timer, * except if handshake (renegotiation) is in progress */ if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) mbedtls_ssl_set_timer( ssl, 0 ); #if defined(MBEDTLS_SSL_PROTO_DTLS) /* If we requested renego but received AppData, resend HelloRequest. * Do it now, after setting in_offt, to avoid taking this branch * again if ssl_write_hello_request() returns WANT_WRITE */ #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ( ret = mbedtls_ssl_resend_hello_request( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend_hello_request", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ #endif /* MBEDTLS_SSL_PROTO_DTLS */ } n = ( len < ssl->in_msglen ) ? len : ssl->in_msglen; memcpy( buf, ssl->in_offt, n ); ssl->in_msglen -= n; /* Zeroising the plaintext buffer to erase unused application data from the memory. */ mbedtls_platform_zeroize( ssl->in_offt, n ); if( ssl->in_msglen == 0 ) { /* all bytes consumed */ ssl->in_offt = NULL; ssl->keep_current_message = 0; } else { /* more data available */ ssl->in_offt += n; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) ); return( (int) n ); } /* * Send application data to be encrypted by the SSL layer, taking care of max * fragment length and buffer size. * * According to RFC 5246 Section 6.2.1: * * Zero-length fragments of Application data MAY be sent as they are * potentially useful as a traffic analysis countermeasure. * * Therefore, it is possible that the input message length is 0 and the * corresponding return code is 0 on success. */ static int ssl_write_real( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = mbedtls_ssl_get_max_out_record_payload( ssl ); const size_t max_len = (size_t) ret; if( ret < 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_get_max_out_record_payload", ret ); return( ret ); } if( len > max_len ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) " "maximum fragment length: %d > %d", len, max_len ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } else #endif len = max_len; } if( ssl->out_left != 0 ) { /* * The user has previously tried to send the data and * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially * written. In this case, we expect the high-level write function * (e.g. mbedtls_ssl_write()) to be called with the same parameters */ if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret ); return( ret ); } } else { /* * The user is trying to send a message the first time, so we need to * copy the data into the internal buffers and setup the data structure * to keep track of partial writes */ ssl->out_msglen = len; ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA; memcpy( ssl->out_msg, buf, len ); if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } } return( (int) len ); } /* * Write application data, doing 1/n-1 splitting if necessary. * * With non-blocking I/O, ssl_write_real() may return WANT_WRITE, * then the caller will call us again with the same arguments, so * remember whether we already did the split or not. */ #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) static int ssl_write_split( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ssl->conf->cbc_record_splitting == MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED || len <= 1 || ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 || mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc ) != MBEDTLS_MODE_CBC ) { return( ssl_write_real( ssl, buf, len ) ); } if( ssl->split_done == 0 ) { if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 ) return( ret ); ssl->split_done = 1; } if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 ) return( ret ); ssl->split_done = 0; return( ret + 1 ); } #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */ /* * Write application data (public-facing wrapper) */ int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) ); if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret ); return( ret ); } #endif if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } } #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) ret = ssl_write_split( ssl, buf, len ); #else ret = ssl_write_real( ssl, buf, len ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) ); return( ret ); } /* * Notify the peer that the connection is being closed */ int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) ); if( ssl->out_left != 0 ) return( mbedtls_ssl_flush_output( ssl ) ); if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) { if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_WARNING, MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret ); return( ret ); } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) ); return( 0 ); } void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform ) { if( transform == NULL ) return; #if defined(MBEDTLS_ZLIB_SUPPORT) deflateEnd( &transform->ctx_deflate ); inflateEnd( &transform->ctx_inflate ); #endif mbedtls_cipher_free( &transform->cipher_ctx_enc ); mbedtls_cipher_free( &transform->cipher_ctx_dec ); #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) mbedtls_md_free( &transform->md_ctx_enc ); mbedtls_md_free( &transform->md_ctx_dec ); #endif mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) void mbedtls_ssl_buffering_free( mbedtls_ssl_context *ssl ) { unsigned offset; mbedtls_ssl_handshake_params * const hs = ssl->handshake; if( hs == NULL ) return; ssl_free_buffered_record( ssl ); for( offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ ) ssl_buffering_free_slot( ssl, offset ); } static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl, uint8_t slot ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot]; if( slot >= MBEDTLS_SSL_MAX_BUFFERED_HS ) return; if( hs_buf->is_valid == 1 ) { hs->buffering.total_bytes_buffered -= hs_buf->data_len; mbedtls_platform_zeroize( hs_buf->data, hs_buf->data_len ); mbedtls_free( hs_buf->data ); memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* * Convert version numbers to/from wire format * and, for DTLS, to/from TLS equivalent. * * For TLS this is the identity. * For DTLS, use 1's complement (v -> 255 - v, and then map as follows: * 1.0 <-> 3.2 (DTLS 1.0 is based on TLS 1.1) * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2) */ void mbedtls_ssl_write_version( int major, int minor, int transport, unsigned char ver[2] ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { if( minor == MBEDTLS_SSL_MINOR_VERSION_2 ) --minor; /* DTLS 1.0 stored as TLS 1.1 internally */ ver[0] = (unsigned char)( 255 - ( major - 2 ) ); ver[1] = (unsigned char)( 255 - ( minor - 1 ) ); } else #else ((void) transport); #endif { ver[0] = (unsigned char) major; ver[1] = (unsigned char) minor; } } void mbedtls_ssl_read_version( int *major, int *minor, int transport, const unsigned char ver[2] ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { *major = 255 - ver[0] + 2; *minor = 255 - ver[1] + 1; if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 ) ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */ } else #else ((void) transport); #endif { *major = ver[0]; *minor = ver[1]; } } #endif /* MBEDTLS_SSL_TLS_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_srv.c
/* * SSLv3/TLSv1 server-side functions * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #if defined(MBEDTLS_SSL_SRV_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/ssl.h" #include "mbedtls/ssl_internal.h" #include "mbedtls/debug.h" #include "mbedtls/error.h" #include "mbedtls/platform_util.h" #include <string.h> #if defined(MBEDTLS_ECP_C) #include "mbedtls/ecp.h" #endif #if defined(MBEDTLS_HAVE_TIME) #include "mbedtls/platform_time.h" #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl, const unsigned char *info, size_t ilen ) { if( ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); mbedtls_free( ssl->cli_id ); if( ( ssl->cli_id = mbedtls_calloc( 1, ilen ) ) == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( ssl->cli_id, info, ilen ); ssl->cli_id_len = ilen; return( 0 ); } void mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf, mbedtls_ssl_cookie_write_t *f_cookie_write, mbedtls_ssl_cookie_check_t *f_cookie_check, void *p_cookie ) { conf->f_cookie_write = f_cookie_write; conf->f_cookie_check = f_cookie_check; conf->p_cookie = p_cookie; } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t servername_list_size, hostname_len; const unsigned char *p; MBEDTLS_SSL_DEBUG_MSG( 3, ( "parse ServerName extension" ) ); if( len < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } servername_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( servername_list_size + 2 != len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } p = buf + 2; while( servername_list_size > 2 ) { hostname_len = ( ( p[1] << 8 ) | p[2] ); if( hostname_len + 3 > servername_list_size ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) { ret = ssl->conf->f_sni( ssl->conf->p_sni, ssl, p + 3, hostname_len ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } return( 0 ); } servername_list_size -= hostname_len + 3; p += hostname_len + 3; } if( servername_list_size != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } return( 0 ); } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static int ssl_conf_has_psk_or_cb( mbedtls_ssl_config const *conf ) { if( conf->f_psk != NULL ) return( 1 ); if( conf->psk_identity_len == 0 || conf->psk_identity == NULL ) return( 0 ); if( conf->psk != NULL && conf->psk_len != 0 ) return( 1 ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ! mbedtls_svc_key_id_is_null( conf->psk_opaque ) ) return( 1 ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ return( 0 ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) static int ssl_use_opaque_psk( mbedtls_ssl_context const *ssl ) { if( ssl->conf->f_psk != NULL ) { /* If we've used a callback to select the PSK, * the static configuration is irrelevant. */ if( ! mbedtls_svc_key_id_is_null( ssl->handshake->psk_opaque ) ) return( 1 ); return( 0 ); } if( ! mbedtls_svc_key_id_is_null( ssl->conf->psk_opaque ) ) return( 1 ); return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { /* Check verify-data in constant-time. The length OTOH is no secret */ if( len != 1 + ssl->verify_data_len || buf[0] != ssl->verify_data_len || mbedtls_ssl_safer_memcmp( buf + 1, ssl->peer_verify_data, ssl->verify_data_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { if( len != 1 || buf[0] != 0x0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; } return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* * Status of the implementation of signature-algorithms extension: * * Currently, we are only considering the signature-algorithm extension * to pick a ciphersuite which allows us to send the ServerKeyExchange * message with a signature-hash combination that the user allows. * * We do *not* check whether all certificates in our certificate * chain are signed with an allowed signature-hash pair. * This needs to be done at a later stage. * */ static int ssl_parse_signature_algorithms_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t sig_alg_list_size; const unsigned char *p; const unsigned char *end = buf + len; mbedtls_md_type_t md_cur; mbedtls_pk_type_t sig_cur; if ( len < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } sig_alg_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( sig_alg_list_size + 2 != len || sig_alg_list_size % 2 != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Currently we only guarantee signing the ServerKeyExchange message according * to the constraints specified in this extension (see above), so it suffices * to remember only one suitable hash for each possible signature algorithm. * * This will change when we also consider certificate signatures, * in which case we will need to remember the whole signature-hash * pair list from the extension. */ for( p = buf + 2; p < end; p += 2 ) { /* Silently ignore unknown signature or hash algorithms. */ if( ( sig_cur = mbedtls_ssl_pk_alg_from_sig( p[1] ) ) == MBEDTLS_PK_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext" " unknown sig alg encoding %d", p[1] ) ); continue; } /* Check if we support the hash the user proposes */ md_cur = mbedtls_ssl_md_alg_from_hash( p[0] ); if( md_cur == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:" " unknown hash alg encoding %d", p[0] ) ); continue; } if( mbedtls_ssl_check_sig_hash( ssl, md_cur ) == 0 ) { mbedtls_ssl_sig_hash_set_add( &ssl->handshake->hash_algs, sig_cur, md_cur ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:" " match sig %d and hash %d", sig_cur, md_cur ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: " "hash alg %d not supported", md_cur ) ); } } return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_parse_supported_elliptic_curves( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_size, our_size; const unsigned char *p; const mbedtls_ecp_curve_info *curve_info, **curves; if ( len < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( list_size + 2 != len || list_size % 2 != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Should never happen unless client duplicates the extension */ if( ssl->handshake->curves != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Don't allow our peer to make us allocate too much memory, * and leave room for a final 0 */ our_size = list_size / 2 + 1; if( our_size > MBEDTLS_ECP_DP_MAX ) our_size = MBEDTLS_ECP_DP_MAX; if( ( curves = mbedtls_calloc( our_size, sizeof( *curves ) ) ) == NULL ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } ssl->handshake->curves = curves; p = buf + 2; while( list_size > 0 && our_size > 1 ) { curve_info = mbedtls_ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] ); if( curve_info != NULL ) { *curves++ = curve_info; our_size--; } list_size -= 2; p += 2; } return( 0 ); } static int ssl_parse_supported_point_formats( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_size; const unsigned char *p; if( len == 0 || (size_t)( buf[0] + 1 ) != len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } list_size = buf[0]; p = buf + 1; while( list_size > 0 ) { if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED || p[0] == MBEDTLS_ECP_PF_COMPRESSED ) { #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ssl->handshake->ecdh_ctx.point_format = p[0]; #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ssl->handshake->ecjpake_ctx.point_format = p[0]; #endif MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) ); return( 0 ); } list_size--; p++; } return( 0 ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) ); return( 0 ); } if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx, buf, len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( ret ); } /* Only mark the extension as OK when we're sure it is */ ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->session_negotiate->mfl_code = buf[0]; return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) static int ssl_parse_cid_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t peer_cid_len; /* CID extension only makes sense in DTLS */ if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Quoting draft-ietf-tls-dtls-connection-id-05 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05 * * struct { * opaque cid<0..2^8-1>; * } ConnectionId; */ if( len < 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } peer_cid_len = *buf++; len--; if( len != peer_cid_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Ignore CID if the user has disabled its use. */ if( ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED ) { /* Leave ssl->handshake->cid_in_use in its default * value of MBEDTLS_SSL_CID_DISABLED. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "Client sent CID extension, but CID disabled" ) ); return( 0 ); } if( peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED; ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len; memcpy( ssl->handshake->peer_cid, buf, peer_cid_len ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use of CID extension negotiated" ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Client CID", buf, peer_cid_len ); return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ((void) buf); if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED ) ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED; return( 0 ); } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ((void) buf); if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED && ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED; } return( 0 ); } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ((void) buf); if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED && ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED; } return( 0 ); } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_ssl_session session; mbedtls_ssl_session_init( &session ); if( ssl->conf->f_ticket_parse == NULL || ssl->conf->f_ticket_write == NULL ) { return( 0 ); } /* Remember the client asked us to send a new ticket */ ssl->handshake->new_session_ticket = 1; MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", len ) ); if( len == 0 ) return( 0 ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket rejected: renegotiating" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /* * Failures are ok: just ignore the ticket and proceed. */ if( ( ret = ssl->conf->f_ticket_parse( ssl->conf->p_ticket, &session, buf, len ) ) != 0 ) { mbedtls_ssl_session_free( &session ); if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is not authentic" ) ); else if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is expired" ) ); else MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_parse", ret ); return( 0 ); } /* * Keep the session ID sent by the client, since we MUST send it back to * inform them we're accepting the ticket (RFC 5077 section 3.4) */ session.id_len = ssl->session_negotiate->id_len; memcpy( &session.id, ssl->session_negotiate->id, session.id_len ); mbedtls_ssl_session_free( ssl->session_negotiate ); memcpy( ssl->session_negotiate, &session, sizeof( mbedtls_ssl_session ) ); /* Zeroize instead of free as we copied the content */ mbedtls_platform_zeroize( &session, sizeof( mbedtls_ssl_session ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from ticket" ) ); ssl->handshake->resume = 1; /* Don't send a new ticket after all, this one is OK */ ssl->handshake->new_session_ticket = 0; return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_ALPN) static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_len, cur_len, ours_len; const unsigned char *theirs, *start, *end; const char **ours; /* If ALPN not configured, just ignore the extension */ if( ssl->conf->alpn_list == NULL ) return( 0 ); /* * opaque ProtocolName<1..2^8-1>; * * struct { * ProtocolName protocol_name_list<2..2^16-1> * } ProtocolNameList; */ /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */ if( len < 4 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } list_len = ( buf[0] << 8 ) | buf[1]; if( list_len != len - 2 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Validate peer's list (lengths) */ start = buf + 2; end = buf + len; for( theirs = start; theirs != end; theirs += cur_len ) { cur_len = *theirs++; /* Current identifier must fit in list */ if( cur_len > (size_t)( end - theirs ) ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Empty strings MUST NOT be included */ if( cur_len == 0 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } /* * Use our order of preference */ for( ours = ssl->conf->alpn_list; *ours != NULL; ours++ ) { ours_len = strlen( *ours ); for( theirs = start; theirs != end; theirs += cur_len ) { cur_len = *theirs++; if( cur_len == ours_len && memcmp( theirs, *ours, cur_len ) == 0 ) { ssl->alpn_chosen = *ours; return( 0 ); } } } /* If we get there, no match was found */ mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_DTLS_SRTP) static int ssl_parse_use_srtp_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { mbedtls_ssl_srtp_profile client_protection = MBEDTLS_TLS_SRTP_UNSET; size_t i,j; size_t profile_length; uint16_t mki_length; /*! 2 bytes for profile length and 1 byte for mki len */ const size_t size_of_lengths = 3; /* If use_srtp is not configured, just ignore the extension */ if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) || ( ssl->conf->dtls_srtp_profile_list == NULL ) || ( ssl->conf->dtls_srtp_profile_list_len == 0 ) ) { return( 0 ); } /* RFC5764 section 4.1.1 * uint8 SRTPProtectionProfile[2]; * * struct { * SRTPProtectionProfiles SRTPProtectionProfiles; * opaque srtp_mki<0..255>; * } UseSRTPData; * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>; */ /* * Min length is 5: at least one protection profile(2 bytes) * and length(2 bytes) + srtp_mki length(1 byte) * Check here that we have at least 2 bytes of protection profiles length * and one of srtp_mki length */ if( len < size_of_lengths ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET; /* first 2 bytes are protection profile length(in bytes) */ profile_length = ( buf[0] << 8 ) | buf[1]; buf += 2; /* The profile length cannot be bigger than input buffer size - lengths fields */ if( profile_length > len - size_of_lengths || profile_length % 2 != 0 ) /* profiles are 2 bytes long, so the length must be even */ { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * parse the extension list values are defined in * http://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml */ for( j = 0; j < profile_length; j += 2 ) { uint16_t protection_profile_value = buf[j] << 8 | buf[j + 1]; client_protection = mbedtls_ssl_check_srtp_profile_value( protection_profile_value ); if( client_protection != MBEDTLS_TLS_SRTP_UNSET ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "found srtp profile: %s", mbedtls_ssl_get_srtp_profile_as_string( client_protection ) ) ); } else { continue; } /* check if suggested profile is in our list */ for( i = 0; i < ssl->conf->dtls_srtp_profile_list_len; i++) { if( client_protection == ssl->conf->dtls_srtp_profile_list[i] ) { ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "selected srtp profile: %s", mbedtls_ssl_get_srtp_profile_as_string( client_protection ) ) ); break; } } if( ssl->dtls_srtp_info.chosen_dtls_srtp_profile != MBEDTLS_TLS_SRTP_UNSET ) break; } buf += profile_length; /* buf points to the mki length */ mki_length = *buf; buf++; if( mki_length > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH || mki_length + profile_length + size_of_lengths != len ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Parse the mki only if present and mki is supported locally */ if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED && mki_length > 0 ) { ssl->dtls_srtp_info.mki_len = mki_length; memcpy( ssl->dtls_srtp_info.mki_value, buf, mki_length ); MBEDTLS_SSL_DEBUG_BUF( 3, "using mki", ssl->dtls_srtp_info.mki_value, ssl->dtls_srtp_info.mki_len ); } return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_SRTP */ /* * Auxiliary functions for ServerHello parsing and related actions */ #if defined(MBEDTLS_X509_CRT_PARSE_C) /* * Return 0 if the given key uses one of the acceptable curves, -1 otherwise */ #if defined(MBEDTLS_ECDSA_C) static int ssl_check_key_curve( mbedtls_pk_context *pk, const mbedtls_ecp_curve_info **curves ) { const mbedtls_ecp_curve_info **crv = curves; mbedtls_ecp_group_id grp_id = mbedtls_pk_ec( *pk )->grp.id; while( *crv != NULL ) { if( (*crv)->grp_id == grp_id ) return( 0 ); crv++; } return( -1 ); } #endif /* MBEDTLS_ECDSA_C */ /* * Try picking a certificate for this ciphersuite, * return 0 on success and -1 on failure. */ static int ssl_pick_cert( mbedtls_ssl_context *ssl, const mbedtls_ssl_ciphersuite_t * ciphersuite_info ) { mbedtls_ssl_key_cert *cur, *list, *fallback = NULL; mbedtls_pk_type_t pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); uint32_t flags; #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_key_cert != NULL ) list = ssl->handshake->sni_key_cert; else #endif list = ssl->conf->key_cert; if( pk_alg == MBEDTLS_PK_NONE ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite requires certificate" ) ); if( list == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "server has no certificate" ) ); return( -1 ); } for( cur = list; cur != NULL; cur = cur->next ) { flags = 0; MBEDTLS_SSL_DEBUG_CRT( 3, "candidate certificate chain, certificate", cur->cert ); if( ! mbedtls_pk_can_do( &cur->cert->pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: key type" ) ); continue; } /* * This avoids sending the client a cert it'll reject based on * keyUsage or other extensions. * * It also allows the user to provision different certificates for * different uses based on keyUsage, eg if they want to avoid signing * and decrypting with the same RSA key. */ if( mbedtls_ssl_check_cert_usage( cur->cert, ciphersuite_info, MBEDTLS_SSL_IS_SERVER, &flags ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: " "(extended) key usage extension" ) ); continue; } #if defined(MBEDTLS_ECDSA_C) if( pk_alg == MBEDTLS_PK_ECDSA && ssl_check_key_curve( &cur->cert->pk, ssl->handshake->curves ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: elliptic curve" ) ); continue; } #endif /* * Try to select a SHA-1 certificate for pre-1.2 clients, but still * present them a SHA-higher cert rather than failing if it's the only * one we got that satisfies the other conditions. */ if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 && cur->cert->sig_md != MBEDTLS_MD_SHA1 ) { if( fallback == NULL ) fallback = cur; { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate not preferred: " "sha-2 with pre-TLS 1.2 client" ) ); continue; } } /* If we get there, we got a winner */ break; } if( cur == NULL ) cur = fallback; /* Do not update ssl->handshake->key_cert unless there is a match */ if( cur != NULL ) { ssl->handshake->key_cert = cur; MBEDTLS_SSL_DEBUG_CRT( 3, "selected certificate chain, certificate", ssl->handshake->key_cert->cert ); return( 0 ); } return( -1 ); } #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * Check if a given ciphersuite is suitable for use with our config/keys/etc * Sets ciphersuite_info only if the suite matches. */ static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id, const mbedtls_ssl_ciphersuite_t **ciphersuite_info ) { const mbedtls_ssl_ciphersuite_t *suite_info; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) mbedtls_pk_type_t sig_type; #endif suite_info = mbedtls_ssl_ciphersuite_from_id( suite_id ); if( suite_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "trying ciphersuite: %#04x (%s)", suite_id, suite_info->name ) ); if( suite_info->min_minor_ver > ssl->minor_ver || suite_info->max_minor_ver < ssl->minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: version" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) ) return( 0 ); #endif #if defined(MBEDTLS_ARC4_C) if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED && suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: rc4" ) ); return( 0 ); } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE && ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: ecjpake " "not configured or ext missing" ) ); return( 0 ); } #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) if( mbedtls_ssl_ciphersuite_uses_ec( suite_info ) && ( ssl->handshake->curves == NULL || ssl->handshake->curves[0] == NULL ) ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: " "no common elliptic curve" ) ); return( 0 ); } #endif #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) /* If the ciphersuite requires a pre-shared key and we don't * have one, skip it now rather than failing later */ if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) && ssl_conf_has_psk_or_cb( ssl->conf ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no pre-shared key" ) ); return( 0 ); } #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* If the ciphersuite requires signing, check whether * a suitable hash algorithm is present. */ if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { sig_type = mbedtls_ssl_get_ciphersuite_sig_alg( suite_info ); if( sig_type != MBEDTLS_PK_NONE && mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_type ) == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no suitable hash algorithm " "for signature algorithm %d", sig_type ) ); return( 0 ); } } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_X509_CRT_PARSE_C) /* * Final check: if ciphersuite requires us to have a * certificate/key of a particular type: * - select the appropriate certificate if we have one, or * - try the next ciphersuite if we don't * This must be done last since we modify the key_cert list. */ if( ssl_pick_cert( ssl, suite_info ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: " "no suitable certificate" ) ); return( 0 ); } #endif *ciphersuite_info = suite_info; return( 0 ); } #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) static int ssl_parse_client_hello_v2( mbedtls_ssl_context *ssl ) { int ret, got_common_suite; unsigned int i, j; size_t n; unsigned int ciph_len, sess_len, chal_len; unsigned char *buf, *p; const int *ciphersuites; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello v2" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "client hello v2 illegal for renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ buf = ssl->in_hdr; MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, 5 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message type: %d", buf[2] ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message len.: %d", ( ( buf[0] & 0x7F ) << 8 ) | buf[1] ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, max. version: [%d:%d]", buf[3], buf[4] ) ); /* * SSLv2 Client Hello * * Record layer: * 0 . 1 message length * * SSL layer: * 2 . 2 message type * 3 . 4 protocol version */ if( buf[2] != MBEDTLS_SSL_HS_CLIENT_HELLO || buf[3] != MBEDTLS_SSL_MAJOR_VERSION_3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } n = ( ( buf[0] << 8 ) | buf[1] ) & 0x7FFF; if( n < 17 || n > 512 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; ssl->minor_ver = ( buf[4] <= ssl->conf->max_minor_ver ) ? buf[4] : ssl->conf->max_minor_ver; if( ssl->minor_ver < ssl->conf->min_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum" " [%d:%d] < [%d:%d]", ssl->major_ver, ssl->minor_ver, ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); } ssl->handshake->max_major_ver = buf[3]; ssl->handshake->max_minor_ver = buf[4]; if( ( ret = mbedtls_ssl_fetch_input( ssl, 2 + n ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } ssl->handshake->update_checksum( ssl, buf + 2, n ); buf = ssl->in_msg; n = ssl->in_left - 5; /* * 0 . 1 ciphersuitelist length * 2 . 3 session id length * 4 . 5 challenge length * 6 . .. ciphersuitelist * .. . .. session id * .. . .. challenge */ MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, n ); ciph_len = ( buf[0] << 8 ) | buf[1]; sess_len = ( buf[2] << 8 ) | buf[3]; chal_len = ( buf[4] << 8 ) | buf[5]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciph_len: %d, sess_len: %d, chal_len: %d", ciph_len, sess_len, chal_len ) ); /* * Make sure each parameter length is valid */ if( ciph_len < 3 || ( ciph_len % 3 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( sess_len > 32 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( chal_len < 8 || chal_len > 32 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( n != 6 + ciph_len + sess_len + chal_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist", buf + 6, ciph_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 6 + ciph_len, sess_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, challenge", buf + 6 + ciph_len + sess_len, chal_len ); p = buf + 6 + ciph_len; ssl->session_negotiate->id_len = sess_len; memset( ssl->session_negotiate->id, 0, sizeof( ssl->session_negotiate->id ) ); memcpy( ssl->session_negotiate->id, p, ssl->session_negotiate->id_len ); p += sess_len; memset( ssl->handshake->randbytes, 0, 64 ); memcpy( ssl->handshake->randbytes + 32 - chal_len, p, chal_len ); /* * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */ for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 ) { if( p[0] == 0 && p[1] == 0 && p[2] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV " "during renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; break; } } #if defined(MBEDTLS_SSL_FALLBACK_SCSV) for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 ) { if( p[0] == 0 && p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) && p[2] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ) & 0xff ) ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "received FALLBACK_SCSV" ) ); if( ssl->minor_ver < ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } break; } } #endif /* MBEDTLS_SSL_FALLBACK_SCSV */ got_common_suite = 0; ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; ciphersuite_info = NULL; #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE) for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 ) for( i = 0; ciphersuites[i] != 0; i++ ) #else for( i = 0; ciphersuites[i] != 0; i++ ) for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 ) #endif { if( p[0] != 0 || p[1] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) || p[2] != ( ( ciphersuites[i] ) & 0xFF ) ) continue; got_common_suite = 1; if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i], &ciphersuite_info ) ) != 0 ) return( ret ); if( ciphersuite_info != NULL ) goto have_ciphersuite_v2; } if( got_common_suite ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, " "but none of them usable" ) ); return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) ); return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } have_ciphersuite_v2: MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) ); ssl->session_negotiate->ciphersuite = ciphersuites[i]; ssl->handshake->ciphersuite_info = ciphersuite_info; /* * SSLv2 Client Hello relevant renegotiation security checks */ if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->in_left = 0; ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello v2" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */ /* This function doesn't alert on errors that happen early during ClientHello parsing because they might indicate that the client is not talking SSL/TLS at all and would not understand our alert. */ static int ssl_parse_client_hello( mbedtls_ssl_context *ssl ) { int ret, got_common_suite; size_t i, j; size_t ciph_offset, comp_offset, ext_offset; size_t msg_len, ciph_len, sess_len, comp_len, ext_len; #if defined(MBEDTLS_SSL_PROTO_DTLS) size_t cookie_offset, cookie_len; #endif unsigned char *buf, *p, *ext; #if defined(MBEDTLS_SSL_RENEGOTIATION) int renegotiation_info_seen = 0; #endif int handshake_failure = 0; const int *ciphersuites; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; int major, minor; /* If there is no signature-algorithm extension present, * we need to fall back to the default values for allowed * signature-hash pairs. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) int sig_hash_alg_ext_present = 0; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello" ) ); #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) read_record_header: #endif /* * If renegotiating, then the input was read with mbedtls_ssl_read_record(), * otherwise read it ourselves manually in order to support SSLv2 * ClientHello, which doesn't use the same record layer format. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) #endif { if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 ) { /* No alert on a read error. */ MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } } buf = ssl->in_hdr; #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM ) #endif if( ( buf[0] & 0x80 ) != 0 ) return( ssl_parse_client_hello_v2( ssl ) ); #endif MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, mbedtls_ssl_in_hdr_len( ssl ) ); /* * SSLv3/TLS Client Hello * * Record layer: * 0 . 0 message type * 1 . 2 protocol version * 3 . 11 DTLS: epoch + record sequence number * 3 . 4 message length */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message type: %d", buf[0] ) ); if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message len.: %d", ( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, protocol version: [%d:%d]", buf[1], buf[2] ) ); mbedtls_ssl_read_version( &major, &minor, ssl->conf->transport, buf + 1 ); /* According to RFC 5246 Appendix E.1, the version here is typically * "{03,00}, the lowest version number supported by the client, [or] the * value of ClientHello.client_version", so the only meaningful check here * is the major version shouldn't be less than 3 */ if( major < MBEDTLS_SSL_MAJOR_VERSION_3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* For DTLS if this is the initial handshake, remember the client sequence * number to use it in our next message (RFC 6347 4.2.1) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM #if defined(MBEDTLS_SSL_RENEGOTIATION) && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE #endif ) { /* Epoch should be 0 for initial handshakes */ if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } memcpy( ssl->cur_out_ctr + 2, ssl->in_ctr + 2, 6 ); #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record, discarding" ) ); ssl->next_record_offset = 0; ssl->in_left = 0; goto read_record_header; } /* No MAC to check yet, so we can update right now */ mbedtls_ssl_dtls_replay_update( ssl ); #endif } #endif /* MBEDTLS_SSL_PROTO_DTLS */ msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1]; #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { /* Set by mbedtls_ssl_read_record() */ msg_len = ssl->in_hslen; } else #endif { if( msg_len > MBEDTLS_SSL_IN_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_in_hdr_len( ssl ) + msg_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } /* Done reading this record, get ready for the next one */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ssl->next_record_offset = msg_len + mbedtls_ssl_in_hdr_len( ssl ); else #endif ssl->in_left = 0; } buf = ssl->in_msg; MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, msg_len ); ssl->handshake->update_checksum( ssl, buf, msg_len ); /* * Handshake layer: * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 5 DTLS only: message seqence number * 6 . 8 DTLS only: fragment offset * 9 . 11 DTLS only: fragment length */ if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake type: %d", buf[0] ) ); if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake len.: %d", ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) ); /* We don't support fragmentation of ClientHello (yet?) */ if( buf[1] != 0 || msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* * Copy the client's handshake message_seq on initial handshakes, * check sequence number on renego. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { /* This couldn't be done in ssl_prepare_handshake_record() */ unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; if( cli_msg_seq != ssl->handshake->in_msg_seq ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message_seq: " "%d (expected %d)", cli_msg_seq, ssl->handshake->in_msg_seq ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->handshake->in_msg_seq++; } else #endif { unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; ssl->handshake->out_msg_seq = cli_msg_seq; ssl->handshake->in_msg_seq = cli_msg_seq + 1; } /* * For now we don't support fragmentation, so make sure * fragment_offset == 0 and fragment_length == length */ if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 || memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ClientHello fragmentation not supported" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ buf += mbedtls_ssl_hs_hdr_len( ssl ); msg_len -= mbedtls_ssl_hs_hdr_len( ssl ); /* * ClientHello layer: * 0 . 1 protocol version * 2 . 33 random bytes (starting with 4 bytes of Unix time) * 34 . 35 session id length (1 byte) * 35 . 34+x session id * 35+x . 35+x DTLS only: cookie length (1 byte) * 36+x . .. DTLS only: cookie * .. . .. ciphersuite list length (2 bytes) * .. . .. ciphersuite list * .. . .. compression alg. list length (1 byte) * .. . .. compression alg. list * .. . .. extensions length (2 bytes, optional) * .. . .. extensions (optional) */ /* * Minimal length (with everything empty and extensions omitted) is * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can * read at least up to session id length without worrying. */ if( msg_len < 38 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Check and save the protocol version */ MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, version", buf, 2 ); mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver, ssl->conf->transport, buf ); ssl->handshake->max_major_ver = ssl->major_ver; ssl->handshake->max_minor_ver = ssl->minor_ver; if( ssl->major_ver < ssl->conf->min_major_ver || ssl->minor_ver < ssl->conf->min_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum" " [%d:%d] < [%d:%d]", ssl->major_ver, ssl->minor_ver, ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); } if( ssl->major_ver > ssl->conf->max_major_ver ) { ssl->major_ver = ssl->conf->max_major_ver; ssl->minor_ver = ssl->conf->max_minor_ver; } else if( ssl->minor_ver > ssl->conf->max_minor_ver ) ssl->minor_ver = ssl->conf->max_minor_ver; /* * Save client random (inc. Unix time) */ MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", buf + 2, 32 ); memcpy( ssl->handshake->randbytes, buf + 2, 32 ); /* * Check the session ID length and save session ID */ sess_len = buf[34]; if( sess_len > sizeof( ssl->session_negotiate->id ) || sess_len + 34 + 2 > msg_len ) /* 2 for cipherlist length field */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 35, sess_len ); ssl->session_negotiate->id_len = sess_len; memset( ssl->session_negotiate->id, 0, sizeof( ssl->session_negotiate->id ) ); memcpy( ssl->session_negotiate->id, buf + 35, ssl->session_negotiate->id_len ); /* * Check the cookie length and content */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { cookie_offset = 35 + sess_len; cookie_len = buf[cookie_offset]; if( cookie_offset + 1 + cookie_len + 2 > msg_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie", buf + cookie_offset + 1, cookie_len ); #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) if( ssl->conf->f_cookie_check != NULL #if defined(MBEDTLS_SSL_RENEGOTIATION) && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE #endif ) { if( ssl->conf->f_cookie_check( ssl->conf->p_cookie, buf + cookie_offset + 1, cookie_len, ssl->cli_id, ssl->cli_id_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification failed" ) ); ssl->handshake->verify_cookie_len = 1; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification passed" ) ); ssl->handshake->verify_cookie_len = 0; } } else #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ { /* We know we didn't send a cookie, so it should be empty */ if( cookie_len != 0 ) { /* This may be an attacker's probe, so don't send an alert */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification skipped" ) ); } /* * Check the ciphersuitelist length (will be parsed later) */ ciph_offset = cookie_offset + 1 + cookie_len; } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ ciph_offset = 35 + sess_len; ciph_len = ( buf[ciph_offset + 0] << 8 ) | ( buf[ciph_offset + 1] ); if( ciph_len < 2 || ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */ ( ciph_len % 2 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist", buf + ciph_offset + 2, ciph_len ); /* * Check the compression algorithms length and pick one */ comp_offset = ciph_offset + 2 + ciph_len; comp_len = buf[comp_offset]; if( comp_len < 1 || comp_len > 16 || comp_len + comp_offset + 1 > msg_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, compression", buf + comp_offset + 1, comp_len ); ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL; #if defined(MBEDTLS_ZLIB_SUPPORT) for( i = 0; i < comp_len; ++i ) { if( buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE ) { ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE; break; } } #endif /* See comments in ssl_write_client_hello() */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL; #endif /* Do not parse the extensions if the protocol is SSLv3 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) ) { #endif /* * Check the extension length */ ext_offset = comp_offset + 1 + comp_len; if( msg_len > ext_offset ) { if( msg_len < ext_offset + 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ext_len = ( buf[ext_offset + 0] << 8 ) | ( buf[ext_offset + 1] ); if( ( ext_len > 0 && ext_len < 4 ) || msg_len != ext_offset + 2 + ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } else ext_len = 0; ext = buf + ext_offset + 2; MBEDTLS_SSL_DEBUG_BUF( 3, "client hello extensions", ext, ext_len ); while( ext_len != 0 ) { unsigned int ext_id; unsigned int ext_size; if ( ext_len < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ext_id = ( ( ext[0] << 8 ) | ( ext[1] ) ); ext_size = ( ( ext[2] << 8 ) | ( ext[3] ) ); if( ext_size + 4 > ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } switch( ext_id ) { #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) case MBEDTLS_TLS_EXT_SERVERNAME: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ServerName extension" ) ); if( ssl->conf->f_sni == NULL ) break; ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) renegotiation_info_seen = 1; #endif ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) case MBEDTLS_TLS_EXT_SIG_ALG: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found signature_algorithms extension" ) ); ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); sig_hash_alg_ext_present = 1; break; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported elliptic curves extension" ) ); ret = ssl_parse_supported_elliptic_curves( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported point formats extension" ) ); ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT; ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_ECJPAKE_KKPP: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake kkpp extension" ) ); ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max fragment length extension" ) ); ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) case MBEDTLS_TLS_EXT_TRUNCATED_HMAC: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated hmac extension" ) ); ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) case MBEDTLS_TLS_EXT_CID: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found CID extension" ) ); ret = ssl_parse_cid_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt then mac extension" ) ); ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended master secret extension" ) ); ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) case MBEDTLS_TLS_EXT_SESSION_TICKET: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session ticket extension" ) ); ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_ALPN) case MBEDTLS_TLS_EXT_ALPN: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) ); ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_DTLS_SRTP) case MBEDTLS_TLS_EXT_USE_SRTP: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found use_srtp extension" ) ); ret = ssl_parse_use_srtp_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_DTLS_SRTP */ default: MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)", ext_id ) ); } ext_len -= 4 + ext_size; ext += 4 + ext_size; if( ext_len > 0 && ext_len < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } #if defined(MBEDTLS_SSL_PROTO_SSL3) } #endif #if defined(MBEDTLS_SSL_FALLBACK_SCSV) for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 ) { if( p[0] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) && p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ) & 0xff ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received FALLBACK_SCSV" ) ); if( ssl->minor_ver < ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } break; } } #endif /* MBEDTLS_SSL_FALLBACK_SCSV */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* * Try to fall back to default hash SHA1 if the client * hasn't provided any preferred signature-hash combinations. */ if( sig_hash_alg_ext_present == 0 ) { mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1; if( mbedtls_ssl_check_sig_hash( ssl, md_default ) != 0 ) md_default = MBEDTLS_MD_NONE; mbedtls_ssl_sig_hash_set_const_hash( &ssl->handshake->hash_algs, md_default ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ /* * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */ for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 ) { if( p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV " "during renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; break; } } /* * Renegotiation security checks */ if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) ); handshake_failure = 1; } #if defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION && renegotiation_info_seen == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && renegotiation_info_seen == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) ); handshake_failure = 1; } #endif /* MBEDTLS_SSL_RENEGOTIATION */ if( handshake_failure == 1 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Search for a matching ciphersuite * (At the end because we need information from the EC-based extensions * and certificate from the SNI callback triggered by the SNI extension.) */ got_common_suite = 0; ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; ciphersuite_info = NULL; #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE) for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) for( i = 0; ciphersuites[i] != 0; i++ ) #else for( i = 0; ciphersuites[i] != 0; i++ ) for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) #endif { if( p[0] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) || p[1] != ( ( ciphersuites[i] ) & 0xFF ) ) continue; got_common_suite = 1; if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i], &ciphersuite_info ) ) != 0 ) return( ret ); if( ciphersuite_info != NULL ) goto have_ciphersuite; } if( got_common_suite ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, " "but none of them usable" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } have_ciphersuite: MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) ); ssl->session_negotiate->ciphersuite = ciphersuites[i]; ssl->handshake->ciphersuite_info = ciphersuite_info; ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_recv_flight_completed( ssl ); #endif /* Debugging-only output for testsuite */ #if defined(MBEDTLS_DEBUG_C) && \ defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg( ciphersuite_info ); if( sig_alg != MBEDTLS_PK_NONE ) { mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_alg ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d", mbedtls_ssl_hash_from_md_alg( md_alg ) ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "no hash algorithm for signature algorithm " "%d - should not happen", sig_alg ) ); } } #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->session_negotiate->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding truncated hmac extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) static void ssl_write_cid_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; size_t ext_len; const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; *olen = 0; /* Skip writing the extension if we don't want to use it or if * the client hasn't offered it. */ if( ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_DISABLED ) return; /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX * which is at most 255, so the increment cannot overflow. */ if( end < p || (size_t)( end - p ) < (unsigned)( ssl->own_cid_len + 5 ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding CID extension" ) ); /* * Quoting draft-ietf-tls-dtls-connection-id-05 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05 * * struct { * opaque cid<0..2^8-1>; * } ConnectionId; */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID ) & 0xFF ); ext_len = (size_t) ssl->own_cid_len + 1; *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); *p++ = (uint8_t) ssl->own_cid_len; memcpy( p, ssl->own_cid, ssl->own_cid_len ); *olen = ssl->own_cid_len + 5; } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; const mbedtls_ssl_ciphersuite_t *suite = NULL; const mbedtls_cipher_info_t *cipher = NULL; if( ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { *olen = 0; return; } /* * RFC 7366: "If a server receives an encrypt-then-MAC request extension * from a client and then selects a stream or Authenticated Encryption * with Associated Data (AEAD) ciphersuite, it MUST NOT send an * encrypt-then-MAC response extension back to the client." */ if( ( suite = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ) ) == NULL || ( cipher = mbedtls_cipher_info_from_type( suite->cipher ) ) == NULL || cipher->mode != MBEDTLS_MODE_CBC ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding encrypt then mac extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding extended master secret " "extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->handshake->new_session_ticket == 0 ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding session ticket extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, secure renegotiation extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { *p++ = 0x00; *p++ = ( ssl->verify_data_len * 2 + 1 ) & 0xFF; *p++ = ssl->verify_data_len * 2 & 0xFF; memcpy( p, ssl->peer_verify_data, ssl->verify_data_len ); p += ssl->verify_data_len; memcpy( p, ssl->own_verify_data, ssl->verify_data_len ); p += ssl->verify_data_len; } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { *p++ = 0x00; *p++ = 0x01; *p++ = 0x00; } *olen = p - buf; } #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, max_fragment_length extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF ); *p++ = 0x00; *p++ = 1; *p++ = ssl->session_negotiate->mfl_code; *olen = 5; } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; ((void) ssl); if( ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT ) == 0 ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, supported_point_formats extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF ); *p++ = 0x00; *p++ = 2; *p++ = 1; *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED; *olen = 6; } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = buf; const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; size_t kkpp_len; *olen = 0; /* Skip costly computation if not needed */ if( ssl->handshake->ciphersuite_info->key_exchange != MBEDTLS_KEY_EXCHANGE_ECJPAKE ) return; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, ecjpake kkpp extension" ) ); if( end - p < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return; } *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF ); ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx, p + 2, end - p - 2, &kkpp_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret ); return; } *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( kkpp_len ) & 0xFF ); *olen = kkpp_len + 4; } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_ALPN ) static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { if( ssl->alpn_chosen == NULL ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding alpn extension" ) ); /* * 0 . 1 ext identifier * 2 . 3 ext length * 4 . 5 protocol list length * 6 . 6 protocol name length * 7 . 7+n protocol name */ buf[0] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF ); buf[1] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF ); *olen = 7 + strlen( ssl->alpn_chosen ); buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF ); buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF ); buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF ); buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF ); buf[6] = (unsigned char)( ( ( *olen - 7 ) ) & 0xFF ); memcpy( buf + 7, ssl->alpn_chosen, *olen - 7 ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */ #if defined(MBEDTLS_SSL_DTLS_SRTP ) && defined(MBEDTLS_SSL_PROTO_DTLS) static void ssl_write_use_srtp_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { size_t mki_len = 0, ext_len = 0; uint16_t profile_value = 0; const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; *olen = 0; if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) || ( ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET ) ) { return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding use_srtp extension" ) ); if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED ) { mki_len = ssl->dtls_srtp_info.mki_len; } /* The extension total size is 9 bytes : * - 2 bytes for the extension tag * - 2 bytes for the total size * - 2 bytes for the protection profile length * - 2 bytes for the protection profile * - 1 byte for the mki length * + the actual mki length * Check we have enough room in the output buffer */ if( (size_t)( end - buf ) < mki_len + 9 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return; } /* extension */ buf[0] = (unsigned char)( ( MBEDTLS_TLS_EXT_USE_SRTP >> 8 ) & 0xFF ); buf[1] = (unsigned char)( ( MBEDTLS_TLS_EXT_USE_SRTP ) & 0xFF ); /* * total length 5 and mki value: only one profile(2 bytes) * and length(2 bytes) and srtp_mki ) */ ext_len = 5 + mki_len; buf[2] = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); buf[3] = (unsigned char)( ext_len & 0xFF ); /* protection profile length: 2 */ buf[4] = 0x00; buf[5] = 0x02; profile_value = mbedtls_ssl_check_srtp_profile_value( ssl->dtls_srtp_info.chosen_dtls_srtp_profile ); if( profile_value != MBEDTLS_TLS_SRTP_UNSET ) { buf[6] = (unsigned char)( ( profile_value >> 8 ) & 0xFF ); buf[7] = (unsigned char)( profile_value & 0xFF ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "use_srtp extension invalid profile" ) ); return; } buf[8] = mki_len & 0xFF; memcpy( &buf[9], ssl->dtls_srtp_info.mki_value, mki_len ); *olen = 9 + mki_len; } #endif /* MBEDTLS_SSL_DTLS_SRTP */ #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) static int ssl_write_hello_verify_request( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = ssl->out_msg + 4; unsigned char *cookie_len_byte; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello verify request" ) ); /* * struct { * ProtocolVersion server_version; * opaque cookie<0..2^8-1>; * } HelloVerifyRequest; */ /* The RFC is not clear on this point, but sending the actual negotiated * version looks like the most interoperable thing to do. */ mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, p ); MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 ); p += 2; /* If we get here, f_cookie_check is not null */ if( ssl->conf->f_cookie_write == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "inconsistent cookie callbacks" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* Skip length byte until we know the length */ cookie_len_byte = p++; if( ( ret = ssl->conf->f_cookie_write( ssl->conf->p_cookie, &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN, ssl->cli_id, ssl->cli_id_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "f_cookie_write", ret ); return( ret ); } *cookie_len_byte = (unsigned char)( p - ( cookie_len_byte + 1 ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "cookie sent", cookie_len_byte + 1, *cookie_len_byte ); ssl->out_msglen = p - ssl->out_msg; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST; ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello verify request" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ static int ssl_write_server_hello( mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_HAVE_TIME) mbedtls_time_t t; #endif int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t olen, ext_len = 0, n; unsigned char *buf, *p; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello" ) ); #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->verify_cookie_len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "client hello was not authenticated" ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) ); return( ssl_write_hello_verify_request( ssl ) ); } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ if( ssl->conf->f_rng == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") ); return( MBEDTLS_ERR_SSL_NO_RNG ); } /* * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 5 protocol version * 6 . 9 UNIX time() * 10 . 37 random bytes */ buf = ssl->out_msg; p = buf + 4; mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, p ); p += 2; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen version: [%d:%d]", buf[4], buf[5] ) ); #if defined(MBEDTLS_HAVE_TIME) t = mbedtls_time( NULL ); *p++ = (unsigned char)( t >> 24 ); *p++ = (unsigned char)( t >> 16 ); *p++ = (unsigned char)( t >> 8 ); *p++ = (unsigned char)( t ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu", t ) ); #else if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 ) return( ret ); p += 4; #endif /* MBEDTLS_HAVE_TIME */ if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 ) return( ret ); p += 28; memcpy( ssl->handshake->randbytes + 32, buf + 6, 32 ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 6, 32 ); /* * Resume is 0 by default, see ssl_handshake_init(). * It may be already set to 1 by ssl_parse_session_ticket_ext(). * If not, try looking up session ID in our cache. */ if( ssl->handshake->resume == 0 && #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE && #endif ssl->session_negotiate->id_len != 0 && ssl->conf->f_get_cache != NULL && ssl->conf->f_get_cache( ssl->conf->p_cache, ssl->session_negotiate ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from cache" ) ); ssl->handshake->resume = 1; } if( ssl->handshake->resume == 0 ) { /* * New session, create a new session id, * unless we're about to issue a session ticket */ ssl->state++; #if defined(MBEDTLS_HAVE_TIME) ssl->session_negotiate->start = mbedtls_time( NULL ); #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) if( ssl->handshake->new_session_ticket != 0 ) { ssl->session_negotiate->id_len = n = 0; memset( ssl->session_negotiate->id, 0, 32 ); } else #endif /* MBEDTLS_SSL_SESSION_TICKETS */ { ssl->session_negotiate->id_len = n = 32; if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, n ) ) != 0 ) return( ret ); } } else { /* * Resuming a session */ n = ssl->session_negotiate->id_len; ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC; if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); return( ret ); } } /* * 38 . 38 session id length * 39 . 38+n session id * 39+n . 40+n chosen ciphersuite * 41+n . 41+n chosen compression alg. * 42+n . 43+n extensions length * 44+n . 43+n+m extensions */ *p++ = (unsigned char) ssl->session_negotiate->id_len; memcpy( p, ssl->session_negotiate->id, ssl->session_negotiate->id_len ); p += ssl->session_negotiate->id_len; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 39, n ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed", ssl->handshake->resume ? "a" : "no" ) ); *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite >> 8 ); *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite ); *p++ = (unsigned char)( ssl->session_negotiate->compression ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", mbedtls_ssl_get_ciphersuite_name( ssl->session_negotiate->ciphersuite ) ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: 0x%02X", ssl->session_negotiate->compression ) ); /* Do not write the extensions if the protocol is SSLv3 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) ) { #endif /* * First write extensions, then the total length */ ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl_write_cid_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if ( mbedtls_ssl_ciphersuite_uses_ec( mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ) ) ) { ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_ALPN) ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_DTLS_SRTP) ssl_write_use_srtp_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, total extension length: %d", ext_len ) ); if( ext_len > 0 ) { *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); p += ext_len; } #if defined(MBEDTLS_SSL_PROTO_SSL3) } #endif ssl->out_msglen = p - buf; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_HELLO; ret = mbedtls_ssl_write_handshake_msg( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) ); return( ret ); } #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) static int ssl_write_certificate_request( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) ); if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_write_certificate_request( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; uint16_t dn_size, total_dn_size; /* excluding length bytes */ size_t ct_len, sa_len; /* including length bytes */ unsigned char *buf, *p; const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; const mbedtls_x509_crt *crt; int authmode; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) ); ssl->state++; #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET ) authmode = ssl->handshake->sni_authmode; else #endif authmode = ssl->conf->authmode; if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) || authmode == MBEDTLS_SSL_VERIFY_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) ); return( 0 ); } /* * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 4 cert type count * 5 .. m-1 cert types * m .. m+1 sig alg length (TLS 1.2 only) * m+1 .. n-1 SignatureAndHashAlgorithms (TLS 1.2 only) * n .. n+1 length of all DNs * n+2 .. n+3 length of DN 1 * n+4 .. ... Distinguished Name #1 * ... .. ... length of DN 2, etc. */ buf = ssl->out_msg; p = buf + 4; /* * Supported certificate types * * ClientCertificateType certificate_types<1..2^8-1>; * enum { (255) } ClientCertificateType; */ ct_len = 0; #if defined(MBEDTLS_RSA_C) p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN; #endif #if defined(MBEDTLS_ECDSA_C) p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN; #endif p[0] = (unsigned char) ct_len++; p += ct_len; sa_len = 0; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) /* * Add signature_algorithms for verify (TLS 1.2) * * SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>; * * struct { * HashAlgorithm hash; * SignatureAlgorithm signature; * } SignatureAndHashAlgorithm; * * enum { (255) } HashAlgorithm; * enum { (255) } SignatureAlgorithm; */ if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { const int *cur; /* * Supported signature algorithms */ for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ ) { unsigned char hash = mbedtls_ssl_hash_from_md_alg( *cur ); if( MBEDTLS_SSL_HASH_NONE == hash || mbedtls_ssl_set_calc_verify_md( ssl, hash ) ) continue; #if defined(MBEDTLS_RSA_C) p[2 + sa_len++] = hash; p[2 + sa_len++] = MBEDTLS_SSL_SIG_RSA; #endif #if defined(MBEDTLS_ECDSA_C) p[2 + sa_len++] = hash; p[2 + sa_len++] = MBEDTLS_SSL_SIG_ECDSA; #endif } p[0] = (unsigned char)( sa_len >> 8 ); p[1] = (unsigned char)( sa_len ); sa_len += 2; p += sa_len; } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ /* * DistinguishedName certificate_authorities<0..2^16-1>; * opaque DistinguishedName<1..2^16-1>; */ p += 2; total_dn_size = 0; if( ssl->conf->cert_req_ca_list == MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED ) { /* NOTE: If trusted certificates are provisioned * via a CA callback (configured through * `mbedtls_ssl_conf_ca_cb()`, then the * CertificateRequest is currently left empty. */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_ca_chain != NULL ) crt = ssl->handshake->sni_ca_chain; else #endif crt = ssl->conf->ca_chain; while( crt != NULL && crt->version != 0 ) { /* It follows from RFC 5280 A.1 that this length * can be represented in at most 11 bits. */ dn_size = (uint16_t) crt->subject_raw.len; if( end < p || (size_t)( end - p ) < 2 + (size_t) dn_size ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "skipping CAs: buffer too short" ) ); break; } *p++ = (unsigned char)( dn_size >> 8 ); *p++ = (unsigned char)( dn_size ); memcpy( p, crt->subject_raw.p, dn_size ); p += dn_size; MBEDTLS_SSL_DEBUG_BUF( 3, "requested DN", p - dn_size, dn_size ); total_dn_size += 2 + dn_size; crt = crt->next; } } ssl->out_msglen = p - buf; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST; ssl->out_msg[4 + ct_len + sa_len] = (unsigned char)( total_dn_size >> 8 ); ssl->out_msg[5 + ct_len + sa_len] = (unsigned char)( total_dn_size ); ret = mbedtls_ssl_write_handshake_msg( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate request" ) ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ! mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECKEY ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, mbedtls_pk_ec( *mbedtls_ssl_own_key( ssl ) ), MBEDTLS_ECDH_OURS ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret ); return( ret ); } return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \ defined(MBEDTLS_SSL_ASYNC_PRIVATE) static int ssl_resume_server_key_exchange( mbedtls_ssl_context *ssl, size_t *signature_len ) { /* Append the signature to ssl->out_msg, leaving 2 bytes for the * signature length which will be added in ssl_write_server_key_exchange * after the call to ssl_prepare_server_key_exchange. * ssl_write_server_key_exchange also takes care of incrementing * ssl->out_msglen. */ unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2; size_t sig_max_len = ( ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN - sig_start ); int ret = ssl->conf->f_async_resume( ssl, sig_start, signature_len, sig_max_len ); if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) { ssl->handshake->async_in_progress = 0; mbedtls_ssl_set_async_operation_data( ssl, NULL ); } MBEDTLS_SSL_DEBUG_RET( 2, "ssl_resume_server_key_exchange", ret ); return( ret ); } #endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && defined(MBEDTLS_SSL_ASYNC_PRIVATE) */ /* Prepare the ServerKeyExchange message, up to and including * calculating the signature if any, but excluding formatting the * signature and sending the message. */ static int ssl_prepare_server_key_exchange( mbedtls_ssl_context *ssl, size_t *signature_len ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED) #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) unsigned char *dig_signed = NULL; #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED */ (void) ciphersuite_info; /* unused in some configurations */ #if !defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) (void) signature_len; #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */ /* * * Part 1: Provide key exchange parameters for chosen ciphersuite. * */ /* * - ECJPAKE key exchanges */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx, ssl->out_msg + ssl->out_msglen, MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret ); return( ret ); } ssl->out_msglen += len; } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ /* * For (EC)DHE key exchanges with PSK, parameters are prefixed by support * identity hint (RFC 4279, Sec. 3). Until someone needs this feature, * we use empty support identity hints here. **/ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { ssl->out_msg[ssl->out_msglen++] = 0x00; ssl->out_msg[ssl->out_msglen++] = 0x00; } #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ /* * - DHE key exchanges */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_dhe( ciphersuite_info ) ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; if( ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no DH parameters set" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* * Ephemeral DH parameters: * * struct { * opaque dh_p<1..2^16-1>; * opaque dh_g<1..2^16-1>; * opaque dh_Ys<1..2^16-1>; * } ServerDHParams; */ if( ( ret = mbedtls_dhm_set_group( &ssl->handshake->dhm_ctx, &ssl->conf->dhm_P, &ssl->conf->dhm_G ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_set_group", ret ); return( ret ); } if( ( ret = mbedtls_dhm_make_params( &ssl->handshake->dhm_ctx, (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ), ssl->out_msg + ssl->out_msglen, &len, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_params", ret ); return( ret ); } #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) dig_signed = ssl->out_msg + ssl->out_msglen; #endif ssl->out_msglen += len; MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED */ /* * - ECDHE key exchanges */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_ecdhe( ciphersuite_info ) ) { /* * Ephemeral ECDH parameters: * * struct { * ECParameters curve_params; * ECPoint public; * } ServerECDHParams; */ const mbedtls_ecp_curve_info **curve = NULL; const mbedtls_ecp_group_id *gid; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; /* Match our preference list against the offered curves */ for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ ) for( curve = ssl->handshake->curves; *curve != NULL; curve++ ) if( (*curve)->grp_id == *gid ) goto curve_matching_done; curve_matching_done: if( curve == NULL || *curve == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no matching curve for ECDHE" ) ); return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDHE curve: %s", (*curve)->name ) ); if( ( ret = mbedtls_ecdh_setup( &ssl->handshake->ecdh_ctx, (*curve)->grp_id ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecp_group_load", ret ); return( ret ); } if( ( ret = mbedtls_ecdh_make_params( &ssl->handshake->ecdh_ctx, &len, ssl->out_msg + ssl->out_msglen, MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_params", ret ); return( ret ); } #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) dig_signed = ssl->out_msg + ssl->out_msglen; #endif ssl->out_msglen += len; MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Q ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED */ /* * * Part 2: For key exchanges involving the server signing the * exchange parameters, compute and add the signature here. * */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) ) { size_t dig_signed_len = ssl->out_msg + ssl->out_msglen - dig_signed; size_t hashlen = 0; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* * 2.1: Choose hash algorithm: * A: For TLS 1.2, obey signature-hash-algorithm extension * to choose appropriate hash. * B: For SSL3, TLS1.0, TLS1.1 and ECDHE_ECDSA, use SHA1 * (RFC 4492, Sec. 5.4) * C: Otherwise, use MD5 + SHA1 (RFC 4346, Sec. 7.4.3) */ mbedtls_md_type_t md_alg; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { /* A: For TLS 1.2, obey signature-hash-algorithm extension * (RFC 5246, Sec. 7.4.1.4.1). */ if( sig_alg == MBEDTLS_PK_NONE || ( md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_alg ) ) == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); /* (... because we choose a cipher suite * only if there is a matching hash.) */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) { /* B: Default hash SHA1 */ md_alg = MBEDTLS_MD_SHA1; } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ { /* C: MD5 + SHA1 */ md_alg = MBEDTLS_MD_NONE; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "pick hash algorithm %d for signing", md_alg ) ); /* * 2.2: Compute the hash to be signed */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( md_alg == MBEDTLS_MD_NONE ) { hashlen = 36; ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, dig_signed, dig_signed_len ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( md_alg != MBEDTLS_MD_NONE ) { ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen, dig_signed, dig_signed_len, md_alg ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen ); /* * 2.3: Compute and add the signature */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { /* * For TLS 1.2, we need to specify signature and hash algorithm * explicitly through a prefix to the signature. * * struct { * HashAlgorithm hash; * SignatureAlgorithm signature; * } SignatureAndHashAlgorithm; * * struct { * SignatureAndHashAlgorithm algorithm; * opaque signature<0..2^16-1>; * } DigitallySigned; * */ ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_hash_from_md_alg( md_alg ); ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_sig_from_pk_alg( sig_alg ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if( ssl->conf->f_async_sign_start != NULL ) { ret = ssl->conf->f_async_sign_start( ssl, mbedtls_ssl_own_cert( ssl ), md_alg, hash, hashlen ); switch( ret ) { case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH: /* act as if f_async_sign was null */ break; case 0: ssl->handshake->async_in_progress = 1; return( ssl_resume_server_key_exchange( ssl, signature_len ) ); case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS: ssl->handshake->async_in_progress = 1; return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ); default: MBEDTLS_SSL_DEBUG_RET( 1, "f_async_sign_start", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ if( mbedtls_ssl_own_key( ssl ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* Append the signature to ssl->out_msg, leaving 2 bytes for the * signature length which will be added in ssl_write_server_key_exchange * after the call to ssl_prepare_server_key_exchange. * ssl_write_server_key_exchange also takes care of incrementing * ssl->out_msglen. */ if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash, hashlen, ssl->out_msg + ssl->out_msglen + 2, signature_len, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret ); return( ret ); } } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ return( 0 ); } /* Prepare the ServerKeyExchange message and send it. For ciphersuites * that do not include a ServerKeyExchange message, do nothing. Either * way, if successful, move on to the next step in the SSL state * machine. */ static int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t signature_len = 0; #if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED) const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; #endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server key exchange" ) ); #if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED) /* Extract static ECDH parameters and abort if ServerKeyExchange * is not needed. */ if( mbedtls_ssl_ciphersuite_no_pfs( ciphersuite_info ) ) { /* For suites involving ECDH, extract DH parameters * from certificate at this point. */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED) if( mbedtls_ssl_ciphersuite_uses_ecdh( ciphersuite_info ) ) { ssl_get_ecdh_params_from_cert( ssl ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED */ /* Key exchanges not involving ephemeral keys don't use * ServerKeyExchange, so end here. */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write server key exchange" ) ); ssl->state++; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \ defined(MBEDTLS_SSL_ASYNC_PRIVATE) /* If we have already prepared the message and there is an ongoing * signature operation, resume signing. */ if( ssl->handshake->async_in_progress != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming signature operation" ) ); ret = ssl_resume_server_key_exchange( ssl, &signature_len ); } else #endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && defined(MBEDTLS_SSL_ASYNC_PRIVATE) */ { /* ServerKeyExchange is needed. Prepare the message. */ ret = ssl_prepare_server_key_exchange( ssl, &signature_len ); } if( ret != 0 ) { /* If we're starting to write a new message, set ssl->out_msglen * to 0. But if we're resuming after an asynchronous message, * out_msglen is the amount of data written so far and mst be * preserved. */ if( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange (pending)" ) ); else ssl->out_msglen = 0; return( ret ); } /* If there is a signature, write its length. * ssl_prepare_server_key_exchange already wrote the signature * itself at its proper place in the output buffer. */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) if( signature_len != 0 ) { ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len >> 8 ); ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "my signature", ssl->out_msg + ssl->out_msglen, signature_len ); /* Skip over the already-written signature */ ssl->out_msglen += signature_len; } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ /* Add header and send. */ ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE; ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange" ) ); return( 0 ); } static int ssl_write_server_hello_done( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello done" ) ); ssl->out_msglen = 4; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_HELLO_DONE; ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_send_flight_completed( ssl ); #endif if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello done" ) ); return( 0 ); } #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) static int ssl_parse_client_dh_public( mbedtls_ssl_context *ssl, unsigned char **p, const unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t n; /* * Receive G^Y mod P, premaster = (G^Y)^X mod P */ if( *p + 2 > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } n = ( (*p)[0] << 8 ) | (*p)[1]; *p += 2; if( *p + n > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ( ret = mbedtls_dhm_read_public( &ssl->handshake->dhm_ctx, *p, n ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_read_public", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP ); } *p += n; MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) static int ssl_resume_decrypt_pms( mbedtls_ssl_context *ssl, unsigned char *peer_pms, size_t *peer_pmslen, size_t peer_pmssize ) { int ret = ssl->conf->f_async_resume( ssl, peer_pms, peer_pmslen, peer_pmssize ); if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) { ssl->handshake->async_in_progress = 0; mbedtls_ssl_set_async_operation_data( ssl, NULL ); } MBEDTLS_SSL_DEBUG_RET( 2, "ssl_decrypt_encrypted_pms", ret ); return( ret ); } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ static int ssl_decrypt_encrypted_pms( mbedtls_ssl_context *ssl, const unsigned char *p, const unsigned char *end, unsigned char *peer_pms, size_t *peer_pmslen, size_t peer_pmssize ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_pk_context *private_key = mbedtls_ssl_own_key( ssl ); mbedtls_pk_context *public_key = &mbedtls_ssl_own_cert( ssl )->pk; size_t len = mbedtls_pk_get_len( public_key ); #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) /* If we have already started decoding the message and there is an ongoing * decryption operation, resume signing. */ if( ssl->handshake->async_in_progress != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming decryption operation" ) ); return( ssl_resume_decrypt_pms( ssl, peer_pms, peer_pmslen, peer_pmssize ) ); } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ /* * Prepare to decrypt the premaster using own private RSA key */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) { if ( p + 2 > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( *p++ != ( ( len >> 8 ) & 0xFF ) || *p++ != ( ( len ) & 0xFF ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } } #endif if( p + len != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } /* * Decrypt the premaster secret */ #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if( ssl->conf->f_async_decrypt_start != NULL ) { ret = ssl->conf->f_async_decrypt_start( ssl, mbedtls_ssl_own_cert( ssl ), p, len ); switch( ret ) { case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH: /* act as if f_async_decrypt_start was null */ break; case 0: ssl->handshake->async_in_progress = 1; return( ssl_resume_decrypt_pms( ssl, peer_pms, peer_pmslen, peer_pmssize ) ); case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS: ssl->handshake->async_in_progress = 1; return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ); default: MBEDTLS_SSL_DEBUG_RET( 1, "f_async_decrypt_start", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ if( ! mbedtls_pk_can_do( private_key, MBEDTLS_PK_RSA ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no RSA private key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } ret = mbedtls_pk_decrypt( private_key, p, len, peer_pms, peer_pmslen, peer_pmssize, ssl->conf->f_rng, ssl->conf->p_rng ); return( ret ); } static int ssl_parse_encrypted_pms( mbedtls_ssl_context *ssl, const unsigned char *p, const unsigned char *end, size_t pms_offset ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *pms = ssl->handshake->premaster + pms_offset; unsigned char ver[2]; unsigned char fake_pms[48], peer_pms[48]; unsigned char mask; size_t i, peer_pmslen; unsigned int diff; /* In case of a failure in decryption, the decryption may write less than * 2 bytes of output, but we always read the first two bytes. It doesn't * matter in the end because diff will be nonzero in that case due to * ret being nonzero, and we only care whether diff is 0. * But do initialize peer_pms and peer_pmslen for robustness anyway. This * also makes memory analyzers happy (don't access uninitialized memory, * even if it's an unsigned char). */ peer_pms[0] = peer_pms[1] = ~0; peer_pmslen = 0; ret = ssl_decrypt_encrypted_pms( ssl, p, end, peer_pms, &peer_pmslen, sizeof( peer_pms ) ); #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if ( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) return( ret ); #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ mbedtls_ssl_write_version( ssl->handshake->max_major_ver, ssl->handshake->max_minor_ver, ssl->conf->transport, ver ); /* Avoid data-dependent branches while checking for invalid * padding, to protect against timing-based Bleichenbacher-type * attacks. */ diff = (unsigned int) ret; diff |= peer_pmslen ^ 48; diff |= peer_pms[0] ^ ver[0]; diff |= peer_pms[1] ^ ver[1]; /* mask = diff ? 0xff : 0x00 using bit operations to avoid branches */ /* MSVC has a warning about unary minus on unsigned, but this is * well-defined and precisely what we want to do here */ #if defined(_MSC_VER) #pragma warning( push ) #pragma warning( disable : 4146 ) #endif mask = - ( ( diff | - diff ) >> ( sizeof( unsigned int ) * 8 - 1 ) ); #if defined(_MSC_VER) #pragma warning( pop ) #endif /* * Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding * must not cause the connection to end immediately; instead, send a * bad_record_mac later in the handshake. * To protect against timing-based variants of the attack, we must * not have any branch that depends on whether the decryption was * successful. In particular, always generate the fake premaster secret, * regardless of whether it will ultimately influence the output or not. */ ret = ssl->conf->f_rng( ssl->conf->p_rng, fake_pms, sizeof( fake_pms ) ); if( ret != 0 ) { /* It's ok to abort on an RNG failure, since this does not reveal * anything about the RSA decryption. */ return( ret ); } #if defined(MBEDTLS_SSL_DEBUG_ALL) if( diff != 0 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); #endif if( sizeof( ssl->handshake->premaster ) < pms_offset || sizeof( ssl->handshake->premaster ) - pms_offset < 48 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->handshake->pmslen = 48; /* Set pms to either the true or the fake PMS, without * data-dependent branches. */ for( i = 0; i < ssl->handshake->pmslen; i++ ) pms[i] = ( mask & fake_pms[i] ) | ( (~mask) & peer_pms[i] ); return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p, const unsigned char *end ) { int ret = 0; uint16_t n; if( ssl_conf_has_psk_or_cb( ssl->conf ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* * Receive client pre-shared key identity name */ if( end - *p < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } n = ( (*p)[0] << 8 ) | (*p)[1]; *p += 2; if( n == 0 || n > end - *p ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->conf->f_psk != NULL ) { if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 ) ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } else { /* Identity is not a big secret since clients send it in the clear, * but treat it carefully anyway, just in case */ if( n != ssl->conf->psk_identity_len || mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 ) { ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } } if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ) { MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY ); return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ); } *p += n; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; unsigned char *p, *end; ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client key exchange" ) ); #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \ ( defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) ) if( ( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) && ( ssl->handshake->async_in_progress != 0 ) ) { /* We've already read a record and there is an asynchronous * operation in progress to decrypt it. So skip reading the * record. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "will resume decryption of previously-read record" ) ); } else #endif if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); end = ssl->in_msg + ssl->in_hslen; if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ) { if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret ); return( ret ); } if( p != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx, ssl->handshake->premaster, MBEDTLS_PREMASTER_SIZE, &ssl->handshake->pmslen, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS ); } MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K ); } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ) { if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx, p, end - p) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_QP ); if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &ssl->handshake->pmslen, ssl->handshake->premaster, MBEDTLS_MPI_MAX_SIZE, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Z ); } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ) { if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } if( p != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* For opaque PSKs, we perform the PSK-to-MS derivation atomatically * and skip the intermediate PMS. */ if( ssl_use_opaque_psk( ssl ) == 1 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "skip PMS generation for opaque PSK" ) ); else #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if ( ssl->handshake->async_in_progress != 0 ) { /* There is an asynchronous operation in progress to * decrypt the encrypted premaster secret, so skip * directly to resuming this operation. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "PSK identity already parsed" ) ); /* Update p to skip the PSK identity. ssl_parse_encrypted_pms * won't actually use it, but maintain p anyway for robustness. */ p += ssl->conf->psk_identity_len + 2; } else #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only. */ if( ssl_use_opaque_psk( ssl ) == 1 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 2 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_encrypted_pms" ), ret ); return( ret ); } if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret ); return( ret ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only. */ if( ssl_use_opaque_psk( ssl ) == 1 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif if( p != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx, p, end - p ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only. */ if( ssl_use_opaque_psk( ssl ) == 1 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_QP ); if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) { if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 0 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_parse_encrypted_pms_secret" ), ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx, p, end - p ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx, ssl->handshake->premaster, 32, &ssl->handshake->pmslen, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); return( ret ); } ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client key exchange" ) ); return( 0 ); } #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) ); if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t i, sig_len; unsigned char hash[48]; unsigned char *hash_start = hash; size_t hashlen; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) mbedtls_pk_type_t pk_alg; #endif mbedtls_md_type_t md_alg; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; mbedtls_pk_context * peer_pk; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) ); if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) if( ssl->session_negotiate->peer_cert == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert_digest == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* Read the message without adding it to the checksum */ ret = mbedtls_ssl_read_record( ssl, 0 /* no checksum update */ ); if( 0 != ret ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record" ), ret ); return( ret ); } ssl->state++; /* Process the message contents */ if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE || ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } i = mbedtls_ssl_hs_hdr_len( ssl ); #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) peer_pk = &ssl->handshake->peer_pubkey; #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert == NULL ) { /* Should never happen */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } peer_pk = &ssl->session_negotiate->peer_cert->pk; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* * struct { * SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only * opaque signature<0..2^16-1>; * } DigitallySigned; */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) { md_alg = MBEDTLS_MD_NONE; hashlen = 36; /* For ECDSA, use SHA-1, not MD-5 + SHA-1 */ if( mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_ECDSA ) ) { hash_start += 16; hashlen -= 16; md_alg = MBEDTLS_MD_SHA1; } } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { if( i + 2 > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } /* * Hash */ md_alg = mbedtls_ssl_md_alg_from_hash( ssl->in_msg[i] ); if( md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md( ssl, ssl->in_msg[i] ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg" " for verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } #if !defined(MBEDTLS_MD_SHA1) if( MBEDTLS_MD_SHA1 == md_alg ) hash_start += 16; #endif /* Info from md_alg will be used instead */ hashlen = 0; i++; /* * Signature */ if( ( pk_alg = mbedtls_ssl_pk_alg_from_sig( ssl->in_msg[i] ) ) == MBEDTLS_PK_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg" " for verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } /* * Check the certificate's key type matches the signature alg */ if( !mbedtls_pk_can_do( peer_pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "sig_alg doesn't match cert key" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } i++; } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( i + 2 > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } sig_len = ( ssl->in_msg[i] << 8 ) | ssl->in_msg[i+1]; i += 2; if( i + sig_len != ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } /* Calculate hash and verify signature */ { size_t dummy_hlen; ssl->handshake->calc_verify( ssl, hash, &dummy_hlen ); } if( ( ret = mbedtls_pk_verify( peer_pk, md_alg, hash_start, hashlen, ssl->in_msg + i, sig_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret ); return( ret ); } mbedtls_ssl_update_handshake_status( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate verify" ) ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_write_new_session_ticket( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t tlen; uint32_t lifetime; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write new session ticket" ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_NEW_SESSION_TICKET; /* * struct { * uint32 ticket_lifetime_hint; * opaque ticket<0..2^16-1>; * } NewSessionTicket; * * 4 . 7 ticket_lifetime_hint (0 = unspecified) * 8 . 9 ticket_len (n) * 10 . 9+n ticket content */ if( ( ret = ssl->conf->f_ticket_write( ssl->conf->p_ticket, ssl->session_negotiate, ssl->out_msg + 10, ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN, &tlen, &lifetime ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_write", ret ); tlen = 0; } ssl->out_msg[4] = ( lifetime >> 24 ) & 0xFF; ssl->out_msg[5] = ( lifetime >> 16 ) & 0xFF; ssl->out_msg[6] = ( lifetime >> 8 ) & 0xFF; ssl->out_msg[7] = ( lifetime ) & 0xFF; ssl->out_msg[8] = (unsigned char)( ( tlen >> 8 ) & 0xFF ); ssl->out_msg[9] = (unsigned char)( ( tlen ) & 0xFF ); ssl->out_msglen = 10 + tlen; /* * Morally equivalent to updating ssl->state, but NewSessionTicket and * ChangeCipherSpec share the same state. */ ssl->handshake->new_session_ticket = 0; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write new session ticket" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ /* * SSL handshake -- server side -- single step */ int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl ) { int ret = 0; if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "server state: %d", ssl->state ) ); if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ switch( ssl->state ) { case MBEDTLS_SSL_HELLO_REQUEST: ssl->state = MBEDTLS_SSL_CLIENT_HELLO; break; /* * <== ClientHello */ case MBEDTLS_SSL_CLIENT_HELLO: ret = ssl_parse_client_hello( ssl ); break; #if defined(MBEDTLS_SSL_PROTO_DTLS) case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT: return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ); #endif /* * ==> ServerHello * Certificate * ( ServerKeyExchange ) * ( CertificateRequest ) * ServerHelloDone */ case MBEDTLS_SSL_SERVER_HELLO: ret = ssl_write_server_hello( ssl ); break; case MBEDTLS_SSL_SERVER_CERTIFICATE: ret = mbedtls_ssl_write_certificate( ssl ); break; case MBEDTLS_SSL_SERVER_KEY_EXCHANGE: ret = ssl_write_server_key_exchange( ssl ); break; case MBEDTLS_SSL_CERTIFICATE_REQUEST: ret = ssl_write_certificate_request( ssl ); break; case MBEDTLS_SSL_SERVER_HELLO_DONE: ret = ssl_write_server_hello_done( ssl ); break; /* * <== ( Certificate/Alert ) * ClientKeyExchange * ( CertificateVerify ) * ChangeCipherSpec * Finished */ case MBEDTLS_SSL_CLIENT_CERTIFICATE: ret = mbedtls_ssl_parse_certificate( ssl ); break; case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE: ret = ssl_parse_client_key_exchange( ssl ); break; case MBEDTLS_SSL_CERTIFICATE_VERIFY: ret = ssl_parse_certificate_verify( ssl ); break; case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC: ret = mbedtls_ssl_parse_change_cipher_spec( ssl ); break; case MBEDTLS_SSL_CLIENT_FINISHED: ret = mbedtls_ssl_parse_finished( ssl ); break; /* * ==> ( NewSessionTicket ) * ChangeCipherSpec * Finished */ case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC: #if defined(MBEDTLS_SSL_SESSION_TICKETS) if( ssl->handshake->new_session_ticket != 0 ) ret = ssl_write_new_session_ticket( ssl ); else #endif ret = mbedtls_ssl_write_change_cipher_spec( ssl ); break; case MBEDTLS_SSL_SERVER_FINISHED: ret = mbedtls_ssl_write_finished( ssl ); break; case MBEDTLS_SSL_FLUSH_BUFFERS: MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) ); ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; break; case MBEDTLS_SSL_HANDSHAKE_WRAPUP: mbedtls_ssl_handshake_wrapup( ssl ); break; default: MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } return( ret ); } #endif /* MBEDTLS_SSL_SRV_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_ticket.c
/* * TLS server tickets callbacks implementation * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #if defined(MBEDTLS_SSL_TICKET_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/ssl_internal.h" #include "mbedtls/ssl_ticket.h" #include "mbedtls/error.h" #include "mbedtls/platform_util.h" #include <string.h> /* * Initialze context */ void mbedtls_ssl_ticket_init( mbedtls_ssl_ticket_context *ctx ) { memset( ctx, 0, sizeof( mbedtls_ssl_ticket_context ) ); #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_init( &ctx->mutex ); #endif } #define MAX_KEY_BYTES 32 /* 256 bits */ #define TICKET_KEY_NAME_BYTES 4 #define TICKET_IV_BYTES 12 #define TICKET_CRYPT_LEN_BYTES 2 #define TICKET_AUTH_TAG_BYTES 16 #define TICKET_MIN_LEN ( TICKET_KEY_NAME_BYTES + \ TICKET_IV_BYTES + \ TICKET_CRYPT_LEN_BYTES + \ TICKET_AUTH_TAG_BYTES ) #define TICKET_ADD_DATA_LEN ( TICKET_KEY_NAME_BYTES + \ TICKET_IV_BYTES + \ TICKET_CRYPT_LEN_BYTES ) /* * Generate/update a key */ static int ssl_ticket_gen_key( mbedtls_ssl_ticket_context *ctx, unsigned char index ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char buf[MAX_KEY_BYTES]; mbedtls_ssl_ticket_key *key = ctx->keys + index; #if defined(MBEDTLS_HAVE_TIME) key->generation_time = (uint32_t) mbedtls_time( NULL ); #endif if( ( ret = ctx->f_rng( ctx->p_rng, key->name, sizeof( key->name ) ) ) != 0 ) return( ret ); if( ( ret = ctx->f_rng( ctx->p_rng, buf, sizeof( buf ) ) ) != 0 ) return( ret ); /* With GCM and CCM, same context can encrypt & decrypt */ ret = mbedtls_cipher_setkey( &key->ctx, buf, mbedtls_cipher_get_key_bitlen( &key->ctx ), MBEDTLS_ENCRYPT ); mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } /* * Rotate/generate keys if necessary */ static int ssl_ticket_update_keys( mbedtls_ssl_ticket_context *ctx ) { #if !defined(MBEDTLS_HAVE_TIME) ((void) ctx); #else if( ctx->ticket_lifetime != 0 ) { uint32_t current_time = (uint32_t) mbedtls_time( NULL ); uint32_t key_time = ctx->keys[ctx->active].generation_time; if( current_time >= key_time && current_time - key_time < ctx->ticket_lifetime ) { return( 0 ); } ctx->active = 1 - ctx->active; return( ssl_ticket_gen_key( ctx, ctx->active ) ); } else #endif /* MBEDTLS_HAVE_TIME */ return( 0 ); } /* * Setup context for actual use */ int mbedtls_ssl_ticket_setup( mbedtls_ssl_ticket_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_cipher_type_t cipher, uint32_t lifetime ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const mbedtls_cipher_info_t *cipher_info; ctx->f_rng = f_rng; ctx->p_rng = p_rng; ctx->ticket_lifetime = lifetime; cipher_info = mbedtls_cipher_info_from_type( cipher); if( cipher_info == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( cipher_info->mode != MBEDTLS_MODE_GCM && cipher_info->mode != MBEDTLS_MODE_CCM ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( cipher_info->key_bitlen > 8 * MAX_KEY_BYTES ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_USE_PSA_CRYPTO) ret = mbedtls_cipher_setup_psa( &ctx->keys[0].ctx, cipher_info, TICKET_AUTH_TAG_BYTES ); if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) return( ret ); /* We don't yet expect to support all ciphers through PSA, * so allow fallback to ordinary mbedtls_cipher_setup(). */ if( ret == MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_cipher_setup( &ctx->keys[0].ctx, cipher_info ) ) != 0 ) return( ret ); #if defined(MBEDTLS_USE_PSA_CRYPTO) ret = mbedtls_cipher_setup_psa( &ctx->keys[1].ctx, cipher_info, TICKET_AUTH_TAG_BYTES ); if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) return( ret ); if( ret == MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_cipher_setup( &ctx->keys[1].ctx, cipher_info ) ) != 0 ) return( ret ); if( ( ret = ssl_ticket_gen_key( ctx, 0 ) ) != 0 || ( ret = ssl_ticket_gen_key( ctx, 1 ) ) != 0 ) { return( ret ); } return( 0 ); } /* * Create session ticket, with the following structure: * * struct { * opaque key_name[4]; * opaque iv[12]; * opaque encrypted_state<0..2^16-1>; * opaque tag[16]; * } ticket; * * The key_name, iv, and length of encrypted_state are the additional * authenticated data. */ int mbedtls_ssl_ticket_write( void *p_ticket, const mbedtls_ssl_session *session, unsigned char *start, const unsigned char *end, size_t *tlen, uint32_t *ticket_lifetime ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_ssl_ticket_context *ctx = p_ticket; mbedtls_ssl_ticket_key *key; unsigned char *key_name = start; unsigned char *iv = start + TICKET_KEY_NAME_BYTES; unsigned char *state_len_bytes = iv + TICKET_IV_BYTES; unsigned char *state = state_len_bytes + TICKET_CRYPT_LEN_BYTES; size_t clear_len, ciph_len; *tlen = 0; if( ctx == NULL || ctx->f_rng == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); /* We need at least 4 bytes for key_name, 12 for IV, 2 for len 16 for tag, * in addition to session itself, that will be checked when writing it. */ MBEDTLS_SSL_CHK_BUF_PTR( start, end, TICKET_MIN_LEN ); #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( ret ); #endif if( ( ret = ssl_ticket_update_keys( ctx ) ) != 0 ) goto cleanup; key = &ctx->keys[ctx->active]; *ticket_lifetime = ctx->ticket_lifetime; memcpy( key_name, key->name, TICKET_KEY_NAME_BYTES ); if( ( ret = ctx->f_rng( ctx->p_rng, iv, TICKET_IV_BYTES ) ) != 0 ) goto cleanup; /* Dump session state */ if( ( ret = mbedtls_ssl_session_save( session, state, end - state, &clear_len ) ) != 0 || (unsigned long) clear_len > 65535 ) { goto cleanup; } state_len_bytes[0] = ( clear_len >> 8 ) & 0xff; state_len_bytes[1] = ( clear_len ) & 0xff; /* Encrypt and authenticate */ if( ( ret = mbedtls_cipher_auth_encrypt_ext( &key->ctx, iv, TICKET_IV_BYTES, /* Additional data: key name, IV and length */ key_name, TICKET_ADD_DATA_LEN, state, clear_len, state, end - state, &ciph_len, TICKET_AUTH_TAG_BYTES ) ) != 0 ) { goto cleanup; } if( ciph_len != clear_len + TICKET_AUTH_TAG_BYTES ) { ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto cleanup; } *tlen = TICKET_MIN_LEN + ciph_len - TICKET_AUTH_TAG_BYTES; cleanup: #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif return( ret ); } /* * Select key based on name */ static mbedtls_ssl_ticket_key *ssl_ticket_select_key( mbedtls_ssl_ticket_context *ctx, const unsigned char name[4] ) { unsigned char i; for( i = 0; i < sizeof( ctx->keys ) / sizeof( *ctx->keys ); i++ ) if( memcmp( name, ctx->keys[i].name, 4 ) == 0 ) return( &ctx->keys[i] ); return( NULL ); } /* * Load session ticket (see mbedtls_ssl_ticket_write for structure) */ int mbedtls_ssl_ticket_parse( void *p_ticket, mbedtls_ssl_session *session, unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_ssl_ticket_context *ctx = p_ticket; mbedtls_ssl_ticket_key *key; unsigned char *key_name = buf; unsigned char *iv = buf + TICKET_KEY_NAME_BYTES; unsigned char *enc_len_p = iv + TICKET_IV_BYTES; unsigned char *ticket = enc_len_p + TICKET_CRYPT_LEN_BYTES; size_t enc_len, clear_len; if( ctx == NULL || ctx->f_rng == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( len < TICKET_MIN_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( ret ); #endif if( ( ret = ssl_ticket_update_keys( ctx ) ) != 0 ) goto cleanup; enc_len = ( enc_len_p[0] << 8 ) | enc_len_p[1]; if( len != TICKET_MIN_LEN + enc_len ) { ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA; goto cleanup; } /* Select key */ if( ( key = ssl_ticket_select_key( ctx, key_name ) ) == NULL ) { /* We can't know for sure but this is a likely option unless we're * under attack - this is only informative anyway */ ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED; goto cleanup; } /* Decrypt and authenticate */ if( ( ret = mbedtls_cipher_auth_decrypt_ext( &key->ctx, iv, TICKET_IV_BYTES, /* Additional data: key name, IV and length */ key_name, TICKET_ADD_DATA_LEN, ticket, enc_len + TICKET_AUTH_TAG_BYTES, ticket, enc_len, &clear_len, TICKET_AUTH_TAG_BYTES ) ) != 0 ) { if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED ) ret = MBEDTLS_ERR_SSL_INVALID_MAC; goto cleanup; } if( clear_len != enc_len ) { ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto cleanup; } /* Actually load session */ if( ( ret = mbedtls_ssl_session_load( session, ticket, clear_len ) ) != 0 ) goto cleanup; #if defined(MBEDTLS_HAVE_TIME) { /* Check for expiration */ mbedtls_time_t current_time = mbedtls_time( NULL ); if( current_time < session->start || (uint32_t)( current_time - session->start ) > ctx->ticket_lifetime ) { ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED; goto cleanup; } } #endif cleanup: #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif return( ret ); } /* * Free context */ void mbedtls_ssl_ticket_free( mbedtls_ssl_ticket_context *ctx ) { mbedtls_cipher_free( &ctx->keys[0].ctx ); mbedtls_cipher_free( &ctx->keys[1].ctx ); #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_free( &ctx->mutex ); #endif mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ssl_ticket_context ) ); } #endif /* MBEDTLS_SSL_TICKET_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_tls.c
/* * SSLv3/TLSv1 shared functions * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The SSL 3.0 specification was drafted by Netscape in 1996, * and became an IETF standard in 1999. * * http://wp.netscape.com/eng/ssl3/ * http://www.ietf.org/rfc/rfc2246.txt * http://www.ietf.org/rfc/rfc4346.txt */ #include "common.h" #if defined(MBEDTLS_SSL_TLS_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/ssl.h" #include "mbedtls/ssl_internal.h" #include "mbedtls/debug.h" #include "mbedtls/error.h" #include "mbedtls/platform_util.h" #include "mbedtls/version.h" #include <string.h> #if defined(MBEDTLS_USE_PSA_CRYPTO) #include "mbedtls/psa_util.h" #include "psa/crypto.h" #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) #include "mbedtls/oid.h" #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* Top-level Connection ID API */ int mbedtls_ssl_conf_cid( mbedtls_ssl_config *conf, size_t len, int ignore_other_cid ) { if( len > MBEDTLS_SSL_CID_IN_LEN_MAX ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_FAIL && ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_IGNORE ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->ignore_unexpected_cid = ignore_other_cid; conf->cid_len = len; return( 0 ); } int mbedtls_ssl_set_cid( mbedtls_ssl_context *ssl, int enable, unsigned char const *own_cid, size_t own_cid_len ) { if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->negotiate_cid = enable; if( enable == MBEDTLS_SSL_CID_DISABLED ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Disable use of CID extension." ) ); return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "Enable use of CID extension." ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Own CID", own_cid, own_cid_len ); if( own_cid_len != ssl->conf->cid_len ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "CID length %u does not match CID length %u in config", (unsigned) own_cid_len, (unsigned) ssl->conf->cid_len ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } memcpy( ssl->own_cid, own_cid, own_cid_len ); /* Truncation is not an issue here because * MBEDTLS_SSL_CID_IN_LEN_MAX at most 255. */ ssl->own_cid_len = (uint8_t) own_cid_len; return( 0 ); } int mbedtls_ssl_get_peer_cid( mbedtls_ssl_context *ssl, int *enabled, unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ], size_t *peer_cid_len ) { *enabled = MBEDTLS_SSL_CID_DISABLED; if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM || ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* We report MBEDTLS_SSL_CID_DISABLED in case the CID extensions * were used, but client and server requested the empty CID. * This is indistinguishable from not using the CID extension * in the first place. */ if( ssl->transform_in->in_cid_len == 0 && ssl->transform_in->out_cid_len == 0 ) { return( 0 ); } if( peer_cid_len != NULL ) { *peer_cid_len = ssl->transform_in->out_cid_len; if( peer_cid != NULL ) { memcpy( peer_cid, ssl->transform_in->out_cid, ssl->transform_in->out_cid_len ); } } *enabled = MBEDTLS_SSL_CID_ENABLED; return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) /* * Convert max_fragment_length codes to length. * RFC 6066 says: * enum{ * 2^9(1), 2^10(2), 2^11(3), 2^12(4), (255) * } MaxFragmentLength; * and we add 0 -> extension unused */ static unsigned int ssl_mfl_code_to_length( int mfl ) { switch( mfl ) { case MBEDTLS_SSL_MAX_FRAG_LEN_NONE: return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ); case MBEDTLS_SSL_MAX_FRAG_LEN_512: return 512; case MBEDTLS_SSL_MAX_FRAG_LEN_1024: return 1024; case MBEDTLS_SSL_MAX_FRAG_LEN_2048: return 2048; case MBEDTLS_SSL_MAX_FRAG_LEN_4096: return 4096; default: return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ); } } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ int mbedtls_ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src ) { mbedtls_ssl_session_free( dst ); memcpy( dst, src, sizeof( mbedtls_ssl_session ) ); #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) if( src->peer_cert != NULL ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) ); if( dst->peer_cert == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); mbedtls_x509_crt_init( dst->peer_cert ); if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p, src->peer_cert->raw.len ) ) != 0 ) { mbedtls_free( dst->peer_cert ); dst->peer_cert = NULL; return( ret ); } } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( src->peer_cert_digest != NULL ) { dst->peer_cert_digest = mbedtls_calloc( 1, src->peer_cert_digest_len ); if( dst->peer_cert_digest == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( dst->peer_cert_digest, src->peer_cert_digest, src->peer_cert_digest_len ); dst->peer_cert_digest_type = src->peer_cert_digest_type; dst->peer_cert_digest_len = src->peer_cert_digest_len; } #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) if( src->ticket != NULL ) { dst->ticket = mbedtls_calloc( 1, src->ticket_len ); if( dst->ticket == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( dst->ticket, src->ticket, src->ticket_len ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ return( 0 ); } #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) static int resize_buffer( unsigned char **buffer, size_t len_new, size_t *len_old ) { unsigned char* resized_buffer = mbedtls_calloc( 1, len_new ); if( resized_buffer == NULL ) return -1; /* We want to copy len_new bytes when downsizing the buffer, and * len_old bytes when upsizing, so we choose the smaller of two sizes, * to fit one buffer into another. Size checks, ensuring that no data is * lost, are done outside of this function. */ memcpy( resized_buffer, *buffer, ( len_new < *len_old ) ? len_new : *len_old ); mbedtls_platform_zeroize( *buffer, *len_old ); mbedtls_free( *buffer ); *buffer = resized_buffer; *len_old = len_new; return 0; } static void handle_buffer_resizing( mbedtls_ssl_context *ssl, int downsizing, size_t in_buf_new_len, size_t out_buf_new_len ) { int modified = 0; size_t written_in = 0, iv_offset_in = 0, len_offset_in = 0; size_t written_out = 0, iv_offset_out = 0, len_offset_out = 0; if( ssl->in_buf != NULL ) { written_in = ssl->in_msg - ssl->in_buf; iv_offset_in = ssl->in_iv - ssl->in_buf; len_offset_in = ssl->in_len - ssl->in_buf; if( downsizing ? ssl->in_buf_len > in_buf_new_len && ssl->in_left < in_buf_new_len : ssl->in_buf_len < in_buf_new_len ) { if( resize_buffer( &ssl->in_buf, in_buf_new_len, &ssl->in_buf_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "input buffer resizing failed - out of memory" ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reallocating in_buf to %d", in_buf_new_len ) ); modified = 1; } } } if( ssl->out_buf != NULL ) { written_out = ssl->out_msg - ssl->out_buf; iv_offset_out = ssl->out_iv - ssl->out_buf; len_offset_out = ssl->out_len - ssl->out_buf; if( downsizing ? ssl->out_buf_len > out_buf_new_len && ssl->out_left < out_buf_new_len : ssl->out_buf_len < out_buf_new_len ) { if( resize_buffer( &ssl->out_buf, out_buf_new_len, &ssl->out_buf_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "output buffer resizing failed - out of memory" ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reallocating out_buf to %d", out_buf_new_len ) ); modified = 1; } } } if( modified ) { /* Update pointers here to avoid doing it twice. */ mbedtls_ssl_reset_in_out_pointers( ssl ); /* Fields below might not be properly updated with record * splitting or with CID, so they are manually updated here. */ ssl->out_msg = ssl->out_buf + written_out; ssl->out_len = ssl->out_buf + len_offset_out; ssl->out_iv = ssl->out_buf + iv_offset_out; ssl->in_msg = ssl->in_buf + written_in; ssl->in_len = ssl->in_buf + len_offset_in; ssl->in_iv = ssl->in_buf + iv_offset_in; } } #endif /* MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH */ /* * Key material generation */ #if defined(MBEDTLS_SSL_PROTO_SSL3) static int ssl3_prf( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { int ret = 0; size_t i; mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char padding[16]; unsigned char sha1sum[20]; ((void)label); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); /* * SSLv3: * block = * MD5( secret + SHA1( 'A' + secret + random ) ) + * MD5( secret + SHA1( 'BB' + secret + random ) ) + * MD5( secret + SHA1( 'CCC' + secret + random ) ) + * ... */ for( i = 0; i < dlen / 16; i++ ) { memset( padding, (unsigned char) ('A' + i), 1 + i ); if( ( ret = mbedtls_sha1_starts_ret( &sha1 ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha1_update_ret( &sha1, padding, 1 + i ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha1_update_ret( &sha1, secret, slen ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha1_update_ret( &sha1, random, rlen ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha1_finish_ret( &sha1, sha1sum ) ) != 0 ) goto exit; if( ( ret = mbedtls_md5_starts_ret( &md5 ) ) != 0 ) goto exit; if( ( ret = mbedtls_md5_update_ret( &md5, secret, slen ) ) != 0 ) goto exit; if( ( ret = mbedtls_md5_update_ret( &md5, sha1sum, 20 ) ) != 0 ) goto exit; if( ( ret = mbedtls_md5_finish_ret( &md5, dstbuf + i * 16 ) ) != 0 ) goto exit; } exit: mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); mbedtls_platform_zeroize( padding, sizeof( padding ) ); mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) static int tls1_prf( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t nb, hs; size_t i, j, k; const unsigned char *S1, *S2; unsigned char *tmp; size_t tmp_len = 0; unsigned char h_i[20]; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_md_init( &md_ctx ); tmp_len = 20 + strlen( label ) + rlen; tmp = mbedtls_calloc( 1, tmp_len ); if( tmp == NULL ) { ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto exit; } hs = ( slen + 1 ) / 2; S1 = secret; S2 = secret + slen - hs; nb = strlen( label ); memcpy( tmp + 20, label, nb ); memcpy( tmp + 20 + nb, random, rlen ); nb += rlen; /* * First compute P_md5(secret,label+random)[0..dlen] */ if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL ) { ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto exit; } if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) { goto exit; } mbedtls_md_hmac_starts( &md_ctx, S1, hs ); mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb ); mbedtls_md_hmac_finish( &md_ctx, 4 + tmp ); for( i = 0; i < dlen; i += 16 ) { mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb ); mbedtls_md_hmac_finish( &md_ctx, h_i ); mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 ); mbedtls_md_hmac_finish( &md_ctx, 4 + tmp ); k = ( i + 16 > dlen ) ? dlen % 16 : 16; for( j = 0; j < k; j++ ) dstbuf[i + j] = h_i[j]; } mbedtls_md_free( &md_ctx ); /* * XOR out with P_sha1(secret,label+random)[0..dlen] */ if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL ) { ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto exit; } if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) { goto exit; } mbedtls_md_hmac_starts( &md_ctx, S2, hs ); mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb ); mbedtls_md_hmac_finish( &md_ctx, tmp ); for( i = 0; i < dlen; i += 20 ) { mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb ); mbedtls_md_hmac_finish( &md_ctx, h_i ); mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, 20 ); mbedtls_md_hmac_finish( &md_ctx, tmp ); k = ( i + 20 > dlen ) ? dlen % 20 : 20; for( j = 0; j < k; j++ ) dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] ); } exit: mbedtls_md_free( &md_ctx ); mbedtls_platform_zeroize( tmp, tmp_len ); mbedtls_platform_zeroize( h_i, sizeof( h_i ) ); mbedtls_free( tmp ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_USE_PSA_CRYPTO) static psa_status_t setup_psa_key_derivation( psa_key_derivation_operation_t* derivation, psa_key_id_t key, psa_algorithm_t alg, const unsigned char* seed, size_t seed_length, const unsigned char* label, size_t label_length, size_t capacity ) { psa_status_t status; status = psa_key_derivation_setup( derivation, alg ); if( status != PSA_SUCCESS ) return( status ); if( PSA_ALG_IS_TLS12_PRF( alg ) || PSA_ALG_IS_TLS12_PSK_TO_MS( alg ) ) { status = psa_key_derivation_input_bytes( derivation, PSA_KEY_DERIVATION_INPUT_SEED, seed, seed_length ); if( status != PSA_SUCCESS ) return( status ); if( mbedtls_svc_key_id_is_null( key ) ) { status = psa_key_derivation_input_bytes( derivation, PSA_KEY_DERIVATION_INPUT_SECRET, NULL, 0 ); } else { status = psa_key_derivation_input_key( derivation, PSA_KEY_DERIVATION_INPUT_SECRET, key ); } if( status != PSA_SUCCESS ) return( status ); status = psa_key_derivation_input_bytes( derivation, PSA_KEY_DERIVATION_INPUT_LABEL, label, label_length ); if( status != PSA_SUCCESS ) return( status ); } else { return( PSA_ERROR_NOT_SUPPORTED ); } status = psa_key_derivation_set_capacity( derivation, capacity ); if( status != PSA_SUCCESS ) return( status ); return( PSA_SUCCESS ); } static int tls_prf_generic( mbedtls_md_type_t md_type, const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { psa_status_t status; psa_algorithm_t alg; psa_key_id_t master_key = MBEDTLS_SVC_KEY_ID_INIT; psa_key_derivation_operation_t derivation = PSA_KEY_DERIVATION_OPERATION_INIT; if( md_type == MBEDTLS_MD_SHA384 ) alg = PSA_ALG_TLS12_PRF(PSA_ALG_SHA_384); else alg = PSA_ALG_TLS12_PRF(PSA_ALG_SHA_256); /* Normally a "secret" should be long enough to be impossible to * find by brute force, and in particular should not be empty. But * this PRF is also used to derive an IV, in particular in EAP-TLS, * and for this use case it makes sense to have a 0-length "secret". * Since the key API doesn't allow importing a key of length 0, * keep master_key=0, which setup_psa_key_derivation() understands * to mean a 0-length "secret" input. */ if( slen != 0 ) { psa_key_attributes_t key_attributes = psa_key_attributes_init(); psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE ); psa_set_key_algorithm( &key_attributes, alg ); psa_set_key_type( &key_attributes, PSA_KEY_TYPE_DERIVE ); status = psa_import_key( &key_attributes, secret, slen, &master_key ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } status = setup_psa_key_derivation( &derivation, master_key, alg, random, rlen, (unsigned char const *) label, (size_t) strlen( label ), dlen ); if( status != PSA_SUCCESS ) { psa_key_derivation_abort( &derivation ); psa_destroy_key( master_key ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } status = psa_key_derivation_output_bytes( &derivation, dstbuf, dlen ); if( status != PSA_SUCCESS ) { psa_key_derivation_abort( &derivation ); psa_destroy_key( master_key ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } status = psa_key_derivation_abort( &derivation ); if( status != PSA_SUCCESS ) { psa_destroy_key( master_key ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } if( ! mbedtls_svc_key_id_is_null( master_key ) ) status = psa_destroy_key( master_key ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); return( 0 ); } #else /* MBEDTLS_USE_PSA_CRYPTO */ static int tls_prf_generic( mbedtls_md_type_t md_type, const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t nb; size_t i, j, k, md_len; unsigned char *tmp; size_t tmp_len = 0; unsigned char h_i[MBEDTLS_MD_MAX_SIZE]; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_md_init( &md_ctx ); if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); md_len = mbedtls_md_get_size( md_info ); tmp_len = md_len + strlen( label ) + rlen; tmp = mbedtls_calloc( 1, tmp_len ); if( tmp == NULL ) { ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto exit; } nb = strlen( label ); memcpy( tmp + md_len, label, nb ); memcpy( tmp + md_len + nb, random, rlen ); nb += rlen; /* * Compute P_<hash>(secret, label + random)[0..dlen] */ if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) goto exit; mbedtls_md_hmac_starts( &md_ctx, secret, slen ); mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb ); mbedtls_md_hmac_finish( &md_ctx, tmp ); for( i = 0; i < dlen; i += md_len ) { mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb ); mbedtls_md_hmac_finish( &md_ctx, h_i ); mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, md_len ); mbedtls_md_hmac_finish( &md_ctx, tmp ); k = ( i + md_len > dlen ) ? dlen % md_len : md_len; for( j = 0; j < k; j++ ) dstbuf[i + j] = h_i[j]; } exit: mbedtls_md_free( &md_ctx ); mbedtls_platform_zeroize( tmp, tmp_len ); mbedtls_platform_zeroize( h_i, sizeof( h_i ) ); mbedtls_free( tmp ); return( ret ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_SHA256_C) static int tls_prf_sha256( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen, label, random, rlen, dstbuf, dlen ) ); } #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) static int tls_prf_sha384( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen, label, random, rlen, dstbuf, dlen ) ); } #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t ); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t ); #endif #if defined(MBEDTLS_SSL_PROTO_SSL3) static void ssl_calc_verify_ssl( const mbedtls_ssl_context *, unsigned char *, size_t * ); static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_calc_verify_tls( const mbedtls_ssl_context *, unsigned char*, size_t * ); static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t ); static void ssl_calc_verify_tls_sha256( const mbedtls_ssl_context *,unsigned char*, size_t * ); static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int ); #endif #if defined(MBEDTLS_SHA512_C) static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t ); static void ssl_calc_verify_tls_sha384( const mbedtls_ssl_context *, unsigned char*, size_t * ); static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) && \ defined(MBEDTLS_USE_PSA_CRYPTO) static int ssl_use_opaque_psk( mbedtls_ssl_context const *ssl ) { if( ssl->conf->f_psk != NULL ) { /* If we've used a callback to select the PSK, * the static configuration is irrelevant. */ if( ! mbedtls_svc_key_id_is_null( ssl->handshake->psk_opaque ) ) return( 1 ); return( 0 ); } if( ! mbedtls_svc_key_id_is_null( ssl->conf->psk_opaque ) ) return( 1 ); return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_SSL_EXPORT_KEYS) static mbedtls_tls_prf_types tls_prf_get_type( mbedtls_ssl_tls_prf_cb *tls_prf ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) if( tls_prf == ssl3_prf ) { return( MBEDTLS_SSL_TLS_PRF_SSL3 ); } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) if( tls_prf == tls1_prf ) { return( MBEDTLS_SSL_TLS_PRF_TLS1 ); } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA512_C) if( tls_prf == tls_prf_sha384 ) { return( MBEDTLS_SSL_TLS_PRF_SHA384 ); } else #endif #if defined(MBEDTLS_SHA256_C) if( tls_prf == tls_prf_sha256 ) { return( MBEDTLS_SSL_TLS_PRF_SHA256 ); } else #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ return( MBEDTLS_SSL_TLS_PRF_NONE ); } #endif /* MBEDTLS_SSL_EXPORT_KEYS */ int mbedtls_ssl_tls_prf( const mbedtls_tls_prf_types prf, const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { mbedtls_ssl_tls_prf_cb *tls_prf = NULL; switch( prf ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) case MBEDTLS_SSL_TLS_PRF_SSL3: tls_prf = ssl3_prf; break; #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) case MBEDTLS_SSL_TLS_PRF_TLS1: tls_prf = tls1_prf; break; #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA512_C) case MBEDTLS_SSL_TLS_PRF_SHA384: tls_prf = tls_prf_sha384; break; #endif /* MBEDTLS_SHA512_C */ #if defined(MBEDTLS_SHA256_C) case MBEDTLS_SSL_TLS_PRF_SHA256: tls_prf = tls_prf_sha256; break; #endif /* MBEDTLS_SHA256_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ default: return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } return( tls_prf( secret, slen, label, random, rlen, dstbuf, dlen ) ); } /* Type for the TLS PRF */ typedef int ssl_tls_prf_t(const unsigned char *, size_t, const char *, const unsigned char *, size_t, unsigned char *, size_t); /* * Populate a transform structure with session keys and all the other * necessary information. * * Parameters: * - [in/out]: transform: structure to populate * [in] must be just initialised with mbedtls_ssl_transform_init() * [out] fully populated, ready for use by mbedtls_ssl_{en,de}crypt_buf() * - [in] ciphersuite * - [in] master * - [in] encrypt_then_mac * - [in] trunc_hmac * - [in] compression * - [in] tls_prf: pointer to PRF to use for key derivation * - [in] randbytes: buffer holding ServerHello.random + ClientHello.random * - [in] minor_ver: SSL/TLS minor version * - [in] endpoint: client or server * - [in] ssl: optionally used for: * - MBEDTLS_SSL_HW_RECORD_ACCEL: whole context (non-const) * - MBEDTLS_SSL_EXPORT_KEYS: ssl->conf->{f,p}_export_keys * - MBEDTLS_DEBUG_C: ssl->conf->{f,p}_dbg */ static int ssl_populate_transform( mbedtls_ssl_transform *transform, int ciphersuite, const unsigned char master[48], #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) int encrypt_then_mac, #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) int trunc_hmac, #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ #if defined(MBEDTLS_ZLIB_SUPPORT) int compression, #endif ssl_tls_prf_t tls_prf, const unsigned char randbytes[64], int minor_ver, unsigned endpoint, #if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL) const #endif mbedtls_ssl_context *ssl ) { int ret = 0; #if defined(MBEDTLS_USE_PSA_CRYPTO) int psa_fallthrough; #endif /* MBEDTLS_USE_PSA_CRYPTO */ unsigned char keyblk[256]; unsigned char *key1; unsigned char *key2; unsigned char *mac_enc; unsigned char *mac_dec; size_t mac_key_len = 0; size_t iv_copy_len; unsigned keylen; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; const mbedtls_cipher_info_t *cipher_info; const mbedtls_md_info_t *md_info; #if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL) && \ !defined(MBEDTLS_SSL_EXPORT_KEYS) && \ !defined(MBEDTLS_DEBUG_C) ssl = NULL; /* make sure we don't use it except for those cases */ (void) ssl; #endif /* * Some data just needs copying into the structure */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \ defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) transform->encrypt_then_mac = encrypt_then_mac; #endif transform->minor_ver = minor_ver; #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION) memcpy( transform->randbytes, randbytes, sizeof( transform->randbytes ) ); #endif /* * Get various info structures */ ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuite ); if( ciphersuite_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %d not found", ciphersuite ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } cipher_info = mbedtls_cipher_info_from_type( ciphersuite_info->cipher ); if( cipher_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found", ciphersuite_info->cipher ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } md_info = mbedtls_md_info_from_type( ciphersuite_info->mac ); if( md_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found", ciphersuite_info->mac ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* Copy own and peer's CID if the use of the CID * extension has been negotiated. */ if( ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_ENABLED ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Copy CIDs into SSL transform" ) ); transform->in_cid_len = ssl->own_cid_len; memcpy( transform->in_cid, ssl->own_cid, ssl->own_cid_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "Incoming CID", transform->in_cid, transform->in_cid_len ); transform->out_cid_len = ssl->handshake->peer_cid_len; memcpy( transform->out_cid, ssl->handshake->peer_cid, ssl->handshake->peer_cid_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "Outgoing CID", transform->out_cid, transform->out_cid_len ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ /* * Compute key block using the PRF */ ret = tls_prf( master, 48, "key expansion", randbytes, 64, keyblk, 256 ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s", mbedtls_ssl_get_ciphersuite_name( ciphersuite ) ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", master, 48 ); MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", randbytes, 64 ); MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 ); /* * Determine the appropriate key, IV and MAC length. */ keylen = cipher_info->key_bitlen / 8; #if defined(MBEDTLS_GCM_C) || \ defined(MBEDTLS_CCM_C) || \ defined(MBEDTLS_CHACHAPOLY_C) if( cipher_info->mode == MBEDTLS_MODE_GCM || cipher_info->mode == MBEDTLS_MODE_CCM || cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY ) { size_t explicit_ivlen; transform->maclen = 0; mac_key_len = 0; transform->taglen = ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16; /* All modes haves 96-bit IVs, but the length of the static parts vary * with mode and version: * - For GCM and CCM in TLS 1.2, there's a static IV of 4 Bytes * (to be concatenated with a dynamically chosen IV of 8 Bytes) * - For ChaChaPoly in TLS 1.2, and all modes in TLS 1.3, there's * a static IV of 12 Bytes (to be XOR'ed with the 8 Byte record * sequence number). */ transform->ivlen = 12; #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) { transform->fixed_ivlen = 12; } else #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ { if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY ) transform->fixed_ivlen = 12; else transform->fixed_ivlen = 4; } /* Minimum length of encrypted record */ explicit_ivlen = transform->ivlen - transform->fixed_ivlen; transform->minlen = explicit_ivlen + transform->taglen; } else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */ #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) if( cipher_info->mode == MBEDTLS_MODE_STREAM || cipher_info->mode == MBEDTLS_MODE_CBC ) { /* Initialize HMAC contexts */ if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 || ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret ); goto end; } /* Get MAC length */ mac_key_len = mbedtls_md_get_size( md_info ); transform->maclen = mac_key_len; #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) /* * If HMAC is to be truncated, we shall keep the leftmost bytes, * (rfc 6066 page 13 or rfc 2104 section 4), * so we only need to adjust the length here. */ if( trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED ) { transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN; #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT) /* Fall back to old, non-compliant version of the truncated * HMAC implementation which also truncates the key * (Mbed TLS versions from 1.3 to 2.6.0) */ mac_key_len = transform->maclen; #endif } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ /* IV length */ transform->ivlen = cipher_info->iv_size; /* Minimum length */ if( cipher_info->mode == MBEDTLS_MODE_STREAM ) transform->minlen = transform->maclen; else { /* * GenericBlockCipher: * 1. if EtM is in use: one block plus MAC * otherwise: * first multiple of blocklen greater than maclen * 2. IV except for SSL3 and TLS 1.0 */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED ) { transform->minlen = transform->maclen + cipher_info->block_size; } else #endif { transform->minlen = transform->maclen + cipher_info->block_size - transform->maclen % cipher_info->block_size; } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 || minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 ) ; /* No need to adjust minlen */ else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 || minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { transform->minlen += transform->ivlen; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto end; } } } else #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %u, minlen: %u, ivlen: %u, maclen: %u", (unsigned) keylen, (unsigned) transform->minlen, (unsigned) transform->ivlen, (unsigned) transform->maclen ) ); /* * Finally setup the cipher contexts, IVs and MAC secrets. */ #if defined(MBEDTLS_SSL_CLI_C) if( endpoint == MBEDTLS_SSL_IS_CLIENT ) { key1 = keyblk + mac_key_len * 2; key2 = keyblk + mac_key_len * 2 + keylen; mac_enc = keyblk; mac_dec = keyblk + mac_key_len; /* * This is not used in TLS v1.1. */ iv_copy_len = ( transform->fixed_ivlen ) ? transform->fixed_ivlen : transform->ivlen; memcpy( transform->iv_enc, key2 + keylen, iv_copy_len ); memcpy( transform->iv_dec, key2 + keylen + iv_copy_len, iv_copy_len ); } else #endif /* MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_SSL_SRV_C) if( endpoint == MBEDTLS_SSL_IS_SERVER ) { key1 = keyblk + mac_key_len * 2 + keylen; key2 = keyblk + mac_key_len * 2; mac_enc = keyblk + mac_key_len; mac_dec = keyblk; /* * This is not used in TLS v1.1. */ iv_copy_len = ( transform->fixed_ivlen ) ? transform->fixed_ivlen : transform->ivlen; memcpy( transform->iv_dec, key1 + keylen, iv_copy_len ); memcpy( transform->iv_enc, key1 + keylen + iv_copy_len, iv_copy_len ); } else #endif /* MBEDTLS_SSL_SRV_C */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto end; } #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) #if defined(MBEDTLS_SSL_PROTO_SSL3) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { if( mac_key_len > sizeof( transform->mac_enc ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto end; } memcpy( transform->mac_enc, mac_enc, mac_key_len ); memcpy( transform->mac_dec, mac_dec, mac_key_len ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) { /* For HMAC-based ciphersuites, initialize the HMAC transforms. For AEAD-based ciphersuites, there is nothing to do here. */ if( mac_key_len != 0 ) { mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len ); mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len ); } } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto end; } #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_init != NULL ) { ret = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) ); if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, keylen, transform->iv_enc, transform->iv_dec, iv_copy_len, mac_enc, mac_dec, mac_key_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret ); ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED; goto end; } } #else ((void) mac_dec); ((void) mac_enc); #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ #if defined(MBEDTLS_SSL_EXPORT_KEYS) if( ssl->conf->f_export_keys != NULL ) { ssl->conf->f_export_keys( ssl->conf->p_export_keys, master, keyblk, mac_key_len, keylen, iv_copy_len ); } if( ssl->conf->f_export_keys_ext != NULL ) { ssl->conf->f_export_keys_ext( ssl->conf->p_export_keys, master, keyblk, mac_key_len, keylen, iv_copy_len, randbytes + 32, randbytes, tls_prf_get_type( tls_prf ) ); } #endif #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Only use PSA-based ciphers for TLS-1.2. * That's relevant at least for TLS-1.0, where * we assume that mbedtls_cipher_crypt() updates * the structure field for the IV, which the PSA-based * implementation currently doesn't. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { ret = mbedtls_cipher_setup_psa( &transform->cipher_ctx_enc, cipher_info, transform->taglen ); if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup_psa", ret ); goto end; } if( ret == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Successfully setup PSA-based encryption cipher context" ) ); psa_fallthrough = 0; } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to setup PSA-based cipher context for record encryption - fall through to default setup." ) ); psa_fallthrough = 1; } } else psa_fallthrough = 1; #else psa_fallthrough = 1; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ if( psa_fallthrough == 1 ) #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc, cipher_info ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret ); goto end; } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Only use PSA-based ciphers for TLS-1.2. * That's relevant at least for TLS-1.0, where * we assume that mbedtls_cipher_crypt() updates * the structure field for the IV, which the PSA-based * implementation currently doesn't. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { ret = mbedtls_cipher_setup_psa( &transform->cipher_ctx_dec, cipher_info, transform->taglen ); if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup_psa", ret ); goto end; } if( ret == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Successfully setup PSA-based decryption cipher context" ) ); psa_fallthrough = 0; } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to setup PSA-based cipher context for record decryption - fall through to default setup." ) ); psa_fallthrough = 1; } } else psa_fallthrough = 1; #else psa_fallthrough = 1; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ if( psa_fallthrough == 1 ) #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec, cipher_info ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret ); goto end; } if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1, cipher_info->key_bitlen, MBEDTLS_ENCRYPT ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret ); goto end; } if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2, cipher_info->key_bitlen, MBEDTLS_DECRYPT ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret ); goto end; } #if defined(MBEDTLS_CIPHER_MODE_CBC) if( cipher_info->mode == MBEDTLS_MODE_CBC ) { if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc, MBEDTLS_PADDING_NONE ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret ); goto end; } if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec, MBEDTLS_PADDING_NONE ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret ); goto end; } } #endif /* MBEDTLS_CIPHER_MODE_CBC */ /* Initialize Zlib contexts */ #if defined(MBEDTLS_ZLIB_SUPPORT) if( compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) ); memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) ); memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) ); if( deflateInit( &transform->ctx_deflate, Z_DEFAULT_COMPRESSION ) != Z_OK || inflateInit( &transform->ctx_inflate ) != Z_OK ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) ); ret = MBEDTLS_ERR_SSL_COMPRESSION_FAILED; goto end; } } #endif /* MBEDTLS_ZLIB_SUPPORT */ end: mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) ); return( ret ); } /* * Set appropriate PRF function and other SSL / TLS 1.0/1.1 / TLS1.2 functions * * Inputs: * - SSL/TLS minor version * - hash associated with the ciphersuite (only used by TLS 1.2) * * Outputs: * - the tls_prf, calc_verify and calc_finished members of handshake structure */ static int ssl_set_handshake_prfs( mbedtls_ssl_handshake_params *handshake, int minor_ver, mbedtls_md_type_t hash ) { #if !defined(MBEDTLS_SSL_PROTO_TLS1_2) || !defined(MBEDTLS_SHA512_C) (void) hash; #endif #if defined(MBEDTLS_SSL_PROTO_SSL3) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { handshake->tls_prf = ssl3_prf; handshake->calc_verify = ssl_calc_verify_ssl; handshake->calc_finished = ssl_calc_finished_ssl; } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) if( minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) { handshake->tls_prf = tls1_prf; handshake->calc_verify = ssl_calc_verify_tls; handshake->calc_finished = ssl_calc_finished_tls; } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA512_C) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 && hash == MBEDTLS_MD_SHA384 ) { handshake->tls_prf = tls_prf_sha384; handshake->calc_verify = ssl_calc_verify_tls_sha384; handshake->calc_finished = ssl_calc_finished_tls_sha384; } else #endif #if defined(MBEDTLS_SHA256_C) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { handshake->tls_prf = tls_prf_sha256; handshake->calc_verify = ssl_calc_verify_tls_sha256; handshake->calc_finished = ssl_calc_finished_tls_sha256; } else #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } return( 0 ); } /* * Compute master secret if needed * * Parameters: * [in/out] handshake * [in] resume, premaster, extended_ms, calc_verify, tls_prf * (PSA-PSK) ciphersuite_info, psk_opaque * [out] premaster (cleared) * [out] master * [in] ssl: optionally used for debugging, EMS and PSA-PSK * debug: conf->f_dbg, conf->p_dbg * EMS: passed to calc_verify (debug + (SSL3) session_negotiate) * PSA-PSA: minor_ver, conf */ static int ssl_compute_master( mbedtls_ssl_handshake_params *handshake, unsigned char *master, const mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* cf. RFC 5246, Section 8.1: * "The master secret is always exactly 48 bytes in length." */ size_t const master_secret_len = 48; #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) unsigned char session_hash[48]; #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ /* The label for the KDF used for key expansion. * This is either "master secret" or "extended master secret" * depending on whether the Extended Master Secret extension * is used. */ char const *lbl = "master secret"; /* The salt for the KDF used for key expansion. * - If the Extended Master Secret extension is not used, * this is ClientHello.Random + ServerHello.Random * (see Sect. 8.1 in RFC 5246). * - If the Extended Master Secret extension is used, * this is the transcript of the handshake so far. * (see Sect. 4 in RFC 7627). */ unsigned char const *salt = handshake->randbytes; size_t salt_len = 64; #if !defined(MBEDTLS_DEBUG_C) && \ !defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \ !(defined(MBEDTLS_USE_PSA_CRYPTO) && \ defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)) ssl = NULL; /* make sure we don't use it except for those cases */ (void) ssl; #endif if( handshake->resume != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) if( handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED ) { lbl = "extended master secret"; salt = session_hash; handshake->calc_verify( ssl, session_hash, &salt_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "session hash for extended master secret", session_hash, salt_len ); } #endif /* MBEDTLS_SSL_EXTENDED_MS_ENABLED */ #if defined(MBEDTLS_USE_PSA_CRYPTO) && \ defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) if( handshake->ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK && ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 && ssl_use_opaque_psk( ssl ) == 1 ) { /* Perform PSK-to-MS expansion in a single step. */ psa_status_t status; psa_algorithm_t alg; psa_key_id_t psk; psa_key_derivation_operation_t derivation = PSA_KEY_DERIVATION_OPERATION_INIT; mbedtls_md_type_t hash_alg = handshake->ciphersuite_info->mac; MBEDTLS_SSL_DEBUG_MSG( 2, ( "perform PSA-based PSK-to-MS expansion" ) ); psk = mbedtls_ssl_get_opaque_psk( ssl ); if( hash_alg == MBEDTLS_MD_SHA384 ) alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_384); else alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_256); status = setup_psa_key_derivation( &derivation, psk, alg, salt, salt_len, (unsigned char const *) lbl, (size_t) strlen( lbl ), master_secret_len ); if( status != PSA_SUCCESS ) { psa_key_derivation_abort( &derivation ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } status = psa_key_derivation_output_bytes( &derivation, master, master_secret_len ); if( status != PSA_SUCCESS ) { psa_key_derivation_abort( &derivation ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } status = psa_key_derivation_abort( &derivation ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } else #endif { ret = handshake->tls_prf( handshake->premaster, handshake->pmslen, lbl, salt, salt_len, master, master_secret_len ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster, handshake->pmslen ); mbedtls_platform_zeroize( handshake->premaster, sizeof(handshake->premaster) ); } return( 0 ); } int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const mbedtls_ssl_ciphersuite_t * const ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) ); /* Set PRF, calc_verify and calc_finished function pointers */ ret = ssl_set_handshake_prfs( ssl->handshake, ssl->minor_ver, ciphersuite_info->mac ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_set_handshake_prfs", ret ); return( ret ); } /* Compute master secret if needed */ ret = ssl_compute_master( ssl->handshake, ssl->session_negotiate->master, ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compute_master", ret ); return( ret ); } /* Swap the client and server random values: * - MS derivation wanted client+server (RFC 5246 8.1) * - key derivation wants server+client (RFC 5246 6.3) */ { unsigned char tmp[64]; memcpy( tmp, ssl->handshake->randbytes, 64 ); memcpy( ssl->handshake->randbytes, tmp + 32, 32 ); memcpy( ssl->handshake->randbytes + 32, tmp, 32 ); mbedtls_platform_zeroize( tmp, sizeof( tmp ) ); } /* Populate transform structure */ ret = ssl_populate_transform( ssl->transform_negotiate, ssl->session_negotiate->ciphersuite, ssl->session_negotiate->master, #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) ssl->session_negotiate->encrypt_then_mac, #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) ssl->session_negotiate->trunc_hmac, #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ #if defined(MBEDTLS_ZLIB_SUPPORT) ssl->session_negotiate->compression, #endif ssl->handshake->tls_prf, ssl->handshake->randbytes, ssl->minor_ver, ssl->conf->endpoint, ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_populate_transform", ret ); return( ret ); } /* We no longer need Server/ClientHello.random values */ mbedtls_platform_zeroize( ssl->handshake->randbytes, sizeof( ssl->handshake->randbytes ) ); /* Allocate compression buffer */ #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->session_negotiate->compression == MBEDTLS_SSL_COMPRESS_DEFLATE && ssl->compress_buf == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) ); ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN ); if( ssl->compress_buf == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_COMPRESS_BUFFER_LEN ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } } #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) void ssl_calc_verify_ssl( const mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hlen ) { mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char pad_1[48]; unsigned char pad_2[48]; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); memset( pad_1, 0x36, 48 ); memset( pad_2, 0x5C, 48 ); mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 ); mbedtls_md5_update_ret( &md5, pad_1, 48 ); mbedtls_md5_finish_ret( &md5, hash ); mbedtls_md5_starts_ret( &md5 ); mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 ); mbedtls_md5_update_ret( &md5, pad_2, 48 ); mbedtls_md5_update_ret( &md5, hash, 16 ); mbedtls_md5_finish_ret( &md5, hash ); mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 ); mbedtls_sha1_update_ret( &sha1, pad_1, 40 ); mbedtls_sha1_finish_ret( &sha1, hash + 16 ); mbedtls_sha1_starts_ret( &sha1 ); mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 ); mbedtls_sha1_update_ret( &sha1, pad_2, 40 ); mbedtls_sha1_update_ret( &sha1, hash + 16, 20 ); mbedtls_sha1_finish_ret( &sha1, hash + 16 ); *hlen = 36; MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); return; } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) void ssl_calc_verify_tls( const mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hlen ) { mbedtls_md5_context md5; mbedtls_sha1_context sha1; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); mbedtls_md5_finish_ret( &md5, hash ); mbedtls_sha1_finish_ret( &sha1, hash + 16 ); *hlen = 36; MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); return; } #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) void ssl_calc_verify_tls_sha256( const mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hlen ) { #if defined(MBEDTLS_USE_PSA_CRYPTO) size_t hash_size; psa_status_t status; psa_hash_operation_t sha256_psa = psa_hash_operation_init(); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> PSA calc verify sha256" ) ); status = psa_hash_clone( &ssl->handshake->fin_sha256_psa, &sha256_psa ); if( status != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) ); return; } status = psa_hash_finish( &sha256_psa, hash, 32, &hash_size ); if( status != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) ); return; } *hlen = 32; MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated verify result", hash, *hlen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= PSA calc verify" ) ); #else mbedtls_sha256_context sha256; mbedtls_sha256_init( &sha256 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) ); mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 ); mbedtls_sha256_finish_ret( &sha256, hash ); *hlen = 32; MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_sha256_free( &sha256 ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ return; } #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) void ssl_calc_verify_tls_sha384( const mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hlen ) { #if defined(MBEDTLS_USE_PSA_CRYPTO) size_t hash_size; psa_status_t status; psa_hash_operation_t sha384_psa = psa_hash_operation_init(); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> PSA calc verify sha384" ) ); status = psa_hash_clone( &ssl->handshake->fin_sha384_psa, &sha384_psa ); if( status != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) ); return; } status = psa_hash_finish( &sha384_psa, hash, 48, &hash_size ); if( status != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) ); return; } *hlen = 48; MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated verify result", hash, *hlen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= PSA calc verify" ) ); #else mbedtls_sha512_context sha512; mbedtls_sha512_init( &sha512 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) ); mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 ); mbedtls_sha512_finish_ret( &sha512, hash ); *hlen = 48; MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_sha512_free( &sha512 ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ return; } #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex ) { unsigned char *p = ssl->handshake->premaster; unsigned char *end = p + sizeof( ssl->handshake->premaster ); const unsigned char *psk = NULL; size_t psk_len = 0; if( mbedtls_ssl_get_psk( ssl, &psk, &psk_len ) == MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ) { /* * This should never happen because the existence of a PSK is always * checked before calling this function */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * PMS = struct { * opaque other_secret<0..2^16-1>; * opaque psk<0..2^16-1>; * }; * with "other_secret" depending on the particular key exchange */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK ) { if( end - p < 2 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); *(p++) = (unsigned char)( psk_len >> 8 ); *(p++) = (unsigned char)( psk_len ); if( end < p || (size_t)( end - p ) < psk_len ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memset( p, 0, psk_len ); p += psk_len; } else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { /* * other_secret already set by the ClientKeyExchange message, * and is 48 bytes long */ if( end - p < 2 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); *p++ = 0; *p++ = 48; p += 48; } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; /* Write length only when we know the actual value */ if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx, p + 2, end - ( p + 2 ), &len, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret ); return( ret ); } *(p++) = (unsigned char)( len >> 8 ); *(p++) = (unsigned char)( len ); p += len; MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K ); } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t zlen; if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen, p + 2, end - ( p + 2 ), ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret ); return( ret ); } *(p++) = (unsigned char)( zlen >> 8 ); *(p++) = (unsigned char)( zlen ); p += zlen; MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Z ); } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* opaque psk<0..2^16-1>; */ if( end - p < 2 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); *(p++) = (unsigned char)( psk_len >> 8 ); *(p++) = (unsigned char)( psk_len ); if( end < p || (size_t)( end - p ) < psk_len ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memcpy( p, psk, psk_len ); p += psk_len; ssl->handshake->pmslen = p - ssl->handshake->premaster; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) static int ssl_write_hello_request( mbedtls_ssl_context *ssl ); #if defined(MBEDTLS_SSL_PROTO_DTLS) int mbedtls_ssl_resend_hello_request( mbedtls_ssl_context *ssl ) { /* If renegotiation is not enforced, retransmit until we would reach max * timeout if we were using the usual handshake doubling scheme */ if( ssl->conf->renego_max_records < 0 ) { uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1; unsigned char doublings = 1; while( ratio != 0 ) { ++doublings; ratio >>= 1; } if( ++ssl->renego_records_seen > doublings ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) ); return( 0 ); } } return( ssl_write_hello_request( ssl ) ); } #endif #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ #if defined(MBEDTLS_X509_CRT_PARSE_C) static void ssl_clear_peer_cert( mbedtls_ssl_session *session ) { #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) if( session->peer_cert != NULL ) { mbedtls_x509_crt_free( session->peer_cert ); mbedtls_free( session->peer_cert ); session->peer_cert = NULL; } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( session->peer_cert_digest != NULL ) { /* Zeroization is not necessary. */ mbedtls_free( session->peer_cert_digest ); session->peer_cert_digest = NULL; session->peer_cert_digest_type = MBEDTLS_MD_NONE; session->peer_cert_digest_len = 0; } #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ } #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * Handshake functions */ #if !defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* No certificate support -> dummy functions */ int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) ); if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ /* Some certificate support -> implement write and parse */ int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t i, n; const mbedtls_x509_crt *crt; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) ); if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) { if( ssl->client_auth == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) /* * If using SSLv3 and got no cert, send an Alert message * (otherwise an empty Certificate message will be sent). */ if( mbedtls_ssl_own_cert( ssl ) == NULL && ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl->out_msglen = 2; ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT; ssl->out_msg[0] = MBEDTLS_SSL_ALERT_LEVEL_WARNING; ssl->out_msg[1] = MBEDTLS_SSL_ALERT_MSG_NO_CERT; MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) ); goto write_msg; } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ } #endif /* MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) { if( mbedtls_ssl_own_cert( ssl ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) ); return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED ); } } #endif MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) ); /* * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 6 length of all certs * 7 . 9 length of cert. 1 * 10 . n-1 peer certificate * n . n+2 length of cert. 2 * n+3 . ... upper level cert, etc. */ i = 7; crt = mbedtls_ssl_own_cert( ssl ); while( crt != NULL ) { n = crt->raw.len; if( n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d", i + 3 + n, MBEDTLS_SSL_OUT_CONTENT_LEN ) ); return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE ); } ssl->out_msg[i ] = (unsigned char)( n >> 16 ); ssl->out_msg[i + 1] = (unsigned char)( n >> 8 ); ssl->out_msg[i + 2] = (unsigned char)( n ); i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n ); i += n; crt = crt->next; } ssl->out_msg[4] = (unsigned char)( ( i - 7 ) >> 16 ); ssl->out_msg[5] = (unsigned char)( ( i - 7 ) >> 8 ); ssl->out_msg[6] = (unsigned char)( ( i - 7 ) ); ssl->out_msglen = i; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE; #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C) write_msg: #endif ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) ); return( ret ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) static int ssl_check_peer_crt_unchanged( mbedtls_ssl_context *ssl, unsigned char *crt_buf, size_t crt_buf_len ) { mbedtls_x509_crt const * const peer_crt = ssl->session->peer_cert; if( peer_crt == NULL ) return( -1 ); if( peer_crt->raw.len != crt_buf_len ) return( -1 ); return( memcmp( peer_crt->raw.p, crt_buf, peer_crt->raw.len ) ); } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ static int ssl_check_peer_crt_unchanged( mbedtls_ssl_context *ssl, unsigned char *crt_buf, size_t crt_buf_len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char const * const peer_cert_digest = ssl->session->peer_cert_digest; mbedtls_md_type_t const peer_cert_digest_type = ssl->session->peer_cert_digest_type; mbedtls_md_info_t const * const digest_info = mbedtls_md_info_from_type( peer_cert_digest_type ); unsigned char tmp_digest[MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN]; size_t digest_len; if( peer_cert_digest == NULL || digest_info == NULL ) return( -1 ); digest_len = mbedtls_md_get_size( digest_info ); if( digest_len > MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN ) return( -1 ); ret = mbedtls_md( digest_info, crt_buf, crt_buf_len, tmp_digest ); if( ret != 0 ) return( -1 ); return( memcmp( tmp_digest, peer_cert_digest, digest_len ) ); } #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */ /* * Once the certificate message is read, parse it into a cert chain and * perform basic checks, but leave actual verification to the caller */ static int ssl_parse_certificate_chain( mbedtls_ssl_context *ssl, mbedtls_x509_crt *chain ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C) int crt_cnt=0; #endif size_t i, n; uint8_t alert; if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE || ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } i = mbedtls_ssl_hs_hdr_len( ssl ); /* * Same message structure as in mbedtls_ssl_write_certificate() */ n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2]; if( ssl->in_msg[i] != 0 || ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* Make &ssl->in_msg[i] point to the beginning of the CRT chain. */ i += 3; /* Iterate through and parse the CRTs in the provided chain. */ while( i < ssl->in_hslen ) { /* Check that there's room for the next CRT's length fields. */ if ( i + 3 > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* In theory, the CRT can be up to 2**24 Bytes, but we don't support * anything beyond 2**16 ~ 64K. */ if( ssl->in_msg[i] != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* Read length of the next CRT in the chain. */ n = ( (unsigned int) ssl->in_msg[i + 1] << 8 ) | (unsigned int) ssl->in_msg[i + 2]; i += 3; if( n < 128 || i + n > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* Check if we're handling the first CRT in the chain. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C) if( crt_cnt++ == 0 && ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { /* During client-side renegotiation, check that the server's * end-CRTs hasn't changed compared to the initial handshake, * mitigating the triple handshake attack. On success, reuse * the original end-CRT instead of parsing it again. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "Check that peer CRT hasn't changed during renegotiation" ) ); if( ssl_check_peer_crt_unchanged( ssl, &ssl->in_msg[i], n ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* Now we can safely free the original chain. */ ssl_clear_peer_cert( ssl->session ); } #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */ /* Parse the next certificate in the chain. */ #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) ret = mbedtls_x509_crt_parse_der( chain, ssl->in_msg + i, n ); #else /* If we don't need to store the CRT chain permanently, parse * it in-place from the input buffer instead of making a copy. */ ret = mbedtls_x509_crt_parse_der_nocopy( chain, ssl->in_msg + i, n ); #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ switch( ret ) { case 0: /*ok*/ case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND: /* Ignore certificate with an unknown algorithm: maybe a prior certificate was already trusted. */ break; case MBEDTLS_ERR_X509_ALLOC_FAILED: alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR; goto crt_parse_der_failed; case MBEDTLS_ERR_X509_UNKNOWN_VERSION: alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; goto crt_parse_der_failed; default: alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT; crt_parse_der_failed: mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert ); MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret ); return( ret ); } i += n; } MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", chain ); return( 0 ); } #if defined(MBEDTLS_SSL_SRV_C) static int ssl_srv_check_client_no_crt_notification( mbedtls_ssl_context *ssl ) { if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) return( -1 ); #if defined(MBEDTLS_SSL_PROTO_SSL3) /* * Check if the client sent an empty certificate */ if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { if( ssl->in_msglen == 2 && ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT && ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) ); return( 0 ); } return( -1 ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->in_hslen == 3 + mbedtls_ssl_hs_hdr_len( ssl ) && ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE && memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) ); return( 0 ); } return( -1 ); #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ } #endif /* MBEDTLS_SSL_SRV_C */ /* Check if a certificate message is expected. * Return either * - SSL_CERTIFICATE_EXPECTED, or * - SSL_CERTIFICATE_SKIP * indicating whether a Certificate message is expected or not. */ #define SSL_CERTIFICATE_EXPECTED 0 #define SSL_CERTIFICATE_SKIP 1 static int ssl_parse_certificate_coordinate( mbedtls_ssl_context *ssl, int authmode ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) ) return( SSL_CERTIFICATE_SKIP ); #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) { if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) return( SSL_CERTIFICATE_SKIP ); if( authmode == MBEDTLS_SSL_VERIFY_NONE ) { ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY; return( SSL_CERTIFICATE_SKIP ); } } #else ((void) authmode); #endif /* MBEDTLS_SSL_SRV_C */ return( SSL_CERTIFICATE_EXPECTED ); } static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl, int authmode, mbedtls_x509_crt *chain, void *rs_ctx ) { int ret = 0; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; int have_ca_chain = 0; int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *); void *p_vrfy; if( authmode == MBEDTLS_SSL_VERIFY_NONE ) return( 0 ); if( ssl->f_vrfy != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use context-specific verification callback" ) ); f_vrfy = ssl->f_vrfy; p_vrfy = ssl->p_vrfy; } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use configuration-specific verification callback" ) ); f_vrfy = ssl->conf->f_vrfy; p_vrfy = ssl->conf->p_vrfy; } /* * Main check: verify certificate */ #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) if( ssl->conf->f_ca_cb != NULL ) { ((void) rs_ctx); have_ca_chain = 1; MBEDTLS_SSL_DEBUG_MSG( 3, ( "use CA callback for X.509 CRT verification" ) ); ret = mbedtls_x509_crt_verify_with_ca_cb( chain, ssl->conf->f_ca_cb, ssl->conf->p_ca_cb, ssl->conf->cert_profile, ssl->hostname, &ssl->session_negotiate->verify_result, f_vrfy, p_vrfy ); } else #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ { mbedtls_x509_crt *ca_chain; mbedtls_x509_crl *ca_crl; #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_ca_chain != NULL ) { ca_chain = ssl->handshake->sni_ca_chain; ca_crl = ssl->handshake->sni_ca_crl; } else #endif { ca_chain = ssl->conf->ca_chain; ca_crl = ssl->conf->ca_crl; } if( ca_chain != NULL ) have_ca_chain = 1; ret = mbedtls_x509_crt_verify_restartable( chain, ca_chain, ca_crl, ssl->conf->cert_profile, ssl->hostname, &ssl->session_negotiate->verify_result, f_vrfy, p_vrfy, rs_ctx ); } if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret ); } #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) return( MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS ); #endif /* * Secondary checks: always done, but change 'ret' only if it was 0 */ #if defined(MBEDTLS_ECP_C) { const mbedtls_pk_context *pk = &chain->pk; /* If certificate uses an EC key, make sure the curve is OK */ if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) && mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 ) { ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY; MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) ); if( ret == 0 ) ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE; } } #endif /* MBEDTLS_ECP_C */ if( mbedtls_ssl_check_cert_usage( chain, ciphersuite_info, ! ssl->conf->endpoint, &ssl->session_negotiate->verify_result ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) ); if( ret == 0 ) ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE; } /* mbedtls_x509_crt_verify_with_profile is supposed to report a * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED, * with details encoded in the verification flags. All other kinds * of error codes, including those from the user provided f_vrfy * functions, are treated as fatal and lead to a failure of * ssl_parse_certificate even if verification was optional. */ if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL && ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED || ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) ) { ret = 0; } if( have_ca_chain == 0 && authmode == MBEDTLS_SSL_VERIFY_REQUIRED ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) ); ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED; } if( ret != 0 ) { uint8_t alert; /* The certificate may have been rejected for several reasons. Pick one and send the corresponding alert. Which alert to send may be a subject of debate in some cases. */ if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER ) alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH ) alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE ) alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE ) alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE ) alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK ) alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY ) alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED ) alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED ) alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED ) alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA; else alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN; mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert ); } #if defined(MBEDTLS_DEBUG_C) if( ssl->session_negotiate->verify_result != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %x", ssl->session_negotiate->verify_result ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) ); } #endif /* MBEDTLS_DEBUG_C */ return( ret ); } #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) static int ssl_remember_peer_crt_digest( mbedtls_ssl_context *ssl, unsigned char *start, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* Remember digest of the peer's end-CRT. */ ssl->session_negotiate->peer_cert_digest = mbedtls_calloc( 1, MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN ); if( ssl->session_negotiate->peer_cert_digest == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } ret = mbedtls_md( mbedtls_md_info_from_type( MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE ), start, len, ssl->session_negotiate->peer_cert_digest ); ssl->session_negotiate->peer_cert_digest_type = MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE; ssl->session_negotiate->peer_cert_digest_len = MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN; return( ret ); } static int ssl_remember_peer_pubkey( mbedtls_ssl_context *ssl, unsigned char *start, size_t len ) { unsigned char *end = start + len; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* Make a copy of the peer's raw public key. */ mbedtls_pk_init( &ssl->handshake->peer_pubkey ); ret = mbedtls_pk_parse_subpubkey( &start, end, &ssl->handshake->peer_pubkey ); if( ret != 0 ) { /* We should have parsed the public key before. */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } return( 0 ); } #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) { int ret = 0; int crt_expected; #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET ? ssl->handshake->sni_authmode : ssl->conf->authmode; #else const int authmode = ssl->conf->authmode; #endif void *rs_ctx = NULL; mbedtls_x509_crt *chain = NULL; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); crt_expected = ssl_parse_certificate_coordinate( ssl, authmode ); if( crt_expected == SSL_CERTIFICATE_SKIP ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); goto exit; } #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled && ssl->handshake->ecrs_state == ssl_ecrs_crt_verify ) { chain = ssl->handshake->ecrs_peer_cert; ssl->handshake->ecrs_peer_cert = NULL; goto crt_verify; } #endif if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { /* mbedtls_ssl_read_record may have sent an alert already. We let it decide whether to alert. */ MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); goto exit; } #if defined(MBEDTLS_SSL_SRV_C) if( ssl_srv_check_client_no_crt_notification( ssl ) == 0 ) { ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING; if( authmode != MBEDTLS_SSL_VERIFY_OPTIONAL ) ret = MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE; goto exit; } #endif /* MBEDTLS_SSL_SRV_C */ /* Clear existing peer CRT structure in case we tried to * reuse a session but it failed, and allocate a new one. */ ssl_clear_peer_cert( ssl->session_negotiate ); chain = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) ); if( chain == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", sizeof( mbedtls_x509_crt ) ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto exit; } mbedtls_x509_crt_init( chain ); ret = ssl_parse_certificate_chain( ssl, chain ); if( ret != 0 ) goto exit; #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled) ssl->handshake->ecrs_state = ssl_ecrs_crt_verify; crt_verify: if( ssl->handshake->ecrs_enabled) rs_ctx = &ssl->handshake->ecrs_ctx; #endif ret = ssl_parse_certificate_verify( ssl, authmode, chain, rs_ctx ); if( ret != 0 ) goto exit; #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) { unsigned char *crt_start, *pk_start; size_t crt_len, pk_len; /* We parse the CRT chain without copying, so * these pointers point into the input buffer, * and are hence still valid after freeing the * CRT chain. */ crt_start = chain->raw.p; crt_len = chain->raw.len; pk_start = chain->pk_raw.p; pk_len = chain->pk_raw.len; /* Free the CRT structures before computing * digest and copying the peer's public key. */ mbedtls_x509_crt_free( chain ); mbedtls_free( chain ); chain = NULL; ret = ssl_remember_peer_crt_digest( ssl, crt_start, crt_len ); if( ret != 0 ) goto exit; ret = ssl_remember_peer_pubkey( ssl, pk_start, pk_len ); if( ret != 0 ) goto exit; } #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* Pass ownership to session structure. */ ssl->session_negotiate->peer_cert = chain; chain = NULL; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) ); exit: if( ret == 0 ) ssl->state++; #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS ) { ssl->handshake->ecrs_peer_cert = chain; chain = NULL; } #endif if( chain != NULL ) { mbedtls_x509_crt_free( chain ); mbedtls_free( chain ); } return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl, const mbedtls_ssl_ciphersuite_t *ciphersuite_info ) { ((void) ciphersuite_info); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) ssl->handshake->update_checksum = ssl_update_checksum_md5sha1; else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA512_C) if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) ssl->handshake->update_checksum = ssl_update_checksum_sha384; else #endif #if defined(MBEDTLS_SHA256_C) if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 ) ssl->handshake->update_checksum = ssl_update_checksum_sha256; else #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return; } } void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_starts_ret( &ssl->handshake->fin_md5 ); mbedtls_sha1_starts_ret( &ssl->handshake->fin_sha1 ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_hash_abort( &ssl->handshake->fin_sha256_psa ); psa_hash_setup( &ssl->handshake->fin_sha256_psa, PSA_ALG_SHA_256 ); #else mbedtls_sha256_starts_ret( &ssl->handshake->fin_sha256, 0 ); #endif #endif #if defined(MBEDTLS_SHA512_C) #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_hash_abort( &ssl->handshake->fin_sha384_psa ); psa_hash_setup( &ssl->handshake->fin_sha384_psa, PSA_ALG_SHA_384 ); #else mbedtls_sha512_starts_ret( &ssl->handshake->fin_sha512, 1 ); #endif #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ } static void ssl_update_checksum_start( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len ); mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_hash_update( &ssl->handshake->fin_sha256_psa, buf, len ); #else mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len ); #endif #endif #if defined(MBEDTLS_SHA512_C) #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_hash_update( &ssl->handshake->fin_sha384_psa, buf, len ); #else mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len ); #endif #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len ); mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len ); } #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_hash_update( &ssl->handshake->fin_sha256_psa, buf, len ); #else mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len ); #endif } #endif #if defined(MBEDTLS_SHA512_C) static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_hash_update( &ssl->handshake->fin_sha384_psa, buf, len ); #else mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len ); #endif } #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) static void ssl_calc_finished_ssl( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { const char *sender; mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char padbuf[48]; unsigned char md5sum[16]; unsigned char sha1sum[20]; mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); /* * SSLv3: * hash = * MD5( master + pad2 + * MD5( handshake + sender + master + pad1 ) ) * + SHA1( master + pad2 + * SHA1( handshake + sender + master + pad1 ) ) */ #if !defined(MBEDTLS_MD5_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) md5.state, sizeof( md5.state ) ); #endif #if !defined(MBEDTLS_SHA1_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) sha1.state, sizeof( sha1.state ) ); #endif sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT" : "SRVR"; memset( padbuf, 0x36, 48 ); mbedtls_md5_update_ret( &md5, (const unsigned char *) sender, 4 ); mbedtls_md5_update_ret( &md5, session->master, 48 ); mbedtls_md5_update_ret( &md5, padbuf, 48 ); mbedtls_md5_finish_ret( &md5, md5sum ); mbedtls_sha1_update_ret( &sha1, (const unsigned char *) sender, 4 ); mbedtls_sha1_update_ret( &sha1, session->master, 48 ); mbedtls_sha1_update_ret( &sha1, padbuf, 40 ); mbedtls_sha1_finish_ret( &sha1, sha1sum ); memset( padbuf, 0x5C, 48 ); mbedtls_md5_starts_ret( &md5 ); mbedtls_md5_update_ret( &md5, session->master, 48 ); mbedtls_md5_update_ret( &md5, padbuf, 48 ); mbedtls_md5_update_ret( &md5, md5sum, 16 ); mbedtls_md5_finish_ret( &md5, buf ); mbedtls_sha1_starts_ret( &sha1 ); mbedtls_sha1_update_ret( &sha1, session->master, 48 ); mbedtls_sha1_update_ret( &sha1, padbuf , 40 ); mbedtls_sha1_update_ret( &sha1, sha1sum, 20 ); mbedtls_sha1_finish_ret( &sha1, buf + 16 ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); mbedtls_platform_zeroize( md5sum, sizeof( md5sum ) ); mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_calc_finished_tls( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char padbuf[36]; mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); /* * TLSv1: * hash = PRF( master, finished_label, * MD5( handshake ) + SHA1( handshake ) )[0..11] */ #if !defined(MBEDTLS_MD5_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) md5.state, sizeof( md5.state ) ); #endif #if !defined(MBEDTLS_SHA1_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) sha1.state, sizeof( sha1.state ) ); #endif sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "client finished" : "server finished"; mbedtls_md5_finish_ret( &md5, padbuf ); mbedtls_sha1_finish_ret( &sha1, padbuf + 16 ); ssl->handshake->tls_prf( session->master, 48, sender, padbuf, 36, buf, len ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; unsigned char padbuf[32]; #if defined(MBEDTLS_USE_PSA_CRYPTO) size_t hash_size; psa_hash_operation_t sha256_psa = PSA_HASH_OPERATION_INIT; psa_status_t status; #else mbedtls_sha256_context sha256; #endif mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "client finished" : "server finished"; #if defined(MBEDTLS_USE_PSA_CRYPTO) sha256_psa = psa_hash_operation_init(); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc PSA finished tls sha256" ) ); status = psa_hash_clone( &ssl->handshake->fin_sha256_psa, &sha256_psa ); if( status != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) ); return; } status = psa_hash_finish( &sha256_psa, padbuf, sizeof( padbuf ), &hash_size ); if( status != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) ); return; } MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated padbuf", padbuf, 32 ); #else mbedtls_sha256_init( &sha256 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha256" ) ); mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 ); /* * TLSv1.2: * hash = PRF( master, finished_label, * Hash( handshake ) )[0.11] */ #if !defined(MBEDTLS_SHA256_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *) sha256.state, sizeof( sha256.state ) ); #endif mbedtls_sha256_finish_ret( &sha256, padbuf ); mbedtls_sha256_free( &sha256 ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ ssl->handshake->tls_prf( session->master, 48, sender, padbuf, 32, buf, len ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) typedef int (*finish_sha384_t)(mbedtls_sha512_context*, unsigned char*); static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; unsigned char padbuf[48]; #if defined(MBEDTLS_USE_PSA_CRYPTO) size_t hash_size; psa_hash_operation_t sha384_psa = PSA_HASH_OPERATION_INIT; psa_status_t status; #else mbedtls_sha512_context sha512; #endif mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "client finished" : "server finished"; #if defined(MBEDTLS_USE_PSA_CRYPTO) sha384_psa = psa_hash_operation_init(); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc PSA finished tls sha384" ) ); status = psa_hash_clone( &ssl->handshake->fin_sha384_psa, &sha384_psa ); if( status != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) ); return; } status = psa_hash_finish( &sha384_psa, padbuf, sizeof( padbuf ), &hash_size ); if( status != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) ); return; } MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated padbuf", padbuf, 48 ); #else mbedtls_sha512_init( &sha512 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha384" ) ); mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 ); /* * TLSv1.2: * hash = PRF( master, finished_label, * Hash( handshake ) )[0.11] */ #if !defined(MBEDTLS_SHA512_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *) sha512.state, sizeof( sha512.state ) ); #endif /* * For SHA-384, we can save 16 bytes by keeping padbuf 48 bytes long. * However, to avoid stringop-overflow warning in gcc, we have to cast * mbedtls_sha512_finish_ret(). */ finish_sha384_t finish = (finish_sha384_t)mbedtls_sha512_finish_ret; finish( &sha512, padbuf ); mbedtls_sha512_free( &sha512 ); #endif ssl->handshake->tls_prf( session->master, 48, sender, padbuf, 48, buf, len ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ void mbedtls_ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) ); /* * Free our handshake params */ mbedtls_ssl_handshake_free( ssl ); mbedtls_free( ssl->handshake ); ssl->handshake = NULL; /* * Free the previous transform and swith in the current one */ if( ssl->transform ) { mbedtls_ssl_transform_free( ssl->transform ); mbedtls_free( ssl->transform ); } ssl->transform = ssl->transform_negotiate; ssl->transform_negotiate = NULL; MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) ); } void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl ) { int resume = ssl->handshake->resume; MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_DONE; ssl->renego_records_seen = 0; } #endif /* * Free the previous session and switch in the current one */ if( ssl->session ) { #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) /* RFC 7366 3.1: keep the EtM state */ ssl->session_negotiate->encrypt_then_mac = ssl->session->encrypt_then_mac; #endif mbedtls_ssl_session_free( ssl->session ); mbedtls_free( ssl->session ); } ssl->session = ssl->session_negotiate; ssl->session_negotiate = NULL; /* * Add cache entry */ if( ssl->conf->f_set_cache != NULL && ssl->session->id_len != 0 && resume == 0 ) { if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->flight != NULL ) { /* Cancel handshake timer */ mbedtls_ssl_set_timer( ssl, 0 ); /* Keep last flight around in case we need to resend it: * we need the handshake and transform structures for that */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) ); } else #endif mbedtls_ssl_handshake_wrapup_free_hs_transform( ssl ); ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) ); } int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl ) { int ret, hash_len; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) ); mbedtls_ssl_update_out_pointers( ssl, ssl->transform_negotiate ); ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint ); /* * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites * may define some other value. Currently (early 2016), no defined * ciphersuite does this (and this is unlikely to change as activity has * moved to TLS 1.3 now) so we can keep the hardcoded 12 here. */ hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12; #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->verify_data_len = hash_len; memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len ); #endif ssl->out_msglen = 4 + hash_len; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_FINISHED; /* * In case of session resuming, invert the client and server * ChangeCipherSpec messages order. */ if( ssl->handshake->resume != 0 ) { #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; #endif #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC; #endif } else ssl->state++; /* * Switch to our negotiated transform and session parameters for outbound * data. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { unsigned char i; /* Remember current epoch settings for resending */ ssl->handshake->alt_transform_out = ssl->transform_out; memcpy( ssl->handshake->alt_out_ctr, ssl->cur_out_ctr, 8 ); /* Set sequence_number to zero */ memset( ssl->cur_out_ctr + 2, 0, 6 ); /* Increment epoch */ for( i = 2; i > 0; i-- ) if( ++ssl->cur_out_ctr[i - 1] != 0 ) break; /* The loop goes to its end iff the counter is wrapping */ if( i == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ memset( ssl->cur_out_ctr, 0, 8 ); ssl->transform_out = ssl->transform_negotiate; ssl->session_out = ssl->session_negotiate; #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_activate != NULL ) { if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_send_flight_completed( ssl ); #endif if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret ); return( ret ); } #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) #define SSL_MAX_HASH_LEN 36 #else #define SSL_MAX_HASH_LEN 12 #endif int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned int hash_len; unsigned char buf[SSL_MAX_HASH_LEN]; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) ); ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 ); if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* There is currently no ciphersuite using another length with TLS 1.2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) hash_len = 36; else #endif hash_len = 12; if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED || ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED ); } if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), buf, hash_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->verify_data_len = hash_len; memcpy( ssl->peer_verify_data, buf, hash_len ); #endif if( ssl->handshake->resume != 0 ) { #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC; #endif #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; #endif } else ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_recv_flight_completed( ssl ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) ); return( 0 ); } static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake ) { memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) ); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_init( &handshake->fin_md5 ); mbedtls_sha1_init( &handshake->fin_sha1 ); mbedtls_md5_starts_ret( &handshake->fin_md5 ); mbedtls_sha1_starts_ret( &handshake->fin_sha1 ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_USE_PSA_CRYPTO) handshake->fin_sha256_psa = psa_hash_operation_init(); psa_hash_setup( &handshake->fin_sha256_psa, PSA_ALG_SHA_256 ); #else mbedtls_sha256_init( &handshake->fin_sha256 ); mbedtls_sha256_starts_ret( &handshake->fin_sha256, 0 ); #endif #endif #if defined(MBEDTLS_SHA512_C) #if defined(MBEDTLS_USE_PSA_CRYPTO) handshake->fin_sha384_psa = psa_hash_operation_init(); psa_hash_setup( &handshake->fin_sha384_psa, PSA_ALG_SHA_384 ); #else mbedtls_sha512_init( &handshake->fin_sha512 ); mbedtls_sha512_starts_ret( &handshake->fin_sha512, 1 ); #endif #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ handshake->update_checksum = ssl_update_checksum_start; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs ); #endif #if defined(MBEDTLS_DHM_C) mbedtls_dhm_init( &handshake->dhm_ctx ); #endif #if defined(MBEDTLS_ECDH_C) mbedtls_ecdh_init( &handshake->ecdh_ctx ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) mbedtls_ecjpake_init( &handshake->ecjpake_ctx ); #if defined(MBEDTLS_SSL_CLI_C) handshake->ecjpake_cache = NULL; handshake->ecjpake_cache_len = 0; #endif #endif #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) mbedtls_x509_crt_restart_init( &handshake->ecrs_ctx ); #endif #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET; #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) mbedtls_pk_init( &handshake->peer_pubkey ); #endif } void mbedtls_ssl_transform_init( mbedtls_ssl_transform *transform ) { memset( transform, 0, sizeof(mbedtls_ssl_transform) ); mbedtls_cipher_init( &transform->cipher_ctx_enc ); mbedtls_cipher_init( &transform->cipher_ctx_dec ); #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) mbedtls_md_init( &transform->md_ctx_enc ); mbedtls_md_init( &transform->md_ctx_dec ); #endif } void mbedtls_ssl_session_init( mbedtls_ssl_session *session ) { memset( session, 0, sizeof(mbedtls_ssl_session) ); } static int ssl_handshake_init( mbedtls_ssl_context *ssl ) { /* Clear old handshake information if present */ if( ssl->transform_negotiate ) mbedtls_ssl_transform_free( ssl->transform_negotiate ); if( ssl->session_negotiate ) mbedtls_ssl_session_free( ssl->session_negotiate ); if( ssl->handshake ) mbedtls_ssl_handshake_free( ssl ); /* * Either the pointers are now NULL or cleared properly and can be freed. * Now allocate missing structures. */ if( ssl->transform_negotiate == NULL ) { ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) ); } if( ssl->session_negotiate == NULL ) { ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) ); } if( ssl->handshake == NULL ) { ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) ); } #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) /* If the buffers are too small - reallocate */ handle_buffer_resizing( ssl, 0, MBEDTLS_SSL_IN_BUFFER_LEN, MBEDTLS_SSL_OUT_BUFFER_LEN ); #endif /* All pointers should exist and can be directly freed without issue */ if( ssl->handshake == NULL || ssl->transform_negotiate == NULL || ssl->session_negotiate == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) ); mbedtls_free( ssl->handshake ); mbedtls_free( ssl->transform_negotiate ); mbedtls_free( ssl->session_negotiate ); ssl->handshake = NULL; ssl->transform_negotiate = NULL; ssl->session_negotiate = NULL; return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } /* Initialize structures */ mbedtls_ssl_session_init( ssl->session_negotiate ); mbedtls_ssl_transform_init( ssl->transform_negotiate ); ssl_handshake_params_init( ssl->handshake ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->handshake->alt_transform_out = ssl->transform_out; if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING; else ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; mbedtls_ssl_set_timer( ssl, 0 ); } #endif return( 0 ); } #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) /* Dummy cookie callbacks for defaults */ static int ssl_cookie_write_dummy( void *ctx, unsigned char **p, unsigned char *end, const unsigned char *cli_id, size_t cli_id_len ) { ((void) ctx); ((void) p); ((void) end); ((void) cli_id); ((void) cli_id_len); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } static int ssl_cookie_check_dummy( void *ctx, const unsigned char *cookie, size_t cookie_len, const unsigned char *cli_id, size_t cli_id_len ) { ((void) ctx); ((void) cookie); ((void) cookie_len); ((void) cli_id); ((void) cli_id_len); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */ /* * Initialize an SSL context */ void mbedtls_ssl_init( mbedtls_ssl_context *ssl ) { memset( ssl, 0, sizeof( mbedtls_ssl_context ) ); } /* * Setup an SSL context */ int mbedtls_ssl_setup( mbedtls_ssl_context *ssl, const mbedtls_ssl_config *conf ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; ssl->conf = conf; /* * Prepare base structures */ /* Set to NULL in case of an error condition */ ssl->out_buf = NULL; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) ssl->in_buf_len = in_buf_len; #endif ssl->in_buf = mbedtls_calloc( 1, in_buf_len ); if( ssl->in_buf == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", in_buf_len ) ); ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto error; } #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) ssl->out_buf_len = out_buf_len; #endif ssl->out_buf = mbedtls_calloc( 1, out_buf_len ); if( ssl->out_buf == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", out_buf_len ) ); ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto error; } mbedtls_ssl_reset_in_out_pointers( ssl ); #if defined(MBEDTLS_SSL_DTLS_SRTP) memset( &ssl->dtls_srtp_info, 0, sizeof(ssl->dtls_srtp_info) ); #endif if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) goto error; return( 0 ); error: mbedtls_free( ssl->in_buf ); mbedtls_free( ssl->out_buf ); ssl->conf = NULL; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) ssl->in_buf_len = 0; ssl->out_buf_len = 0; #endif ssl->in_buf = NULL; ssl->out_buf = NULL; ssl->in_hdr = NULL; ssl->in_ctr = NULL; ssl->in_len = NULL; ssl->in_iv = NULL; ssl->in_msg = NULL; ssl->out_hdr = NULL; ssl->out_ctr = NULL; ssl->out_len = NULL; ssl->out_iv = NULL; ssl->out_msg = NULL; return( ret ); } /* * Reset an initialized and used SSL context for re-use while retaining * all application-set variables, function pointers and data. * * If partial is non-zero, keep data in the input buffer and client ID. * (Use when a DTLS client reconnects from the same port.) */ int mbedtls_ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t in_buf_len = ssl->in_buf_len; size_t out_buf_len = ssl->out_buf_len; #else size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; #endif #if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) || \ !defined(MBEDTLS_SSL_SRV_C) ((void) partial); #endif ssl->state = MBEDTLS_SSL_HELLO_REQUEST; /* Cancel any possibly running timer */ mbedtls_ssl_set_timer( ssl, 0 ); #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE; ssl->renego_records_seen = 0; ssl->verify_data_len = 0; memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN ); memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN ); #endif ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION; ssl->in_offt = NULL; mbedtls_ssl_reset_in_out_pointers( ssl ); ssl->in_msgtype = 0; ssl->in_msglen = 0; #if defined(MBEDTLS_SSL_PROTO_DTLS) ssl->next_record_offset = 0; ssl->in_epoch = 0; #endif #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) mbedtls_ssl_dtls_replay_reset( ssl ); #endif ssl->in_hslen = 0; ssl->nb_zero = 0; ssl->keep_current_message = 0; ssl->out_msgtype = 0; ssl->out_msglen = 0; ssl->out_left = 0; #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ) ssl->split_done = 0; #endif memset( ssl->cur_out_ctr, 0, sizeof( ssl->cur_out_ctr ) ); ssl->transform_in = NULL; ssl->transform_out = NULL; ssl->session_in = NULL; ssl->session_out = NULL; memset( ssl->out_buf, 0, out_buf_len ); #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) if( partial == 0 ) #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ { ssl->in_left = 0; memset( ssl->in_buf, 0, in_buf_len ); } #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_reset != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) ); if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif if( ssl->transform ) { mbedtls_ssl_transform_free( ssl->transform ); mbedtls_free( ssl->transform ); ssl->transform = NULL; } if( ssl->session ) { mbedtls_ssl_session_free( ssl->session ); mbedtls_free( ssl->session ); ssl->session = NULL; } #if defined(MBEDTLS_SSL_ALPN) ssl->alpn_chosen = NULL; #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) if( partial == 0 ) #endif { mbedtls_free( ssl->cli_id ); ssl->cli_id = NULL; ssl->cli_id_len = 0; } #endif if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) return( ret ); return( 0 ); } /* * Reset an initialized and used SSL context for re-use while retaining * all application-set variables, function pointers and data. */ int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl ) { return( mbedtls_ssl_session_reset_int( ssl, 0 ) ); } /* * SSL set accessors */ void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint ) { conf->endpoint = endpoint; } void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport ) { conf->transport = transport; } #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode ) { conf->anti_replay = mode; } #endif #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit ) { conf->badmac_limit = limit; } #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl, unsigned allow_packing ) { ssl->disable_datagram_packing = !allow_packing; } void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max ) { conf->hs_timeout_min = min; conf->hs_timeout_max = max; } #endif void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode ) { conf->authmode = authmode; } #if defined(MBEDTLS_X509_CRT_PARSE_C) void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { conf->f_vrfy = f_vrfy; conf->p_vrfy = p_vrfy; } #endif /* MBEDTLS_X509_CRT_PARSE_C */ void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { conf->f_rng = f_rng; conf->p_rng = p_rng; } void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf, void (*f_dbg)(void *, int, const char *, int, const char *), void *p_dbg ) { conf->f_dbg = f_dbg; conf->p_dbg = p_dbg; } void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl, void *p_bio, mbedtls_ssl_send_t *f_send, mbedtls_ssl_recv_t *f_recv, mbedtls_ssl_recv_timeout_t *f_recv_timeout ) { ssl->p_bio = p_bio; ssl->f_send = f_send; ssl->f_recv = f_recv; ssl->f_recv_timeout = f_recv_timeout; } #if defined(MBEDTLS_SSL_PROTO_DTLS) void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu ) { ssl->mtu = mtu; } #endif void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout ) { conf->read_timeout = timeout; } void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl, void *p_timer, mbedtls_ssl_set_timer_t *f_set_timer, mbedtls_ssl_get_timer_t *f_get_timer ) { ssl->p_timer = p_timer; ssl->f_set_timer = f_set_timer; ssl->f_get_timer = f_get_timer; /* Make sure we start with no timer running */ mbedtls_ssl_set_timer( ssl, 0 ); } #if defined(MBEDTLS_SSL_SRV_C) void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf, void *p_cache, int (*f_get_cache)(void *, mbedtls_ssl_session *), int (*f_set_cache)(void *, const mbedtls_ssl_session *) ) { conf->p_cache = p_cache; conf->f_get_cache = f_get_cache; conf->f_set_cache = f_set_cache; } #endif /* MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_SSL_CLI_C) int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ssl == NULL || session == NULL || ssl->session_negotiate == NULL || ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ( ret = mbedtls_ssl_session_copy( ssl->session_negotiate, session ) ) != 0 ) return( ret ); ssl->handshake->resume = 1; return( 0 ); } #endif /* MBEDTLS_SSL_CLI_C */ void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf, const int *ciphersuites ) { conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites; } void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf, const int *ciphersuites, int major, int minor ) { if( major != MBEDTLS_SSL_MAJOR_VERSION_3 ) return; if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 ) return; conf->ciphersuite_list[minor] = ciphersuites; } #if defined(MBEDTLS_X509_CRT_PARSE_C) void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf, const mbedtls_x509_crt_profile *profile ) { conf->cert_profile = profile; } /* Append a new keycert entry to a (possibly empty) list */ static int ssl_append_key_cert( mbedtls_ssl_key_cert **head, mbedtls_x509_crt *cert, mbedtls_pk_context *key ) { mbedtls_ssl_key_cert *new_cert; new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) ); if( new_cert == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); new_cert->cert = cert; new_cert->key = key; new_cert->next = NULL; /* Update head is the list was null, else add to the end */ if( *head == NULL ) { *head = new_cert; } else { mbedtls_ssl_key_cert *cur = *head; while( cur->next != NULL ) cur = cur->next; cur->next = new_cert; } return( 0 ); } int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf, mbedtls_x509_crt *own_cert, mbedtls_pk_context *pk_key ) { return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) ); } void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf, mbedtls_x509_crt *ca_chain, mbedtls_x509_crl *ca_crl ) { conf->ca_chain = ca_chain; conf->ca_crl = ca_crl; #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb() * cannot be used together. */ conf->f_ca_cb = NULL; conf->p_ca_cb = NULL; #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ } #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) void mbedtls_ssl_conf_ca_cb( mbedtls_ssl_config *conf, mbedtls_x509_crt_ca_cb_t f_ca_cb, void *p_ca_cb ) { conf->f_ca_cb = f_ca_cb; conf->p_ca_cb = p_ca_cb; /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb() * cannot be used together. */ conf->ca_chain = NULL; conf->ca_crl = NULL; } #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl, mbedtls_x509_crt *own_cert, mbedtls_pk_context *pk_key ) { return( ssl_append_key_cert( &ssl->handshake->sni_key_cert, own_cert, pk_key ) ); } void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl, mbedtls_x509_crt *ca_chain, mbedtls_x509_crl *ca_crl ) { ssl->handshake->sni_ca_chain = ca_chain; ssl->handshake->sni_ca_crl = ca_crl; } void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl, int authmode ) { ssl->handshake->sni_authmode = authmode; } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_X509_CRT_PARSE_C) void mbedtls_ssl_set_verify( mbedtls_ssl_context *ssl, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { ssl->f_vrfy = f_vrfy; ssl->p_vrfy = p_vrfy; } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) /* * Set EC J-PAKE password for current handshake */ int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl, const unsigned char *pw, size_t pw_len ) { mbedtls_ecjpake_role role; if( ssl->handshake == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) role = MBEDTLS_ECJPAKE_SERVER; else role = MBEDTLS_ECJPAKE_CLIENT; return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx, role, MBEDTLS_MD_SHA256, MBEDTLS_ECP_DP_SECP256R1, pw, pw_len ) ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static void ssl_conf_remove_psk( mbedtls_ssl_config *conf ) { /* Remove reference to existing PSK, if any. */ #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ! mbedtls_svc_key_id_is_null( conf->psk_opaque ) ) { /* The maintenance of the PSK key slot is the * user's responsibility. */ conf->psk_opaque = MBEDTLS_SVC_KEY_ID_INIT; } /* This and the following branch should never * be taken simultaenously as we maintain the * invariant that raw and opaque PSKs are never * configured simultaneously. As a safeguard, * though, `else` is omitted here. */ #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( conf->psk != NULL ) { mbedtls_platform_zeroize( conf->psk, conf->psk_len ); mbedtls_free( conf->psk ); conf->psk = NULL; conf->psk_len = 0; } /* Remove reference to PSK identity, if any. */ if( conf->psk_identity != NULL ) { mbedtls_free( conf->psk_identity ); conf->psk_identity = NULL; conf->psk_identity_len = 0; } } /* This function assumes that PSK identity in the SSL config is unset. * It checks that the provided identity is well-formed and attempts * to make a copy of it in the SSL config. * On failure, the PSK identity in the config remains unset. */ static int ssl_conf_set_psk_identity( mbedtls_ssl_config *conf, unsigned char const *psk_identity, size_t psk_identity_len ) { /* Identity len will be encoded on two bytes */ if( psk_identity == NULL || ( psk_identity_len >> 16 ) != 0 || psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ); if( conf->psk_identity == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); conf->psk_identity_len = psk_identity_len; memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len ); return( 0 ); } int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, const unsigned char *psk, size_t psk_len, const unsigned char *psk_identity, size_t psk_identity_len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* Remove opaque/raw PSK + PSK Identity */ ssl_conf_remove_psk( conf ); /* Check and set raw PSK */ if( psk == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( psk_len == 0 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( psk_len > MBEDTLS_PSK_MAX_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); conf->psk_len = psk_len; memcpy( conf->psk, psk, conf->psk_len ); /* Check and set PSK Identity */ ret = ssl_conf_set_psk_identity( conf, psk_identity, psk_identity_len ); if( ret != 0 ) ssl_conf_remove_psk( conf ); return( ret ); } static void ssl_remove_psk( mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ! mbedtls_svc_key_id_is_null( ssl->handshake->psk_opaque ) ) { ssl->handshake->psk_opaque = MBEDTLS_SVC_KEY_ID_INIT; } else #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ssl->handshake->psk != NULL ) { mbedtls_platform_zeroize( ssl->handshake->psk, ssl->handshake->psk_len ); mbedtls_free( ssl->handshake->psk ); ssl->handshake->psk_len = 0; } } int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, const unsigned char *psk, size_t psk_len ) { if( psk == NULL || ssl->handshake == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( psk_len > MBEDTLS_PSK_MAX_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl_remove_psk( ssl ); if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); ssl->handshake->psk_len = psk_len; memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len ); return( 0 ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) int mbedtls_ssl_conf_psk_opaque( mbedtls_ssl_config *conf, psa_key_id_t psk, const unsigned char *psk_identity, size_t psk_identity_len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* Clear opaque/raw PSK + PSK Identity, if present. */ ssl_conf_remove_psk( conf ); /* Check and set opaque PSK */ if( mbedtls_svc_key_id_is_null( psk ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); conf->psk_opaque = psk; /* Check and set PSK Identity */ ret = ssl_conf_set_psk_identity( conf, psk_identity, psk_identity_len ); if( ret != 0 ) ssl_conf_remove_psk( conf ); return( ret ); } int mbedtls_ssl_set_hs_psk_opaque( mbedtls_ssl_context *ssl, psa_key_id_t psk ) { if( ( mbedtls_svc_key_id_is_null( psk ) ) || ( ssl->handshake == NULL ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl_remove_psk( ssl ); ssl->handshake->psk_opaque = psk; return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf, int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *, size_t), void *p_psk ) { conf->f_psk = f_psk; conf->p_psk = p_psk; } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) #if !defined(MBEDTLS_DEPRECATED_REMOVED) int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 || ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 ) { mbedtls_mpi_free( &conf->dhm_P ); mbedtls_mpi_free( &conf->dhm_G ); return( ret ); } return( 0 ); } #endif /* MBEDTLS_DEPRECATED_REMOVED */ int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf, const unsigned char *dhm_P, size_t P_len, const unsigned char *dhm_G, size_t G_len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P, dhm_P, P_len ) ) != 0 || ( ret = mbedtls_mpi_read_binary( &conf->dhm_G, dhm_G, G_len ) ) != 0 ) { mbedtls_mpi_free( &conf->dhm_P ); mbedtls_mpi_free( &conf->dhm_G ); return( ret ); } return( 0 ); } int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 || ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 ) { mbedtls_mpi_free( &conf->dhm_P ); mbedtls_mpi_free( &conf->dhm_G ); return( ret ); } return( 0 ); } #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C) /* * Set the minimum length for Diffie-Hellman parameters */ void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf, unsigned int bitlen ) { conf->dhm_min_bitlen = bitlen; } #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* * Set allowed/preferred hashes for handshake signatures */ void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf, const int *hashes ) { conf->sig_hashes = hashes; } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECP_C) /* * Set the allowed elliptic curves */ void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf, const mbedtls_ecp_group_id *curve_list ) { conf->curve_list = curve_list; } #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_X509_CRT_PARSE_C) int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ) { /* Initialize to suppress unnecessary compiler warning */ size_t hostname_len = 0; /* Check if new hostname is valid before * making any change to current one */ if( hostname != NULL ) { hostname_len = strlen( hostname ); if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Now it's clear that we will overwrite the old hostname, * so we can free it safely */ if( ssl->hostname != NULL ) { mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) ); mbedtls_free( ssl->hostname ); } /* Passing NULL as hostname shall clear the old one */ if( hostname == NULL ) { ssl->hostname = NULL; } else { ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 ); if( ssl->hostname == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( ssl->hostname, hostname, hostname_len ); ssl->hostname[hostname_len] = '\0'; } return( 0 ); } #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf, int (*f_sni)(void *, mbedtls_ssl_context *, const unsigned char *, size_t), void *p_sni ) { conf->f_sni = f_sni; conf->p_sni = p_sni; } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_ALPN) int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos ) { size_t cur_len, tot_len; const char **p; /* * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings * MUST NOT be truncated." * We check lengths now rather than later. */ tot_len = 0; for( p = protos; *p != NULL; p++ ) { cur_len = strlen( *p ); tot_len += cur_len; if( ( cur_len == 0 ) || ( cur_len > MBEDTLS_SSL_MAX_ALPN_NAME_LEN ) || ( tot_len > MBEDTLS_SSL_MAX_ALPN_LIST_LEN ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->alpn_list = protos; return( 0 ); } const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl ) { return( ssl->alpn_chosen ); } #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_DTLS_SRTP) void mbedtls_ssl_conf_srtp_mki_value_supported( mbedtls_ssl_config *conf, int support_mki_value ) { conf->dtls_srtp_mki_support = support_mki_value; } int mbedtls_ssl_dtls_srtp_set_mki_value( mbedtls_ssl_context *ssl, unsigned char *mki_value, uint16_t mki_len ) { if( mki_len > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED ) { return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } memcpy( ssl->dtls_srtp_info.mki_value, mki_value, mki_len ); ssl->dtls_srtp_info.mki_len = mki_len; return( 0 ); } int mbedtls_ssl_conf_dtls_srtp_protection_profiles( mbedtls_ssl_config *conf, const mbedtls_ssl_srtp_profile *profiles ) { const mbedtls_ssl_srtp_profile *p; size_t list_size = 0; /* check the profiles list: all entry must be valid, * its size cannot be more than the total number of supported profiles, currently 4 */ for( p = profiles; *p != MBEDTLS_TLS_SRTP_UNSET && list_size <= MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH; p++ ) { if( mbedtls_ssl_check_srtp_profile_value( *p ) != MBEDTLS_TLS_SRTP_UNSET ) { list_size++; } else { /* unsupported value, stop parsing and set the size to an error value */ list_size = MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH + 1; } } if( list_size > MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH ) { conf->dtls_srtp_profile_list = NULL; conf->dtls_srtp_profile_list_len = 0; return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->dtls_srtp_profile_list = profiles; conf->dtls_srtp_profile_list_len = list_size; return( 0 ); } void mbedtls_ssl_get_dtls_srtp_negotiation_result( const mbedtls_ssl_context *ssl, mbedtls_dtls_srtp_info *dtls_srtp_info ) { dtls_srtp_info->chosen_dtls_srtp_profile = ssl->dtls_srtp_info.chosen_dtls_srtp_profile; /* do not copy the mki value if there is no chosen profile */ if( dtls_srtp_info->chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET ) { dtls_srtp_info->mki_len = 0; } else { dtls_srtp_info->mki_len = ssl->dtls_srtp_info.mki_len; memcpy( dtls_srtp_info->mki_value, ssl->dtls_srtp_info.mki_value, ssl->dtls_srtp_info.mki_len ); } } #endif /* MBEDTLS_SSL_DTLS_SRTP */ void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor ) { conf->max_major_ver = major; conf->max_minor_ver = minor; } void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor ) { conf->min_major_ver = major; conf->min_minor_ver = minor; } #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C) void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback ) { conf->fallback = fallback; } #endif #if defined(MBEDTLS_SSL_SRV_C) void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf, char cert_req_ca_list ) { conf->cert_req_ca_list = cert_req_ca_list; } #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm ) { conf->encrypt_then_mac = etm; } #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems ) { conf->extended_ms = ems; } #endif #if defined(MBEDTLS_ARC4_C) void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 ) { conf->arc4_disabled = arc4; } #endif #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code ) { if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID || ssl_mfl_code_to_length( mfl_code ) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->mfl_code = mfl_code; return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate ) { conf->trunc_hmac = truncate; } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split ) { conf->cbc_record_splitting = split; } #endif void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy ) { conf->allow_legacy_renegotiation = allow_legacy; } #if defined(MBEDTLS_SSL_RENEGOTIATION) void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation ) { conf->disable_renegotiation = renegotiation; } void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records ) { conf->renego_max_records = max_records; } void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf, const unsigned char period[8] ) { memcpy( conf->renego_period, period, 8 ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) #if defined(MBEDTLS_SSL_CLI_C) void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets ) { conf->session_tickets = use_tickets; } #endif #if defined(MBEDTLS_SSL_SRV_C) void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf, mbedtls_ssl_ticket_write_t *f_ticket_write, mbedtls_ssl_ticket_parse_t *f_ticket_parse, void *p_ticket ) { conf->f_ticket_write = f_ticket_write; conf->f_ticket_parse = f_ticket_parse; conf->p_ticket = p_ticket; } #endif #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_EXPORT_KEYS) void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf, mbedtls_ssl_export_keys_t *f_export_keys, void *p_export_keys ) { conf->f_export_keys = f_export_keys; conf->p_export_keys = p_export_keys; } void mbedtls_ssl_conf_export_keys_ext_cb( mbedtls_ssl_config *conf, mbedtls_ssl_export_keys_ext_t *f_export_keys_ext, void *p_export_keys ) { conf->f_export_keys_ext = f_export_keys_ext; conf->p_export_keys = p_export_keys; } #endif #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) void mbedtls_ssl_conf_async_private_cb( mbedtls_ssl_config *conf, mbedtls_ssl_async_sign_t *f_async_sign, mbedtls_ssl_async_decrypt_t *f_async_decrypt, mbedtls_ssl_async_resume_t *f_async_resume, mbedtls_ssl_async_cancel_t *f_async_cancel, void *async_config_data ) { conf->f_async_sign_start = f_async_sign; conf->f_async_decrypt_start = f_async_decrypt; conf->f_async_resume = f_async_resume; conf->f_async_cancel = f_async_cancel; conf->p_async_config_data = async_config_data; } void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf ) { return( conf->p_async_config_data ); } void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl ) { if( ssl->handshake == NULL ) return( NULL ); else return( ssl->handshake->user_async_ctx ); } void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl, void *ctx ) { if( ssl->handshake != NULL ) ssl->handshake->user_async_ctx = ctx; } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ /* * SSL get accessors */ uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl ) { if( ssl->session != NULL ) return( ssl->session->verify_result ); if( ssl->session_negotiate != NULL ) return( ssl->session_negotiate->verify_result ); return( 0xFFFFFFFF ); } const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl ) { if( ssl == NULL || ssl->session == NULL ) return( NULL ); return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite ); } const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { switch( ssl->minor_ver ) { case MBEDTLS_SSL_MINOR_VERSION_2: return( "DTLSv1.0" ); case MBEDTLS_SSL_MINOR_VERSION_3: return( "DTLSv1.2" ); default: return( "unknown (DTLS)" ); } } #endif switch( ssl->minor_ver ) { case MBEDTLS_SSL_MINOR_VERSION_0: return( "SSLv3.0" ); case MBEDTLS_SSL_MINOR_VERSION_1: return( "TLSv1.0" ); case MBEDTLS_SSL_MINOR_VERSION_2: return( "TLSv1.1" ); case MBEDTLS_SSL_MINOR_VERSION_3: return( "TLSv1.2" ); default: return( "unknown" ); } } #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) size_t mbedtls_ssl_get_input_max_frag_len( const mbedtls_ssl_context *ssl ) { size_t max_len = MBEDTLS_SSL_MAX_CONTENT_LEN; size_t read_mfl; /* Use the configured MFL for the client if we're past SERVER_HELLO_DONE */ if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && ssl->state >= MBEDTLS_SSL_SERVER_HELLO_DONE ) { return ssl_mfl_code_to_length( ssl->conf->mfl_code ); } /* Check if a smaller max length was negotiated */ if( ssl->session_out != NULL ) { read_mfl = ssl_mfl_code_to_length( ssl->session_out->mfl_code ); if( read_mfl < max_len ) { max_len = read_mfl; } } // During a handshake, use the value being negotiated if( ssl->session_negotiate != NULL ) { read_mfl = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ); if( read_mfl < max_len ) { max_len = read_mfl; } } return( max_len ); } size_t mbedtls_ssl_get_output_max_frag_len( const mbedtls_ssl_context *ssl ) { size_t max_len; /* * Assume mfl_code is correct since it was checked when set */ max_len = ssl_mfl_code_to_length( ssl->conf->mfl_code ); /* Check if a smaller max length was negotiated */ if( ssl->session_out != NULL && ssl_mfl_code_to_length( ssl->session_out->mfl_code ) < max_len ) { max_len = ssl_mfl_code_to_length( ssl->session_out->mfl_code ); } /* During a handshake, use the value being negotiated */ if( ssl->session_negotiate != NULL && ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ) < max_len ) { max_len = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ); } return( max_len ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl ) { return mbedtls_ssl_get_output_max_frag_len( ssl ); } #endif /* !MBEDTLS_DEPRECATED_REMOVED */ #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_PROTO_DTLS) size_t mbedtls_ssl_get_current_mtu( const mbedtls_ssl_context *ssl ) { /* Return unlimited mtu for client hello messages to avoid fragmentation. */ if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && ( ssl->state == MBEDTLS_SSL_CLIENT_HELLO || ssl->state == MBEDTLS_SSL_SERVER_HELLO ) ) return ( 0 ); if( ssl->handshake == NULL || ssl->handshake->mtu == 0 ) return( ssl->mtu ); if( ssl->mtu == 0 ) return( ssl->handshake->mtu ); return( ssl->mtu < ssl->handshake->mtu ? ssl->mtu : ssl->handshake->mtu ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl ) { size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN; #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \ !defined(MBEDTLS_SSL_PROTO_DTLS) (void) ssl; #endif #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) const size_t mfl = mbedtls_ssl_get_output_max_frag_len( ssl ); if( max_len > mfl ) max_len = mfl; #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) if( mbedtls_ssl_get_current_mtu( ssl ) != 0 ) { const size_t mtu = mbedtls_ssl_get_current_mtu( ssl ); const int ret = mbedtls_ssl_get_record_expansion( ssl ); const size_t overhead = (size_t) ret; if( ret < 0 ) return( ret ); if( mtu <= overhead ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "MTU too low for record expansion" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } if( max_len > mtu - overhead ) max_len = mtu - overhead; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \ !defined(MBEDTLS_SSL_PROTO_DTLS) ((void) ssl); #endif return( (int) max_len ); } #if defined(MBEDTLS_X509_CRT_PARSE_C) const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl ) { if( ssl == NULL || ssl->session == NULL ) return( NULL ); #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) return( ssl->session->peer_cert ); #else return( NULL ); #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ } #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_CLI_C) int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst ) { if( ssl == NULL || dst == NULL || ssl->session == NULL || ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } return( mbedtls_ssl_session_copy( dst, ssl->session ) ); } #endif /* MBEDTLS_SSL_CLI_C */ const mbedtls_ssl_session *mbedtls_ssl_get_session_pointer( const mbedtls_ssl_context *ssl ) { if( ssl == NULL ) return( NULL ); return( ssl->session ); } /* * Define ticket header determining Mbed TLS version * and structure of the ticket. */ /* * Define bitflag determining compile-time settings influencing * structure of serialized SSL sessions. */ #if defined(MBEDTLS_HAVE_TIME) #define SSL_SERIALIZED_SESSION_CONFIG_TIME 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_TIME 0 #endif /* MBEDTLS_HAVE_TIME */ #if defined(MBEDTLS_X509_CRT_PARSE_C) #define SSL_SERIALIZED_SESSION_CONFIG_CRT 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_CRT 0 #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_SESSION_TICKETS) #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 0 #endif /* MBEDTLS_SSL_CLI_C && MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) #define SSL_SERIALIZED_SESSION_CONFIG_MFL 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_MFL 0 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 0 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) #define SSL_SERIALIZED_SESSION_CONFIG_ETM 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_ETM 0 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 0 #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #define SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT 0 #define SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT 1 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT 2 #define SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT 3 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT 4 #define SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT 5 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT 6 #define SSL_SERIALIZED_SESSION_CONFIG_BITFLAG \ ( (uint16_t) ( \ ( SSL_SERIALIZED_SESSION_CONFIG_TIME << SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_CRT << SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET << SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_MFL << SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC << SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_ETM << SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_TICKET << SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT ) ) ) static unsigned char ssl_serialized_session_header[] = { MBEDTLS_VERSION_MAJOR, MBEDTLS_VERSION_MINOR, MBEDTLS_VERSION_PATCH, ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 8 ) & 0xFF, ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 0 ) & 0xFF, }; /* * Serialize a session in the following format: * (in the presentation language of TLS, RFC 8446 section 3) * * opaque mbedtls_version[3]; // major, minor, patch * opaque session_format[2]; // version-specific 16-bit field determining * // the format of the remaining * // serialized data. * * Note: When updating the format, remember to keep * these version+format bytes. * * // In this version, `session_format` determines * // the setting of those compile-time * // configuration options which influence * // the structure of mbedtls_ssl_session. * uint64 start_time; * uint8 ciphersuite[2]; // defined by the standard * uint8 compression; // 0 or 1 * uint8 session_id_len; // at most 32 * opaque session_id[32]; * opaque master[48]; // fixed length in the standard * uint32 verify_result; * opaque peer_cert<0..2^24-1>; // length 0 means no peer cert * opaque ticket<0..2^24-1>; // length 0 means no ticket * uint32 ticket_lifetime; * uint8 mfl_code; // up to 255 according to standard * uint8 trunc_hmac; // 0 or 1 * uint8 encrypt_then_mac; // 0 or 1 * * The order is the same as in the definition of the structure, except * verify_result is put before peer_cert so that all mandatory fields come * together in one block. */ static int ssl_session_save( const mbedtls_ssl_session *session, unsigned char omit_header, unsigned char *buf, size_t buf_len, size_t *olen ) { unsigned char *p = buf; size_t used = 0; #if defined(MBEDTLS_HAVE_TIME) uint64_t start; #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) size_t cert_len; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ if( !omit_header ) { /* * Add version identifier */ used += sizeof( ssl_serialized_session_header ); if( used <= buf_len ) { memcpy( p, ssl_serialized_session_header, sizeof( ssl_serialized_session_header ) ); p += sizeof( ssl_serialized_session_header ); } } /* * Time */ #if defined(MBEDTLS_HAVE_TIME) used += 8; if( used <= buf_len ) { start = (uint64_t) session->start; *p++ = (unsigned char)( ( start >> 56 ) & 0xFF ); *p++ = (unsigned char)( ( start >> 48 ) & 0xFF ); *p++ = (unsigned char)( ( start >> 40 ) & 0xFF ); *p++ = (unsigned char)( ( start >> 32 ) & 0xFF ); *p++ = (unsigned char)( ( start >> 24 ) & 0xFF ); *p++ = (unsigned char)( ( start >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( start >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( start ) & 0xFF ); } #endif /* MBEDTLS_HAVE_TIME */ /* * Basic mandatory fields */ used += 2 /* ciphersuite */ + 1 /* compression */ + 1 /* id_len */ + sizeof( session->id ) + sizeof( session->master ) + 4; /* verify_result */ if( used <= buf_len ) { *p++ = (unsigned char)( ( session->ciphersuite >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( session->ciphersuite ) & 0xFF ); *p++ = (unsigned char)( session->compression & 0xFF ); *p++ = (unsigned char)( session->id_len & 0xFF ); memcpy( p, session->id, 32 ); p += 32; memcpy( p, session->master, 48 ); p += 48; *p++ = (unsigned char)( ( session->verify_result >> 24 ) & 0xFF ); *p++ = (unsigned char)( ( session->verify_result >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( session->verify_result >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( session->verify_result ) & 0xFF ); } /* * Peer's end-entity certificate */ #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) if( session->peer_cert == NULL ) cert_len = 0; else cert_len = session->peer_cert->raw.len; used += 3 + cert_len; if( used <= buf_len ) { *p++ = (unsigned char)( ( cert_len >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( cert_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( cert_len ) & 0xFF ); if( session->peer_cert != NULL ) { memcpy( p, session->peer_cert->raw.p, cert_len ); p += cert_len; } } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( session->peer_cert_digest != NULL ) { used += 1 /* type */ + 1 /* length */ + session->peer_cert_digest_len; if( used <= buf_len ) { *p++ = (unsigned char) session->peer_cert_digest_type; *p++ = (unsigned char) session->peer_cert_digest_len; memcpy( p, session->peer_cert_digest, session->peer_cert_digest_len ); p += session->peer_cert_digest_len; } } else { used += 2; if( used <= buf_len ) { *p++ = (unsigned char) MBEDTLS_MD_NONE; *p++ = 0; } } #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * Session ticket if any, plus associated data */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) used += 3 + session->ticket_len + 4; /* len + ticket + lifetime */ if( used <= buf_len ) { *p++ = (unsigned char)( ( session->ticket_len >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( session->ticket_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( session->ticket_len ) & 0xFF ); if( session->ticket != NULL ) { memcpy( p, session->ticket, session->ticket_len ); p += session->ticket_len; } *p++ = (unsigned char)( ( session->ticket_lifetime >> 24 ) & 0xFF ); *p++ = (unsigned char)( ( session->ticket_lifetime >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( session->ticket_lifetime >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( session->ticket_lifetime ) & 0xFF ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ /* * Misc extension-related info */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) used += 1; if( used <= buf_len ) *p++ = session->mfl_code; #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) used += 1; if( used <= buf_len ) *p++ = (unsigned char)( ( session->trunc_hmac ) & 0xFF ); #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) used += 1; if( used <= buf_len ) *p++ = (unsigned char)( ( session->encrypt_then_mac ) & 0xFF ); #endif /* Done */ *olen = used; if( used > buf_len ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); return( 0 ); } /* * Public wrapper for ssl_session_save() */ int mbedtls_ssl_session_save( const mbedtls_ssl_session *session, unsigned char *buf, size_t buf_len, size_t *olen ) { return( ssl_session_save( session, 0, buf, buf_len, olen ) ); } /* * Deserialize session, see mbedtls_ssl_session_save() for format. * * This internal version is wrapped by a public function that cleans up in * case of error, and has an extra option omit_header. */ static int ssl_session_load( mbedtls_ssl_session *session, unsigned char omit_header, const unsigned char *buf, size_t len ) { const unsigned char *p = buf; const unsigned char * const end = buf + len; #if defined(MBEDTLS_HAVE_TIME) uint64_t start; #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) size_t cert_len; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ if( !omit_header ) { /* * Check version identifier */ if( (size_t)( end - p ) < sizeof( ssl_serialized_session_header ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( memcmp( p, ssl_serialized_session_header, sizeof( ssl_serialized_session_header ) ) != 0 ) { return( MBEDTLS_ERR_SSL_VERSION_MISMATCH ); } p += sizeof( ssl_serialized_session_header ); } /* * Time */ #if defined(MBEDTLS_HAVE_TIME) if( 8 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); start = ( (uint64_t) p[0] << 56 ) | ( (uint64_t) p[1] << 48 ) | ( (uint64_t) p[2] << 40 ) | ( (uint64_t) p[3] << 32 ) | ( (uint64_t) p[4] << 24 ) | ( (uint64_t) p[5] << 16 ) | ( (uint64_t) p[6] << 8 ) | ( (uint64_t) p[7] ); p += 8; session->start = (time_t) start; #endif /* MBEDTLS_HAVE_TIME */ /* * Basic mandatory fields */ if( 2 + 1 + 1 + 32 + 48 + 4 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->ciphersuite = ( p[0] << 8 ) | p[1]; p += 2; session->compression = *p++; session->id_len = *p++; memcpy( session->id, p, 32 ); p += 32; memcpy( session->master, p, 48 ); p += 48; session->verify_result = ( (uint32_t) p[0] << 24 ) | ( (uint32_t) p[1] << 16 ) | ( (uint32_t) p[2] << 8 ) | ( (uint32_t) p[3] ); p += 4; /* Immediately clear invalid pointer values that have been read, in case * we exit early before we replaced them with valid ones. */ #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) session->peer_cert = NULL; #else session->peer_cert_digest = NULL; #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) session->ticket = NULL; #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ /* * Peer certificate */ #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* Deserialize CRT from the end of the ticket. */ if( 3 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); cert_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2]; p += 3; if( cert_len != 0 ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( cert_len > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->peer_cert = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) ); if( session->peer_cert == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); mbedtls_x509_crt_init( session->peer_cert ); if( ( ret = mbedtls_x509_crt_parse_der( session->peer_cert, p, cert_len ) ) != 0 ) { mbedtls_x509_crt_free( session->peer_cert ); mbedtls_free( session->peer_cert ); session->peer_cert = NULL; return( ret ); } p += cert_len; } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* Deserialize CRT digest from the end of the ticket. */ if( 2 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->peer_cert_digest_type = (mbedtls_md_type_t) *p++; session->peer_cert_digest_len = (size_t) *p++; if( session->peer_cert_digest_len != 0 ) { const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( session->peer_cert_digest_type ); if( md_info == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( session->peer_cert_digest_len != mbedtls_md_get_size( md_info ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( session->peer_cert_digest_len > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->peer_cert_digest = mbedtls_calloc( 1, session->peer_cert_digest_len ); if( session->peer_cert_digest == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( session->peer_cert_digest, p, session->peer_cert_digest_len ); p += session->peer_cert_digest_len; } #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * Session ticket and associated data */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) if( 3 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->ticket_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2]; p += 3; if( session->ticket_len != 0 ) { if( session->ticket_len > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->ticket = mbedtls_calloc( 1, session->ticket_len ); if( session->ticket == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( session->ticket, p, session->ticket_len ); p += session->ticket_len; } if( 4 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->ticket_lifetime = ( (uint32_t) p[0] << 24 ) | ( (uint32_t) p[1] << 16 ) | ( (uint32_t) p[2] << 8 ) | ( (uint32_t) p[3] ); p += 4; #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ /* * Misc extension-related info */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) if( 1 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->mfl_code = *p++; #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) if( 1 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->trunc_hmac = *p++; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( 1 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->encrypt_then_mac = *p++; #endif /* Done, should have consumed entire buffer */ if( p != end ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); return( 0 ); } /* * Deserialize session: public wrapper for error cleaning */ int mbedtls_ssl_session_load( mbedtls_ssl_session *session, const unsigned char *buf, size_t len ) { int ret = ssl_session_load( session, 0, buf, len ); if( ret != 0 ) mbedtls_ssl_session_free( session ); return( ret ); } /* * Perform a single step of the SSL handshake */ int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ret = mbedtls_ssl_handshake_client_step( ssl ); #endif #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ret = mbedtls_ssl_handshake_server_step( ssl ); #endif return( ret ); } /* * Perform the SSL handshake */ int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl ) { int ret = 0; /* Sanity checks */ if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use " "mbedtls_ssl_set_timer_cb() for DTLS" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) ); /* Main handshake loop */ while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { ret = mbedtls_ssl_handshake_step( ssl ); if( ret != 0 ) break; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) ); return( ret ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) #if defined(MBEDTLS_SSL_SRV_C) /* * Write HelloRequest to request renegotiation on server */ static int ssl_write_hello_request( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) ); ssl->out_msglen = 4; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_REQUEST; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SRV_C */ /* * Actually renegotiate current connection, triggered by either: * - any side: calling mbedtls_ssl_renegotiate(), * - client: receiving a HelloRequest during mbedtls_ssl_read(), * - server: receiving any handshake message on server during mbedtls_ssl_read() after * the initial handshake is completed. * If the handshake doesn't complete due to waiting for I/O, it will continue * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively. */ int mbedtls_ssl_start_renegotiation( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) ); if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) return( ret ); /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and * the ServerHello will have message_seq = 1" */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ssl->handshake->out_msg_seq = 1; else ssl->handshake->in_msg_seq = 1; } #endif ssl->state = MBEDTLS_SSL_HELLO_REQUEST; ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS; if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) ); return( 0 ); } /* * Renegotiate current connection on client, * or request renegotiation on server */ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_SSL_SRV_C) /* On server, just send the request */ if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) { if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING; /* Did we already try/start sending HelloRequest? */ if( ssl->out_left != 0 ) return( mbedtls_ssl_flush_output( ssl ) ); return( ssl_write_hello_request( ssl ) ); } #endif /* MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_SSL_CLI_C) /* * On client, either start the renegotiation process or, * if already in progress, continue the handshake */ if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ( ret = mbedtls_ssl_start_renegotiation( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_start_renegotiation", ret ); return( ret ); } } else { if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_CLI_C */ return( ret ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ #if defined(MBEDTLS_X509_CRT_PARSE_C) static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert ) { mbedtls_ssl_key_cert *cur = key_cert, *next; while( cur != NULL ) { next = cur->next; mbedtls_free( cur ); cur = next; } } #endif /* MBEDTLS_X509_CRT_PARSE_C */ void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl ) { mbedtls_ssl_handshake_params *handshake = ssl->handshake; if( handshake == NULL ) return; #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if( ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0 ) { ssl->conf->f_async_cancel( ssl ); handshake->async_in_progress = 0; } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_free( &handshake->fin_md5 ); mbedtls_sha1_free( &handshake->fin_sha1 ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_hash_abort( &handshake->fin_sha256_psa ); #else mbedtls_sha256_free( &handshake->fin_sha256 ); #endif #endif #if defined(MBEDTLS_SHA512_C) #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_hash_abort( &handshake->fin_sha384_psa ); #else mbedtls_sha512_free( &handshake->fin_sha512 ); #endif #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_DHM_C) mbedtls_dhm_free( &handshake->dhm_ctx ); #endif #if defined(MBEDTLS_ECDH_C) mbedtls_ecdh_free( &handshake->ecdh_ctx ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) mbedtls_ecjpake_free( &handshake->ecjpake_ctx ); #if defined(MBEDTLS_SSL_CLI_C) mbedtls_free( handshake->ecjpake_cache ); handshake->ecjpake_cache = NULL; handshake->ecjpake_cache_len = 0; #endif #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) /* explicit void pointer cast for buggy MS compiler */ mbedtls_free( (void *) handshake->curves ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) if( handshake->psk != NULL ) { mbedtls_platform_zeroize( handshake->psk, handshake->psk_len ); mbedtls_free( handshake->psk ); } #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) /* * Free only the linked list wrapper, not the keys themselves * since the belong to the SNI callback */ if( handshake->sni_key_cert != NULL ) { mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next; while( cur != NULL ) { next = cur->next; mbedtls_free( cur ); cur = next; } } #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) mbedtls_x509_crt_restart_free( &handshake->ecrs_ctx ); if( handshake->ecrs_peer_cert != NULL ) { mbedtls_x509_crt_free( handshake->ecrs_peer_cert ); mbedtls_free( handshake->ecrs_peer_cert ); } #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) mbedtls_pk_free( &handshake->peer_pubkey ); #endif /* MBEDTLS_X509_CRT_PARSE_C && !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #if defined(MBEDTLS_SSL_PROTO_DTLS) mbedtls_free( handshake->verify_cookie ); mbedtls_ssl_flight_free( handshake->flight ); mbedtls_ssl_buffering_free( ssl ); #endif #if defined(MBEDTLS_ECDH_C) && \ defined(MBEDTLS_USE_PSA_CRYPTO) psa_destroy_key( handshake->ecdh_psa_privkey ); #endif /* MBEDTLS_ECDH_C && MBEDTLS_USE_PSA_CRYPTO */ mbedtls_platform_zeroize( handshake, sizeof( mbedtls_ssl_handshake_params ) ); #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) /* If the buffers are too big - reallocate. Because of the way Mbed TLS * processes datagrams and the fact that a datagram is allowed to have * several records in it, it is possible that the I/O buffers are not * empty at this stage */ handle_buffer_resizing( ssl, 1, mbedtls_ssl_get_input_buflen( ssl ), mbedtls_ssl_get_output_buflen( ssl ) ); #endif } void mbedtls_ssl_session_free( mbedtls_ssl_session *session ) { if( session == NULL ) return; #if defined(MBEDTLS_X509_CRT_PARSE_C) ssl_clear_peer_cert( session ); #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) mbedtls_free( session->ticket ); #endif mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) ); } #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION) #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 1u #else #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 0u #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 1u #else #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 0u #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 1u #else #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 0u #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ #if defined(MBEDTLS_SSL_ALPN) #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 1u #else #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 0u #endif /* MBEDTLS_SSL_ALPN */ #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT 0 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT 1 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT 2 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT 3 #define SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG \ ( (uint32_t) ( \ ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT ) | \ ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT ) | \ ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT ) | \ ( SSL_SERIALIZED_CONTEXT_CONFIG_ALPN << SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT ) | \ 0u ) ) static unsigned char ssl_serialized_context_header[] = { MBEDTLS_VERSION_MAJOR, MBEDTLS_VERSION_MINOR, MBEDTLS_VERSION_PATCH, ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 8 ) & 0xFF, ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 0 ) & 0xFF, ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >> 16 ) & 0xFF, ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >> 8 ) & 0xFF, ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >> 0 ) & 0xFF, }; /* * Serialize a full SSL context * * The format of the serialized data is: * (in the presentation language of TLS, RFC 8446 section 3) * * // header * opaque mbedtls_version[3]; // major, minor, patch * opaque context_format[5]; // version-specific field determining * // the format of the remaining * // serialized data. * Note: When updating the format, remember to keep these * version+format bytes. (We may make their size part of the API.) * * // session sub-structure * opaque session<1..2^32-1>; // see mbedtls_ssl_session_save() * // transform sub-structure * uint8 random[64]; // ServerHello.random+ClientHello.random * uint8 in_cid<0..2^8-1> // Connection ID: expected incoming value * uint8 out_cid<0..2^8-1> // Connection ID: outgoing value to use * // fields from ssl_context * uint32 badmac_seen; // DTLS: number of records with failing MAC * uint64 in_window_top; // DTLS: last validated record seq_num * uint64 in_window; // DTLS: bitmask for replay protection * uint8 disable_datagram_packing; // DTLS: only one record per datagram * uint64 cur_out_ctr; // Record layer: outgoing sequence number * uint16 mtu; // DTLS: path mtu (max outgoing fragment size) * uint8 alpn_chosen<0..2^8-1> // ALPN: negotiated application protocol * * Note that many fields of the ssl_context or sub-structures are not * serialized, as they fall in one of the following categories: * * 1. forced value (eg in_left must be 0) * 2. pointer to dynamically-allocated memory (eg session, transform) * 3. value can be re-derived from other data (eg session keys from MS) * 4. value was temporary (eg content of input buffer) * 5. value will be provided by the user again (eg I/O callbacks and context) */ int mbedtls_ssl_context_save( mbedtls_ssl_context *ssl, unsigned char *buf, size_t buf_len, size_t *olen ) { unsigned char *p = buf; size_t used = 0; size_t session_len; int ret = 0; /* * Enforce usage restrictions, see "return BAD_INPUT_DATA" in * this function's documentation. * * These are due to assumptions/limitations in the implementation. Some of * them are likely to stay (no handshake in progress) some might go away * (only DTLS) but are currently used to simplify the implementation. */ /* The initial handshake must be over */ if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Initial handshake isn't over" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ssl->handshake != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Handshake isn't completed" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Double-check that sub-structures are indeed ready */ if( ssl->transform == NULL || ssl->session == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Serialised structures aren't ready" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* There must be no pending incoming or outgoing data */ if( mbedtls_ssl_check_pending( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "There is pending incoming data" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ssl->out_left != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "There is pending outgoing data" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Protocol must be DLTS, not TLS */ if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only DTLS is supported" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Version must be 1.2 */ if( ssl->major_ver != MBEDTLS_SSL_MAJOR_VERSION_3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only version 1.2 supported" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only version 1.2 supported" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* We must be using an AEAD ciphersuite */ if( mbedtls_ssl_transform_uses_aead( ssl->transform ) != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only AEAD ciphersuites supported" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Renegotiation must not be enabled */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Renegotiation must not be enabled" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } #endif /* * Version and format identifier */ used += sizeof( ssl_serialized_context_header ); if( used <= buf_len ) { memcpy( p, ssl_serialized_context_header, sizeof( ssl_serialized_context_header ) ); p += sizeof( ssl_serialized_context_header ); } /* * Session (length + data) */ ret = ssl_session_save( ssl->session, 1, NULL, 0, &session_len ); if( ret != MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ) return( ret ); used += 4 + session_len; if( used <= buf_len ) { *p++ = (unsigned char)( ( session_len >> 24 ) & 0xFF ); *p++ = (unsigned char)( ( session_len >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( session_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( session_len ) & 0xFF ); ret = ssl_session_save( ssl->session, 1, p, session_len, &session_len ); if( ret != 0 ) return( ret ); p += session_len; } /* * Transform */ used += sizeof( ssl->transform->randbytes ); if( used <= buf_len ) { memcpy( p, ssl->transform->randbytes, sizeof( ssl->transform->randbytes ) ); p += sizeof( ssl->transform->randbytes ); } #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) used += 2 + ssl->transform->in_cid_len + ssl->transform->out_cid_len; if( used <= buf_len ) { *p++ = ssl->transform->in_cid_len; memcpy( p, ssl->transform->in_cid, ssl->transform->in_cid_len ); p += ssl->transform->in_cid_len; *p++ = ssl->transform->out_cid_len; memcpy( p, ssl->transform->out_cid, ssl->transform->out_cid_len ); p += ssl->transform->out_cid_len; } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ /* * Saved fields from top-level ssl_context structure */ #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) used += 4; if( used <= buf_len ) { *p++ = (unsigned char)( ( ssl->badmac_seen >> 24 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->badmac_seen >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->badmac_seen >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->badmac_seen ) & 0xFF ); } #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) used += 16; if( used <= buf_len ) { *p++ = (unsigned char)( ( ssl->in_window_top >> 56 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window_top >> 48 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window_top >> 40 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window_top >> 32 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window_top >> 24 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window_top >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window_top >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window_top ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window >> 56 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window >> 48 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window >> 40 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window >> 32 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window >> 24 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->in_window ) & 0xFF ); } #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ #if defined(MBEDTLS_SSL_PROTO_DTLS) used += 1; if( used <= buf_len ) { *p++ = ssl->disable_datagram_packing; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ used += 8; if( used <= buf_len ) { memcpy( p, ssl->cur_out_ctr, 8 ); p += 8; } #if defined(MBEDTLS_SSL_PROTO_DTLS) used += 2; if( used <= buf_len ) { *p++ = (unsigned char)( ( ssl->mtu >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->mtu ) & 0xFF ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_ALPN) { const uint8_t alpn_len = ssl->alpn_chosen ? (uint8_t) strlen( ssl->alpn_chosen ) : 0; used += 1 + alpn_len; if( used <= buf_len ) { *p++ = alpn_len; if( ssl->alpn_chosen != NULL ) { memcpy( p, ssl->alpn_chosen, alpn_len ); p += alpn_len; } } } #endif /* MBEDTLS_SSL_ALPN */ /* * Done */ *olen = used; if( used > buf_len ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); MBEDTLS_SSL_DEBUG_BUF( 4, "saved context", buf, used ); return( mbedtls_ssl_session_reset_int( ssl, 0 ) ); } /* * Helper to get TLS 1.2 PRF from ciphersuite * (Duplicates bits of logic from ssl_set_handshake_prfs().) */ typedef int (*tls_prf_fn)( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ); static tls_prf_fn ssl_tls12prf_from_cs( int ciphersuite_id ) { #if defined(MBEDTLS_SHA512_C) const mbedtls_ssl_ciphersuite_t * const ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuite_id ); if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) return( tls_prf_sha384 ); #else (void) ciphersuite_id; #endif return( tls_prf_sha256 ); } /* * Deserialize context, see mbedtls_ssl_context_save() for format. * * This internal version is wrapped by a public function that cleans up in * case of error. */ static int ssl_context_load( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { const unsigned char *p = buf; const unsigned char * const end = buf + len; size_t session_len; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* * The context should have been freshly setup or reset. * Give the user an error in case of obvious misuse. * (Checking session is useful because it won't be NULL if we're * renegotiating, or if the user mistakenly loaded a session first.) */ if( ssl->state != MBEDTLS_SSL_HELLO_REQUEST || ssl->session != NULL ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* * We can't check that the config matches the initial one, but we can at * least check it matches the requirements for serializing. */ if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM || ssl->conf->max_major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 || ssl->conf->min_major_ver > MBEDTLS_SSL_MAJOR_VERSION_3 || ssl->conf->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 || ssl->conf->min_minor_ver > MBEDTLS_SSL_MINOR_VERSION_3 || #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED || #endif 0 ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } MBEDTLS_SSL_DEBUG_BUF( 4, "context to load", buf, len ); /* * Check version identifier */ if( (size_t)( end - p ) < sizeof( ssl_serialized_context_header ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( memcmp( p, ssl_serialized_context_header, sizeof( ssl_serialized_context_header ) ) != 0 ) { return( MBEDTLS_ERR_SSL_VERSION_MISMATCH ); } p += sizeof( ssl_serialized_context_header ); /* * Session */ if( (size_t)( end - p ) < 4 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session_len = ( (size_t) p[0] << 24 ) | ( (size_t) p[1] << 16 ) | ( (size_t) p[2] << 8 ) | ( (size_t) p[3] ); p += 4; /* This has been allocated by ssl_handshake_init(), called by * by either mbedtls_ssl_session_reset_int() or mbedtls_ssl_setup(). */ ssl->session = ssl->session_negotiate; ssl->session_in = ssl->session; ssl->session_out = ssl->session; ssl->session_negotiate = NULL; if( (size_t)( end - p ) < session_len ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ret = ssl_session_load( ssl->session, 1, p, session_len ); if( ret != 0 ) { mbedtls_ssl_session_free( ssl->session ); return( ret ); } p += session_len; /* * Transform */ /* This has been allocated by ssl_handshake_init(), called by * by either mbedtls_ssl_session_reset_int() or mbedtls_ssl_setup(). */ ssl->transform = ssl->transform_negotiate; ssl->transform_in = ssl->transform; ssl->transform_out = ssl->transform; ssl->transform_negotiate = NULL; /* Read random bytes and populate structure */ if( (size_t)( end - p ) < sizeof( ssl->transform->randbytes ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ret = ssl_populate_transform( ssl->transform, ssl->session->ciphersuite, ssl->session->master, #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) ssl->session->encrypt_then_mac, #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) ssl->session->trunc_hmac, #endif #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ #if defined(MBEDTLS_ZLIB_SUPPORT) ssl->session->compression, #endif ssl_tls12prf_from_cs( ssl->session->ciphersuite ), p, /* currently pointing to randbytes */ MBEDTLS_SSL_MINOR_VERSION_3, /* (D)TLS 1.2 is forced */ ssl->conf->endpoint, ssl ); if( ret != 0 ) return( ret ); p += sizeof( ssl->transform->randbytes ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* Read connection IDs and store them */ if( (size_t)( end - p ) < 1 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->transform->in_cid_len = *p++; if( (size_t)( end - p ) < ssl->transform->in_cid_len + 1u ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memcpy( ssl->transform->in_cid, p, ssl->transform->in_cid_len ); p += ssl->transform->in_cid_len; ssl->transform->out_cid_len = *p++; if( (size_t)( end - p ) < ssl->transform->out_cid_len ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memcpy( ssl->transform->out_cid, p, ssl->transform->out_cid_len ); p += ssl->transform->out_cid_len; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ /* * Saved fields from top-level ssl_context structure */ #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) if( (size_t)( end - p ) < 4 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->badmac_seen = ( (uint32_t) p[0] << 24 ) | ( (uint32_t) p[1] << 16 ) | ( (uint32_t) p[2] << 8 ) | ( (uint32_t) p[3] ); p += 4; #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) if( (size_t)( end - p ) < 16 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->in_window_top = ( (uint64_t) p[0] << 56 ) | ( (uint64_t) p[1] << 48 ) | ( (uint64_t) p[2] << 40 ) | ( (uint64_t) p[3] << 32 ) | ( (uint64_t) p[4] << 24 ) | ( (uint64_t) p[5] << 16 ) | ( (uint64_t) p[6] << 8 ) | ( (uint64_t) p[7] ); p += 8; ssl->in_window = ( (uint64_t) p[0] << 56 ) | ( (uint64_t) p[1] << 48 ) | ( (uint64_t) p[2] << 40 ) | ( (uint64_t) p[3] << 32 ) | ( (uint64_t) p[4] << 24 ) | ( (uint64_t) p[5] << 16 ) | ( (uint64_t) p[6] << 8 ) | ( (uint64_t) p[7] ); p += 8; #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( (size_t)( end - p ) < 1 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->disable_datagram_packing = *p++; #endif /* MBEDTLS_SSL_PROTO_DTLS */ if( (size_t)( end - p ) < 8 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memcpy( ssl->cur_out_ctr, p, 8 ); p += 8; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( (size_t)( end - p ) < 2 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->mtu = ( p[0] << 8 ) | p[1]; p += 2; #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_ALPN) { uint8_t alpn_len; const char **cur; if( (size_t)( end - p ) < 1 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); alpn_len = *p++; if( alpn_len != 0 && ssl->conf->alpn_list != NULL ) { /* alpn_chosen should point to an item in the configured list */ for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ ) { if( strlen( *cur ) == alpn_len && memcmp( p, cur, alpn_len ) == 0 ) { ssl->alpn_chosen = *cur; break; } } } /* can only happen on conf mismatch */ if( alpn_len != 0 && ssl->alpn_chosen == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); p += alpn_len; } #endif /* MBEDTLS_SSL_ALPN */ /* * Forced fields from top-level ssl_context structure * * Most of them already set to the correct value by mbedtls_ssl_init() and * mbedtls_ssl_reset(), so we only need to set the remaining ones. */ ssl->state = MBEDTLS_SSL_HANDSHAKE_OVER; ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; ssl->minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* Adjust pointers for header fields of outgoing records to * the given transform, accounting for explicit IV and CID. */ mbedtls_ssl_update_out_pointers( ssl, ssl->transform ); #if defined(MBEDTLS_SSL_PROTO_DTLS) ssl->in_epoch = 1; #endif /* mbedtls_ssl_reset() leaves the handshake sub-structure allocated, * which we don't want - otherwise we'd end up freeing the wrong transform * by calling mbedtls_ssl_handshake_wrapup_free_hs_transform() * inappropriately. */ if( ssl->handshake != NULL ) { mbedtls_ssl_handshake_free( ssl ); mbedtls_free( ssl->handshake ); ssl->handshake = NULL; } /* * Done - should have consumed entire buffer */ if( p != end ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); return( 0 ); } /* * Deserialize context: public wrapper for error cleaning */ int mbedtls_ssl_context_load( mbedtls_ssl_context *context, const unsigned char *buf, size_t len ) { int ret = ssl_context_load( context, buf, len ); if( ret != 0 ) mbedtls_ssl_free( context ); return( ret ); } #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */ /* * Free an SSL context */ void mbedtls_ssl_free( mbedtls_ssl_context *ssl ) { if( ssl == NULL ) return; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) ); if( ssl->out_buf != NULL ) { #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t out_buf_len = ssl->out_buf_len; #else size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; #endif mbedtls_platform_zeroize( ssl->out_buf, out_buf_len ); mbedtls_free( ssl->out_buf ); ssl->out_buf = NULL; } if( ssl->in_buf != NULL ) { #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t in_buf_len = ssl->in_buf_len; #else size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; #endif mbedtls_platform_zeroize( ssl->in_buf, in_buf_len ); mbedtls_free( ssl->in_buf ); ssl->in_buf = NULL; } #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->compress_buf != NULL ) { mbedtls_platform_zeroize( ssl->compress_buf, MBEDTLS_SSL_COMPRESS_BUFFER_LEN ); mbedtls_free( ssl->compress_buf ); } #endif if( ssl->transform ) { mbedtls_ssl_transform_free( ssl->transform ); mbedtls_free( ssl->transform ); } if( ssl->handshake ) { mbedtls_ssl_handshake_free( ssl ); mbedtls_ssl_transform_free( ssl->transform_negotiate ); mbedtls_ssl_session_free( ssl->session_negotiate ); mbedtls_free( ssl->handshake ); mbedtls_free( ssl->transform_negotiate ); mbedtls_free( ssl->session_negotiate ); } if( ssl->session ) { mbedtls_ssl_session_free( ssl->session ); mbedtls_free( ssl->session ); } #if defined(MBEDTLS_X509_CRT_PARSE_C) if( ssl->hostname != NULL ) { mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) ); mbedtls_free( ssl->hostname ); } #endif #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_finish != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) ); mbedtls_ssl_hw_record_finish( ssl ); } #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) mbedtls_free( ssl->cli_id ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) ); /* Actually clear after last debug message */ mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) ); } /* * Initialze mbedtls_ssl_config */ void mbedtls_ssl_config_init( mbedtls_ssl_config *conf ) { memset( conf, 0, sizeof( mbedtls_ssl_config ) ); } #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) static int ssl_preset_default_hashes[] = { #if defined(MBEDTLS_SHA512_C) MBEDTLS_MD_SHA512, MBEDTLS_MD_SHA384, #endif #if defined(MBEDTLS_SHA256_C) MBEDTLS_MD_SHA256, MBEDTLS_MD_SHA224, #endif #if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE) MBEDTLS_MD_SHA1, #endif MBEDTLS_MD_NONE }; #endif static int ssl_preset_suiteb_ciphersuites[] = { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 0 }; #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) static int ssl_preset_suiteb_hashes[] = { MBEDTLS_MD_SHA256, MBEDTLS_MD_SHA384, MBEDTLS_MD_NONE }; #endif #if defined(MBEDTLS_ECP_C) static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = { #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) MBEDTLS_ECP_DP_SECP256R1, #endif #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) MBEDTLS_ECP_DP_SECP384R1, #endif MBEDTLS_ECP_DP_NONE }; #endif /* * Load default in mbedtls_ssl_config */ int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf, int endpoint, int transport, int preset ) { #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; #endif /* Use the functions here so that they are covered in tests, * but otherwise access member directly for efficiency */ mbedtls_ssl_conf_endpoint( conf, endpoint ); mbedtls_ssl_conf_transport( conf, transport ); /* * Things that are common to all presets */ #if defined(MBEDTLS_SSL_CLI_C) if( endpoint == MBEDTLS_SSL_IS_CLIENT ) { conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED; #if defined(MBEDTLS_SSL_SESSION_TICKETS) conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED; #endif } #endif #if defined(MBEDTLS_ARC4_C) conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED; #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED; #endif #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED; #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) conf->f_cookie_write = ssl_cookie_write_dummy; conf->f_cookie_check = ssl_cookie_check_dummy; #endif #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED; #endif #if defined(MBEDTLS_SSL_SRV_C) conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED; #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN; conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX; #endif #if defined(MBEDTLS_SSL_RENEGOTIATION) conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT; memset( conf->renego_period, 0x00, 2 ); memset( conf->renego_period + 2, 0xFF, 6 ); #endif #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) if( endpoint == MBEDTLS_SSL_IS_SERVER ) { const unsigned char dhm_p[] = MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN; const unsigned char dhm_g[] = MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN; if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf, dhm_p, sizeof( dhm_p ), dhm_g, sizeof( dhm_g ) ) ) != 0 ) { return( ret ); } } #endif /* * Preset-specific defaults */ switch( preset ) { /* * NSA Suite B */ case MBEDTLS_SSL_PRESET_SUITEB: conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */ conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION; conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ssl_preset_suiteb_ciphersuites; #if defined(MBEDTLS_X509_CRT_PARSE_C) conf->cert_profile = &mbedtls_x509_crt_profile_suiteb; #endif #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) conf->sig_hashes = ssl_preset_suiteb_hashes; #endif #if defined(MBEDTLS_ECP_C) conf->curve_list = ssl_preset_suiteb_curves; #endif break; /* * Default */ default: conf->min_major_ver = ( MBEDTLS_SSL_MIN_MAJOR_VERSION > MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ? MBEDTLS_SSL_MIN_MAJOR_VERSION : MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION; conf->min_minor_ver = ( MBEDTLS_SSL_MIN_MINOR_VERSION > MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ? MBEDTLS_SSL_MIN_MINOR_VERSION : MBEDTLS_SSL_MIN_VALID_MINOR_VERSION; conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION; conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2; #endif conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = mbedtls_ssl_list_ciphersuites(); #if defined(MBEDTLS_X509_CRT_PARSE_C) conf->cert_profile = &mbedtls_x509_crt_profile_default; #endif #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) conf->sig_hashes = ssl_preset_default_hashes; #endif #if defined(MBEDTLS_ECP_C) conf->curve_list = mbedtls_ecp_grp_id_list(); #endif #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C) conf->dhm_min_bitlen = 1024; #endif } return( 0 ); } /* * Free mbedtls_ssl_config */ void mbedtls_ssl_config_free( mbedtls_ssl_config *conf ) { #if defined(MBEDTLS_DHM_C) mbedtls_mpi_free( &conf->dhm_P ); mbedtls_mpi_free( &conf->dhm_G ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) if( conf->psk != NULL ) { mbedtls_platform_zeroize( conf->psk, conf->psk_len ); mbedtls_free( conf->psk ); conf->psk = NULL; conf->psk_len = 0; } if( conf->psk_identity != NULL ) { mbedtls_platform_zeroize( conf->psk_identity, conf->psk_identity_len ); mbedtls_free( conf->psk_identity ); conf->psk_identity = NULL; conf->psk_identity_len = 0; } #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) ssl_key_cert_free( conf->key_cert ); #endif mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) ); } #if defined(MBEDTLS_PK_C) && \ ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) ) /* * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX */ unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk ) { #if defined(MBEDTLS_RSA_C) if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) ) return( MBEDTLS_SSL_SIG_RSA ); #endif #if defined(MBEDTLS_ECDSA_C) if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) ) return( MBEDTLS_SSL_SIG_ECDSA ); #endif return( MBEDTLS_SSL_SIG_ANON ); } unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type ) { switch( type ) { case MBEDTLS_PK_RSA: return( MBEDTLS_SSL_SIG_RSA ); case MBEDTLS_PK_ECDSA: case MBEDTLS_PK_ECKEY: return( MBEDTLS_SSL_SIG_ECDSA ); default: return( MBEDTLS_SSL_SIG_ANON ); } } mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig ) { switch( sig ) { #if defined(MBEDTLS_RSA_C) case MBEDTLS_SSL_SIG_RSA: return( MBEDTLS_PK_RSA ); #endif #if defined(MBEDTLS_ECDSA_C) case MBEDTLS_SSL_SIG_ECDSA: return( MBEDTLS_PK_ECDSA ); #endif default: return( MBEDTLS_PK_NONE ); } } #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* Find an entry in a signature-hash set matching a given hash algorithm. */ mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set, mbedtls_pk_type_t sig_alg ) { switch( sig_alg ) { case MBEDTLS_PK_RSA: return( set->rsa ); case MBEDTLS_PK_ECDSA: return( set->ecdsa ); default: return( MBEDTLS_MD_NONE ); } } /* Add a signature-hash-pair to a signature-hash set */ void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set, mbedtls_pk_type_t sig_alg, mbedtls_md_type_t md_alg ) { switch( sig_alg ) { case MBEDTLS_PK_RSA: if( set->rsa == MBEDTLS_MD_NONE ) set->rsa = md_alg; break; case MBEDTLS_PK_ECDSA: if( set->ecdsa == MBEDTLS_MD_NONE ) set->ecdsa = md_alg; break; default: break; } } /* Allow exactly one hash algorithm for each signature. */ void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set, mbedtls_md_type_t md_alg ) { set->rsa = md_alg; set->ecdsa = md_alg; } #endif /* MBEDTLS_SSL_PROTO_TLS1_2) && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ /* * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX */ mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash ) { switch( hash ) { #if defined(MBEDTLS_MD5_C) case MBEDTLS_SSL_HASH_MD5: return( MBEDTLS_MD_MD5 ); #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_SSL_HASH_SHA1: return( MBEDTLS_MD_SHA1 ); #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_SSL_HASH_SHA224: return( MBEDTLS_MD_SHA224 ); case MBEDTLS_SSL_HASH_SHA256: return( MBEDTLS_MD_SHA256 ); #endif #if defined(MBEDTLS_SHA512_C) case MBEDTLS_SSL_HASH_SHA384: return( MBEDTLS_MD_SHA384 ); case MBEDTLS_SSL_HASH_SHA512: return( MBEDTLS_MD_SHA512 ); #endif default: return( MBEDTLS_MD_NONE ); } } /* * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX */ unsigned char mbedtls_ssl_hash_from_md_alg( int md ) { switch( md ) { #if defined(MBEDTLS_MD5_C) case MBEDTLS_MD_MD5: return( MBEDTLS_SSL_HASH_MD5 ); #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_MD_SHA1: return( MBEDTLS_SSL_HASH_SHA1 ); #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_MD_SHA224: return( MBEDTLS_SSL_HASH_SHA224 ); case MBEDTLS_MD_SHA256: return( MBEDTLS_SSL_HASH_SHA256 ); #endif #if defined(MBEDTLS_SHA512_C) case MBEDTLS_MD_SHA384: return( MBEDTLS_SSL_HASH_SHA384 ); case MBEDTLS_MD_SHA512: return( MBEDTLS_SSL_HASH_SHA512 ); #endif default: return( MBEDTLS_SSL_HASH_NONE ); } } #if defined(MBEDTLS_ECP_C) /* * Check if a curve proposed by the peer is in our list. * Return 0 if we're willing to use it, -1 otherwise. */ int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id ) { const mbedtls_ecp_group_id *gid; if( ssl->conf->curve_list == NULL ) return( -1 ); for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ ) if( *gid == grp_id ) return( 0 ); return( -1 ); } #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* * Check if a hash proposed by the peer is in our list. * Return 0 if we're willing to use it, -1 otherwise. */ int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl, mbedtls_md_type_t md ) { const int *cur; if( ssl->conf->sig_hashes == NULL ) return( -1 ); for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ ) if( *cur == (int) md ) return( 0 ); return( -1 ); } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_X509_CRT_PARSE_C) int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert, const mbedtls_ssl_ciphersuite_t *ciphersuite, int cert_endpoint, uint32_t *flags ) { int ret = 0; #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) int usage = 0; #endif #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) const char *ext_oid; size_t ext_len; #endif #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) && \ !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) ((void) cert); ((void) cert_endpoint); ((void) flags); #endif #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) if( cert_endpoint == MBEDTLS_SSL_IS_SERVER ) { /* Server part of the key exchange */ switch( ciphersuite->key_exchange ) { case MBEDTLS_KEY_EXCHANGE_RSA: case MBEDTLS_KEY_EXCHANGE_RSA_PSK: usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT; break; case MBEDTLS_KEY_EXCHANGE_DHE_RSA: case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE; break; case MBEDTLS_KEY_EXCHANGE_ECDH_RSA: case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA: usage = MBEDTLS_X509_KU_KEY_AGREEMENT; break; /* Don't use default: we want warnings when adding new values */ case MBEDTLS_KEY_EXCHANGE_NONE: case MBEDTLS_KEY_EXCHANGE_PSK: case MBEDTLS_KEY_EXCHANGE_DHE_PSK: case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK: case MBEDTLS_KEY_EXCHANGE_ECJPAKE: usage = 0; } } else { /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */ usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE; } if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE; ret = -1; } #else ((void) ciphersuite); #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */ #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) if( cert_endpoint == MBEDTLS_SSL_IS_SERVER ) { ext_oid = MBEDTLS_OID_SERVER_AUTH; ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH ); } else { ext_oid = MBEDTLS_OID_CLIENT_AUTH; ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH ); } if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE; ret = -1; } #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */ return( ret ); } #endif /* MBEDTLS_X509_CRT_PARSE_C */ int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md ) { #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; switch( md ) { #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) #if defined(MBEDTLS_MD5_C) case MBEDTLS_SSL_HASH_MD5: return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_SSL_HASH_SHA1: ssl->handshake->calc_verify = ssl_calc_verify_tls; break; #endif #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SHA512_C) case MBEDTLS_SSL_HASH_SHA384: ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384; break; #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_SSL_HASH_SHA256: ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256; break; #endif default: return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; } return 0; #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */ (void) ssl; (void) md; return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl, unsigned char *output, unsigned char *data, size_t data_len ) { int ret = 0; mbedtls_md5_context mbedtls_md5; mbedtls_sha1_context mbedtls_sha1; mbedtls_md5_init( &mbedtls_md5 ); mbedtls_sha1_init( &mbedtls_sha1 ); /* * digitally-signed struct { * opaque md5_hash[16]; * opaque sha_hash[20]; * }; * * md5_hash * MD5(ClientHello.random + ServerHello.random * + ServerParams); * sha_hash * SHA(ClientHello.random + ServerHello.random * + ServerParams); */ if( ( ret = mbedtls_md5_starts_ret( &mbedtls_md5 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_starts_ret", ret ); goto exit; } if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, ssl->handshake->randbytes, 64 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret ); goto exit; } if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, data, data_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret ); goto exit; } if( ( ret = mbedtls_md5_finish_ret( &mbedtls_md5, output ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_finish_ret", ret ); goto exit; } if( ( ret = mbedtls_sha1_starts_ret( &mbedtls_sha1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_starts_ret", ret ); goto exit; } if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, ssl->handshake->randbytes, 64 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret ); goto exit; } if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, data, data_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret ); goto exit; } if( ( ret = mbedtls_sha1_finish_ret( &mbedtls_sha1, output + 16 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_finish_ret", ret ); goto exit; } exit: mbedtls_md5_free( &mbedtls_md5 ); mbedtls_sha1_free( &mbedtls_sha1 ); if( ret != 0 ) mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_USE_PSA_CRYPTO) int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hashlen, unsigned char *data, size_t data_len, mbedtls_md_type_t md_alg ) { psa_status_t status; psa_hash_operation_t hash_operation = PSA_HASH_OPERATION_INIT; psa_algorithm_t hash_alg = mbedtls_psa_translate_md( md_alg ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "Perform PSA-based computation of digest of ServerKeyExchange" ) ); if( ( status = psa_hash_setup( &hash_operation, hash_alg ) ) != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_setup", status ); goto exit; } if( ( status = psa_hash_update( &hash_operation, ssl->handshake->randbytes, 64 ) ) != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_update", status ); goto exit; } if( ( status = psa_hash_update( &hash_operation, data, data_len ) ) != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_update", status ); goto exit; } if( ( status = psa_hash_finish( &hash_operation, hash, MBEDTLS_MD_MAX_SIZE, hashlen ) ) != PSA_SUCCESS ) { MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_finish", status ); goto exit; } exit: if( status != PSA_SUCCESS ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); switch( status ) { case PSA_ERROR_NOT_SUPPORTED: return( MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE ); case PSA_ERROR_BAD_STATE: /* Intentional fallthrough */ case PSA_ERROR_BUFFER_TOO_SMALL: return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); case PSA_ERROR_INSUFFICIENT_MEMORY: return( MBEDTLS_ERR_MD_ALLOC_FAILED ); default: return( MBEDTLS_ERR_MD_HW_ACCEL_FAILED ); } } return( 0 ); } #else int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hashlen, unsigned char *data, size_t data_len, mbedtls_md_type_t md_alg ) { int ret = 0; mbedtls_md_context_t ctx; const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg ); *hashlen = mbedtls_md_get_size( md_info ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "Perform mbedtls-based computation of digest of ServerKeyExchange" ) ); mbedtls_md_init( &ctx ); /* * digitally-signed struct { * opaque client_random[32]; * opaque server_random[32]; * ServerDHParams params; * }; */ if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret ); goto exit; } if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_starts", ret ); goto exit; } if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret ); goto exit; } if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret ); goto exit; } if( ( ret = mbedtls_md_finish( &ctx, hash ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_finish", ret ); goto exit; } exit: mbedtls_md_free( &ctx ); if( ret != 0 ) mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( ret ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ #endif /* MBEDTLS_SSL_TLS_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_tls13_keys.c
/* * TLS 1.3 key schedule * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 ( the "License" ); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) #include "mbedtls/hkdf.h" #include "mbedtls/ssl_internal.h" #include "ssl_tls13_keys.h" #include <stdint.h> #include <string.h> #define MBEDTLS_SSL_TLS1_3_LABEL( name, string ) \ .name = string, struct mbedtls_ssl_tls1_3_labels_struct const mbedtls_ssl_tls1_3_labels = { /* This seems to work in C, despite the string literal being one * character too long due to the 0-termination. */ MBEDTLS_SSL_TLS1_3_LABEL_LIST }; #undef MBEDTLS_SSL_TLS1_3_LABEL /* * This function creates a HkdfLabel structure used in the TLS 1.3 key schedule. * * The HkdfLabel is specified in RFC 8446 as follows: * * struct HkdfLabel { * uint16 length; // Length of expanded key material * opaque label<7..255>; // Always prefixed by "tls13 " * opaque context<0..255>; // Usually a communication transcript hash * }; * * Parameters: * - desired_length: Length of expanded key material * Even though the standard allows expansion to up to * 2**16 Bytes, TLS 1.3 never uses expansion to more than * 255 Bytes, so we require `desired_length` to be at most * 255. This allows us to save a few Bytes of code by * hardcoding the writing of the high bytes. * - (label, llen): label + label length, without "tls13 " prefix * The label length MUST be less than or equal to * MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_LABEL_LEN * It is the caller's responsibility to ensure this. * All (label, label length) pairs used in TLS 1.3 * can be obtained via MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(). * - (ctx, clen): context + context length * The context length MUST be less than or equal to * MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_CONTEXT_LEN * It is the caller's responsibility to ensure this. * - dst: Target buffer for HkdfLabel structure, * This MUST be a writable buffer of size * at least SSL_TLS1_3_KEY_SCHEDULE_MAX_HKDF_LABEL_LEN Bytes. * - dlen: Pointer at which to store the actual length of * the HkdfLabel structure on success. */ static const char tls1_3_label_prefix[6] = "tls13 "; #define SSL_TLS1_3_KEY_SCHEDULE_HKDF_LABEL_LEN( label_len, context_len ) \ ( 2 /* expansion length */ \ + 1 /* label length */ \ + label_len \ + 1 /* context length */ \ + context_len ) #define SSL_TLS1_3_KEY_SCHEDULE_MAX_HKDF_LABEL_LEN \ SSL_TLS1_3_KEY_SCHEDULE_HKDF_LABEL_LEN( \ sizeof(tls1_3_label_prefix) + \ MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_LABEL_LEN, \ MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_CONTEXT_LEN ) static void ssl_tls1_3_hkdf_encode_label( size_t desired_length, const unsigned char *label, size_t llen, const unsigned char *ctx, size_t clen, unsigned char *dst, size_t *dlen ) { size_t total_label_len = sizeof(tls1_3_label_prefix) + llen; size_t total_hkdf_lbl_len = SSL_TLS1_3_KEY_SCHEDULE_HKDF_LABEL_LEN( total_label_len, clen ); unsigned char *p = dst; /* Add the size of the expanded key material. * We're hardcoding the high byte to 0 here assuming that we never use * TLS 1.3 HKDF key expansion to more than 255 Bytes. */ #if MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_EXPANSION_LEN > 255 #error "The implementation of ssl_tls1_3_hkdf_encode_label() is not fit for the \ value of MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_EXPANSION_LEN" #endif *p++ = 0; *p++ = (unsigned char)( ( desired_length >> 0 ) & 0xFF ); /* Add label incl. prefix */ *p++ = (unsigned char)( total_label_len & 0xFF ); memcpy( p, tls1_3_label_prefix, sizeof(tls1_3_label_prefix) ); p += sizeof(tls1_3_label_prefix); memcpy( p, label, llen ); p += llen; /* Add context value */ *p++ = (unsigned char)( clen & 0xFF ); if( clen != 0 ) memcpy( p, ctx, clen ); /* Return total length to the caller. */ *dlen = total_hkdf_lbl_len; } int mbedtls_ssl_tls1_3_hkdf_expand_label( mbedtls_md_type_t hash_alg, const unsigned char *secret, size_t slen, const unsigned char *label, size_t llen, const unsigned char *ctx, size_t clen, unsigned char *buf, size_t blen ) { const mbedtls_md_info_t *md; unsigned char hkdf_label[ SSL_TLS1_3_KEY_SCHEDULE_MAX_HKDF_LABEL_LEN ]; size_t hkdf_label_len; if( llen > MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_LABEL_LEN ) { /* Should never happen since this is an internal * function, and we know statically which labels * are allowed. */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( clen > MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_CONTEXT_LEN ) { /* Should not happen, as above. */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( blen > MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_EXPANSION_LEN ) { /* Should not happen, as above. */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } md = mbedtls_md_info_from_type( hash_alg ); if( md == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl_tls1_3_hkdf_encode_label( blen, label, llen, ctx, clen, hkdf_label, &hkdf_label_len ); return( mbedtls_hkdf_expand( md, secret, slen, hkdf_label, hkdf_label_len, buf, blen ) ); } /* * The traffic keying material is generated from the following inputs: * * - One secret value per sender. * - A purpose value indicating the specific value being generated * - The desired lengths of key and IV. * * The expansion itself is based on HKDF: * * [sender]_write_key = HKDF-Expand-Label( Secret, "key", "", key_length ) * [sender]_write_iv = HKDF-Expand-Label( Secret, "iv" , "", iv_length ) * * [sender] denotes the sending side and the Secret value is provided * by the function caller. Note that we generate server and client side * keys in a single function call. */ int mbedtls_ssl_tls1_3_make_traffic_keys( mbedtls_md_type_t hash_alg, const unsigned char *client_secret, const unsigned char *server_secret, size_t slen, size_t key_len, size_t iv_len, mbedtls_ssl_key_set *keys ) { int ret = 0; ret = mbedtls_ssl_tls1_3_hkdf_expand_label( hash_alg, client_secret, slen, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( key ), NULL, 0, keys->client_write_key, key_len ); if( ret != 0 ) return( ret ); ret = mbedtls_ssl_tls1_3_hkdf_expand_label( hash_alg, server_secret, slen, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( key ), NULL, 0, keys->server_write_key, key_len ); if( ret != 0 ) return( ret ); ret = mbedtls_ssl_tls1_3_hkdf_expand_label( hash_alg, client_secret, slen, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( iv ), NULL, 0, keys->client_write_iv, iv_len ); if( ret != 0 ) return( ret ); ret = mbedtls_ssl_tls1_3_hkdf_expand_label( hash_alg, server_secret, slen, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( iv ), NULL, 0, keys->server_write_iv, iv_len ); if( ret != 0 ) return( ret ); keys->key_len = key_len; keys->iv_len = iv_len; return( 0 ); } int mbedtls_ssl_tls1_3_derive_secret( mbedtls_md_type_t hash_alg, const unsigned char *secret, size_t slen, const unsigned char *label, size_t llen, const unsigned char *ctx, size_t clen, int ctx_hashed, unsigned char *dstbuf, size_t buflen ) { int ret; unsigned char hashed_context[ MBEDTLS_MD_MAX_SIZE ]; const mbedtls_md_info_t *md; md = mbedtls_md_info_from_type( hash_alg ); if( md == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ctx_hashed == MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED ) { ret = mbedtls_md( md, ctx, clen, hashed_context ); if( ret != 0 ) return( ret ); clen = mbedtls_md_get_size( md ); } else { if( clen > sizeof(hashed_context) ) { /* This should never happen since this function is internal * and the code sets `ctx_hashed` correctly. * Let's double-check nonetheless to not run at the risk * of getting a stack overflow. */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } memcpy( hashed_context, ctx, clen ); } return( mbedtls_ssl_tls1_3_hkdf_expand_label( hash_alg, secret, slen, label, llen, hashed_context, clen, dstbuf, buflen ) ); } int mbedtls_ssl_tls1_3_evolve_secret( mbedtls_md_type_t hash_alg, const unsigned char *secret_old, const unsigned char *input, size_t input_len, unsigned char *secret_new ) { int ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; size_t hlen, ilen; unsigned char tmp_secret[ MBEDTLS_MD_MAX_SIZE ] = { 0 }; unsigned char tmp_input [ MBEDTLS_MD_MAX_SIZE ] = { 0 }; const mbedtls_md_info_t *md; md = mbedtls_md_info_from_type( hash_alg ); if( md == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); hlen = mbedtls_md_get_size( md ); /* For non-initial runs, call Derive-Secret( ., "derived", "") * on the old secret. */ if( secret_old != NULL ) { ret = mbedtls_ssl_tls1_3_derive_secret( hash_alg, secret_old, hlen, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( derived ), NULL, 0, /* context */ MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED, tmp_secret, hlen ); if( ret != 0 ) goto cleanup; } if( input != NULL ) { memcpy( tmp_input, input, input_len ); ilen = input_len; } else { ilen = hlen; } /* HKDF-Extract takes a salt and input key material. * The salt is the old secret, and the input key material * is the input secret (PSK / ECDHE). */ ret = mbedtls_hkdf_extract( md, tmp_secret, hlen, tmp_input, ilen, secret_new ); if( ret != 0 ) goto cleanup; ret = 0; cleanup: mbedtls_platform_zeroize( tmp_secret, sizeof(tmp_secret) ); mbedtls_platform_zeroize( tmp_input, sizeof(tmp_input) ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\ssl_tls13_keys.h
/* * TLS 1.3 key schedule * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 ( the "License" ); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MBEDTLS_SSL_TLS1_3_KEYS_H) #define MBEDTLS_SSL_TLS1_3_KEYS_H /* This requires MBEDTLS_SSL_TLS1_3_LABEL( idx, name, string ) to be defined at * the point of use. See e.g. the definition of mbedtls_ssl_tls1_3_labels_union * below. */ #define MBEDTLS_SSL_TLS1_3_LABEL_LIST \ MBEDTLS_SSL_TLS1_3_LABEL( finished , "finished" ) \ MBEDTLS_SSL_TLS1_3_LABEL( resumption , "resumption" ) \ MBEDTLS_SSL_TLS1_3_LABEL( traffic_upd , "traffic upd" ) \ MBEDTLS_SSL_TLS1_3_LABEL( exporter , "exporter" ) \ MBEDTLS_SSL_TLS1_3_LABEL( key , "key" ) \ MBEDTLS_SSL_TLS1_3_LABEL( iv , "iv" ) \ MBEDTLS_SSL_TLS1_3_LABEL( c_hs_traffic, "c hs traffic" ) \ MBEDTLS_SSL_TLS1_3_LABEL( c_ap_traffic, "c ap traffic" ) \ MBEDTLS_SSL_TLS1_3_LABEL( c_e_traffic , "c e traffic" ) \ MBEDTLS_SSL_TLS1_3_LABEL( s_hs_traffic, "s hs traffic" ) \ MBEDTLS_SSL_TLS1_3_LABEL( s_ap_traffic, "s ap traffic" ) \ MBEDTLS_SSL_TLS1_3_LABEL( s_e_traffic , "s e traffic" ) \ MBEDTLS_SSL_TLS1_3_LABEL( e_exp_master, "e exp master" ) \ MBEDTLS_SSL_TLS1_3_LABEL( res_master , "res master" ) \ MBEDTLS_SSL_TLS1_3_LABEL( exp_master , "exp master" ) \ MBEDTLS_SSL_TLS1_3_LABEL( ext_binder , "ext binder" ) \ MBEDTLS_SSL_TLS1_3_LABEL( res_binder , "res binder" ) \ MBEDTLS_SSL_TLS1_3_LABEL( derived , "derived" ) #define MBEDTLS_SSL_TLS1_3_LABEL( name, string ) \ const unsigned char name [ sizeof(string) - 1 ]; union mbedtls_ssl_tls1_3_labels_union { MBEDTLS_SSL_TLS1_3_LABEL_LIST }; struct mbedtls_ssl_tls1_3_labels_struct { MBEDTLS_SSL_TLS1_3_LABEL_LIST }; #undef MBEDTLS_SSL_TLS1_3_LABEL extern const struct mbedtls_ssl_tls1_3_labels_struct mbedtls_ssl_tls1_3_labels; #define MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( LABEL ) \ mbedtls_ssl_tls1_3_labels.LABEL, \ sizeof(mbedtls_ssl_tls1_3_labels.LABEL) #define MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_LABEL_LEN \ sizeof( union mbedtls_ssl_tls1_3_labels_union ) /* The maximum length of HKDF contexts used in the TLS 1.3 standard. * Since contexts are always hashes of message transcripts, this can * be approximated from above by the maximum hash size. */ #define MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_CONTEXT_LEN \ MBEDTLS_MD_MAX_SIZE /* Maximum desired length for expanded key material generated * by HKDF-Expand-Label. * * Warning: If this ever needs to be increased, the implementation * ssl_tls1_3_hkdf_encode_label() in ssl_tls13_keys.c needs to be * adjusted since it currently assumes that HKDF key expansion * is never used with more than 255 Bytes of output. */ #define MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_EXPANSION_LEN 255 /** * \brief The \c HKDF-Expand-Label function from * the TLS 1.3 standard RFC 8446. * * <tt> * HKDF-Expand-Label( Secret, Label, Context, Length ) = * HKDF-Expand( Secret, HkdfLabel, Length ) * </tt> * * \param hash_alg The identifier for the hash algorithm to use. * \param secret The \c Secret argument to \c HKDF-Expand-Label. * This must be a readable buffer of length \p slen Bytes. * \param slen The length of \p secret in Bytes. * \param label The \c Label argument to \c HKDF-Expand-Label. * This must be a readable buffer of length \p llen Bytes. * \param llen The length of \p label in Bytes. * \param ctx The \c Context argument to \c HKDF-Expand-Label. * This must be a readable buffer of length \p clen Bytes. * \param clen The length of \p context in Bytes. * \param buf The destination buffer to hold the expanded secret. * This must be a writable buffer of length \p blen Bytes. * \param blen The desired size of the expanded secret in Bytes. * * \returns \c 0 on success. * \return A negative error code on failure. */ int mbedtls_ssl_tls1_3_hkdf_expand_label( mbedtls_md_type_t hash_alg, const unsigned char *secret, size_t slen, const unsigned char *label, size_t llen, const unsigned char *ctx, size_t clen, unsigned char *buf, size_t blen ); /** * \brief This function is part of the TLS 1.3 key schedule. * It extracts key and IV for the actual client/server traffic * from the client/server traffic secrets. * * From RFC 8446: * * <tt> * [sender]_write_key = HKDF-Expand-Label(Secret, "key", "", key_length) * [sender]_write_iv = HKDF-Expand-Label(Secret, "iv", "", iv_length)* * </tt> * * \param hash_alg The identifier for the hash algorithm to be used * for the HKDF-based expansion of the secret. * \param client_secret The client traffic secret. * This must be a readable buffer of size \p slen Bytes * \param server_secret The server traffic secret. * This must be a readable buffer of size \p slen Bytes * \param slen Length of the secrets \p client_secret and * \p server_secret in Bytes. * \param key_len The desired length of the key to be extracted in Bytes. * \param iv_len The desired length of the IV to be extracted in Bytes. * \param keys The address of the structure holding the generated * keys and IVs. * * \returns \c 0 on success. * \returns A negative error code on failure. */ int mbedtls_ssl_tls1_3_make_traffic_keys( mbedtls_md_type_t hash_alg, const unsigned char *client_secret, const unsigned char *server_secret, size_t slen, size_t key_len, size_t iv_len, mbedtls_ssl_key_set *keys ); #define MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED 0 #define MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED 1 /** * \brief The \c Derive-Secret function from the TLS 1.3 standard RFC 8446. * * <tt> * Derive-Secret( Secret, Label, Messages ) = * HKDF-Expand-Label( Secret, Label, * Hash( Messages ), * Hash.Length ) ) * </tt> * * \param hash_alg The identifier for the hash function used for the * applications of HKDF. * \param secret The \c Secret argument to the \c Derive-Secret function. * This must be a readable buffer of length \p slen Bytes. * \param slen The length of \p secret in Bytes. * \param label The \c Label argument to the \c Derive-Secret function. * This must be a readable buffer of length \p llen Bytes. * \param llen The length of \p label in Bytes. * \param ctx The hash of the \c Messages argument to the * \c Derive-Secret function, or the \c Messages argument * itself, depending on \p context_already_hashed. * \param clen The length of \p hash. * \param ctx_hashed This indicates whether the \p ctx contains the hash of * the \c Messages argument in the application of the * \c Derive-Secret function * (value MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED), or whether * it is the content of \c Messages itself, in which case * the function takes care of the hashing * (value MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED). * \param dstbuf The target buffer to write the output of * \c Derive-Secret to. This must be a writable buffer of * size \p buflen Bytes. * \param buflen The length of \p dstbuf in Bytes. * * \returns \c 0 on success. * \returns A negative error code on failure. */ int mbedtls_ssl_tls1_3_derive_secret( mbedtls_md_type_t hash_alg, const unsigned char *secret, size_t slen, const unsigned char *label, size_t llen, const unsigned char *ctx, size_t clen, int ctx_hashed, unsigned char *dstbuf, size_t buflen ); /** * \brief Compute the next secret in the TLS 1.3 key schedule * * The TLS 1.3 key schedule proceeds as follows to compute * the three main secrets during the handshake: The early * secret for early data, the handshake secret for all * other encrypted handshake messages, and the master * secret for all application traffic. * * <tt> * 0 * | * v * PSK -> HKDF-Extract = Early Secret * | * v * Derive-Secret( ., "derived", "" ) * | * v * (EC)DHE -> HKDF-Extract = Handshake Secret * | * v * Derive-Secret( ., "derived", "" ) * | * v * 0 -> HKDF-Extract = Master Secret * </tt> * * Each of the three secrets in turn is the basis for further * key derivations, such as the derivation of traffic keys and IVs; * see e.g. mbedtls_ssl_tls1_3_make_traffic_keys(). * * This function implements one step in this evolution of secrets: * * <tt> * old_secret * | * v * Derive-Secret( ., "derived", "" ) * | * v * input -> HKDF-Extract = new_secret * </tt> * * \param hash_alg The identifier for the hash function used for the * applications of HKDF. * \param secret_old The address of the buffer holding the old secret * on function entry. If not \c NULL, this must be a * readable buffer whose size matches the output size * of the hash function represented by \p hash_alg. * If \c NULL, an all \c 0 array will be used instead. * \param input The address of the buffer holding the additional * input for the key derivation (e.g., the PSK or the * ephemeral (EC)DH secret). If not \c NULL, this must be * a readable buffer whose size \p input_len Bytes. * If \c NULL, an all \c 0 array will be used instead. * \param input_len The length of \p input in Bytes. * \param secret_new The address of the buffer holding the new secret * on function exit. This must be a writable buffer * whose size matches the output size of the hash * function represented by \p hash_alg. * This may be the same as \p secret_old. * * \returns \c 0 on success. * \returns A negative error code on failure. */ int mbedtls_ssl_tls1_3_evolve_secret( mbedtls_md_type_t hash_alg, const unsigned char *secret_old, const unsigned char *input, size_t input_len, unsigned char *secret_new ); #endif /* MBEDTLS_SSL_TLS1_3_KEYS_H */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\threading.c
/* * Threading abstraction layer * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Ensure gmtime_r is available even with -std=c99; must be defined before * config.h, which pulls in glibc's features.h. Harmless on other platforms. */ #if !defined(_POSIX_C_SOURCE) #define _POSIX_C_SOURCE 200112L #endif #include "common.h" #if defined(MBEDTLS_THREADING_C) #include "mbedtls/threading.h" #if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_PLATFORM_GMTIME_R_ALT) #if !defined(_WIN32) && (defined(unix) || \ defined(__unix) || defined(__unix__) || (defined(__APPLE__) && \ defined(__MACH__))) #include <unistd.h> #endif /* !_WIN32 && (unix || __unix || __unix__ || * (__APPLE__ && __MACH__)) */ #if !( ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L ) || \ ( defined(_POSIX_THREAD_SAFE_FUNCTIONS ) && \ _POSIX_THREAD_SAFE_FUNCTIONS >= 200112L ) ) /* * This is a convenience shorthand macro to avoid checking the long * preprocessor conditions above. Ideally, we could expose this macro in * platform_util.h and simply use it in platform_util.c, threading.c and * threading.h. However, this macro is not part of the Mbed TLS public API, so * we keep it private by only defining it in this file */ #if ! ( defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) ) #define THREADING_USE_GMTIME #endif /* ! ( defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) ) */ #endif /* !( ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L ) || \ ( defined(_POSIX_THREAD_SAFE_FUNCTIONS ) && \ _POSIX_THREAD_SAFE_FUNCTIONS >= 200112L ) ) */ #endif /* MBEDTLS_HAVE_TIME_DATE && !MBEDTLS_PLATFORM_GMTIME_R_ALT */ #if defined(MBEDTLS_THREADING_PTHREAD) static void threading_mutex_init_pthread( mbedtls_threading_mutex_t *mutex ) { if( mutex == NULL ) return; mutex->is_valid = pthread_mutex_init( &mutex->mutex, NULL ) == 0; } static void threading_mutex_free_pthread( mbedtls_threading_mutex_t *mutex ) { if( mutex == NULL || !mutex->is_valid ) return; (void) pthread_mutex_destroy( &mutex->mutex ); mutex->is_valid = 0; } static int threading_mutex_lock_pthread( mbedtls_threading_mutex_t *mutex ) { if( mutex == NULL || ! mutex->is_valid ) return( MBEDTLS_ERR_THREADING_BAD_INPUT_DATA ); if( pthread_mutex_lock( &mutex->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); return( 0 ); } static int threading_mutex_unlock_pthread( mbedtls_threading_mutex_t *mutex ) { if( mutex == NULL || ! mutex->is_valid ) return( MBEDTLS_ERR_THREADING_BAD_INPUT_DATA ); if( pthread_mutex_unlock( &mutex->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); return( 0 ); } void (*mbedtls_mutex_init)( mbedtls_threading_mutex_t * ) = threading_mutex_init_pthread; void (*mbedtls_mutex_free)( mbedtls_threading_mutex_t * ) = threading_mutex_free_pthread; int (*mbedtls_mutex_lock)( mbedtls_threading_mutex_t * ) = threading_mutex_lock_pthread; int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t * ) = threading_mutex_unlock_pthread; /* * With phtreads we can statically initialize mutexes */ #define MUTEX_INIT = { PTHREAD_MUTEX_INITIALIZER, 1 } #endif /* MBEDTLS_THREADING_PTHREAD */ #if defined(MBEDTLS_THREADING_ALT) static int threading_mutex_fail( mbedtls_threading_mutex_t *mutex ) { ((void) mutex ); return( MBEDTLS_ERR_THREADING_BAD_INPUT_DATA ); } static void threading_mutex_dummy( mbedtls_threading_mutex_t *mutex ) { ((void) mutex ); return; } void (*mbedtls_mutex_init)( mbedtls_threading_mutex_t * ) = threading_mutex_dummy; void (*mbedtls_mutex_free)( mbedtls_threading_mutex_t * ) = threading_mutex_dummy; int (*mbedtls_mutex_lock)( mbedtls_threading_mutex_t * ) = threading_mutex_fail; int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t * ) = threading_mutex_fail; /* * Set functions pointers and initialize global mutexes */ void mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t * ), void (*mutex_free)( mbedtls_threading_mutex_t * ), int (*mutex_lock)( mbedtls_threading_mutex_t * ), int (*mutex_unlock)( mbedtls_threading_mutex_t * ) ) { mbedtls_mutex_init = mutex_init; mbedtls_mutex_free = mutex_free; mbedtls_mutex_lock = mutex_lock; mbedtls_mutex_unlock = mutex_unlock; #if defined(MBEDTLS_FS_IO) mbedtls_mutex_init( &mbedtls_threading_readdir_mutex ); #endif #if defined(THREADING_USE_GMTIME) mbedtls_mutex_init( &mbedtls_threading_gmtime_mutex ); #endif } /* * Free global mutexes */ void mbedtls_threading_free_alt( void ) { #if defined(MBEDTLS_FS_IO) mbedtls_mutex_free( &mbedtls_threading_readdir_mutex ); #endif #if defined(THREADING_USE_GMTIME) mbedtls_mutex_free( &mbedtls_threading_gmtime_mutex ); #endif } #endif /* MBEDTLS_THREADING_ALT */ /* * Define global mutexes */ #ifndef MUTEX_INIT #define MUTEX_INIT #endif #if defined(MBEDTLS_FS_IO) mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex MUTEX_INIT; #endif #if defined(THREADING_USE_GMTIME) mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex MUTEX_INIT; #endif #endif /* MBEDTLS_THREADING_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\timing.c
/* * Portable interface to the CPU cycle counter * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #define mbedtls_printf printf #endif #if defined(MBEDTLS_TIMING_C) #include "mbedtls/timing.h" #if !defined(MBEDTLS_TIMING_ALT) #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \ !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \ !defined(__HAIKU__) && !defined(__midipix__) #error "This module only works on Unix and Windows, see MBEDTLS_TIMING_C in config.h" #endif #ifndef asm #define asm __asm #endif #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) #include <windows.h> #include <process.h> struct _hr_time { LARGE_INTEGER start; }; #else #include <unistd.h> #include <sys/types.h> #include <sys/time.h> #include <signal.h> #include <time.h> struct _hr_time { struct timeval start; }; #endif /* _WIN32 && !EFIX64 && !EFI32 */ #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \ ( defined(_MSC_VER) && defined(_M_IX86) ) || defined(__WATCOMC__) #define HAVE_HARDCLOCK unsigned long mbedtls_timing_hardclock( void ) { unsigned long tsc; __asm rdtsc __asm mov [tsc], eax return( tsc ); } #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM && ( _MSC_VER && _M_IX86 ) || __WATCOMC__ */ /* some versions of mingw-64 have 32-bit longs even on x84_64 */ #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \ defined(__GNUC__) && ( defined(__i386__) || ( \ ( defined(__amd64__) || defined( __x86_64__) ) && __SIZEOF_LONG__ == 4 ) ) #define HAVE_HARDCLOCK unsigned long mbedtls_timing_hardclock( void ) { unsigned long lo, hi; asm volatile( "rdtsc" : "=a" (lo), "=d" (hi) ); return( lo ); } #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM && __GNUC__ && __i386__ */ #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \ defined(__GNUC__) && ( defined(__amd64__) || defined(__x86_64__) ) #define HAVE_HARDCLOCK unsigned long mbedtls_timing_hardclock( void ) { unsigned long lo, hi; asm volatile( "rdtsc" : "=a" (lo), "=d" (hi) ); return( lo | ( hi << 32 ) ); } #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM && __GNUC__ && ( __amd64__ || __x86_64__ ) */ #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \ defined(__GNUC__) && ( defined(__powerpc__) || defined(__ppc__) ) #define HAVE_HARDCLOCK unsigned long mbedtls_timing_hardclock( void ) { unsigned long tbl, tbu0, tbu1; do { asm volatile( "mftbu %0" : "=r" (tbu0) ); asm volatile( "mftb %0" : "=r" (tbl ) ); asm volatile( "mftbu %0" : "=r" (tbu1) ); } while( tbu0 != tbu1 ); return( tbl ); } #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM && __GNUC__ && ( __powerpc__ || __ppc__ ) */ #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \ defined(__GNUC__) && defined(__sparc64__) #if defined(__OpenBSD__) #warning OpenBSD does not allow access to tick register using software version instead #else #define HAVE_HARDCLOCK unsigned long mbedtls_timing_hardclock( void ) { unsigned long tick; asm volatile( "rdpr %%tick, %0;" : "=&r" (tick) ); return( tick ); } #endif /* __OpenBSD__ */ #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM && __GNUC__ && __sparc64__ */ #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \ defined(__GNUC__) && defined(__sparc__) && !defined(__sparc64__) #define HAVE_HARDCLOCK unsigned long mbedtls_timing_hardclock( void ) { unsigned long tick; asm volatile( ".byte 0x83, 0x41, 0x00, 0x00" ); asm volatile( "mov %%g1, %0" : "=r" (tick) ); return( tick ); } #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM && __GNUC__ && __sparc__ && !__sparc64__ */ #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \ defined(__GNUC__) && defined(__alpha__) #define HAVE_HARDCLOCK unsigned long mbedtls_timing_hardclock( void ) { unsigned long cc; asm volatile( "rpcc %0" : "=r" (cc) ); return( cc & 0xFFFFFFFF ); } #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM && __GNUC__ && __alpha__ */ #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \ defined(__GNUC__) && defined(__ia64__) #define HAVE_HARDCLOCK unsigned long mbedtls_timing_hardclock( void ) { unsigned long itc; asm volatile( "mov %0 = ar.itc" : "=r" (itc) ); return( itc ); } #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM && __GNUC__ && __ia64__ */ #if !defined(HAVE_HARDCLOCK) && defined(_MSC_VER) && \ !defined(EFIX64) && !defined(EFI32) #define HAVE_HARDCLOCK unsigned long mbedtls_timing_hardclock( void ) { LARGE_INTEGER offset; QueryPerformanceCounter( &offset ); return( (unsigned long)( offset.QuadPart ) ); } #endif /* !HAVE_HARDCLOCK && _MSC_VER && !EFIX64 && !EFI32 */ #if !defined(HAVE_HARDCLOCK) #define HAVE_HARDCLOCK static int hardclock_init = 0; static struct timeval tv_init; unsigned long mbedtls_timing_hardclock( void ) { struct timeval tv_cur; if( hardclock_init == 0 ) { gettimeofday( &tv_init, NULL ); hardclock_init = 1; } gettimeofday( &tv_cur, NULL ); return( ( tv_cur.tv_sec - tv_init.tv_sec ) * 1000000 + ( tv_cur.tv_usec - tv_init.tv_usec ) ); } #endif /* !HAVE_HARDCLOCK */ volatile int mbedtls_timing_alarmed = 0; #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset ) { struct _hr_time *t = (struct _hr_time *) val; if( reset ) { QueryPerformanceCounter( &t->start ); return( 0 ); } else { unsigned long delta; LARGE_INTEGER now, hfreq; QueryPerformanceCounter( &now ); QueryPerformanceFrequency( &hfreq ); delta = (unsigned long)( ( now.QuadPart - t->start.QuadPart ) * 1000ul / hfreq.QuadPart ); return( delta ); } } /* It's OK to use a global because alarm() is supposed to be global anyway */ static DWORD alarmMs; static void TimerProc( void *TimerContext ) { (void) TimerContext; Sleep( alarmMs ); mbedtls_timing_alarmed = 1; /* _endthread will be called implicitly on return * That ensures execution of thread funcition's epilogue */ } void mbedtls_set_alarm( int seconds ) { if( seconds == 0 ) { /* No need to create a thread for this simple case. * Also, this shorcut is more reliable at least on MinGW32 */ mbedtls_timing_alarmed = 1; return; } mbedtls_timing_alarmed = 0; alarmMs = seconds * 1000; (void) _beginthread( TimerProc, 0, NULL ); } #else /* _WIN32 && !EFIX64 && !EFI32 */ unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset ) { struct _hr_time *t = (struct _hr_time *) val; if( reset ) { gettimeofday( &t->start, NULL ); return( 0 ); } else { unsigned long delta; struct timeval now; gettimeofday( &now, NULL ); delta = ( now.tv_sec - t->start.tv_sec ) * 1000ul + ( now.tv_usec - t->start.tv_usec ) / 1000; return( delta ); } } static void sighandler( int signum ) { mbedtls_timing_alarmed = 1; signal( signum, sighandler ); } void mbedtls_set_alarm( int seconds ) { mbedtls_timing_alarmed = 0; signal( SIGALRM, sighandler ); alarm( seconds ); if( seconds == 0 ) { /* alarm(0) cancelled any previous pending alarm, but the handler won't fire, so raise the flag straight away. */ mbedtls_timing_alarmed = 1; } } #endif /* _WIN32 && !EFIX64 && !EFI32 */ /* * Set delays to watch */ void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms ) { mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data; ctx->int_ms = int_ms; ctx->fin_ms = fin_ms; if( fin_ms != 0 ) (void) mbedtls_timing_get_timer( &ctx->timer, 1 ); } /* * Get number of delays expired */ int mbedtls_timing_get_delay( void *data ) { mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data; unsigned long elapsed_ms; if( ctx->fin_ms == 0 ) return( -1 ); elapsed_ms = mbedtls_timing_get_timer( &ctx->timer, 0 ); if( elapsed_ms >= ctx->fin_ms ) return( 2 ); if( elapsed_ms >= ctx->int_ms ) return( 1 ); return( 0 ); } #endif /* !MBEDTLS_TIMING_ALT */ #if defined(MBEDTLS_SELF_TEST) /* * Busy-waits for the given number of milliseconds. * Used for testing mbedtls_timing_hardclock. */ static void busy_msleep( unsigned long msec ) { struct mbedtls_timing_hr_time hires; unsigned long i = 0; /* for busy-waiting */ volatile unsigned long j; /* to prevent optimisation */ (void) mbedtls_timing_get_timer( &hires, 1 ); while( mbedtls_timing_get_timer( &hires, 0 ) < msec ) i++; j = i; (void) j; } #define FAIL do \ { \ if( verbose != 0 ) \ { \ mbedtls_printf( "failed at line %d\n", __LINE__ ); \ mbedtls_printf( " cycles=%lu ratio=%lu millisecs=%lu secs=%lu hardfail=%d a=%lu b=%lu\n", \ cycles, ratio, millisecs, secs, hardfail, \ (unsigned long) a, (unsigned long) b ); \ mbedtls_printf( " elapsed(hires)=%lu elapsed(ctx)=%lu status(ctx)=%d\n", \ mbedtls_timing_get_timer( &hires, 0 ), \ mbedtls_timing_get_timer( &ctx.timer, 0 ), \ mbedtls_timing_get_delay( &ctx ) ); \ } \ return( 1 ); \ } while( 0 ) /* * Checkup routine * * Warning: this is work in progress, some tests may not be reliable enough * yet! False positives may happen. */ int mbedtls_timing_self_test( int verbose ) { unsigned long cycles = 0, ratio = 0; unsigned long millisecs = 0, secs = 0; int hardfail = 0; struct mbedtls_timing_hr_time hires; uint32_t a = 0, b = 0; mbedtls_timing_delay_context ctx; if( verbose != 0 ) mbedtls_printf( " TIMING tests note: will take some time!\n" ); if( verbose != 0 ) mbedtls_printf( " TIMING test #1 (set_alarm / get_timer): " ); { secs = 1; (void) mbedtls_timing_get_timer( &hires, 1 ); mbedtls_set_alarm( (int) secs ); while( !mbedtls_timing_alarmed ) ; millisecs = mbedtls_timing_get_timer( &hires, 0 ); /* For some reason on Windows it looks like alarm has an extra delay * (maybe related to creating a new thread). Allow some room here. */ if( millisecs < 800 * secs || millisecs > 1200 * secs + 300 ) FAIL; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); if( verbose != 0 ) mbedtls_printf( " TIMING test #2 (set/get_delay ): " ); { a = 800; b = 400; mbedtls_timing_set_delay( &ctx, a, a + b ); /* T = 0 */ busy_msleep( a - a / 4 ); /* T = a - a/4 */ if( mbedtls_timing_get_delay( &ctx ) != 0 ) FAIL; busy_msleep( a / 4 + b / 4 ); /* T = a + b/4 */ if( mbedtls_timing_get_delay( &ctx ) != 1 ) FAIL; busy_msleep( b ); /* T = a + b + b/4 */ if( mbedtls_timing_get_delay( &ctx ) != 2 ) FAIL; } mbedtls_timing_set_delay( &ctx, 0, 0 ); busy_msleep( 200 ); if( mbedtls_timing_get_delay( &ctx ) != -1 ) FAIL; if( verbose != 0 ) mbedtls_printf( "passed\n" ); if( verbose != 0 ) mbedtls_printf( " TIMING test #3 (hardclock / get_timer): " ); /* * Allow one failure for possible counter wrapping. * On a 4Ghz 32-bit machine the cycle counter wraps about once per second; * since the whole test is about 10ms, it shouldn't happen twice in a row. */ hard_test: if( hardfail > 1 ) { if( verbose != 0 ) mbedtls_printf( "failed (ignored)\n" ); goto hard_test_done; } /* Get a reference ratio cycles/ms */ millisecs = 1; cycles = mbedtls_timing_hardclock(); busy_msleep( millisecs ); cycles = mbedtls_timing_hardclock() - cycles; ratio = cycles / millisecs; /* Check that the ratio is mostly constant */ for( millisecs = 2; millisecs <= 4; millisecs++ ) { cycles = mbedtls_timing_hardclock(); busy_msleep( millisecs ); cycles = mbedtls_timing_hardclock() - cycles; /* Allow variation up to 20% */ if( cycles / millisecs < ratio - ratio / 5 || cycles / millisecs > ratio + ratio / 5 ) { hardfail++; goto hard_test; } } if( verbose != 0 ) mbedtls_printf( "passed\n" ); hard_test_done: if( verbose != 0 ) mbedtls_printf( "\n" ); return( 0 ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_TIMING_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\version.c
/* * Version information * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #if defined(MBEDTLS_VERSION_C) #include "mbedtls/version.h" #include <string.h> unsigned int mbedtls_version_get_number( void ) { return( MBEDTLS_VERSION_NUMBER ); } void mbedtls_version_get_string( char *string ) { memcpy( string, MBEDTLS_VERSION_STRING, sizeof( MBEDTLS_VERSION_STRING ) ); } void mbedtls_version_get_string_full( char *string ) { memcpy( string, MBEDTLS_VERSION_STRING_FULL, sizeof( MBEDTLS_VERSION_STRING_FULL ) ); } #endif /* MBEDTLS_VERSION_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\version_features.c
/* * Version feature information * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #if defined(MBEDTLS_VERSION_C) #include "mbedtls/version.h" #include <string.h> static const char * const features[] = { #if defined(MBEDTLS_VERSION_FEATURES) #if defined(MBEDTLS_HAVE_ASM) "MBEDTLS_HAVE_ASM", #endif /* MBEDTLS_HAVE_ASM */ #if defined(MBEDTLS_NO_UDBL_DIVISION) "MBEDTLS_NO_UDBL_DIVISION", #endif /* MBEDTLS_NO_UDBL_DIVISION */ #if defined(MBEDTLS_NO_64BIT_MULTIPLICATION) "MBEDTLS_NO_64BIT_MULTIPLICATION", #endif /* MBEDTLS_NO_64BIT_MULTIPLICATION */ #if defined(MBEDTLS_HAVE_SSE2) "MBEDTLS_HAVE_SSE2", #endif /* MBEDTLS_HAVE_SSE2 */ #if defined(MBEDTLS_HAVE_TIME) "MBEDTLS_HAVE_TIME", #endif /* MBEDTLS_HAVE_TIME */ #if defined(MBEDTLS_HAVE_TIME_DATE) "MBEDTLS_HAVE_TIME_DATE", #endif /* MBEDTLS_HAVE_TIME_DATE */ #if defined(MBEDTLS_PLATFORM_MEMORY) "MBEDTLS_PLATFORM_MEMORY", #endif /* MBEDTLS_PLATFORM_MEMORY */ #if defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) "MBEDTLS_PLATFORM_NO_STD_FUNCTIONS", #endif /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */ #if defined(MBEDTLS_PLATFORM_EXIT_ALT) "MBEDTLS_PLATFORM_EXIT_ALT", #endif /* MBEDTLS_PLATFORM_EXIT_ALT */ #if defined(MBEDTLS_PLATFORM_TIME_ALT) "MBEDTLS_PLATFORM_TIME_ALT", #endif /* MBEDTLS_PLATFORM_TIME_ALT */ #if defined(MBEDTLS_PLATFORM_FPRINTF_ALT) "MBEDTLS_PLATFORM_FPRINTF_ALT", #endif /* MBEDTLS_PLATFORM_FPRINTF_ALT */ #if defined(MBEDTLS_PLATFORM_PRINTF_ALT) "MBEDTLS_PLATFORM_PRINTF_ALT", #endif /* MBEDTLS_PLATFORM_PRINTF_ALT */ #if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) "MBEDTLS_PLATFORM_SNPRINTF_ALT", #endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */ #if defined(MBEDTLS_PLATFORM_VSNPRINTF_ALT) "MBEDTLS_PLATFORM_VSNPRINTF_ALT", #endif /* MBEDTLS_PLATFORM_VSNPRINTF_ALT */ #if defined(MBEDTLS_PLATFORM_NV_SEED_ALT) "MBEDTLS_PLATFORM_NV_SEED_ALT", #endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */ #if defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT) "MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT", #endif /* MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */ #if defined(MBEDTLS_DEPRECATED_WARNING) "MBEDTLS_DEPRECATED_WARNING", #endif /* MBEDTLS_DEPRECATED_WARNING */ #if defined(MBEDTLS_DEPRECATED_REMOVED) "MBEDTLS_DEPRECATED_REMOVED", #endif /* MBEDTLS_DEPRECATED_REMOVED */ #if defined(MBEDTLS_CHECK_PARAMS) "MBEDTLS_CHECK_PARAMS", #endif /* MBEDTLS_CHECK_PARAMS */ #if defined(MBEDTLS_CHECK_PARAMS_ASSERT) "MBEDTLS_CHECK_PARAMS_ASSERT", #endif /* MBEDTLS_CHECK_PARAMS_ASSERT */ #if defined(MBEDTLS_TIMING_ALT) "MBEDTLS_TIMING_ALT", #endif /* MBEDTLS_TIMING_ALT */ #if defined(MBEDTLS_AES_ALT) "MBEDTLS_AES_ALT", #endif /* MBEDTLS_AES_ALT */ #if defined(MBEDTLS_ARC4_ALT) "MBEDTLS_ARC4_ALT", #endif /* MBEDTLS_ARC4_ALT */ #if defined(MBEDTLS_ARIA_ALT) "MBEDTLS_ARIA_ALT", #endif /* MBEDTLS_ARIA_ALT */ #if defined(MBEDTLS_BLOWFISH_ALT) "MBEDTLS_BLOWFISH_ALT", #endif /* MBEDTLS_BLOWFISH_ALT */ #if defined(MBEDTLS_CAMELLIA_ALT) "MBEDTLS_CAMELLIA_ALT", #endif /* MBEDTLS_CAMELLIA_ALT */ #if defined(MBEDTLS_CCM_ALT) "MBEDTLS_CCM_ALT", #endif /* MBEDTLS_CCM_ALT */ #if defined(MBEDTLS_CHACHA20_ALT) "MBEDTLS_CHACHA20_ALT", #endif /* MBEDTLS_CHACHA20_ALT */ #if defined(MBEDTLS_CHACHAPOLY_ALT) "MBEDTLS_CHACHAPOLY_ALT", #endif /* MBEDTLS_CHACHAPOLY_ALT */ #if defined(MBEDTLS_CMAC_ALT) "MBEDTLS_CMAC_ALT", #endif /* MBEDTLS_CMAC_ALT */ #if defined(MBEDTLS_DES_ALT) "MBEDTLS_DES_ALT", #endif /* MBEDTLS_DES_ALT */ #if defined(MBEDTLS_DHM_ALT) "MBEDTLS_DHM_ALT", #endif /* MBEDTLS_DHM_ALT */ #if defined(MBEDTLS_ECJPAKE_ALT) "MBEDTLS_ECJPAKE_ALT", #endif /* MBEDTLS_ECJPAKE_ALT */ #if defined(MBEDTLS_GCM_ALT) "MBEDTLS_GCM_ALT", #endif /* MBEDTLS_GCM_ALT */ #if defined(MBEDTLS_NIST_KW_ALT) "MBEDTLS_NIST_KW_ALT", #endif /* MBEDTLS_NIST_KW_ALT */ #if defined(MBEDTLS_MD2_ALT) "MBEDTLS_MD2_ALT", #endif /* MBEDTLS_MD2_ALT */ #if defined(MBEDTLS_MD4_ALT) "MBEDTLS_MD4_ALT", #endif /* MBEDTLS_MD4_ALT */ #if defined(MBEDTLS_MD5_ALT) "MBEDTLS_MD5_ALT", #endif /* MBEDTLS_MD5_ALT */ #if defined(MBEDTLS_POLY1305_ALT) "MBEDTLS_POLY1305_ALT", #endif /* MBEDTLS_POLY1305_ALT */ #if defined(MBEDTLS_RIPEMD160_ALT) "MBEDTLS_RIPEMD160_ALT", #endif /* MBEDTLS_RIPEMD160_ALT */ #if defined(MBEDTLS_RSA_ALT) "MBEDTLS_RSA_ALT", #endif /* MBEDTLS_RSA_ALT */ #if defined(MBEDTLS_SHA1_ALT) "MBEDTLS_SHA1_ALT", #endif /* MBEDTLS_SHA1_ALT */ #if defined(MBEDTLS_SHA256_ALT) "MBEDTLS_SHA256_ALT", #endif /* MBEDTLS_SHA256_ALT */ #if defined(MBEDTLS_SHA512_ALT) "MBEDTLS_SHA512_ALT", #endif /* MBEDTLS_SHA512_ALT */ #if defined(MBEDTLS_XTEA_ALT) "MBEDTLS_XTEA_ALT", #endif /* MBEDTLS_XTEA_ALT */ #if defined(MBEDTLS_ECP_ALT) "MBEDTLS_ECP_ALT", #endif /* MBEDTLS_ECP_ALT */ #if defined(MBEDTLS_MD2_PROCESS_ALT) "MBEDTLS_MD2_PROCESS_ALT", #endif /* MBEDTLS_MD2_PROCESS_ALT */ #if defined(MBEDTLS_MD4_PROCESS_ALT) "MBEDTLS_MD4_PROCESS_ALT", #endif /* MBEDTLS_MD4_PROCESS_ALT */ #if defined(MBEDTLS_MD5_PROCESS_ALT) "MBEDTLS_MD5_PROCESS_ALT", #endif /* MBEDTLS_MD5_PROCESS_ALT */ #if defined(MBEDTLS_RIPEMD160_PROCESS_ALT) "MBEDTLS_RIPEMD160_PROCESS_ALT", #endif /* MBEDTLS_RIPEMD160_PROCESS_ALT */ #if defined(MBEDTLS_SHA1_PROCESS_ALT) "MBEDTLS_SHA1_PROCESS_ALT", #endif /* MBEDTLS_SHA1_PROCESS_ALT */ #if defined(MBEDTLS_SHA256_PROCESS_ALT) "MBEDTLS_SHA256_PROCESS_ALT", #endif /* MBEDTLS_SHA256_PROCESS_ALT */ #if defined(MBEDTLS_SHA512_PROCESS_ALT) "MBEDTLS_SHA512_PROCESS_ALT", #endif /* MBEDTLS_SHA512_PROCESS_ALT */ #if defined(MBEDTLS_DES_SETKEY_ALT) "MBEDTLS_DES_SETKEY_ALT", #endif /* MBEDTLS_DES_SETKEY_ALT */ #if defined(MBEDTLS_DES_CRYPT_ECB_ALT) "MBEDTLS_DES_CRYPT_ECB_ALT", #endif /* MBEDTLS_DES_CRYPT_ECB_ALT */ #if defined(MBEDTLS_DES3_CRYPT_ECB_ALT) "MBEDTLS_DES3_CRYPT_ECB_ALT", #endif /* MBEDTLS_DES3_CRYPT_ECB_ALT */ #if defined(MBEDTLS_AES_SETKEY_ENC_ALT) "MBEDTLS_AES_SETKEY_ENC_ALT", #endif /* MBEDTLS_AES_SETKEY_ENC_ALT */ #if defined(MBEDTLS_AES_SETKEY_DEC_ALT) "MBEDTLS_AES_SETKEY_DEC_ALT", #endif /* MBEDTLS_AES_SETKEY_DEC_ALT */ #if defined(MBEDTLS_AES_ENCRYPT_ALT) "MBEDTLS_AES_ENCRYPT_ALT", #endif /* MBEDTLS_AES_ENCRYPT_ALT */ #if defined(MBEDTLS_AES_DECRYPT_ALT) "MBEDTLS_AES_DECRYPT_ALT", #endif /* MBEDTLS_AES_DECRYPT_ALT */ #if defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT) "MBEDTLS_ECDH_GEN_PUBLIC_ALT", #endif /* MBEDTLS_ECDH_GEN_PUBLIC_ALT */ #if defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT) "MBEDTLS_ECDH_COMPUTE_SHARED_ALT", #endif /* MBEDTLS_ECDH_COMPUTE_SHARED_ALT */ #if defined(MBEDTLS_ECDSA_VERIFY_ALT) "MBEDTLS_ECDSA_VERIFY_ALT", #endif /* MBEDTLS_ECDSA_VERIFY_ALT */ #if defined(MBEDTLS_ECDSA_SIGN_ALT) "MBEDTLS_ECDSA_SIGN_ALT", #endif /* MBEDTLS_ECDSA_SIGN_ALT */ #if defined(MBEDTLS_ECDSA_GENKEY_ALT) "MBEDTLS_ECDSA_GENKEY_ALT", #endif /* MBEDTLS_ECDSA_GENKEY_ALT */ #if defined(MBEDTLS_ECP_INTERNAL_ALT) "MBEDTLS_ECP_INTERNAL_ALT", #endif /* MBEDTLS_ECP_INTERNAL_ALT */ #if defined(MBEDTLS_ECP_NO_FALLBACK) "MBEDTLS_ECP_NO_FALLBACK", #endif /* MBEDTLS_ECP_NO_FALLBACK */ #if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) "MBEDTLS_ECP_RANDOMIZE_JAC_ALT", #endif /* MBEDTLS_ECP_RANDOMIZE_JAC_ALT */ #if defined(MBEDTLS_ECP_ADD_MIXED_ALT) "MBEDTLS_ECP_ADD_MIXED_ALT", #endif /* MBEDTLS_ECP_ADD_MIXED_ALT */ #if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) "MBEDTLS_ECP_DOUBLE_JAC_ALT", #endif /* MBEDTLS_ECP_DOUBLE_JAC_ALT */ #if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) "MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT", #endif /* MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT */ #if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) "MBEDTLS_ECP_NORMALIZE_JAC_ALT", #endif /* MBEDTLS_ECP_NORMALIZE_JAC_ALT */ #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) "MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT", #endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */ #if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) "MBEDTLS_ECP_RANDOMIZE_MXZ_ALT", #endif /* MBEDTLS_ECP_RANDOMIZE_MXZ_ALT */ #if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) "MBEDTLS_ECP_NORMALIZE_MXZ_ALT", #endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */ #if defined(MBEDTLS_TEST_NULL_ENTROPY) "MBEDTLS_TEST_NULL_ENTROPY", #endif /* MBEDTLS_TEST_NULL_ENTROPY */ #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT) "MBEDTLS_ENTROPY_HARDWARE_ALT", #endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */ #if defined(MBEDTLS_AES_ROM_TABLES) "MBEDTLS_AES_ROM_TABLES", #endif /* MBEDTLS_AES_ROM_TABLES */ #if defined(MBEDTLS_AES_FEWER_TABLES) "MBEDTLS_AES_FEWER_TABLES", #endif /* MBEDTLS_AES_FEWER_TABLES */ #if defined(MBEDTLS_CAMELLIA_SMALL_MEMORY) "MBEDTLS_CAMELLIA_SMALL_MEMORY", #endif /* MBEDTLS_CAMELLIA_SMALL_MEMORY */ #if defined(MBEDTLS_CIPHER_MODE_CBC) "MBEDTLS_CIPHER_MODE_CBC", #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_CFB) "MBEDTLS_CIPHER_MODE_CFB", #endif /* MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) "MBEDTLS_CIPHER_MODE_CTR", #endif /* MBEDTLS_CIPHER_MODE_CTR */ #if defined(MBEDTLS_CIPHER_MODE_OFB) "MBEDTLS_CIPHER_MODE_OFB", #endif /* MBEDTLS_CIPHER_MODE_OFB */ #if defined(MBEDTLS_CIPHER_MODE_XTS) "MBEDTLS_CIPHER_MODE_XTS", #endif /* MBEDTLS_CIPHER_MODE_XTS */ #if defined(MBEDTLS_CIPHER_NULL_CIPHER) "MBEDTLS_CIPHER_NULL_CIPHER", #endif /* MBEDTLS_CIPHER_NULL_CIPHER */ #if defined(MBEDTLS_CIPHER_PADDING_PKCS7) "MBEDTLS_CIPHER_PADDING_PKCS7", #endif /* MBEDTLS_CIPHER_PADDING_PKCS7 */ #if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS) "MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS", #endif /* MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS */ #if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN) "MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN", #endif /* MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN */ #if defined(MBEDTLS_CIPHER_PADDING_ZEROS) "MBEDTLS_CIPHER_PADDING_ZEROS", #endif /* MBEDTLS_CIPHER_PADDING_ZEROS */ #if defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY) "MBEDTLS_CTR_DRBG_USE_128_BIT_KEY", #endif /* MBEDTLS_CTR_DRBG_USE_128_BIT_KEY */ #if defined(MBEDTLS_ENABLE_WEAK_CIPHERSUITES) "MBEDTLS_ENABLE_WEAK_CIPHERSUITES", #endif /* MBEDTLS_ENABLE_WEAK_CIPHERSUITES */ #if defined(MBEDTLS_REMOVE_ARC4_CIPHERSUITES) "MBEDTLS_REMOVE_ARC4_CIPHERSUITES", #endif /* MBEDTLS_REMOVE_ARC4_CIPHERSUITES */ #if defined(MBEDTLS_REMOVE_3DES_CIPHERSUITES) "MBEDTLS_REMOVE_3DES_CIPHERSUITES", #endif /* MBEDTLS_REMOVE_3DES_CIPHERSUITES */ #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) "MBEDTLS_ECP_DP_SECP192R1_ENABLED", #endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) "MBEDTLS_ECP_DP_SECP224R1_ENABLED", #endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) "MBEDTLS_ECP_DP_SECP256R1_ENABLED", #endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) "MBEDTLS_ECP_DP_SECP384R1_ENABLED", #endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) "MBEDTLS_ECP_DP_SECP521R1_ENABLED", #endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) "MBEDTLS_ECP_DP_SECP192K1_ENABLED", #endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) "MBEDTLS_ECP_DP_SECP224K1_ENABLED", #endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) "MBEDTLS_ECP_DP_SECP256K1_ENABLED", #endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) "MBEDTLS_ECP_DP_BP256R1_ENABLED", #endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) "MBEDTLS_ECP_DP_BP384R1_ENABLED", #endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) "MBEDTLS_ECP_DP_BP512R1_ENABLED", #endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) "MBEDTLS_ECP_DP_CURVE25519_ENABLED", #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */ #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) "MBEDTLS_ECP_DP_CURVE448_ENABLED", #endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */ #if defined(MBEDTLS_ECP_NIST_OPTIM) "MBEDTLS_ECP_NIST_OPTIM", #endif /* MBEDTLS_ECP_NIST_OPTIM */ #if defined(MBEDTLS_ECP_NO_INTERNAL_RNG) "MBEDTLS_ECP_NO_INTERNAL_RNG", #endif /* MBEDTLS_ECP_NO_INTERNAL_RNG */ #if defined(MBEDTLS_ECP_RESTARTABLE) "MBEDTLS_ECP_RESTARTABLE", #endif /* MBEDTLS_ECP_RESTARTABLE */ #if defined(MBEDTLS_ECDH_LEGACY_CONTEXT) "MBEDTLS_ECDH_LEGACY_CONTEXT", #endif /* MBEDTLS_ECDH_LEGACY_CONTEXT */ #if defined(MBEDTLS_ECDSA_DETERMINISTIC) "MBEDTLS_ECDSA_DETERMINISTIC", #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) "MBEDTLS_KEY_EXCHANGE_PSK_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) "MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) "MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) "MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) "MBEDTLS_KEY_EXCHANGE_RSA_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) "MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) "MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) "MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) "MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) "MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) "MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED", #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED) "MBEDTLS_PK_PARSE_EC_EXTENDED", #endif /* MBEDTLS_PK_PARSE_EC_EXTENDED */ #if defined(MBEDTLS_ERROR_STRERROR_DUMMY) "MBEDTLS_ERROR_STRERROR_DUMMY", #endif /* MBEDTLS_ERROR_STRERROR_DUMMY */ #if defined(MBEDTLS_GENPRIME) "MBEDTLS_GENPRIME", #endif /* MBEDTLS_GENPRIME */ #if defined(MBEDTLS_FS_IO) "MBEDTLS_FS_IO", #endif /* MBEDTLS_FS_IO */ #if defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES) "MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES", #endif /* MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES */ #if defined(MBEDTLS_NO_PLATFORM_ENTROPY) "MBEDTLS_NO_PLATFORM_ENTROPY", #endif /* MBEDTLS_NO_PLATFORM_ENTROPY */ #if defined(MBEDTLS_ENTROPY_FORCE_SHA256) "MBEDTLS_ENTROPY_FORCE_SHA256", #endif /* MBEDTLS_ENTROPY_FORCE_SHA256 */ #if defined(MBEDTLS_ENTROPY_NV_SEED) "MBEDTLS_ENTROPY_NV_SEED", #endif /* MBEDTLS_ENTROPY_NV_SEED */ #if defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER) "MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER", #endif /* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */ #if defined(MBEDTLS_MEMORY_DEBUG) "MBEDTLS_MEMORY_DEBUG", #endif /* MBEDTLS_MEMORY_DEBUG */ #if defined(MBEDTLS_MEMORY_BACKTRACE) "MBEDTLS_MEMORY_BACKTRACE", #endif /* MBEDTLS_MEMORY_BACKTRACE */ #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) "MBEDTLS_PK_RSA_ALT_SUPPORT", #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */ #if defined(MBEDTLS_PKCS1_V15) "MBEDTLS_PKCS1_V15", #endif /* MBEDTLS_PKCS1_V15 */ #if defined(MBEDTLS_PKCS1_V21) "MBEDTLS_PKCS1_V21", #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PSA_CRYPTO_DRIVERS) "MBEDTLS_PSA_CRYPTO_DRIVERS", #endif /* MBEDTLS_PSA_CRYPTO_DRIVERS */ #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) "MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG", #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */ #if defined(MBEDTLS_PSA_CRYPTO_SPM) "MBEDTLS_PSA_CRYPTO_SPM", #endif /* MBEDTLS_PSA_CRYPTO_SPM */ #if defined(MBEDTLS_PSA_INJECT_ENTROPY) "MBEDTLS_PSA_INJECT_ENTROPY", #endif /* MBEDTLS_PSA_INJECT_ENTROPY */ #if defined(MBEDTLS_RSA_NO_CRT) "MBEDTLS_RSA_NO_CRT", #endif /* MBEDTLS_RSA_NO_CRT */ #if defined(MBEDTLS_SELF_TEST) "MBEDTLS_SELF_TEST", #endif /* MBEDTLS_SELF_TEST */ #if defined(MBEDTLS_SHA256_SMALLER) "MBEDTLS_SHA256_SMALLER", #endif /* MBEDTLS_SHA256_SMALLER */ #if defined(MBEDTLS_SHA512_SMALLER) "MBEDTLS_SHA512_SMALLER", #endif /* MBEDTLS_SHA512_SMALLER */ #if defined(MBEDTLS_SHA512_NO_SHA384) "MBEDTLS_SHA512_NO_SHA384", #endif /* MBEDTLS_SHA512_NO_SHA384 */ #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) "MBEDTLS_SSL_ALL_ALERT_MESSAGES", #endif /* MBEDTLS_SSL_ALL_ALERT_MESSAGES */ #if defined(MBEDTLS_SSL_RECORD_CHECKING) "MBEDTLS_SSL_RECORD_CHECKING", #endif /* MBEDTLS_SSL_RECORD_CHECKING */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) "MBEDTLS_SSL_DTLS_CONNECTION_ID", #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) "MBEDTLS_SSL_ASYNC_PRIVATE", #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION) "MBEDTLS_SSL_CONTEXT_SERIALIZATION", #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */ #if defined(MBEDTLS_SSL_DEBUG_ALL) "MBEDTLS_SSL_DEBUG_ALL", #endif /* MBEDTLS_SSL_DEBUG_ALL */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) "MBEDTLS_SSL_ENCRYPT_THEN_MAC", #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) "MBEDTLS_SSL_EXTENDED_MASTER_SECRET", #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_FALLBACK_SCSV) "MBEDTLS_SSL_FALLBACK_SCSV", #endif /* MBEDTLS_SSL_FALLBACK_SCSV */ #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) "MBEDTLS_SSL_KEEP_PEER_CERTIFICATE", #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) "MBEDTLS_SSL_HW_RECORD_ACCEL", #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) "MBEDTLS_SSL_CBC_RECORD_SPLITTING", #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */ #if defined(MBEDTLS_SSL_RENEGOTIATION) "MBEDTLS_SSL_RENEGOTIATION", #endif /* MBEDTLS_SSL_RENEGOTIATION */ #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) "MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO", #endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */ #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE) "MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE", #endif /* MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) "MBEDTLS_SSL_MAX_FRAGMENT_LENGTH", #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_PROTO_SSL3) "MBEDTLS_SSL_PROTO_SSL3", #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) "MBEDTLS_SSL_PROTO_TLS1", #endif /* MBEDTLS_SSL_PROTO_TLS1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_1) "MBEDTLS_SSL_PROTO_TLS1_1", #endif /* MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) "MBEDTLS_SSL_PROTO_TLS1_2", #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) "MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL", #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ #if defined(MBEDTLS_SSL_PROTO_DTLS) "MBEDTLS_SSL_PROTO_DTLS", #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_ALPN) "MBEDTLS_SSL_ALPN", #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) "MBEDTLS_SSL_DTLS_ANTI_REPLAY", #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) "MBEDTLS_SSL_DTLS_HELLO_VERIFY", #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ #if defined(MBEDTLS_SSL_DTLS_SRTP) "MBEDTLS_SSL_DTLS_SRTP", #endif /* MBEDTLS_SSL_DTLS_SRTP */ #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) "MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE", #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE */ #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) "MBEDTLS_SSL_DTLS_BADMAC_LIMIT", #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) "MBEDTLS_SSL_SESSION_TICKETS", #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_EXPORT_KEYS) "MBEDTLS_SSL_EXPORT_KEYS", #endif /* MBEDTLS_SSL_EXPORT_KEYS */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) "MBEDTLS_SSL_SERVER_NAME_INDICATION", #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) "MBEDTLS_SSL_TRUNCATED_HMAC", #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT) "MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT", #endif /* MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT */ #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) "MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH", #endif /* MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH */ #if defined(MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN) "MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN", #endif /* MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN */ #if defined(MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND) "MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND", #endif /* MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND */ #if defined(MBEDTLS_TEST_HOOKS) "MBEDTLS_TEST_HOOKS", #endif /* MBEDTLS_TEST_HOOKS */ #if defined(MBEDTLS_THREADING_ALT) "MBEDTLS_THREADING_ALT", #endif /* MBEDTLS_THREADING_ALT */ #if defined(MBEDTLS_THREADING_PTHREAD) "MBEDTLS_THREADING_PTHREAD", #endif /* MBEDTLS_THREADING_PTHREAD */ #if defined(MBEDTLS_USE_PSA_CRYPTO) "MBEDTLS_USE_PSA_CRYPTO", #endif /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_PSA_CRYPTO_CONFIG) "MBEDTLS_PSA_CRYPTO_CONFIG", #endif /* MBEDTLS_PSA_CRYPTO_CONFIG */ #if defined(MBEDTLS_VERSION_FEATURES) "MBEDTLS_VERSION_FEATURES", #endif /* MBEDTLS_VERSION_FEATURES */ #if defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3) "MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3", #endif /* MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 */ #if defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION) "MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION", #endif /* MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION */ #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) "MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK", #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) "MBEDTLS_X509_CHECK_KEY_USAGE", #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */ #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) "MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE", #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */ #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) "MBEDTLS_X509_RSASSA_PSS_SUPPORT", #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */ #if defined(MBEDTLS_ZLIB_SUPPORT) "MBEDTLS_ZLIB_SUPPORT", #endif /* MBEDTLS_ZLIB_SUPPORT */ #if defined(MBEDTLS_AESNI_C) "MBEDTLS_AESNI_C", #endif /* MBEDTLS_AESNI_C */ #if defined(MBEDTLS_AES_C) "MBEDTLS_AES_C", #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_ARC4_C) "MBEDTLS_ARC4_C", #endif /* MBEDTLS_ARC4_C */ #if defined(MBEDTLS_ASN1_PARSE_C) "MBEDTLS_ASN1_PARSE_C", #endif /* MBEDTLS_ASN1_PARSE_C */ #if defined(MBEDTLS_ASN1_WRITE_C) "MBEDTLS_ASN1_WRITE_C", #endif /* MBEDTLS_ASN1_WRITE_C */ #if defined(MBEDTLS_BASE64_C) "MBEDTLS_BASE64_C", #endif /* MBEDTLS_BASE64_C */ #if defined(MBEDTLS_BIGNUM_C) "MBEDTLS_BIGNUM_C", #endif /* MBEDTLS_BIGNUM_C */ #if defined(MBEDTLS_BLOWFISH_C) "MBEDTLS_BLOWFISH_C", #endif /* MBEDTLS_BLOWFISH_C */ #if defined(MBEDTLS_CAMELLIA_C) "MBEDTLS_CAMELLIA_C", #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_ARIA_C) "MBEDTLS_ARIA_C", #endif /* MBEDTLS_ARIA_C */ #if defined(MBEDTLS_CCM_C) "MBEDTLS_CCM_C", #endif /* MBEDTLS_CCM_C */ #if defined(MBEDTLS_CERTS_C) "MBEDTLS_CERTS_C", #endif /* MBEDTLS_CERTS_C */ #if defined(MBEDTLS_CHACHA20_C) "MBEDTLS_CHACHA20_C", #endif /* MBEDTLS_CHACHA20_C */ #if defined(MBEDTLS_CHACHAPOLY_C) "MBEDTLS_CHACHAPOLY_C", #endif /* MBEDTLS_CHACHAPOLY_C */ #if defined(MBEDTLS_CIPHER_C) "MBEDTLS_CIPHER_C", #endif /* MBEDTLS_CIPHER_C */ #if defined(MBEDTLS_CMAC_C) "MBEDTLS_CMAC_C", #endif /* MBEDTLS_CMAC_C */ #if defined(MBEDTLS_CTR_DRBG_C) "MBEDTLS_CTR_DRBG_C", #endif /* MBEDTLS_CTR_DRBG_C */ #if defined(MBEDTLS_DEBUG_C) "MBEDTLS_DEBUG_C", #endif /* MBEDTLS_DEBUG_C */ #if defined(MBEDTLS_DES_C) "MBEDTLS_DES_C", #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_DHM_C) "MBEDTLS_DHM_C", #endif /* MBEDTLS_DHM_C */ #if defined(MBEDTLS_ECDH_C) "MBEDTLS_ECDH_C", #endif /* MBEDTLS_ECDH_C */ #if defined(MBEDTLS_ECDSA_C) "MBEDTLS_ECDSA_C", #endif /* MBEDTLS_ECDSA_C */ #if defined(MBEDTLS_ECJPAKE_C) "MBEDTLS_ECJPAKE_C", #endif /* MBEDTLS_ECJPAKE_C */ #if defined(MBEDTLS_ECP_C) "MBEDTLS_ECP_C", #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_ENTROPY_C) "MBEDTLS_ENTROPY_C", #endif /* MBEDTLS_ENTROPY_C */ #if defined(MBEDTLS_ERROR_C) "MBEDTLS_ERROR_C", #endif /* MBEDTLS_ERROR_C */ #if defined(MBEDTLS_GCM_C) "MBEDTLS_GCM_C", #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_HAVEGE_C) "MBEDTLS_HAVEGE_C", #endif /* MBEDTLS_HAVEGE_C */ #if defined(MBEDTLS_HKDF_C) "MBEDTLS_HKDF_C", #endif /* MBEDTLS_HKDF_C */ #if defined(MBEDTLS_HMAC_DRBG_C) "MBEDTLS_HMAC_DRBG_C", #endif /* MBEDTLS_HMAC_DRBG_C */ #if defined(MBEDTLS_NIST_KW_C) "MBEDTLS_NIST_KW_C", #endif /* MBEDTLS_NIST_KW_C */ #if defined(MBEDTLS_MD_C) "MBEDTLS_MD_C", #endif /* MBEDTLS_MD_C */ #if defined(MBEDTLS_MD2_C) "MBEDTLS_MD2_C", #endif /* MBEDTLS_MD2_C */ #if defined(MBEDTLS_MD4_C) "MBEDTLS_MD4_C", #endif /* MBEDTLS_MD4_C */ #if defined(MBEDTLS_MD5_C) "MBEDTLS_MD5_C", #endif /* MBEDTLS_MD5_C */ #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) "MBEDTLS_MEMORY_BUFFER_ALLOC_C", #endif /* MBEDTLS_MEMORY_BUFFER_ALLOC_C */ #if defined(MBEDTLS_NET_C) "MBEDTLS_NET_C", #endif /* MBEDTLS_NET_C */ #if defined(MBEDTLS_OID_C) "MBEDTLS_OID_C", #endif /* MBEDTLS_OID_C */ #if defined(MBEDTLS_PADLOCK_C) "MBEDTLS_PADLOCK_C", #endif /* MBEDTLS_PADLOCK_C */ #if defined(MBEDTLS_PEM_PARSE_C) "MBEDTLS_PEM_PARSE_C", #endif /* MBEDTLS_PEM_PARSE_C */ #if defined(MBEDTLS_PEM_WRITE_C) "MBEDTLS_PEM_WRITE_C", #endif /* MBEDTLS_PEM_WRITE_C */ #if defined(MBEDTLS_PK_C) "MBEDTLS_PK_C", #endif /* MBEDTLS_PK_C */ #if defined(MBEDTLS_PK_PARSE_C) "MBEDTLS_PK_PARSE_C", #endif /* MBEDTLS_PK_PARSE_C */ #if defined(MBEDTLS_PK_WRITE_C) "MBEDTLS_PK_WRITE_C", #endif /* MBEDTLS_PK_WRITE_C */ #if defined(MBEDTLS_PKCS5_C) "MBEDTLS_PKCS5_C", #endif /* MBEDTLS_PKCS5_C */ #if defined(MBEDTLS_PKCS11_C) "MBEDTLS_PKCS11_C", #endif /* MBEDTLS_PKCS11_C */ #if defined(MBEDTLS_PKCS12_C) "MBEDTLS_PKCS12_C", #endif /* MBEDTLS_PKCS12_C */ #if defined(MBEDTLS_PLATFORM_C) "MBEDTLS_PLATFORM_C", #endif /* MBEDTLS_PLATFORM_C */ #if defined(MBEDTLS_POLY1305_C) "MBEDTLS_POLY1305_C", #endif /* MBEDTLS_POLY1305_C */ #if defined(MBEDTLS_PSA_CRYPTO_C) "MBEDTLS_PSA_CRYPTO_C", #endif /* MBEDTLS_PSA_CRYPTO_C */ #if defined(MBEDTLS_PSA_CRYPTO_SE_C) "MBEDTLS_PSA_CRYPTO_SE_C", #endif /* MBEDTLS_PSA_CRYPTO_SE_C */ #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) "MBEDTLS_PSA_CRYPTO_STORAGE_C", #endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C */ #if defined(MBEDTLS_PSA_ITS_FILE_C) "MBEDTLS_PSA_ITS_FILE_C", #endif /* MBEDTLS_PSA_ITS_FILE_C */ #if defined(MBEDTLS_RIPEMD160_C) "MBEDTLS_RIPEMD160_C", #endif /* MBEDTLS_RIPEMD160_C */ #if defined(MBEDTLS_RSA_C) "MBEDTLS_RSA_C", #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_SHA1_C) "MBEDTLS_SHA1_C", #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) "MBEDTLS_SHA256_C", #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) "MBEDTLS_SHA512_C", #endif /* MBEDTLS_SHA512_C */ #if defined(MBEDTLS_SSL_CACHE_C) "MBEDTLS_SSL_CACHE_C", #endif /* MBEDTLS_SSL_CACHE_C */ #if defined(MBEDTLS_SSL_COOKIE_C) "MBEDTLS_SSL_COOKIE_C", #endif /* MBEDTLS_SSL_COOKIE_C */ #if defined(MBEDTLS_SSL_TICKET_C) "MBEDTLS_SSL_TICKET_C", #endif /* MBEDTLS_SSL_TICKET_C */ #if defined(MBEDTLS_SSL_CLI_C) "MBEDTLS_SSL_CLI_C", #endif /* MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_SSL_SRV_C) "MBEDTLS_SSL_SRV_C", #endif /* MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_SSL_TLS_C) "MBEDTLS_SSL_TLS_C", #endif /* MBEDTLS_SSL_TLS_C */ #if defined(MBEDTLS_THREADING_C) "MBEDTLS_THREADING_C", #endif /* MBEDTLS_THREADING_C */ #if defined(MBEDTLS_TIMING_C) "MBEDTLS_TIMING_C", #endif /* MBEDTLS_TIMING_C */ #if defined(MBEDTLS_VERSION_C) "MBEDTLS_VERSION_C", #endif /* MBEDTLS_VERSION_C */ #if defined(MBEDTLS_X509_USE_C) "MBEDTLS_X509_USE_C", #endif /* MBEDTLS_X509_USE_C */ #if defined(MBEDTLS_X509_CRT_PARSE_C) "MBEDTLS_X509_CRT_PARSE_C", #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_X509_CRL_PARSE_C) "MBEDTLS_X509_CRL_PARSE_C", #endif /* MBEDTLS_X509_CRL_PARSE_C */ #if defined(MBEDTLS_X509_CSR_PARSE_C) "MBEDTLS_X509_CSR_PARSE_C", #endif /* MBEDTLS_X509_CSR_PARSE_C */ #if defined(MBEDTLS_X509_CREATE_C) "MBEDTLS_X509_CREATE_C", #endif /* MBEDTLS_X509_CREATE_C */ #if defined(MBEDTLS_X509_CRT_WRITE_C) "MBEDTLS_X509_CRT_WRITE_C", #endif /* MBEDTLS_X509_CRT_WRITE_C */ #if defined(MBEDTLS_X509_CSR_WRITE_C) "MBEDTLS_X509_CSR_WRITE_C", #endif /* MBEDTLS_X509_CSR_WRITE_C */ #if defined(MBEDTLS_XTEA_C) "MBEDTLS_XTEA_C", #endif /* MBEDTLS_XTEA_C */ #endif /* MBEDTLS_VERSION_FEATURES */ NULL }; int mbedtls_version_check_feature( const char *feature ) { const char * const *idx = features; if( *idx == NULL ) return( -2 ); if( feature == NULL ) return( -1 ); while( *idx != NULL ) { if( !strcmp( *idx, feature ) ) return( 0 ); idx++; } return( -1 ); } #endif /* MBEDTLS_VERSION_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\x509.c
/* * X.509 common functions for parsing and verification * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The ITU-T X.509 standard defines a certificate format for PKI. * * http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs) * http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs) * http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10) * * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf */ #include "common.h" #if defined(MBEDTLS_X509_USE_C) #include "mbedtls/x509.h" #include "mbedtls/asn1.h" #include "mbedtls/error.h" #include "mbedtls/oid.h" #include <stdio.h> #include <string.h> #if defined(MBEDTLS_PEM_PARSE_C) #include "mbedtls/pem.h" #endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #include <stdlib.h> #define mbedtls_free free #define mbedtls_calloc calloc #define mbedtls_printf printf #define mbedtls_snprintf snprintf #endif #if defined(MBEDTLS_HAVE_TIME) #include "mbedtls/platform_time.h" #endif #if defined(MBEDTLS_HAVE_TIME_DATE) #include "mbedtls/platform_util.h" #include <time.h> #endif #define CHECK(code) if( ( ret = ( code ) ) != 0 ){ return( ret ); } #define CHECK_RANGE(min, max, val) \ do \ { \ if( ( val ) < ( min ) || ( val ) > ( max ) ) \ { \ return( ret ); \ } \ } while( 0 ) /* * CertificateSerialNumber ::= INTEGER */ int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *serial ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_SERIAL + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); if( **p != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_PRIMITIVE | 2 ) && **p != MBEDTLS_ASN1_INTEGER ) return( MBEDTLS_ERR_X509_INVALID_SERIAL + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); serial->tag = *(*p)++; if( ( ret = mbedtls_asn1_get_len( p, end, &serial->len ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_SERIAL + ret ); serial->p = *p; *p += serial->len; return( 0 ); } /* Get an algorithm identifier without parameters (eg for signatures) * * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL } */ int mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *alg ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ( ret = mbedtls_asn1_get_alg_null( p, end, alg ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); return( 0 ); } /* * Parse an algorithm identifier with (optional) parameters */ int mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *alg, mbedtls_x509_buf *params ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ( ret = mbedtls_asn1_get_alg( p, end, alg, params ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); return( 0 ); } #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) /* * HashAlgorithm ::= AlgorithmIdentifier * * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL } * * For HashAlgorithm, parameters MUST be NULL or absent. */ static int x509_get_hash_alg( const mbedtls_x509_buf *alg, mbedtls_md_type_t *md_alg ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p; const unsigned char *end; mbedtls_x509_buf md_oid; size_t len; /* Make sure we got a SEQUENCE and setup bounds */ if( alg->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) return( MBEDTLS_ERR_X509_INVALID_ALG + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); p = alg->p; end = p + alg->len; if( p >= end ) return( MBEDTLS_ERR_X509_INVALID_ALG + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); /* Parse md_oid */ md_oid.tag = *p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &md_oid.len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); md_oid.p = p; p += md_oid.len; /* Get md_alg from md_oid */ if( ( ret = mbedtls_oid_get_md_alg( &md_oid, md_alg ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); /* Make sure params is absent of NULL */ if( p == end ) return( 0 ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_NULL ) ) != 0 || len != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); if( p != end ) return( MBEDTLS_ERR_X509_INVALID_ALG + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * RSASSA-PSS-params ::= SEQUENCE { * hashAlgorithm [0] HashAlgorithm DEFAULT sha1Identifier, * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier, * saltLength [2] INTEGER DEFAULT 20, * trailerField [3] INTEGER DEFAULT 1 } * -- Note that the tags in this Sequence are explicit. * * RFC 4055 (which defines use of RSASSA-PSS in PKIX) states that the value * of trailerField MUST be 1, and PKCS#1 v2.2 doesn't even define any other * option. Enfore this at parsing time. */ int mbedtls_x509_get_rsassa_pss_params( const mbedtls_x509_buf *params, mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md, int *salt_len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p; const unsigned char *end, *end2; size_t len; mbedtls_x509_buf alg_id, alg_params; /* First set everything to defaults */ *md_alg = MBEDTLS_MD_SHA1; *mgf_md = MBEDTLS_MD_SHA1; *salt_len = 20; /* Make sure params is a SEQUENCE and setup bounds */ if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) return( MBEDTLS_ERR_X509_INVALID_ALG + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); p = (unsigned char *) params->p; end = p + params->len; if( p == end ) return( 0 ); /* * HashAlgorithm */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) == 0 ) { end2 = p + len; /* HashAlgorithm ::= AlgorithmIdentifier (without parameters) */ if( ( ret = mbedtls_x509_get_alg_null( &p, end2, &alg_id ) ) != 0 ) return( ret ); if( ( ret = mbedtls_oid_get_md_alg( &alg_id, md_alg ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); if( p != end2 ) return( MBEDTLS_ERR_X509_INVALID_ALG + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); if( p == end ) return( 0 ); /* * MaskGenAlgorithm */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) ) == 0 ) { end2 = p + len; /* MaskGenAlgorithm ::= AlgorithmIdentifier (params = HashAlgorithm) */ if( ( ret = mbedtls_x509_get_alg( &p, end2, &alg_id, &alg_params ) ) != 0 ) return( ret ); /* Only MFG1 is recognised for now */ if( MBEDTLS_OID_CMP( MBEDTLS_OID_MGF1, &alg_id ) != 0 ) return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE + MBEDTLS_ERR_OID_NOT_FOUND ); /* Parse HashAlgorithm */ if( ( ret = x509_get_hash_alg( &alg_params, mgf_md ) ) != 0 ) return( ret ); if( p != end2 ) return( MBEDTLS_ERR_X509_INVALID_ALG + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); if( p == end ) return( 0 ); /* * salt_len */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 2 ) ) == 0 ) { end2 = p + len; if( ( ret = mbedtls_asn1_get_int( &p, end2, salt_len ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); if( p != end2 ) return( MBEDTLS_ERR_X509_INVALID_ALG + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); if( p == end ) return( 0 ); /* * trailer_field (if present, must be 1) */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 3 ) ) == 0 ) { int trailer_field; end2 = p + len; if( ( ret = mbedtls_asn1_get_int( &p, end2, &trailer_field ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); if( p != end2 ) return( MBEDTLS_ERR_X509_INVALID_ALG + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); if( trailer_field != 1 ) return( MBEDTLS_ERR_X509_INVALID_ALG ); } else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); if( p != end ) return( MBEDTLS_ERR_X509_INVALID_ALG + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */ /* * AttributeTypeAndValue ::= SEQUENCE { * type AttributeType, * value AttributeValue } * * AttributeType ::= OBJECT IDENTIFIER * * AttributeValue ::= ANY DEFINED BY AttributeType */ static int x509_get_attr_type_value( unsigned char **p, const unsigned char *end, mbedtls_x509_name *cur ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; mbedtls_x509_buf *oid; mbedtls_x509_buf *val; if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_NAME + ret ); end = *p + len; if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_NAME + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); oid = &cur->oid; oid->tag = **p; if( ( ret = mbedtls_asn1_get_tag( p, end, &oid->len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_NAME + ret ); oid->p = *p; *p += oid->len; if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_NAME + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); if( **p != MBEDTLS_ASN1_BMP_STRING && **p != MBEDTLS_ASN1_UTF8_STRING && **p != MBEDTLS_ASN1_T61_STRING && **p != MBEDTLS_ASN1_PRINTABLE_STRING && **p != MBEDTLS_ASN1_IA5_STRING && **p != MBEDTLS_ASN1_UNIVERSAL_STRING && **p != MBEDTLS_ASN1_BIT_STRING ) return( MBEDTLS_ERR_X509_INVALID_NAME + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); val = &cur->val; val->tag = *(*p)++; if( ( ret = mbedtls_asn1_get_len( p, end, &val->len ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_NAME + ret ); val->p = *p; *p += val->len; if( *p != end ) { return( MBEDTLS_ERR_X509_INVALID_NAME + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } cur->next = NULL; return( 0 ); } /* * Name ::= CHOICE { -- only one possibility for now -- * rdnSequence RDNSequence } * * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= * SET OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type AttributeType, * value AttributeValue } * * AttributeType ::= OBJECT IDENTIFIER * * AttributeValue ::= ANY DEFINED BY AttributeType * * The data structure is optimized for the common case where each RDN has only * one element, which is represented as a list of AttributeTypeAndValue. * For the general case we still use a flat list, but we mark elements of the * same set so that they are "merged" together in the functions that consume * this list, eg mbedtls_x509_dn_gets(). */ int mbedtls_x509_get_name( unsigned char **p, const unsigned char *end, mbedtls_x509_name *cur ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t set_len; const unsigned char *end_set; /* don't use recursion, we'd risk stack overflow if not optimized */ while( 1 ) { /* * parse SET */ if( ( ret = mbedtls_asn1_get_tag( p, end, &set_len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_NAME + ret ); end_set = *p + set_len; while( 1 ) { if( ( ret = x509_get_attr_type_value( p, end_set, cur ) ) != 0 ) return( ret ); if( *p == end_set ) break; /* Mark this item as being no the only one in a set */ cur->next_merged = 1; cur->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_name ) ); if( cur->next == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); cur = cur->next; } /* * continue until end of SEQUENCE is reached */ if( *p == end ) return( 0 ); cur->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_name ) ); if( cur->next == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); cur = cur->next; } } static int x509_parse_int( unsigned char **p, size_t n, int *res ) { *res = 0; for( ; n > 0; --n ) { if( ( **p < '0') || ( **p > '9' ) ) return ( MBEDTLS_ERR_X509_INVALID_DATE ); *res *= 10; *res += ( *(*p)++ - '0' ); } return( 0 ); } static int x509_date_is_valid(const mbedtls_x509_time *t ) { int ret = MBEDTLS_ERR_X509_INVALID_DATE; int month_len; CHECK_RANGE( 0, 9999, t->year ); CHECK_RANGE( 0, 23, t->hour ); CHECK_RANGE( 0, 59, t->min ); CHECK_RANGE( 0, 59, t->sec ); switch( t->mon ) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: month_len = 31; break; case 4: case 6: case 9: case 11: month_len = 30; break; case 2: if( ( !( t->year % 4 ) && t->year % 100 ) || !( t->year % 400 ) ) month_len = 29; else month_len = 28; break; default: return( ret ); } CHECK_RANGE( 1, month_len, t->day ); return( 0 ); } /* * Parse an ASN1_UTC_TIME (yearlen=2) or ASN1_GENERALIZED_TIME (yearlen=4) * field. */ static int x509_parse_time( unsigned char **p, size_t len, size_t yearlen, mbedtls_x509_time *tm ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* * Minimum length is 10 or 12 depending on yearlen */ if ( len < yearlen + 8 ) return ( MBEDTLS_ERR_X509_INVALID_DATE ); len -= yearlen + 8; /* * Parse year, month, day, hour, minute */ CHECK( x509_parse_int( p, yearlen, &tm->year ) ); if ( 2 == yearlen ) { if ( tm->year < 50 ) tm->year += 100; tm->year += 1900; } CHECK( x509_parse_int( p, 2, &tm->mon ) ); CHECK( x509_parse_int( p, 2, &tm->day ) ); CHECK( x509_parse_int( p, 2, &tm->hour ) ); CHECK( x509_parse_int( p, 2, &tm->min ) ); /* * Parse seconds if present */ if ( len >= 2 ) { CHECK( x509_parse_int( p, 2, &tm->sec ) ); len -= 2; } else return ( MBEDTLS_ERR_X509_INVALID_DATE ); /* * Parse trailing 'Z' if present */ if ( 1 == len && 'Z' == **p ) { (*p)++; len--; } /* * We should have parsed all characters at this point */ if ( 0 != len ) return ( MBEDTLS_ERR_X509_INVALID_DATE ); CHECK( x509_date_is_valid( tm ) ); return ( 0 ); } /* * Time ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime } */ int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end, mbedtls_x509_time *tm ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len, year_len; unsigned char tag; if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_DATE + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); tag = **p; if( tag == MBEDTLS_ASN1_UTC_TIME ) year_len = 2; else if( tag == MBEDTLS_ASN1_GENERALIZED_TIME ) year_len = 4; else return( MBEDTLS_ERR_X509_INVALID_DATE + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); (*p)++; ret = mbedtls_asn1_get_len( p, end, &len ); if( ret != 0 ) return( MBEDTLS_ERR_X509_INVALID_DATE + ret ); return x509_parse_time( p, len, year_len, tm ); } int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; int tag_type; if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_SIGNATURE + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); tag_type = **p; if( ( ret = mbedtls_asn1_get_bitstring_null( p, end, &len ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_SIGNATURE + ret ); sig->tag = tag_type; sig->len = len; sig->p = *p; *p += len; return( 0 ); } /* * Get signature algorithm from alg OID and optional parameters */ int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params, mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg, void **sig_opts ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( *sig_opts != NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); if( ( ret = mbedtls_oid_get_sig_alg( sig_oid, md_alg, pk_alg ) ) != 0 ) return( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + ret ); #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) if( *pk_alg == MBEDTLS_PK_RSASSA_PSS ) { mbedtls_pk_rsassa_pss_options *pss_opts; pss_opts = mbedtls_calloc( 1, sizeof( mbedtls_pk_rsassa_pss_options ) ); if( pss_opts == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); ret = mbedtls_x509_get_rsassa_pss_params( sig_params, md_alg, &pss_opts->mgf1_hash_id, &pss_opts->expected_salt_len ); if( ret != 0 ) { mbedtls_free( pss_opts ); return( ret ); } *sig_opts = (void *) pss_opts; } else #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */ { /* Make sure parameters are absent or NULL */ if( ( sig_params->tag != MBEDTLS_ASN1_NULL && sig_params->tag != 0 ) || sig_params->len != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG ); } return( 0 ); } /* * X.509 Extensions (No parsing of extensions, pointer should * be either manually updated or extensions should be parsed!) */ int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *ext, int tag ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; /* Extension structure use EXPLICIT tagging. That is, the actual * `Extensions` structure is wrapped by a tag-length pair using * the respective context-specific tag. */ ret = mbedtls_asn1_get_tag( p, end, &ext->len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag ); if( ret != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); ext->tag = MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag; ext->p = *p; end = *p + ext->len; /* * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( end != *p + len ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * Store the name in printable form into buf; no more * than size characters will be written */ int mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t i, n; unsigned char c, merge = 0; const mbedtls_x509_name *name; const char *short_name = NULL; char s[MBEDTLS_X509_MAX_DN_NAME_SIZE], *p; memset( s, 0, sizeof( s ) ); name = dn; p = buf; n = size; while( name != NULL ) { if( !name->oid.p ) { name = name->next; continue; } if( name != dn ) { ret = mbedtls_snprintf( p, n, merge ? " + " : ", " ); MBEDTLS_X509_SAFE_SNPRINTF; } ret = mbedtls_oid_get_attr_short_name( &name->oid, &short_name ); if( ret == 0 ) ret = mbedtls_snprintf( p, n, "%s=", short_name ); else ret = mbedtls_snprintf( p, n, "\?\?=" ); MBEDTLS_X509_SAFE_SNPRINTF; for( i = 0; i < name->val.len; i++ ) { if( i >= sizeof( s ) - 1 ) break; c = name->val.p[i]; if( c < 32 || c >= 127 ) s[i] = '?'; else s[i] = c; } s[i] = '\0'; ret = mbedtls_snprintf( p, n, "%s", s ); MBEDTLS_X509_SAFE_SNPRINTF; merge = name->next_merged; name = name->next; } return( (int) ( size - n ) ); } /* * Store the serial in printable form into buf; no more * than size characters will be written */ int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *serial ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t i, n, nr; char *p; p = buf; n = size; nr = ( serial->len <= 32 ) ? serial->len : 28; for( i = 0; i < nr; i++ ) { if( i == 0 && nr > 1 && serial->p[i] == 0x0 ) continue; ret = mbedtls_snprintf( p, n, "%02X%s", serial->p[i], ( i < nr - 1 ) ? ":" : "" ); MBEDTLS_X509_SAFE_SNPRINTF; } if( nr != serial->len ) { ret = mbedtls_snprintf( p, n, "...." ); MBEDTLS_X509_SAFE_SNPRINTF; } return( (int) ( size - n ) ); } /* * Helper for writing signature algorithms */ int mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *sig_oid, mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg, const void *sig_opts ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; char *p = buf; size_t n = size; const char *desc = NULL; ret = mbedtls_oid_get_sig_alg_desc( sig_oid, &desc ); if( ret != 0 ) ret = mbedtls_snprintf( p, n, "???" ); else ret = mbedtls_snprintf( p, n, "%s", desc ); MBEDTLS_X509_SAFE_SNPRINTF; #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) if( pk_alg == MBEDTLS_PK_RSASSA_PSS ) { const mbedtls_pk_rsassa_pss_options *pss_opts; const mbedtls_md_info_t *md_info, *mgf_md_info; pss_opts = (const mbedtls_pk_rsassa_pss_options *) sig_opts; md_info = mbedtls_md_info_from_type( md_alg ); mgf_md_info = mbedtls_md_info_from_type( pss_opts->mgf1_hash_id ); ret = mbedtls_snprintf( p, n, " (%s, MGF1-%s, 0x%02X)", md_info ? mbedtls_md_get_name( md_info ) : "???", mgf_md_info ? mbedtls_md_get_name( mgf_md_info ) : "???", (unsigned int) pss_opts->expected_salt_len ); MBEDTLS_X509_SAFE_SNPRINTF; } #else ((void) pk_alg); ((void) md_alg); ((void) sig_opts); #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */ return( (int)( size - n ) ); } /* * Helper for writing "RSA key size", "EC key size", etc */ int mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name ) { char *p = buf; size_t n = buf_size; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; ret = mbedtls_snprintf( p, n, "%s key size", name ); MBEDTLS_X509_SAFE_SNPRINTF; return( 0 ); } #if defined(MBEDTLS_HAVE_TIME_DATE) /* * Set the time structure to the current time. * Return 0 on success, non-zero on failure. */ static int x509_get_current_time( mbedtls_x509_time *now ) { struct tm *lt, tm_buf; mbedtls_time_t tt; int ret = 0; tt = mbedtls_time( NULL ); lt = mbedtls_platform_gmtime_r( &tt, &tm_buf ); if( lt == NULL ) ret = -1; else { now->year = lt->tm_year + 1900; now->mon = lt->tm_mon + 1; now->day = lt->tm_mday; now->hour = lt->tm_hour; now->min = lt->tm_min; now->sec = lt->tm_sec; } return( ret ); } /* * Return 0 if before <= after, 1 otherwise */ static int x509_check_time( const mbedtls_x509_time *before, const mbedtls_x509_time *after ) { if( before->year > after->year ) return( 1 ); if( before->year == after->year && before->mon > after->mon ) return( 1 ); if( before->year == after->year && before->mon == after->mon && before->day > after->day ) return( 1 ); if( before->year == after->year && before->mon == after->mon && before->day == after->day && before->hour > after->hour ) return( 1 ); if( before->year == after->year && before->mon == after->mon && before->day == after->day && before->hour == after->hour && before->min > after->min ) return( 1 ); if( before->year == after->year && before->mon == after->mon && before->day == after->day && before->hour == after->hour && before->min == after->min && before->sec > after->sec ) return( 1 ); return( 0 ); } int mbedtls_x509_time_is_past( const mbedtls_x509_time *to ) { mbedtls_x509_time now; if( x509_get_current_time( &now ) != 0 ) return( 1 ); return( x509_check_time( &now, to ) ); } int mbedtls_x509_time_is_future( const mbedtls_x509_time *from ) { mbedtls_x509_time now; if( x509_get_current_time( &now ) != 0 ) return( 1 ); return( x509_check_time( from, &now ) ); } #else /* MBEDTLS_HAVE_TIME_DATE */ int mbedtls_x509_time_is_past( const mbedtls_x509_time *to ) { ((void) to); return( 0 ); } int mbedtls_x509_time_is_future( const mbedtls_x509_time *from ) { ((void) from); return( 0 ); } #endif /* MBEDTLS_HAVE_TIME_DATE */ #if defined(MBEDTLS_SELF_TEST) #include "mbedtls/x509_crt.h" #include "mbedtls/certs.h" /* * Checkup routine */ int mbedtls_x509_self_test( int verbose ) { int ret = 0; #if defined(MBEDTLS_CERTS_C) && defined(MBEDTLS_SHA256_C) uint32_t flags; mbedtls_x509_crt cacert; mbedtls_x509_crt clicert; if( verbose != 0 ) mbedtls_printf( " X.509 certificate load: " ); mbedtls_x509_crt_init( &cacert ); mbedtls_x509_crt_init( &clicert ); ret = mbedtls_x509_crt_parse( &clicert, (const unsigned char *) mbedtls_test_cli_crt, mbedtls_test_cli_crt_len ); if( ret != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); goto cleanup; } ret = mbedtls_x509_crt_parse( &cacert, (const unsigned char *) mbedtls_test_ca_crt, mbedtls_test_ca_crt_len ); if( ret != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n X.509 signature verify: "); ret = mbedtls_x509_crt_verify( &clicert, &cacert, NULL, NULL, &flags, NULL, NULL ); if( ret != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n\n"); cleanup: mbedtls_x509_crt_free( &cacert ); mbedtls_x509_crt_free( &clicert ); #else ((void) verbose); #endif /* MBEDTLS_CERTS_C && MBEDTLS_SHA256_C */ return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_X509_USE_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\x509write_crt.c
/* * X.509 certificate writing * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * References: * - certificates: RFC 5280, updated by RFC 6818 * - CSRs: PKCS#10 v1.7 aka RFC 2986 * - attributes: PKCS#9 v2.0 aka RFC 2985 */ #include "common.h" #if defined(MBEDTLS_X509_CRT_WRITE_C) #include "mbedtls/x509_crt.h" #include "mbedtls/asn1write.h" #include "mbedtls/error.h" #include "mbedtls/oid.h" #include "mbedtls/platform_util.h" #include "mbedtls/sha1.h" #include <string.h> #if defined(MBEDTLS_PEM_WRITE_C) #include "mbedtls/pem.h" #endif /* MBEDTLS_PEM_WRITE_C */ void mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx ) { memset( ctx, 0, sizeof( mbedtls_x509write_cert ) ); mbedtls_mpi_init( &ctx->serial ); ctx->version = MBEDTLS_X509_CRT_VERSION_3; } void mbedtls_x509write_crt_free( mbedtls_x509write_cert *ctx ) { mbedtls_mpi_free( &ctx->serial ); mbedtls_asn1_free_named_data_list( &ctx->subject ); mbedtls_asn1_free_named_data_list( &ctx->issuer ); mbedtls_asn1_free_named_data_list( &ctx->extensions ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x509write_cert ) ); } void mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx, int version ) { ctx->version = version; } void mbedtls_x509write_crt_set_md_alg( mbedtls_x509write_cert *ctx, mbedtls_md_type_t md_alg ) { ctx->md_alg = md_alg; } void mbedtls_x509write_crt_set_subject_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key ) { ctx->subject_key = key; } void mbedtls_x509write_crt_set_issuer_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key ) { ctx->issuer_key = key; } int mbedtls_x509write_crt_set_subject_name( mbedtls_x509write_cert *ctx, const char *subject_name ) { return mbedtls_x509_string_to_names( &ctx->subject, subject_name ); } int mbedtls_x509write_crt_set_issuer_name( mbedtls_x509write_cert *ctx, const char *issuer_name ) { return mbedtls_x509_string_to_names( &ctx->issuer, issuer_name ); } int mbedtls_x509write_crt_set_serial( mbedtls_x509write_cert *ctx, const mbedtls_mpi *serial ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ( ret = mbedtls_mpi_copy( &ctx->serial, serial ) ) != 0 ) return( ret ); return( 0 ); } int mbedtls_x509write_crt_set_validity( mbedtls_x509write_cert *ctx, const char *not_before, const char *not_after ) { if( strlen( not_before ) != MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1 || strlen( not_after ) != MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1 ) { return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); } strncpy( ctx->not_before, not_before, MBEDTLS_X509_RFC5280_UTC_TIME_LEN ); strncpy( ctx->not_after , not_after , MBEDTLS_X509_RFC5280_UTC_TIME_LEN ); ctx->not_before[MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1] = 'Z'; ctx->not_after[MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1] = 'Z'; return( 0 ); } int mbedtls_x509write_crt_set_extension( mbedtls_x509write_cert *ctx, const char *oid, size_t oid_len, int critical, const unsigned char *val, size_t val_len ) { return( mbedtls_x509_set_extension( &ctx->extensions, oid, oid_len, critical, val, val_len ) ); } int mbedtls_x509write_crt_set_basic_constraints( mbedtls_x509write_cert *ctx, int is_ca, int max_pathlen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char buf[9]; unsigned char *c = buf + sizeof(buf); size_t len = 0; memset( buf, 0, sizeof(buf) ); if( is_ca && max_pathlen > 127 ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); if( is_ca ) { if( max_pathlen >= 0 ) { MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, max_pathlen ) ); } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_bool( &c, buf, 1 ) ); } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); return( mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_BASIC_CONSTRAINTS, MBEDTLS_OID_SIZE( MBEDTLS_OID_BASIC_CONSTRAINTS ), is_ca, buf + sizeof(buf) - len, len ) ); } #if defined(MBEDTLS_SHA1_C) int mbedtls_x509write_crt_set_subject_key_identifier( mbedtls_x509write_cert *ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char buf[MBEDTLS_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */ unsigned char *c = buf + sizeof(buf); size_t len = 0; memset( buf, 0, sizeof(buf) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_pk_write_pubkey( &c, buf, ctx->subject_key ) ); ret = mbedtls_sha1_ret( buf + sizeof( buf ) - len, len, buf + sizeof( buf ) - 20 ); if( ret != 0 ) return( ret ); c = buf + sizeof( buf ) - 20; len = 20; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_OCTET_STRING ) ); return mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER, MBEDTLS_OID_SIZE( MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER ), 0, buf + sizeof(buf) - len, len ); } int mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert *ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char buf[MBEDTLS_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */ unsigned char *c = buf + sizeof( buf ); size_t len = 0; memset( buf, 0, sizeof(buf) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_pk_write_pubkey( &c, buf, ctx->issuer_key ) ); ret = mbedtls_sha1_ret( buf + sizeof( buf ) - len, len, buf + sizeof( buf ) - 20 ); if( ret != 0 ) return( ret ); c = buf + sizeof( buf ) - 20; len = 20; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 0 ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); return mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER, MBEDTLS_OID_SIZE( MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER ), 0, buf + sizeof( buf ) - len, len ); } #endif /* MBEDTLS_SHA1_C */ int mbedtls_x509write_crt_set_key_usage( mbedtls_x509write_cert *ctx, unsigned int key_usage ) { unsigned char buf[5], ku[2]; unsigned char *c; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const unsigned int allowed_bits = MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_NON_REPUDIATION | MBEDTLS_X509_KU_KEY_ENCIPHERMENT | MBEDTLS_X509_KU_DATA_ENCIPHERMENT | MBEDTLS_X509_KU_KEY_AGREEMENT | MBEDTLS_X509_KU_KEY_CERT_SIGN | MBEDTLS_X509_KU_CRL_SIGN | MBEDTLS_X509_KU_ENCIPHER_ONLY | MBEDTLS_X509_KU_DECIPHER_ONLY; /* Check that nothing other than the allowed flags is set */ if( ( key_usage & ~allowed_bits ) != 0 ) return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ); c = buf + 5; ku[0] = (unsigned char)( key_usage ); ku[1] = (unsigned char)( key_usage >> 8 ); ret = mbedtls_asn1_write_named_bitstring( &c, buf, ku, 9 ); if( ret < 0 ) return( ret ); else if( ret < 3 || ret > 5 ) return( MBEDTLS_ERR_X509_INVALID_FORMAT ); ret = mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_KEY_USAGE, MBEDTLS_OID_SIZE( MBEDTLS_OID_KEY_USAGE ), 1, c, (size_t)ret ); if( ret != 0 ) return( ret ); return( 0 ); } int mbedtls_x509write_crt_set_ns_cert_type( mbedtls_x509write_cert *ctx, unsigned char ns_cert_type ) { unsigned char buf[4]; unsigned char *c; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; c = buf + 4; ret = mbedtls_asn1_write_named_bitstring( &c, buf, &ns_cert_type, 8 ); if( ret < 3 || ret > 4 ) return( ret ); ret = mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_NS_CERT_TYPE, MBEDTLS_OID_SIZE( MBEDTLS_OID_NS_CERT_TYPE ), 0, c, (size_t)ret ); if( ret != 0 ) return( ret ); return( 0 ); } static int x509_write_time( unsigned char **p, unsigned char *start, const char *t, size_t size ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; /* * write MBEDTLS_ASN1_UTC_TIME if year < 2050 (2 bytes shorter) */ if( t[0] == '2' && t[1] == '0' && t[2] < '5' ) { MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, (const unsigned char *) t + 2, size - 2 ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_UTC_TIME ) ); } else { MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, (const unsigned char *) t, size ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_GENERALIZED_TIME ) ); } return( (int) len ); } int mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const char *sig_oid; size_t sig_oid_len = 0; unsigned char *c, *c2; unsigned char hash[64]; unsigned char sig[MBEDTLS_PK_SIGNATURE_MAX_SIZE]; size_t sub_len = 0, pub_len = 0, sig_and_oid_len = 0, sig_len; size_t len = 0; mbedtls_pk_type_t pk_alg; /* * Prepare data to be signed at the end of the target buffer */ c = buf + size; /* Signature algorithm needed in TBS, and later for actual signature */ /* There's no direct way of extracting a signature algorithm * (represented as an element of mbedtls_pk_type_t) from a PK instance. */ if( mbedtls_pk_can_do( ctx->issuer_key, MBEDTLS_PK_RSA ) ) pk_alg = MBEDTLS_PK_RSA; else if( mbedtls_pk_can_do( ctx->issuer_key, MBEDTLS_PK_ECDSA ) ) pk_alg = MBEDTLS_PK_ECDSA; else return( MBEDTLS_ERR_X509_INVALID_ALG ); if( ( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg, &sig_oid, &sig_oid_len ) ) != 0 ) { return( ret ); } /* * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension */ /* Only for v3 */ if( ctx->version == MBEDTLS_X509_CRT_VERSION_3 ) { MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_extensions( &c, buf, ctx->extensions ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 3 ) ); } /* * SubjectPublicKeyInfo */ MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_pk_write_pubkey_der( ctx->subject_key, buf, c - buf ) ); c -= pub_len; len += pub_len; /* * Subject ::= Name */ MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_names( &c, buf, ctx->subject ) ); /* * Validity ::= SEQUENCE { * notBefore Time, * notAfter Time } */ sub_len = 0; MBEDTLS_ASN1_CHK_ADD( sub_len, x509_write_time( &c, buf, ctx->not_after, MBEDTLS_X509_RFC5280_UTC_TIME_LEN ) ); MBEDTLS_ASN1_CHK_ADD( sub_len, x509_write_time( &c, buf, ctx->not_before, MBEDTLS_X509_RFC5280_UTC_TIME_LEN ) ); len += sub_len; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, sub_len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); /* * Issuer ::= Name */ MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_names( &c, buf, ctx->issuer ) ); /* * Signature ::= AlgorithmIdentifier */ MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_algorithm_identifier( &c, buf, sig_oid, strlen( sig_oid ), 0 ) ); /* * Serial ::= INTEGER */ MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf, &ctx->serial ) ); /* * Version ::= INTEGER { v1(0), v2(1), v3(2) } */ /* Can be omitted for v1 */ if( ctx->version != MBEDTLS_X509_CRT_VERSION_1 ) { sub_len = 0; MBEDTLS_ASN1_CHK_ADD( sub_len, mbedtls_asn1_write_int( &c, buf, ctx->version ) ); len += sub_len; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, sub_len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ); } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); /* * Make signature */ /* Compute hash of CRT. */ if( ( ret = mbedtls_md( mbedtls_md_info_from_type( ctx->md_alg ), c, len, hash ) ) != 0 ) { return( ret ); } if( ( ret = mbedtls_pk_sign( ctx->issuer_key, ctx->md_alg, hash, 0, sig, &sig_len, f_rng, p_rng ) ) != 0 ) { return( ret ); } /* Move CRT to the front of the buffer to have space * for the signature. */ memmove( buf, c, len ); c = buf + len; /* Add signature at the end of the buffer, * making sure that it doesn't underflow * into the CRT buffer. */ c2 = buf + size; MBEDTLS_ASN1_CHK_ADD( sig_and_oid_len, mbedtls_x509_write_sig( &c2, c, sig_oid, sig_oid_len, sig, sig_len ) ); /* * Memory layout after this step: * * buf c=buf+len c2 buf+size * [CRT0,...,CRTn, UNUSED, ..., UNUSED, SIG0, ..., SIGm] */ /* Move raw CRT to just before the signature. */ c = c2 - len; memmove( c, buf, len ); len += sig_and_oid_len; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); return( (int) len ); } #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n" #define PEM_END_CRT "-----END CERTIFICATE-----\n" #if defined(MBEDTLS_PEM_WRITE_C) int mbedtls_x509write_crt_pem( mbedtls_x509write_cert *crt, unsigned char *buf, size_t size, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t olen; if( ( ret = mbedtls_x509write_crt_der( crt, buf, size, f_rng, p_rng ) ) < 0 ) { return( ret ); } if( ( ret = mbedtls_pem_write_buffer( PEM_BEGIN_CRT, PEM_END_CRT, buf + size - ret, ret, buf, size, &olen ) ) != 0 ) { return( ret ); } return( 0 ); } #endif /* MBEDTLS_PEM_WRITE_C */ #endif /* MBEDTLS_X509_CRT_WRITE_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\x509write_csr.c
/* * X.509 Certificate Signing Request writing * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * References: * - CSRs: PKCS#10 v1.7 aka RFC 2986 * - attributes: PKCS#9 v2.0 aka RFC 2985 */ #include "common.h" #if defined(MBEDTLS_X509_CSR_WRITE_C) #include "mbedtls/x509_csr.h" #include "mbedtls/asn1write.h" #include "mbedtls/error.h" #include "mbedtls/oid.h" #include "mbedtls/platform_util.h" #if defined(MBEDTLS_USE_PSA_CRYPTO) #include "psa/crypto.h" #include "mbedtls/psa_util.h" #endif #include <string.h> #include <stdlib.h> #if defined(MBEDTLS_PEM_WRITE_C) #include "mbedtls/pem.h" #endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif void mbedtls_x509write_csr_init( mbedtls_x509write_csr *ctx ) { memset( ctx, 0, sizeof( mbedtls_x509write_csr ) ); } void mbedtls_x509write_csr_free( mbedtls_x509write_csr *ctx ) { mbedtls_asn1_free_named_data_list( &ctx->subject ); mbedtls_asn1_free_named_data_list( &ctx->extensions ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x509write_csr ) ); } void mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *ctx, mbedtls_md_type_t md_alg ) { ctx->md_alg = md_alg; } void mbedtls_x509write_csr_set_key( mbedtls_x509write_csr *ctx, mbedtls_pk_context *key ) { ctx->key = key; } int mbedtls_x509write_csr_set_subject_name( mbedtls_x509write_csr *ctx, const char *subject_name ) { return mbedtls_x509_string_to_names( &ctx->subject, subject_name ); } int mbedtls_x509write_csr_set_extension( mbedtls_x509write_csr *ctx, const char *oid, size_t oid_len, const unsigned char *val, size_t val_len ) { return mbedtls_x509_set_extension( &ctx->extensions, oid, oid_len, 0, val, val_len ); } int mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *ctx, unsigned char key_usage ) { unsigned char buf[4]; unsigned char *c; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; c = buf + 4; ret = mbedtls_asn1_write_named_bitstring( &c, buf, &key_usage, 8 ); if( ret < 3 || ret > 4 ) return( ret ); ret = mbedtls_x509write_csr_set_extension( ctx, MBEDTLS_OID_KEY_USAGE, MBEDTLS_OID_SIZE( MBEDTLS_OID_KEY_USAGE ), c, (size_t)ret ); if( ret != 0 ) return( ret ); return( 0 ); } int mbedtls_x509write_csr_set_ns_cert_type( mbedtls_x509write_csr *ctx, unsigned char ns_cert_type ) { unsigned char buf[4]; unsigned char *c; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; c = buf + 4; ret = mbedtls_asn1_write_named_bitstring( &c, buf, &ns_cert_type, 8 ); if( ret < 3 || ret > 4 ) return( ret ); ret = mbedtls_x509write_csr_set_extension( ctx, MBEDTLS_OID_NS_CERT_TYPE, MBEDTLS_OID_SIZE( MBEDTLS_OID_NS_CERT_TYPE ), c, (size_t)ret ); if( ret != 0 ) return( ret ); return( 0 ); } static int x509write_csr_der_internal( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size, unsigned char *sig, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const char *sig_oid; size_t sig_oid_len = 0; unsigned char *c, *c2; unsigned char hash[64]; size_t pub_len = 0, sig_and_oid_len = 0, sig_len; size_t len = 0; mbedtls_pk_type_t pk_alg; #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_hash_operation_t hash_operation = PSA_HASH_OPERATION_INIT; size_t hash_len; psa_algorithm_t hash_alg = mbedtls_psa_translate_md( ctx->md_alg ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ /* Write the CSR backwards starting from the end of buf */ c = buf + size; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_extensions( &c, buf, ctx->extensions ) ); if( len ) { MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( &c, buf, MBEDTLS_OID_PKCS9_CSR_EXT_REQ, MBEDTLS_OID_SIZE( MBEDTLS_OID_PKCS9_CSR_EXT_REQ ) ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ); MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_pk_write_pubkey_der( ctx->key, buf, c - buf ) ); c -= pub_len; len += pub_len; /* * Subject ::= Name */ MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_names( &c, buf, ctx->subject ) ); /* * Version ::= INTEGER { v1(0), v2(1), v3(2) } */ MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 0 ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); /* * Sign the written CSR data into the sig buffer * Note: hash errors can happen only after an internal error */ #if defined(MBEDTLS_USE_PSA_CRYPTO) if( psa_hash_setup( &hash_operation, hash_alg ) != PSA_SUCCESS ) return( MBEDTLS_ERR_X509_FATAL_ERROR ); if( psa_hash_update( &hash_operation, c, len ) != PSA_SUCCESS ) return( MBEDTLS_ERR_X509_FATAL_ERROR ); if( psa_hash_finish( &hash_operation, hash, sizeof( hash ), &hash_len ) != PSA_SUCCESS ) { return( MBEDTLS_ERR_X509_FATAL_ERROR ); } #else /* MBEDTLS_USE_PSA_CRYPTO */ ret = mbedtls_md( mbedtls_md_info_from_type( ctx->md_alg ), c, len, hash ); if( ret != 0 ) return( ret ); #endif if( ( ret = mbedtls_pk_sign( ctx->key, ctx->md_alg, hash, 0, sig, &sig_len, f_rng, p_rng ) ) != 0 ) { return( ret ); } if( mbedtls_pk_can_do( ctx->key, MBEDTLS_PK_RSA ) ) pk_alg = MBEDTLS_PK_RSA; else if( mbedtls_pk_can_do( ctx->key, MBEDTLS_PK_ECDSA ) ) pk_alg = MBEDTLS_PK_ECDSA; else return( MBEDTLS_ERR_X509_INVALID_ALG ); if( ( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg, &sig_oid, &sig_oid_len ) ) != 0 ) { return( ret ); } /* * Move the written CSR data to the start of buf to create space for * writing the signature into buf. */ memmove( buf, c, len ); /* * Write sig and its OID into buf backwards from the end of buf. * Note: mbedtls_x509_write_sig will check for c2 - ( buf + len ) < sig_len * and return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL if needed. */ c2 = buf + size; MBEDTLS_ASN1_CHK_ADD( sig_and_oid_len, mbedtls_x509_write_sig( &c2, buf + len, sig_oid, sig_oid_len, sig, sig_len ) ); /* * Compact the space between the CSR data and signature by moving the * CSR data to the start of the signature. */ c2 -= len; memmove( c2, buf, len ); /* ASN encode the total size and tag the CSR data with it. */ len += sig_and_oid_len; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c2, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c2, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); /* Zero the unused bytes at the start of buf */ memset( buf, 0, c2 - buf); return( (int) len ); } int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret; unsigned char *sig; if( ( sig = mbedtls_calloc( 1, MBEDTLS_PK_SIGNATURE_MAX_SIZE ) ) == NULL ) { return( MBEDTLS_ERR_X509_ALLOC_FAILED ); } ret = x509write_csr_der_internal( ctx, buf, size, sig, f_rng, p_rng ); mbedtls_free( sig ); return( ret ); } #define PEM_BEGIN_CSR "-----BEGIN CERTIFICATE REQUEST-----\n" #define PEM_END_CSR "-----END CERTIFICATE REQUEST-----\n" #if defined(MBEDTLS_PEM_WRITE_C) int mbedtls_x509write_csr_pem( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t olen = 0; if( ( ret = mbedtls_x509write_csr_der( ctx, buf, size, f_rng, p_rng ) ) < 0 ) { return( ret ); } if( ( ret = mbedtls_pem_write_buffer( PEM_BEGIN_CSR, PEM_END_CSR, buf + size - ret, ret, buf, size, &olen ) ) != 0 ) { return( ret ); } return( 0 ); } #endif /* MBEDTLS_PEM_WRITE_C */ #endif /* MBEDTLS_X509_CSR_WRITE_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\x509_create.c
/* * X.509 base functions for creating certificates / CSRs * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #if defined(MBEDTLS_X509_CREATE_C) #include "mbedtls/x509.h" #include "mbedtls/asn1write.h" #include "mbedtls/error.h" #include "mbedtls/oid.h" #include <string.h> /* Structure linking OIDs for X.509 DN AttributeTypes to their * string representations and default string encodings used by Mbed TLS. */ typedef struct { const char *name; /* String representation of AttributeType, e.g. * "CN" or "emailAddress". */ size_t name_len; /* Length of 'name', without trailing 0 byte. */ const char *oid; /* String representation of OID of AttributeType, * as per RFC 5280, Appendix A.1. */ int default_tag; /* The default character encoding used for the * given attribute type, e.g. * MBEDTLS_ASN1_UTF8_STRING for UTF-8. */ } x509_attr_descriptor_t; #define ADD_STRLEN( s ) s, sizeof( s ) - 1 /* X.509 DN attributes from RFC 5280, Appendix A.1. */ static const x509_attr_descriptor_t x509_attrs[] = { { ADD_STRLEN( "CN" ), MBEDTLS_OID_AT_CN, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "commonName" ), MBEDTLS_OID_AT_CN, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "C" ), MBEDTLS_OID_AT_COUNTRY, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "countryName" ), MBEDTLS_OID_AT_COUNTRY, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "O" ), MBEDTLS_OID_AT_ORGANIZATION, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "organizationName" ), MBEDTLS_OID_AT_ORGANIZATION, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "L" ), MBEDTLS_OID_AT_LOCALITY, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "locality" ), MBEDTLS_OID_AT_LOCALITY, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "R" ), MBEDTLS_OID_PKCS9_EMAIL, MBEDTLS_ASN1_IA5_STRING }, { ADD_STRLEN( "OU" ), MBEDTLS_OID_AT_ORG_UNIT, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "organizationalUnitName" ), MBEDTLS_OID_AT_ORG_UNIT, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "ST" ), MBEDTLS_OID_AT_STATE, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "stateOrProvinceName" ), MBEDTLS_OID_AT_STATE, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "emailAddress" ), MBEDTLS_OID_PKCS9_EMAIL, MBEDTLS_ASN1_IA5_STRING }, { ADD_STRLEN( "serialNumber" ), MBEDTLS_OID_AT_SERIAL_NUMBER, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "postalAddress" ), MBEDTLS_OID_AT_POSTAL_ADDRESS, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "postalCode" ), MBEDTLS_OID_AT_POSTAL_CODE, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "dnQualifier" ), MBEDTLS_OID_AT_DN_QUALIFIER, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "title" ), MBEDTLS_OID_AT_TITLE, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "surName" ), MBEDTLS_OID_AT_SUR_NAME, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "SN" ), MBEDTLS_OID_AT_SUR_NAME, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "givenName" ), MBEDTLS_OID_AT_GIVEN_NAME, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "GN" ), MBEDTLS_OID_AT_GIVEN_NAME, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "initials" ), MBEDTLS_OID_AT_INITIALS, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "pseudonym" ), MBEDTLS_OID_AT_PSEUDONYM, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "generationQualifier" ), MBEDTLS_OID_AT_GENERATION_QUALIFIER, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "domainComponent" ), MBEDTLS_OID_DOMAIN_COMPONENT, MBEDTLS_ASN1_IA5_STRING }, { ADD_STRLEN( "DC" ), MBEDTLS_OID_DOMAIN_COMPONENT, MBEDTLS_ASN1_IA5_STRING }, { NULL, 0, NULL, MBEDTLS_ASN1_NULL } }; static const x509_attr_descriptor_t *x509_attr_descr_from_name( const char *name, size_t name_len ) { const x509_attr_descriptor_t *cur; for( cur = x509_attrs; cur->name != NULL; cur++ ) if( cur->name_len == name_len && strncmp( cur->name, name, name_len ) == 0 ) break; if ( cur->name == NULL ) return( NULL ); return( cur ); } int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *name ) { int ret = 0; const char *s = name, *c = s; const char *end = s + strlen( s ); const char *oid = NULL; const x509_attr_descriptor_t* attr_descr = NULL; int in_tag = 1; char data[MBEDTLS_X509_MAX_DN_NAME_SIZE]; char *d = data; /* Clear existing chain if present */ mbedtls_asn1_free_named_data_list( head ); while( c <= end ) { if( in_tag && *c == '=' ) { if( ( attr_descr = x509_attr_descr_from_name( s, c - s ) ) == NULL ) { ret = MBEDTLS_ERR_X509_UNKNOWN_OID; goto exit; } oid = attr_descr->oid; s = c + 1; in_tag = 0; d = data; } if( !in_tag && *c == '\\' && c != end ) { c++; /* Check for valid escaped characters */ if( c == end || *c != ',' ) { ret = MBEDTLS_ERR_X509_INVALID_NAME; goto exit; } } else if( !in_tag && ( *c == ',' || c == end ) ) { mbedtls_asn1_named_data* cur = mbedtls_asn1_store_named_data( head, oid, strlen( oid ), (unsigned char *) data, d - data ); if(cur == NULL ) { return( MBEDTLS_ERR_X509_ALLOC_FAILED ); } // set tagType cur->val.tag = attr_descr->default_tag; while( c < end && *(c + 1) == ' ' ) c++; s = c + 1; in_tag = 1; } if( !in_tag && s != c + 1 ) { *(d++) = *c; if( d - data == MBEDTLS_X509_MAX_DN_NAME_SIZE ) { ret = MBEDTLS_ERR_X509_INVALID_NAME; goto exit; } } c++; } exit: return( ret ); } /* The first byte of the value in the mbedtls_asn1_named_data structure is reserved * to store the critical boolean for us */ int mbedtls_x509_set_extension( mbedtls_asn1_named_data **head, const char *oid, size_t oid_len, int critical, const unsigned char *val, size_t val_len ) { mbedtls_asn1_named_data *cur; if( ( cur = mbedtls_asn1_store_named_data( head, oid, oid_len, NULL, val_len + 1 ) ) == NULL ) { return( MBEDTLS_ERR_X509_ALLOC_FAILED ); } cur->val.p[0] = critical; memcpy( cur->val.p + 1, val, val_len ); return( 0 ); } /* * RelativeDistinguishedName ::= * SET OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type AttributeType, * value AttributeValue } * * AttributeType ::= OBJECT IDENTIFIER * * AttributeValue ::= ANY DEFINED BY AttributeType */ static int x509_write_name( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data* cur_name) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; const char *oid = (const char*)cur_name->oid.p; size_t oid_len = cur_name->oid.len; const unsigned char *name = cur_name->val.p; size_t name_len = cur_name->val.len; // Write correct string tag and value MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tagged_string( p, start, cur_name->val.tag, (const char *) name, name_len ) ); // Write OID // MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, oid_len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ); return( (int) len ); } int mbedtls_x509_write_names( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data *first ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; mbedtls_asn1_named_data *cur = first; while( cur != NULL ) { MBEDTLS_ASN1_CHK_ADD( len, x509_write_name( p, start, cur ) ); cur = cur->next; } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); return( (int) len ); } int mbedtls_x509_write_sig( unsigned char **p, unsigned char *start, const char *oid, size_t oid_len, unsigned char *sig, size_t size ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; if( *p < start || (size_t)( *p - start ) < size ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); len = size; (*p) -= len; memcpy( *p, sig, len ); if( *p - start < 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = 0; len += 1; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BIT_STRING ) ); // Write OID // MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_algorithm_identifier( p, start, oid, oid_len, 0 ) ); return( (int) len ); } static int x509_write_extension( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data *ext ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, ext->val.p + 1, ext->val.len - 1 ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, ext->val.len - 1 ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OCTET_STRING ) ); if( ext->val.p[0] != 0 ) { MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_bool( p, start, 1 ) ); } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, ext->oid.p, ext->oid.len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, ext->oid.len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OID ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); return( (int) len ); } /* * Extension ::= SEQUENCE { * extnID OBJECT IDENTIFIER, * critical BOOLEAN DEFAULT FALSE, * extnValue OCTET STRING * -- contains the DER encoding of an ASN.1 value * -- corresponding to the extension type identified * -- by extnID * } */ int mbedtls_x509_write_extensions( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data *first ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; mbedtls_asn1_named_data *cur_ext = first; while( cur_ext != NULL ) { MBEDTLS_ASN1_CHK_ADD( len, x509_write_extension( p, start, cur_ext ) ); cur_ext = cur_ext->next; } return( (int) len ); } #endif /* MBEDTLS_X509_CREATE_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\x509_crl.c
/* * X.509 Certidicate Revocation List (CRL) parsing * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The ITU-T X.509 standard defines a certificate format for PKI. * * http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs) * http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs) * http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10) * * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf */ #include "common.h" #if defined(MBEDTLS_X509_CRL_PARSE_C) #include "mbedtls/x509_crl.h" #include "mbedtls/error.h" #include "mbedtls/oid.h" #include "mbedtls/platform_util.h" #include <string.h> #if defined(MBEDTLS_PEM_PARSE_C) #include "mbedtls/pem.h" #endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #include <stdio.h> #define mbedtls_free free #define mbedtls_calloc calloc #define mbedtls_snprintf snprintf #endif #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) #include <windows.h> #else #include <time.h> #endif #if defined(MBEDTLS_FS_IO) || defined(EFIX64) || defined(EFI32) #include <stdio.h> #endif /* * Version ::= INTEGER { v1(0), v2(1) } */ static int x509_crl_get_version( unsigned char **p, const unsigned char *end, int *ver ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) { *ver = 0; return( 0 ); } return( MBEDTLS_ERR_X509_INVALID_VERSION + ret ); } return( 0 ); } /* * X.509 CRL v2 extensions * * We currently don't parse any extension's content, but we do check that the * list of extensions is well-formed and abort on critical extensions (that * are unsupported as we don't support any extension so far) */ static int x509_get_crl_ext( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *ext ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( *p == end ) return( 0 ); /* * crlExtensions [0] EXPLICIT Extensions OPTIONAL * -- if present, version MUST be v2 */ if( ( ret = mbedtls_x509_get_ext( p, end, ext, 0 ) ) != 0 ) return( ret ); end = ext->p + ext->len; while( *p < end ) { /* * Extension ::= SEQUENCE { * extnID OBJECT IDENTIFIER, * critical BOOLEAN DEFAULT FALSE, * extnValue OCTET STRING } */ int is_critical = 0; const unsigned char *end_ext_data; size_t len; /* Get enclosing sequence tag */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); end_ext_data = *p + len; /* Get OID (currently ignored) */ if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len, MBEDTLS_ASN1_OID ) ) != 0 ) { return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); } *p += len; /* Get optional critical */ if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 && ( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) ) { return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); } /* Data should be octet string type */ if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); /* Ignore data so far and just check its length */ *p += len; if( *p != end_ext_data ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); /* Abort on (unsupported) critical extensions */ if( is_critical ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); } if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * X.509 CRL v2 entry extensions (no extensions parsed yet.) */ static int x509_get_crl_entry_ext( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *ext ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; /* OPTIONAL */ if( end <= *p ) return( 0 ); ext->tag = **p; ext->p = *p; /* * Get CRL-entry extension sequence header * crlEntryExtensions Extensions OPTIONAL -- if present, MUST be v2 */ if( ( ret = mbedtls_asn1_get_tag( p, end, &ext->len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) { ext->p = NULL; return( 0 ); } return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); } end = *p + ext->len; if( end != *p + ext->len ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); while( *p < end ) { if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); *p += len; } if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * X.509 CRL Entries */ static int x509_get_entries( unsigned char **p, const unsigned char *end, mbedtls_x509_crl_entry *entry ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t entry_len; mbedtls_x509_crl_entry *cur_entry = entry; if( *p == end ) return( 0 ); if( ( ret = mbedtls_asn1_get_tag( p, end, &entry_len, MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) return( 0 ); return( ret ); } end = *p + entry_len; while( *p < end ) { size_t len2; const unsigned char *end2; cur_entry->raw.tag = **p; if( ( ret = mbedtls_asn1_get_tag( p, end, &len2, MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED ) ) != 0 ) { return( ret ); } cur_entry->raw.p = *p; cur_entry->raw.len = len2; end2 = *p + len2; if( ( ret = mbedtls_x509_get_serial( p, end2, &cur_entry->serial ) ) != 0 ) return( ret ); if( ( ret = mbedtls_x509_get_time( p, end2, &cur_entry->revocation_date ) ) != 0 ) return( ret ); if( ( ret = x509_get_crl_entry_ext( p, end2, &cur_entry->entry_ext ) ) != 0 ) return( ret ); if( *p < end ) { cur_entry->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crl_entry ) ); if( cur_entry->next == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); cur_entry = cur_entry->next; } } return( 0 ); } /* * Parse one CRLs in DER format and append it to the chained list */ int mbedtls_x509_crl_parse_der( mbedtls_x509_crl *chain, const unsigned char *buf, size_t buflen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; unsigned char *p = NULL, *end = NULL; mbedtls_x509_buf sig_params1, sig_params2, sig_oid2; mbedtls_x509_crl *crl = chain; /* * Check for valid input */ if( crl == NULL || buf == NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) ); memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) ); memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) ); /* * Add new CRL on the end of the chain if needed. */ while( crl->version != 0 && crl->next != NULL ) crl = crl->next; if( crl->version != 0 && crl->next == NULL ) { crl->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crl ) ); if( crl->next == NULL ) { mbedtls_x509_crl_free( crl ); return( MBEDTLS_ERR_X509_ALLOC_FAILED ); } mbedtls_x509_crl_init( crl->next ); crl = crl->next; } /* * Copy raw DER-encoded CRL */ if( buflen == 0 ) return( MBEDTLS_ERR_X509_INVALID_FORMAT ); p = mbedtls_calloc( 1, buflen ); if( p == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); memcpy( p, buf, buflen ); crl->raw.p = p; crl->raw.len = buflen; end = p + buflen; /* * CertificateList ::= SEQUENCE { * tbsCertList TBSCertList, * signatureAlgorithm AlgorithmIdentifier, * signatureValue BIT STRING } */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crl_free( crl ); return( MBEDTLS_ERR_X509_INVALID_FORMAT ); } if( len != (size_t) ( end - p ) ) { mbedtls_x509_crl_free( crl ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } /* * TBSCertList ::= SEQUENCE { */ crl->tbs.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crl_free( crl ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } end = p + len; crl->tbs.len = end - crl->tbs.p; /* * Version ::= INTEGER OPTIONAL { v1(0), v2(1) } * -- if present, MUST be v2 * * signature AlgorithmIdentifier */ if( ( ret = x509_crl_get_version( &p, end, &crl->version ) ) != 0 || ( ret = mbedtls_x509_get_alg( &p, end, &crl->sig_oid, &sig_params1 ) ) != 0 ) { mbedtls_x509_crl_free( crl ); return( ret ); } if( crl->version < 0 || crl->version > 1 ) { mbedtls_x509_crl_free( crl ); return( MBEDTLS_ERR_X509_UNKNOWN_VERSION ); } crl->version++; if( ( ret = mbedtls_x509_get_sig_alg( &crl->sig_oid, &sig_params1, &crl->sig_md, &crl->sig_pk, &crl->sig_opts ) ) != 0 ) { mbedtls_x509_crl_free( crl ); return( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG ); } /* * issuer Name */ crl->issuer_raw.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crl_free( crl ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } if( ( ret = mbedtls_x509_get_name( &p, p + len, &crl->issuer ) ) != 0 ) { mbedtls_x509_crl_free( crl ); return( ret ); } crl->issuer_raw.len = p - crl->issuer_raw.p; /* * thisUpdate Time * nextUpdate Time OPTIONAL */ if( ( ret = mbedtls_x509_get_time( &p, end, &crl->this_update ) ) != 0 ) { mbedtls_x509_crl_free( crl ); return( ret ); } if( ( ret = mbedtls_x509_get_time( &p, end, &crl->next_update ) ) != 0 ) { if( ret != ( MBEDTLS_ERR_X509_INVALID_DATE + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) && ret != ( MBEDTLS_ERR_X509_INVALID_DATE + MBEDTLS_ERR_ASN1_OUT_OF_DATA ) ) { mbedtls_x509_crl_free( crl ); return( ret ); } } /* * revokedCertificates SEQUENCE OF SEQUENCE { * userCertificate CertificateSerialNumber, * revocationDate Time, * crlEntryExtensions Extensions OPTIONAL * -- if present, MUST be v2 * } OPTIONAL */ if( ( ret = x509_get_entries( &p, end, &crl->entry ) ) != 0 ) { mbedtls_x509_crl_free( crl ); return( ret ); } /* * crlExtensions EXPLICIT Extensions OPTIONAL * -- if present, MUST be v2 */ if( crl->version == 2 ) { ret = x509_get_crl_ext( &p, end, &crl->crl_ext ); if( ret != 0 ) { mbedtls_x509_crl_free( crl ); return( ret ); } } if( p != end ) { mbedtls_x509_crl_free( crl ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } end = crl->raw.p + crl->raw.len; /* * signatureAlgorithm AlgorithmIdentifier, * signatureValue BIT STRING */ if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 ) { mbedtls_x509_crl_free( crl ); return( ret ); } if( crl->sig_oid.len != sig_oid2.len || memcmp( crl->sig_oid.p, sig_oid2.p, crl->sig_oid.len ) != 0 || sig_params1.len != sig_params2.len || ( sig_params1.len != 0 && memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) ) { mbedtls_x509_crl_free( crl ); return( MBEDTLS_ERR_X509_SIG_MISMATCH ); } if( ( ret = mbedtls_x509_get_sig( &p, end, &crl->sig ) ) != 0 ) { mbedtls_x509_crl_free( crl ); return( ret ); } if( p != end ) { mbedtls_x509_crl_free( crl ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } return( 0 ); } /* * Parse one or more CRLs and add them to the chained list */ int mbedtls_x509_crl_parse( mbedtls_x509_crl *chain, const unsigned char *buf, size_t buflen ) { #if defined(MBEDTLS_PEM_PARSE_C) int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t use_len = 0; mbedtls_pem_context pem; int is_pem = 0; if( chain == NULL || buf == NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); do { mbedtls_pem_init( &pem ); // Avoid calling mbedtls_pem_read_buffer() on non-null-terminated // string if( buflen == 0 || buf[buflen - 1] != '\0' ) ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT; else ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN X509 CRL-----", "-----END X509 CRL-----", buf, NULL, 0, &use_len ); if( ret == 0 ) { /* * Was PEM encoded */ is_pem = 1; buflen -= use_len; buf += use_len; if( ( ret = mbedtls_x509_crl_parse_der( chain, pem.buf, pem.buflen ) ) != 0 ) { mbedtls_pem_free( &pem ); return( ret ); } } else if( is_pem ) { mbedtls_pem_free( &pem ); return( ret ); } mbedtls_pem_free( &pem ); } /* In the PEM case, buflen is 1 at the end, for the terminated NULL byte. * And a valid CRL cannot be less than 1 byte anyway. */ while( is_pem && buflen > 1 ); if( is_pem ) return( 0 ); else #endif /* MBEDTLS_PEM_PARSE_C */ return( mbedtls_x509_crl_parse_der( chain, buf, buflen ) ); } #if defined(MBEDTLS_FS_IO) /* * Load one or more CRLs and add them to the chained list */ int mbedtls_x509_crl_parse_file( mbedtls_x509_crl *chain, const char *path ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n; unsigned char *buf; if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 ) return( ret ); ret = mbedtls_x509_crl_parse( chain, buf, n ); mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); } #endif /* MBEDTLS_FS_IO */ /* * Return an informational string about the certificate. */ #define BEFORE_COLON 14 #define BC "14" /* * Return an informational string about the CRL. */ int mbedtls_x509_crl_info( char *buf, size_t size, const char *prefix, const mbedtls_x509_crl *crl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n; char *p; const mbedtls_x509_crl_entry *entry; p = buf; n = size; ret = mbedtls_snprintf( p, n, "%sCRL version : %d", prefix, crl->version ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%sissuer name : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_dn_gets( p, n, &crl->issuer ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%sthis update : " \ "%04d-%02d-%02d %02d:%02d:%02d", prefix, crl->this_update.year, crl->this_update.mon, crl->this_update.day, crl->this_update.hour, crl->this_update.min, crl->this_update.sec ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%snext update : " \ "%04d-%02d-%02d %02d:%02d:%02d", prefix, crl->next_update.year, crl->next_update.mon, crl->next_update.day, crl->next_update.hour, crl->next_update.min, crl->next_update.sec ); MBEDTLS_X509_SAFE_SNPRINTF; entry = &crl->entry; ret = mbedtls_snprintf( p, n, "\n%sRevoked certificates:", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; while( entry != NULL && entry->raw.len != 0 ) { ret = mbedtls_snprintf( p, n, "\n%sserial number: ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_serial_gets( p, n, &entry->serial ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, " revocation date: " \ "%04d-%02d-%02d %02d:%02d:%02d", entry->revocation_date.year, entry->revocation_date.mon, entry->revocation_date.day, entry->revocation_date.hour, entry->revocation_date.min, entry->revocation_date.sec ); MBEDTLS_X509_SAFE_SNPRINTF; entry = entry->next; } ret = mbedtls_snprintf( p, n, "\n%ssigned using : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_sig_alg_gets( p, n, &crl->sig_oid, crl->sig_pk, crl->sig_md, crl->sig_opts ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n" ); MBEDTLS_X509_SAFE_SNPRINTF; return( (int) ( size - n ) ); } /* * Initialize a CRL chain */ void mbedtls_x509_crl_init( mbedtls_x509_crl *crl ) { memset( crl, 0, sizeof(mbedtls_x509_crl) ); } /* * Unallocate all CRL data */ void mbedtls_x509_crl_free( mbedtls_x509_crl *crl ) { mbedtls_x509_crl *crl_cur = crl; mbedtls_x509_crl *crl_prv; mbedtls_x509_name *name_cur; mbedtls_x509_name *name_prv; mbedtls_x509_crl_entry *entry_cur; mbedtls_x509_crl_entry *entry_prv; if( crl == NULL ) return; do { #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) mbedtls_free( crl_cur->sig_opts ); #endif name_cur = crl_cur->issuer.next; while( name_cur != NULL ) { name_prv = name_cur; name_cur = name_cur->next; mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } entry_cur = crl_cur->entry.next; while( entry_cur != NULL ) { entry_prv = entry_cur; entry_cur = entry_cur->next; mbedtls_platform_zeroize( entry_prv, sizeof( mbedtls_x509_crl_entry ) ); mbedtls_free( entry_prv ); } if( crl_cur->raw.p != NULL ) { mbedtls_platform_zeroize( crl_cur->raw.p, crl_cur->raw.len ); mbedtls_free( crl_cur->raw.p ); } crl_cur = crl_cur->next; } while( crl_cur != NULL ); crl_cur = crl; do { crl_prv = crl_cur; crl_cur = crl_cur->next; mbedtls_platform_zeroize( crl_prv, sizeof( mbedtls_x509_crl ) ); if( crl_prv != crl ) mbedtls_free( crl_prv ); } while( crl_cur != NULL ); } #endif /* MBEDTLS_X509_CRL_PARSE_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\x509_crt.c
/* * X.509 certificate parsing and verification * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The ITU-T X.509 standard defines a certificate format for PKI. * * http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs) * http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs) * http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10) * * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf * * [SIRO] https://cabforum.org/wp-content/uploads/Chunghwatelecom201503cabforumV4.pdf */ #include "common.h" #if defined(MBEDTLS_X509_CRT_PARSE_C) #include "mbedtls/x509_crt.h" #include "mbedtls/error.h" #include "mbedtls/oid.h" #include "mbedtls/platform_util.h" #include <string.h> #if defined(MBEDTLS_PEM_PARSE_C) #include "mbedtls/pem.h" #endif #if defined(MBEDTLS_USE_PSA_CRYPTO) #include "psa/crypto.h" #include "mbedtls/psa_util.h" #endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #include <stdlib.h> #define mbedtls_free free #define mbedtls_calloc calloc #define mbedtls_snprintf snprintf #endif #if defined(MBEDTLS_THREADING_C) #include "mbedtls/threading.h" #endif #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) #include <windows.h> #else #include <time.h> #endif #if defined(MBEDTLS_FS_IO) #include <stdio.h> #if !defined(_WIN32) || defined(EFIX64) || defined(EFI32) #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #endif /* !_WIN32 || EFIX64 || EFI32 */ #endif /* * Item in a verification chain: cert and flags for it */ typedef struct { mbedtls_x509_crt *crt; uint32_t flags; } x509_crt_verify_chain_item; /* * Max size of verification chain: end-entity + intermediates + trusted root */ #define X509_MAX_VERIFY_CHAIN_SIZE ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 ) /* * Default profile */ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default = { #if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES) /* Allow SHA-1 (weak, but still safe in controlled environments) */ MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) | #endif /* Only SHA-2 hashes */ MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ), 0xFFFFFFF, /* Any PK alg */ 0xFFFFFFF, /* Any curve */ 2048, }; /* * Next-default profile */ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next = { /* Hashes from SHA-256 and above */ MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ), 0xFFFFFFF, /* Any PK alg */ #if defined(MBEDTLS_ECP_C) /* Curves at or above 128-bit security level */ MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ), #else 0, #endif 2048, }; /* * NSA Suite B Profile */ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb = { /* Only SHA-256 and 384 */ MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ), /* Only ECDSA */ MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECKEY ), #if defined(MBEDTLS_ECP_C) /* Only NIST P-256 and P-384 */ MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ), #else 0, #endif 0, }; /* * Check md_alg against profile * Return 0 if md_alg is acceptable for this profile, -1 otherwise */ static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile, mbedtls_md_type_t md_alg ) { if( md_alg == MBEDTLS_MD_NONE ) return( -1 ); if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 ) return( 0 ); return( -1 ); } /* * Check pk_alg against profile * Return 0 if pk_alg is acceptable for this profile, -1 otherwise */ static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile, mbedtls_pk_type_t pk_alg ) { if( pk_alg == MBEDTLS_PK_NONE ) return( -1 ); if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 ) return( 0 ); return( -1 ); } /* * Check key against profile * Return 0 if pk is acceptable for this profile, -1 otherwise */ static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile, const mbedtls_pk_context *pk ) { const mbedtls_pk_type_t pk_alg = mbedtls_pk_get_type( pk ); #if defined(MBEDTLS_RSA_C) if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS ) { if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen ) return( 0 ); return( -1 ); } #endif #if defined(MBEDTLS_ECP_C) if( pk_alg == MBEDTLS_PK_ECDSA || pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH ) { const mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id; if( gid == MBEDTLS_ECP_DP_NONE ) return( -1 ); if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 ) return( 0 ); return( -1 ); } #endif return( -1 ); } /* * Like memcmp, but case-insensitive and always returns -1 if different */ static int x509_memcasecmp( const void *s1, const void *s2, size_t len ) { size_t i; unsigned char diff; const unsigned char *n1 = s1, *n2 = s2; for( i = 0; i < len; i++ ) { diff = n1[i] ^ n2[i]; if( diff == 0 ) continue; if( diff == 32 && ( ( n1[i] >= 'a' && n1[i] <= 'z' ) || ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) ) { continue; } return( -1 ); } return( 0 ); } /* * Return 0 if name matches wildcard, -1 otherwise */ static int x509_check_wildcard( const char *cn, const mbedtls_x509_buf *name ) { size_t i; size_t cn_idx = 0, cn_len = strlen( cn ); /* We can't have a match if there is no wildcard to match */ if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' ) return( -1 ); for( i = 0; i < cn_len; ++i ) { if( cn[i] == '.' ) { cn_idx = i; break; } } if( cn_idx == 0 ) return( -1 ); if( cn_len - cn_idx == name->len - 1 && x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 ) { return( 0 ); } return( -1 ); } /* * Compare two X.509 strings, case-insensitive, and allowing for some encoding * variations (but not all). * * Return 0 if equal, -1 otherwise. */ static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b ) { if( a->tag == b->tag && a->len == b->len && memcmp( a->p, b->p, b->len ) == 0 ) { return( 0 ); } if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) && ( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) && a->len == b->len && x509_memcasecmp( a->p, b->p, b->len ) == 0 ) { return( 0 ); } return( -1 ); } /* * Compare two X.509 Names (aka rdnSequence). * * See RFC 5280 section 7.1, though we don't implement the whole algorithm: * we sometimes return unequal when the full algorithm would return equal, * but never the other way. (In particular, we don't do Unicode normalisation * or space folding.) * * Return 0 if equal, -1 otherwise. */ static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b ) { /* Avoid recursion, it might not be optimised by the compiler */ while( a != NULL || b != NULL ) { if( a == NULL || b == NULL ) return( -1 ); /* type */ if( a->oid.tag != b->oid.tag || a->oid.len != b->oid.len || memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 ) { return( -1 ); } /* value */ if( x509_string_cmp( &a->val, &b->val ) != 0 ) return( -1 ); /* structure of the list of sets */ if( a->next_merged != b->next_merged ) return( -1 ); a = a->next; b = b->next; } /* a == NULL == b */ return( 0 ); } /* * Reset (init or clear) a verify_chain */ static void x509_crt_verify_chain_reset( mbedtls_x509_crt_verify_chain *ver_chain ) { size_t i; for( i = 0; i < MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE; i++ ) { ver_chain->items[i].crt = NULL; ver_chain->items[i].flags = (uint32_t) -1; } ver_chain->len = 0; #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) ver_chain->trust_ca_cb_result = NULL; #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ } /* * Version ::= INTEGER { v1(0), v2(1), v3(2) } */ static int x509_get_version( unsigned char **p, const unsigned char *end, int *ver ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) { *ver = 0; return( 0 ); } return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } end = *p + len; if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_VERSION + ret ); if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_VERSION + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * Validity ::= SEQUENCE { * notBefore Time, * notAfter Time } */ static int x509_get_dates( unsigned char **p, const unsigned char *end, mbedtls_x509_time *from, mbedtls_x509_time *to ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_DATE + ret ); end = *p + len; if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 ) return( ret ); if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 ) return( ret ); if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_DATE + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * X.509 v2/v3 unique identifier (not parsed) */ static int x509_get_uid( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *uid, int n ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( *p == end ) return( 0 ); uid->tag = **p; if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) return( 0 ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } uid->p = *p; *p += uid->len; return( 0 ); } static int x509_get_basic_constraints( unsigned char **p, const unsigned char *end, int *ca_istrue, int *max_pathlen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; /* * BasicConstraints ::= SEQUENCE { * cA BOOLEAN DEFAULT FALSE, * pathLenConstraint INTEGER (0..MAX) OPTIONAL } */ *ca_istrue = 0; /* DEFAULT FALSE */ *max_pathlen = 0; /* endless */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( *p == end ) return( 0 ); if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) ret = mbedtls_asn1_get_int( p, end, ca_istrue ); if( ret != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( *ca_istrue != 0 ) *ca_istrue = 1; } if( *p == end ) return( 0 ); if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); /* Do not accept max_pathlen equal to INT_MAX to avoid a signed integer * overflow, which is an undefined behavior. */ if( *max_pathlen == INT_MAX ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_INVALID_LENGTH ); (*max_pathlen)++; return( 0 ); } static int x509_get_ns_cert_type( unsigned char **p, const unsigned char *end, unsigned char *ns_cert_type) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_x509_bitstring bs = { 0, 0, NULL }; if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( bs.len != 1 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_INVALID_LENGTH ); /* Get actual bitstring */ *ns_cert_type = *bs.p; return( 0 ); } static int x509_get_key_usage( unsigned char **p, const unsigned char *end, unsigned int *key_usage) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t i; mbedtls_x509_bitstring bs = { 0, 0, NULL }; if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( bs.len < 1 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_INVALID_LENGTH ); /* Get actual bitstring */ *key_usage = 0; for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ ) { *key_usage |= (unsigned int) bs.p[i] << (8*i); } return( 0 ); } /* * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId * * KeyPurposeId ::= OBJECT IDENTIFIER */ static int x509_get_ext_key_usage( unsigned char **p, const unsigned char *end, mbedtls_x509_sequence *ext_key_usage) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); /* Sequence length must be >= 1 */ if( ext_key_usage->buf.p == NULL ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_INVALID_LENGTH ); return( 0 ); } /* * SubjectAltName ::= GeneralNames * * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName * * GeneralName ::= CHOICE { * otherName [0] OtherName, * rfc822Name [1] IA5String, * dNSName [2] IA5String, * x400Address [3] ORAddress, * directoryName [4] Name, * ediPartyName [5] EDIPartyName, * uniformResourceIdentifier [6] IA5String, * iPAddress [7] OCTET STRING, * registeredID [8] OBJECT IDENTIFIER } * * OtherName ::= SEQUENCE { * type-id OBJECT IDENTIFIER, * value [0] EXPLICIT ANY DEFINED BY type-id } * * EDIPartyName ::= SEQUENCE { * nameAssigner [0] DirectoryString OPTIONAL, * partyName [1] DirectoryString } * * NOTE: we list all types, but only use dNSName and otherName * of type HwModuleName, as defined in RFC 4108, at this point. */ static int x509_get_subject_alt_name( unsigned char **p, const unsigned char *end, mbedtls_x509_sequence *subject_alt_name ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len, tag_len; mbedtls_asn1_buf *buf; unsigned char tag; mbedtls_asn1_sequence *cur = subject_alt_name; /* Get main sequence tag */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( *p + len != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); while( *p < end ) { mbedtls_x509_subject_alternative_name dummy_san_buf; memset( &dummy_san_buf, 0, sizeof( dummy_san_buf ) ); tag = **p; (*p)++; if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( ( tag & MBEDTLS_ASN1_TAG_CLASS_MASK ) != MBEDTLS_ASN1_CONTEXT_SPECIFIC ) { return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); } /* * Check that the SAN is structured correctly. */ ret = mbedtls_x509_parse_subject_alt_name( &(cur->buf), &dummy_san_buf ); /* * In case the extension is malformed, return an error, * and clear the allocated sequences. */ if( ret != 0 && ret != MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ) { mbedtls_x509_sequence *seq_cur = subject_alt_name->next; mbedtls_x509_sequence *seq_prv; while( seq_cur != NULL ) { seq_prv = seq_cur; seq_cur = seq_cur->next; mbedtls_platform_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) ); mbedtls_free( seq_prv ); } subject_alt_name->next = NULL; return( ret ); } /* Allocate and assign next pointer */ if( cur->buf.p != NULL ) { if( cur->next != NULL ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS ); cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) ); if( cur->next == NULL ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_ALLOC_FAILED ); cur = cur->next; } buf = &(cur->buf); buf->tag = tag; buf->p = *p; buf->len = tag_len; *p += buf->len; } /* Set final sequence entry's next pointer to NULL */ cur->next = NULL; if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 } * * anyPolicy OBJECT IDENTIFIER ::= { id-ce-certificatePolicies 0 } * * certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation * * PolicyInformation ::= SEQUENCE { * policyIdentifier CertPolicyId, * policyQualifiers SEQUENCE SIZE (1..MAX) OF * PolicyQualifierInfo OPTIONAL } * * CertPolicyId ::= OBJECT IDENTIFIER * * PolicyQualifierInfo ::= SEQUENCE { * policyQualifierId PolicyQualifierId, * qualifier ANY DEFINED BY policyQualifierId } * * -- policyQualifierIds for Internet policy qualifiers * * id-qt OBJECT IDENTIFIER ::= { id-pkix 2 } * id-qt-cps OBJECT IDENTIFIER ::= { id-qt 1 } * id-qt-unotice OBJECT IDENTIFIER ::= { id-qt 2 } * * PolicyQualifierId ::= OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice ) * * Qualifier ::= CHOICE { * cPSuri CPSuri, * userNotice UserNotice } * * CPSuri ::= IA5String * * UserNotice ::= SEQUENCE { * noticeRef NoticeReference OPTIONAL, * explicitText DisplayText OPTIONAL } * * NoticeReference ::= SEQUENCE { * organization DisplayText, * noticeNumbers SEQUENCE OF INTEGER } * * DisplayText ::= CHOICE { * ia5String IA5String (SIZE (1..200)), * visibleString VisibleString (SIZE (1..200)), * bmpString BMPString (SIZE (1..200)), * utf8String UTF8String (SIZE (1..200)) } * * NOTE: we only parse and use anyPolicy without qualifiers at this point * as defined in RFC 5280. */ static int x509_get_certificate_policies( unsigned char **p, const unsigned char *end, mbedtls_x509_sequence *certificate_policies ) { int ret, parse_ret = 0; size_t len; mbedtls_asn1_buf *buf; mbedtls_asn1_sequence *cur = certificate_policies; /* Get main sequence tag */ ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ); if( ret != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( *p + len != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); /* * Cannot be an empty sequence. */ if( len == 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); while( *p < end ) { mbedtls_x509_buf policy_oid; const unsigned char *policy_end; /* * Get the policy sequence */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); policy_end = *p + len; if( ( ret = mbedtls_asn1_get_tag( p, policy_end, &len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); policy_oid.tag = MBEDTLS_ASN1_OID; policy_oid.len = len; policy_oid.p = *p; /* * Only AnyPolicy is currently supported when enforcing policy. */ if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_POLICY, &policy_oid ) != 0 ) { /* * Set the parsing return code but continue parsing, in case this * extension is critical and MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION * is configured. */ parse_ret = MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE; } /* Allocate and assign next pointer */ if( cur->buf.p != NULL ) { if( cur->next != NULL ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS ); cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) ); if( cur->next == NULL ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_ALLOC_FAILED ); cur = cur->next; } buf = &( cur->buf ); buf->tag = policy_oid.tag; buf->p = policy_oid.p; buf->len = policy_oid.len; *p += len; /* * If there is an optional qualifier, then *p < policy_end * Check the Qualifier len to verify it doesn't exceed policy_end. */ if( *p < policy_end ) { if( ( ret = mbedtls_asn1_get_tag( p, policy_end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); /* * Skip the optional policy qualifiers. */ *p += len; } if( *p != policy_end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } /* Set final sequence entry's next pointer to NULL */ cur->next = NULL; if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( parse_ret ); } /* * X.509 v3 extensions * */ static int x509_get_crt_ext( unsigned char **p, const unsigned char *end, mbedtls_x509_crt *crt, mbedtls_x509_crt_ext_cb_t cb, void *p_ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; unsigned char *end_ext_data, *start_ext_octet, *end_ext_octet; if( *p == end ) return( 0 ); if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 ) return( ret ); end = crt->v3_ext.p + crt->v3_ext.len; while( *p < end ) { /* * Extension ::= SEQUENCE { * extnID OBJECT IDENTIFIER, * critical BOOLEAN DEFAULT FALSE, * extnValue OCTET STRING } */ mbedtls_x509_buf extn_oid = {0, 0, NULL}; int is_critical = 0; /* DEFAULT FALSE */ int ext_type = 0; if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); end_ext_data = *p + len; /* Get extension ID */ if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &extn_oid.len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); extn_oid.tag = MBEDTLS_ASN1_OID; extn_oid.p = *p; *p += extn_oid.len; /* Get optional critical */ if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 && ( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); /* Data should be octet string type */ if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); start_ext_octet = *p; end_ext_octet = *p + len; if( end_ext_octet != end_ext_data ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); /* * Detect supported extensions */ ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type ); if( ret != 0 ) { /* Give the callback (if any) a chance to handle the extension */ if( cb != NULL ) { ret = cb( p_ctx, crt, &extn_oid, is_critical, *p, end_ext_octet ); if( ret != 0 && is_critical ) return( ret ); *p = end_ext_octet; continue; } /* No parser found, skip extension */ *p = end_ext_octet; #if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION) if( is_critical ) { /* Data is marked as critical: fail */ return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); } #endif continue; } /* Forbid repeated extensions */ if( ( crt->ext_types & ext_type ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS ); crt->ext_types |= ext_type; switch( ext_type ) { case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS: /* Parse basic constraints */ if( ( ret = x509_get_basic_constraints( p, end_ext_octet, &crt->ca_istrue, &crt->max_pathlen ) ) != 0 ) return( ret ); break; case MBEDTLS_X509_EXT_KEY_USAGE: /* Parse key usage */ if( ( ret = x509_get_key_usage( p, end_ext_octet, &crt->key_usage ) ) != 0 ) return( ret ); break; case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE: /* Parse extended key usage */ if( ( ret = x509_get_ext_key_usage( p, end_ext_octet, &crt->ext_key_usage ) ) != 0 ) return( ret ); break; case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME: /* Parse subject alt name */ if( ( ret = x509_get_subject_alt_name( p, end_ext_octet, &crt->subject_alt_names ) ) != 0 ) return( ret ); break; case MBEDTLS_X509_EXT_NS_CERT_TYPE: /* Parse netscape certificate type */ if( ( ret = x509_get_ns_cert_type( p, end_ext_octet, &crt->ns_cert_type ) ) != 0 ) return( ret ); break; case MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES: /* Parse certificate policies type */ if( ( ret = x509_get_certificate_policies( p, end_ext_octet, &crt->certificate_policies ) ) != 0 ) { /* Give the callback (if any) a chance to handle the extension * if it contains unsupported policies */ if( ret == MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE && cb != NULL && cb( p_ctx, crt, &extn_oid, is_critical, start_ext_octet, end_ext_octet ) == 0 ) break; #if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION) if( is_critical ) return( ret ); else #endif /* * If MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE is returned, then we * cannot interpret or enforce the policy. However, it is up to * the user to choose how to enforce the policies, * unless the extension is critical. */ if( ret != MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ) return( ret ); } break; default: /* * If this is a non-critical extension, which the oid layer * supports, but there isn't an x509 parser for it, * skip the extension. */ #if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION) if( is_critical ) return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ); else #endif *p = end_ext_octet; } } if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * Parse and fill a single X.509 certificate in DER format */ static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf, size_t buflen, int make_copy, mbedtls_x509_crt_ext_cb_t cb, void *p_ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; unsigned char *p, *end, *crt_end; mbedtls_x509_buf sig_params1, sig_params2, sig_oid2; memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) ); memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) ); memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) ); /* * Check for valid input */ if( crt == NULL || buf == NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); /* Use the original buffer until we figure out actual length. */ p = (unsigned char*) buf; len = buflen; end = p + len; /* * Certificate ::= SEQUENCE { * tbsCertificate TBSCertificate, * signatureAlgorithm AlgorithmIdentifier, * signatureValue BIT STRING } */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT ); } end = crt_end = p + len; crt->raw.len = crt_end - buf; if( make_copy != 0 ) { /* Create and populate a new buffer for the raw field. */ crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len ); if( crt->raw.p == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); memcpy( crt->raw.p, buf, crt->raw.len ); crt->own_buffer = 1; p += crt->raw.len - len; end = crt_end = p + len; } else { crt->raw.p = (unsigned char*) buf; crt->own_buffer = 0; } /* * TBSCertificate ::= SEQUENCE { */ crt->tbs.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } end = p + len; crt->tbs.len = end - crt->tbs.p; /* * Version ::= INTEGER { v1(0), v2(1), v3(2) } * * CertificateSerialNumber ::= INTEGER * * signature AlgorithmIdentifier */ if( ( ret = x509_get_version( &p, end, &crt->version ) ) != 0 || ( ret = mbedtls_x509_get_serial( &p, end, &crt->serial ) ) != 0 || ( ret = mbedtls_x509_get_alg( &p, end, &crt->sig_oid, &sig_params1 ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } if( crt->version < 0 || crt->version > 2 ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_UNKNOWN_VERSION ); } crt->version++; if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1, &crt->sig_md, &crt->sig_pk, &crt->sig_opts ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } /* * issuer Name */ crt->issuer_raw.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } crt->issuer_raw.len = p - crt->issuer_raw.p; /* * Validity ::= SEQUENCE { * notBefore Time, * notAfter Time } * */ if( ( ret = x509_get_dates( &p, end, &crt->valid_from, &crt->valid_to ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } /* * subject Name */ crt->subject_raw.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } crt->subject_raw.len = p - crt->subject_raw.p; /* * SubjectPublicKeyInfo */ crt->pk_raw.p = p; if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } crt->pk_raw.len = p - crt->pk_raw.p; /* * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, * -- If present, version shall be v2 or v3 * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, * -- If present, version shall be v2 or v3 * extensions [3] EXPLICIT Extensions OPTIONAL * -- If present, version shall be v3 */ if( crt->version == 2 || crt->version == 3 ) { ret = x509_get_uid( &p, end, &crt->issuer_id, 1 ); if( ret != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } } if( crt->version == 2 || crt->version == 3 ) { ret = x509_get_uid( &p, end, &crt->subject_id, 2 ); if( ret != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } } #if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3) if( crt->version == 3 ) #endif { ret = x509_get_crt_ext( &p, end, crt, cb, p_ctx ); if( ret != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } } if( p != end ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } end = crt_end; /* * } * -- end of TBSCertificate * * signatureAlgorithm AlgorithmIdentifier, * signatureValue BIT STRING */ if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } if( crt->sig_oid.len != sig_oid2.len || memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 || sig_params1.tag != sig_params2.tag || sig_params1.len != sig_params2.len || ( sig_params1.len != 0 && memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_SIG_MISMATCH ); } if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } if( p != end ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } return( 0 ); } /* * Parse one X.509 certificate in DER format from a buffer and add them to a * chained list */ static int mbedtls_x509_crt_parse_der_internal( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen, int make_copy, mbedtls_x509_crt_ext_cb_t cb, void *p_ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_x509_crt *crt = chain, *prev = NULL; /* * Check for valid input */ if( crt == NULL || buf == NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); while( crt->version != 0 && crt->next != NULL ) { prev = crt; crt = crt->next; } /* * Add new certificate on the end of the chain if needed. */ if( crt->version != 0 && crt->next == NULL ) { crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) ); if( crt->next == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); prev = crt; mbedtls_x509_crt_init( crt->next ); crt = crt->next; } ret = x509_crt_parse_der_core( crt, buf, buflen, make_copy, cb, p_ctx ); if( ret != 0 ) { if( prev ) prev->next = NULL; if( crt != chain ) mbedtls_free( crt ); return( ret ); } return( 0 ); } int mbedtls_x509_crt_parse_der_nocopy( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen ) { return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, 0, NULL, NULL ) ); } int mbedtls_x509_crt_parse_der_with_ext_cb( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen, int make_copy, mbedtls_x509_crt_ext_cb_t cb, void *p_ctx ) { return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, make_copy, cb, p_ctx ) ); } int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen ) { return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, 1, NULL, NULL ) ); } /* * Parse one or more PEM certificates from a buffer and add them to the chained * list */ int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen ) { #if defined(MBEDTLS_PEM_PARSE_C) int success = 0, first_error = 0, total_failed = 0; int buf_format = MBEDTLS_X509_FORMAT_DER; #endif /* * Check for valid input */ if( chain == NULL || buf == NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); /* * Determine buffer content. Buffer contains either one DER certificate or * one or more PEM certificates. */ #if defined(MBEDTLS_PEM_PARSE_C) if( buflen != 0 && buf[buflen - 1] == '\0' && strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL ) { buf_format = MBEDTLS_X509_FORMAT_PEM; } if( buf_format == MBEDTLS_X509_FORMAT_DER ) return mbedtls_x509_crt_parse_der( chain, buf, buflen ); #else return mbedtls_x509_crt_parse_der( chain, buf, buflen ); #endif #if defined(MBEDTLS_PEM_PARSE_C) if( buf_format == MBEDTLS_X509_FORMAT_PEM ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_pem_context pem; /* 1 rather than 0 since the terminating NULL byte is counted in */ while( buflen > 1 ) { size_t use_len; mbedtls_pem_init( &pem ); /* If we get there, we know the string is null-terminated */ ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----", buf, NULL, 0, &use_len ); if( ret == 0 ) { /* * Was PEM encoded */ buflen -= use_len; buf += use_len; } else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA ) { return( ret ); } else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) { mbedtls_pem_free( &pem ); /* * PEM header and footer were found */ buflen -= use_len; buf += use_len; if( first_error == 0 ) first_error = ret; total_failed++; continue; } else break; ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen ); mbedtls_pem_free( &pem ); if( ret != 0 ) { /* * Quit parsing on a memory error */ if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED ) return( ret ); if( first_error == 0 ) first_error = ret; total_failed++; continue; } success = 1; } } if( success ) return( total_failed ); else if( first_error ) return( first_error ); else return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT ); #endif /* MBEDTLS_PEM_PARSE_C */ } #if defined(MBEDTLS_FS_IO) /* * Load one or more certificates and add them to the chained list */ int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n; unsigned char *buf; if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 ) return( ret ); ret = mbedtls_x509_crt_parse( chain, buf, n ); mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); } int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path ) { int ret = 0; #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) int w_ret; WCHAR szDir[MAX_PATH]; char filename[MAX_PATH]; char *p; size_t len = strlen( path ); WIN32_FIND_DATAW file_data; HANDLE hFind; if( len > MAX_PATH - 3 ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); memset( szDir, 0, sizeof(szDir) ); memset( filename, 0, MAX_PATH ); memcpy( filename, path, len ); filename[len++] = '\\'; p = filename + len; filename[len++] = '*'; w_ret = MultiByteToWideChar( CP_ACP, 0, filename, (int)len, szDir, MAX_PATH - 3 ); if( w_ret == 0 ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); hFind = FindFirstFileW( szDir, &file_data ); if( hFind == INVALID_HANDLE_VALUE ) return( MBEDTLS_ERR_X509_FILE_IO_ERROR ); len = MAX_PATH - len; do { memset( p, 0, len ); if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) continue; w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName, lstrlenW( file_data.cFileName ), p, (int) len - 1, NULL, NULL ); if( w_ret == 0 ) { ret = MBEDTLS_ERR_X509_FILE_IO_ERROR; goto cleanup; } w_ret = mbedtls_x509_crt_parse_file( chain, filename ); if( w_ret < 0 ) ret++; else ret += w_ret; } while( FindNextFileW( hFind, &file_data ) != 0 ); if( GetLastError() != ERROR_NO_MORE_FILES ) ret = MBEDTLS_ERR_X509_FILE_IO_ERROR; cleanup: FindClose( hFind ); #else /* _WIN32 */ int t_ret; int snp_ret; struct stat sb; struct dirent *entry; char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN]; DIR *dir = opendir( path ); if( dir == NULL ) return( MBEDTLS_ERR_X509_FILE_IO_ERROR ); #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 ) { closedir( dir ); return( ret ); } #endif /* MBEDTLS_THREADING_C */ while( ( entry = readdir( dir ) ) != NULL ) { snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name, "%s/%s", path, entry->d_name ); if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name ) { ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL; goto cleanup; } else if( stat( entry_name, &sb ) == -1 ) { ret = MBEDTLS_ERR_X509_FILE_IO_ERROR; goto cleanup; } if( !S_ISREG( sb.st_mode ) ) continue; // Ignore parse errors // t_ret = mbedtls_x509_crt_parse_file( chain, entry_name ); if( t_ret < 0 ) ret++; else ret += t_ret; } cleanup: closedir( dir ); #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 ) ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR; #endif /* MBEDTLS_THREADING_C */ #endif /* _WIN32 */ return( ret ); } #endif /* MBEDTLS_FS_IO */ /* * OtherName ::= SEQUENCE { * type-id OBJECT IDENTIFIER, * value [0] EXPLICIT ANY DEFINED BY type-id } * * HardwareModuleName ::= SEQUENCE { * hwType OBJECT IDENTIFIER, * hwSerialNum OCTET STRING } * * NOTE: we currently only parse and use otherName of type HwModuleName, * as defined in RFC 4108. */ static int x509_get_other_name( const mbedtls_x509_buf *subject_alt_name, mbedtls_x509_san_other_name *other_name ) { int ret = 0; size_t len; unsigned char *p = subject_alt_name->p; const unsigned char *end = p + subject_alt_name->len; mbedtls_x509_buf cur_oid; if( ( subject_alt_name->tag & ( MBEDTLS_ASN1_TAG_CLASS_MASK | MBEDTLS_ASN1_TAG_VALUE_MASK ) ) != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_OTHER_NAME ) ) { /* * The given subject alternative name is not of type "othername". */ return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); } if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); cur_oid.tag = MBEDTLS_ASN1_OID; cur_oid.p = p; cur_oid.len = len; /* * Only HwModuleName is currently supported. */ if( MBEDTLS_OID_CMP( MBEDTLS_OID_ON_HW_MODULE_NAME, &cur_oid ) != 0 ) { return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ); } if( p + len >= end ) { mbedtls_platform_zeroize( other_name, sizeof( *other_name ) ); return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } p += len; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); other_name->value.hardware_module_name.oid.tag = MBEDTLS_ASN1_OID; other_name->value.hardware_module_name.oid.p = p; other_name->value.hardware_module_name.oid.len = len; if( p + len >= end ) { mbedtls_platform_zeroize( other_name, sizeof( *other_name ) ); return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } p += len; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); other_name->value.hardware_module_name.val.tag = MBEDTLS_ASN1_OCTET_STRING; other_name->value.hardware_module_name.val.p = p; other_name->value.hardware_module_name.val.len = len; p += len; if( p != end ) { mbedtls_platform_zeroize( other_name, sizeof( *other_name ) ); return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } return( 0 ); } static int x509_info_subject_alt_name( char **buf, size_t *size, const mbedtls_x509_sequence *subject_alt_name, const char *prefix ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n = *size; char *p = *buf; const mbedtls_x509_sequence *cur = subject_alt_name; mbedtls_x509_subject_alternative_name san; int parse_ret; while( cur != NULL ) { memset( &san, 0, sizeof( san ) ); parse_ret = mbedtls_x509_parse_subject_alt_name( &cur->buf, &san ); if( parse_ret != 0 ) { if( parse_ret == MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ) { ret = mbedtls_snprintf( p, n, "\n%s <unsupported>", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; } else { ret = mbedtls_snprintf( p, n, "\n%s <malformed>", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; } cur = cur->next; continue; } switch( san.type ) { /* * otherName */ case MBEDTLS_X509_SAN_OTHER_NAME: { mbedtls_x509_san_other_name *other_name = &san.san.other_name; ret = mbedtls_snprintf( p, n, "\n%s otherName :", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( MBEDTLS_OID_CMP( MBEDTLS_OID_ON_HW_MODULE_NAME, &other_name->value.hardware_module_name.oid ) != 0 ) { ret = mbedtls_snprintf( p, n, "\n%s hardware module name :", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%s hardware type : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_oid_get_numeric_string( p, n, &other_name->value.hardware_module_name.oid ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%s hardware serial number : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( other_name->value.hardware_module_name.val.len >= n ) { *p = '\0'; return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL ); } memcpy( p, other_name->value.hardware_module_name.val.p, other_name->value.hardware_module_name.val.len ); p += other_name->value.hardware_module_name.val.len; n -= other_name->value.hardware_module_name.val.len; }/* MBEDTLS_OID_ON_HW_MODULE_NAME */ } break; /* * dNSName */ case MBEDTLS_X509_SAN_DNS_NAME: { ret = mbedtls_snprintf( p, n, "\n%s dNSName : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( san.san.unstructured_name.len >= n ) { *p = '\0'; return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL ); } memcpy( p, san.san.unstructured_name.p, san.san.unstructured_name.len ); p += san.san.unstructured_name.len; n -= san.san.unstructured_name.len; } break; /* * Type not supported, skip item. */ default: ret = mbedtls_snprintf( p, n, "\n%s <unsupported>", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; break; } cur = cur->next; } *p = '\0'; *size = n; *buf = p; return( 0 ); } int mbedtls_x509_parse_subject_alt_name( const mbedtls_x509_buf *san_buf, mbedtls_x509_subject_alternative_name *san ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; switch( san_buf->tag & ( MBEDTLS_ASN1_TAG_CLASS_MASK | MBEDTLS_ASN1_TAG_VALUE_MASK ) ) { /* * otherName */ case( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_OTHER_NAME ): { mbedtls_x509_san_other_name other_name; ret = x509_get_other_name( san_buf, &other_name ); if( ret != 0 ) return( ret ); memset( san, 0, sizeof( mbedtls_x509_subject_alternative_name ) ); san->type = MBEDTLS_X509_SAN_OTHER_NAME; memcpy( &san->san.other_name, &other_name, sizeof( other_name ) ); } break; /* * dNSName */ case( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_DNS_NAME ): { memset( san, 0, sizeof( mbedtls_x509_subject_alternative_name ) ); san->type = MBEDTLS_X509_SAN_DNS_NAME; memcpy( &san->san.unstructured_name, san_buf, sizeof( *san_buf ) ); } break; /* * Type not supported */ default: return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ); } return( 0 ); } #define PRINT_ITEM(i) \ { \ ret = mbedtls_snprintf( p, n, "%s" i, sep ); \ MBEDTLS_X509_SAFE_SNPRINTF; \ sep = ", "; \ } #define CERT_TYPE(type,name) \ if( ns_cert_type & (type) ) \ PRINT_ITEM( name ); static int x509_info_cert_type( char **buf, size_t *size, unsigned char ns_cert_type ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n = *size; char *p = *buf; const char *sep = ""; CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT, "SSL Client" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER, "SSL Server" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL, "Email" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING, "Object Signing" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED, "Reserved" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA, "SSL CA" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA, "Email CA" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA, "Object Signing CA" ); *size = n; *buf = p; return( 0 ); } #define KEY_USAGE(code,name) \ if( key_usage & (code) ) \ PRINT_ITEM( name ); static int x509_info_key_usage( char **buf, size_t *size, unsigned int key_usage ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n = *size; char *p = *buf; const char *sep = ""; KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE, "Digital Signature" ); KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION, "Non Repudiation" ); KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT, "Key Encipherment" ); KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT, "Data Encipherment" ); KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT, "Key Agreement" ); KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN, "Key Cert Sign" ); KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN, "CRL Sign" ); KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY, "Encipher Only" ); KEY_USAGE( MBEDTLS_X509_KU_DECIPHER_ONLY, "Decipher Only" ); *size = n; *buf = p; return( 0 ); } static int x509_info_ext_key_usage( char **buf, size_t *size, const mbedtls_x509_sequence *extended_key_usage ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const char *desc; size_t n = *size; char *p = *buf; const mbedtls_x509_sequence *cur = extended_key_usage; const char *sep = ""; while( cur != NULL ) { if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 ) desc = "???"; ret = mbedtls_snprintf( p, n, "%s%s", sep, desc ); MBEDTLS_X509_SAFE_SNPRINTF; sep = ", "; cur = cur->next; } *size = n; *buf = p; return( 0 ); } static int x509_info_cert_policies( char **buf, size_t *size, const mbedtls_x509_sequence *certificate_policies ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const char *desc; size_t n = *size; char *p = *buf; const mbedtls_x509_sequence *cur = certificate_policies; const char *sep = ""; while( cur != NULL ) { if( mbedtls_oid_get_certificate_policies( &cur->buf, &desc ) != 0 ) desc = "???"; ret = mbedtls_snprintf( p, n, "%s%s", sep, desc ); MBEDTLS_X509_SAFE_SNPRINTF; sep = ", "; cur = cur->next; } *size = n; *buf = p; return( 0 ); } /* * Return an informational string about the certificate. */ #define BEFORE_COLON 18 #define BC "18" int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix, const mbedtls_x509_crt *crt ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n; char *p; char key_size_str[BEFORE_COLON]; p = buf; n = size; if( NULL == crt ) { ret = mbedtls_snprintf( p, n, "\nCertificate is uninitialised!\n" ); MBEDTLS_X509_SAFE_SNPRINTF; return( (int) ( size - n ) ); } ret = mbedtls_snprintf( p, n, "%scert. version : %d\n", prefix, crt->version ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "%sserial number : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_serial_gets( p, n, &crt->serial ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%sissuer name : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_dn_gets( p, n, &crt->issuer ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%ssubject name : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_dn_gets( p, n, &crt->subject ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%sissued on : " \ "%04d-%02d-%02d %02d:%02d:%02d", prefix, crt->valid_from.year, crt->valid_from.mon, crt->valid_from.day, crt->valid_from.hour, crt->valid_from.min, crt->valid_from.sec ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%sexpires on : " \ "%04d-%02d-%02d %02d:%02d:%02d", prefix, crt->valid_to.year, crt->valid_to.mon, crt->valid_to.day, crt->valid_to.hour, crt->valid_to.min, crt->valid_to.sec ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%ssigned using : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk, crt->sig_md, crt->sig_opts ); MBEDTLS_X509_SAFE_SNPRINTF; /* Key size */ if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON, mbedtls_pk_get_name( &crt->pk ) ) ) != 0 ) { return( ret ); } ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str, (int) mbedtls_pk_get_bitlen( &crt->pk ) ); MBEDTLS_X509_SAFE_SNPRINTF; /* * Optional extensions */ if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS ) { ret = mbedtls_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix, crt->ca_istrue ? "true" : "false" ); MBEDTLS_X509_SAFE_SNPRINTF; if( crt->max_pathlen > 0 ) { ret = mbedtls_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 ); MBEDTLS_X509_SAFE_SNPRINTF; } } if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME ) { ret = mbedtls_snprintf( p, n, "\n%ssubject alt name :", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = x509_info_subject_alt_name( &p, &n, &crt->subject_alt_names, prefix ) ) != 0 ) return( ret ); } if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE ) { ret = mbedtls_snprintf( p, n, "\n%scert. type : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 ) return( ret ); } if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) { ret = mbedtls_snprintf( p, n, "\n%skey usage : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 ) return( ret ); } if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) { ret = mbedtls_snprintf( p, n, "\n%sext key usage : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = x509_info_ext_key_usage( &p, &n, &crt->ext_key_usage ) ) != 0 ) return( ret ); } if( crt->ext_types & MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES ) { ret = mbedtls_snprintf( p, n, "\n%scertificate policies : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = x509_info_cert_policies( &p, &n, &crt->certificate_policies ) ) != 0 ) return( ret ); } ret = mbedtls_snprintf( p, n, "\n" ); MBEDTLS_X509_SAFE_SNPRINTF; return( (int) ( size - n ) ); } struct x509_crt_verify_string { int code; const char *string; }; static const struct x509_crt_verify_string x509_crt_verify_strings[] = { { MBEDTLS_X509_BADCERT_EXPIRED, "The certificate validity has expired" }, { MBEDTLS_X509_BADCERT_REVOKED, "The certificate has been revoked (is on a CRL)" }, { MBEDTLS_X509_BADCERT_CN_MISMATCH, "The certificate Common Name (CN) does not match with the expected CN" }, { MBEDTLS_X509_BADCERT_NOT_TRUSTED, "The certificate is not correctly signed by the trusted CA" }, { MBEDTLS_X509_BADCRL_NOT_TRUSTED, "The CRL is not correctly signed by the trusted CA" }, { MBEDTLS_X509_BADCRL_EXPIRED, "The CRL is expired" }, { MBEDTLS_X509_BADCERT_MISSING, "Certificate was missing" }, { MBEDTLS_X509_BADCERT_SKIP_VERIFY, "Certificate verification was skipped" }, { MBEDTLS_X509_BADCERT_OTHER, "Other reason (can be used by verify callback)" }, { MBEDTLS_X509_BADCERT_FUTURE, "The certificate validity starts in the future" }, { MBEDTLS_X509_BADCRL_FUTURE, "The CRL is from the future" }, { MBEDTLS_X509_BADCERT_KEY_USAGE, "Usage does not match the keyUsage extension" }, { MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, "Usage does not match the extendedKeyUsage extension" }, { MBEDTLS_X509_BADCERT_NS_CERT_TYPE, "Usage does not match the nsCertType extension" }, { MBEDTLS_X509_BADCERT_BAD_MD, "The certificate is signed with an unacceptable hash." }, { MBEDTLS_X509_BADCERT_BAD_PK, "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA)." }, { MBEDTLS_X509_BADCERT_BAD_KEY, "The certificate is signed with an unacceptable key (eg bad curve, RSA too short)." }, { MBEDTLS_X509_BADCRL_BAD_MD, "The CRL is signed with an unacceptable hash." }, { MBEDTLS_X509_BADCRL_BAD_PK, "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA)." }, { MBEDTLS_X509_BADCRL_BAD_KEY, "The CRL is signed with an unacceptable key (eg bad curve, RSA too short)." }, { 0, NULL } }; int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix, uint32_t flags ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const struct x509_crt_verify_string *cur; char *p = buf; size_t n = size; for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ ) { if( ( flags & cur->code ) == 0 ) continue; ret = mbedtls_snprintf( p, n, "%s%s\n", prefix, cur->string ); MBEDTLS_X509_SAFE_SNPRINTF; flags ^= cur->code; } if( flags != 0 ) { ret = mbedtls_snprintf( p, n, "%sUnknown reason " "(this should not happen)\n", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; } return( (int) ( size - n ) ); } #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt, unsigned int usage ) { unsigned int usage_must, usage_may; unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY | MBEDTLS_X509_KU_DECIPHER_ONLY; if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 ) return( 0 ); usage_must = usage & ~may_mask; if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); usage_may = usage & may_mask; if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); return( 0 ); } #endif #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt, const char *usage_oid, size_t usage_len ) { const mbedtls_x509_sequence *cur; /* Extension is not mandatory, absent means no restriction */ if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 ) return( 0 ); /* * Look for the requested usage (or wildcard ANY) in our list */ for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next ) { const mbedtls_x509_buf *cur_oid = &cur->buf; if( cur_oid->len == usage_len && memcmp( cur_oid->p, usage_oid, usage_len ) == 0 ) { return( 0 ); } if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 ) return( 0 ); } return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); } #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */ #if defined(MBEDTLS_X509_CRL_PARSE_C) /* * Return 1 if the certificate is revoked, or 0 otherwise. */ int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl ) { const mbedtls_x509_crl_entry *cur = &crl->entry; while( cur != NULL && cur->serial.len != 0 ) { if( crt->serial.len == cur->serial.len && memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 ) { return( 1 ); } cur = cur->next; } return( 0 ); } /* * Check that the given certificate is not revoked according to the CRL. * Skip validation if no CRL for the given CA is present. */ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca, mbedtls_x509_crl *crl_list, const mbedtls_x509_crt_profile *profile ) { int flags = 0; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; const mbedtls_md_info_t *md_info; if( ca == NULL ) return( flags ); while( crl_list != NULL ) { if( crl_list->version == 0 || x509_name_cmp( &crl_list->issuer, &ca->subject ) != 0 ) { crl_list = crl_list->next; continue; } /* * Check if the CA is configured to sign CRLs */ #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) if( mbedtls_x509_crt_check_key_usage( ca, MBEDTLS_X509_KU_CRL_SIGN ) != 0 ) { flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED; break; } #endif /* * Check if CRL is correctly signed by the trusted CA */ if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 ) flags |= MBEDTLS_X509_BADCRL_BAD_MD; if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 ) flags |= MBEDTLS_X509_BADCRL_BAD_PK; md_info = mbedtls_md_info_from_type( crl_list->sig_md ); if( mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash ) != 0 ) { /* Note: this can't happen except after an internal error */ flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED; break; } if( x509_profile_check_key( profile, &ca->pk ) != 0 ) flags |= MBEDTLS_X509_BADCERT_BAD_KEY; if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk, crl_list->sig_md, hash, mbedtls_md_get_size( md_info ), crl_list->sig.p, crl_list->sig.len ) != 0 ) { flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED; break; } /* * Check for validity of CRL (Do not drop out) */ if( mbedtls_x509_time_is_past( &crl_list->next_update ) ) flags |= MBEDTLS_X509_BADCRL_EXPIRED; if( mbedtls_x509_time_is_future( &crl_list->this_update ) ) flags |= MBEDTLS_X509_BADCRL_FUTURE; /* * Check if certificate is revoked */ if( mbedtls_x509_crt_is_revoked( crt, crl_list ) ) { flags |= MBEDTLS_X509_BADCERT_REVOKED; break; } crl_list = crl_list->next; } return( flags ); } #endif /* MBEDTLS_X509_CRL_PARSE_C */ /* * Check the signature of a certificate by its parent */ static int x509_crt_check_signature( const mbedtls_x509_crt *child, mbedtls_x509_crt *parent, mbedtls_x509_crt_restart_ctx *rs_ctx ) { unsigned char hash[MBEDTLS_MD_MAX_SIZE]; size_t hash_len; #if !defined(MBEDTLS_USE_PSA_CRYPTO) const mbedtls_md_info_t *md_info; md_info = mbedtls_md_info_from_type( child->sig_md ); hash_len = mbedtls_md_get_size( md_info ); /* Note: hash errors can happen only after an internal error */ if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 ) return( -1 ); #else psa_hash_operation_t hash_operation = PSA_HASH_OPERATION_INIT; psa_algorithm_t hash_alg = mbedtls_psa_translate_md( child->sig_md ); if( psa_hash_setup( &hash_operation, hash_alg ) != PSA_SUCCESS ) return( -1 ); if( psa_hash_update( &hash_operation, child->tbs.p, child->tbs.len ) != PSA_SUCCESS ) { return( -1 ); } if( psa_hash_finish( &hash_operation, hash, sizeof( hash ), &hash_len ) != PSA_SUCCESS ) { return( -1 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ /* Skip expensive computation on obvious mismatch */ if( ! mbedtls_pk_can_do( &parent->pk, child->sig_pk ) ) return( -1 ); #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && child->sig_pk == MBEDTLS_PK_ECDSA ) { return( mbedtls_pk_verify_restartable( &parent->pk, child->sig_md, hash, hash_len, child->sig.p, child->sig.len, &rs_ctx->pk ) ); } #else (void) rs_ctx; #endif return( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, child->sig_md, hash, hash_len, child->sig.p, child->sig.len ) ); } /* * Check if 'parent' is a suitable parent (signing CA) for 'child'. * Return 0 if yes, -1 if not. * * top means parent is a locally-trusted certificate */ static int x509_crt_check_parent( const mbedtls_x509_crt *child, const mbedtls_x509_crt *parent, int top ) { int need_ca_bit; /* Parent must be the issuer */ if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 ) return( -1 ); /* Parent must have the basicConstraints CA bit set as a general rule */ need_ca_bit = 1; /* Exception: v1/v2 certificates that are locally trusted. */ if( top && parent->version < 3 ) need_ca_bit = 0; if( need_ca_bit && ! parent->ca_istrue ) return( -1 ); #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) if( need_ca_bit && mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 ) { return( -1 ); } #endif return( 0 ); } /* * Find a suitable parent for child in candidates, or return NULL. * * Here suitable is defined as: * 1. subject name matches child's issuer * 2. if necessary, the CA bit is set and key usage allows signing certs * 3. for trusted roots, the signature is correct * (for intermediates, the signature is checked and the result reported) * 4. pathlen constraints are satisfied * * If there's a suitable candidate which is also time-valid, return the first * such. Otherwise, return the first suitable candidate (or NULL if there is * none). * * The rationale for this rule is that someone could have a list of trusted * roots with two versions on the same root with different validity periods. * (At least one user reported having such a list and wanted it to just work.) * The reason we don't just require time-validity is that generally there is * only one version, and if it's expired we want the flags to state that * rather than NOT_TRUSTED, as would be the case if we required it here. * * The rationale for rule 3 (signature for trusted roots) is that users might * have two versions of the same CA with different keys in their list, and the * way we select the correct one is by checking the signature (as we don't * rely on key identifier extensions). (This is one way users might choose to * handle key rollover, another relies on self-issued certs, see [SIRO].) * * Arguments: * - [in] child: certificate for which we're looking for a parent * - [in] candidates: chained list of potential parents * - [out] r_parent: parent found (or NULL) * - [out] r_signature_is_good: 1 if child signature by parent is valid, or 0 * - [in] top: 1 if candidates consists of trusted roots, ie we're at the top * of the chain, 0 otherwise * - [in] path_cnt: number of intermediates seen so far * - [in] self_cnt: number of self-signed intermediates seen so far * (will never be greater than path_cnt) * - [in-out] rs_ctx: context for restarting operations * * Return value: * - 0 on success * - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise */ static int x509_crt_find_parent_in( mbedtls_x509_crt *child, mbedtls_x509_crt *candidates, mbedtls_x509_crt **r_parent, int *r_signature_is_good, int top, unsigned path_cnt, unsigned self_cnt, mbedtls_x509_crt_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_x509_crt *parent, *fallback_parent; int signature_is_good = 0, fallback_signature_is_good; #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* did we have something in progress? */ if( rs_ctx != NULL && rs_ctx->parent != NULL ) { /* restore saved state */ parent = rs_ctx->parent; fallback_parent = rs_ctx->fallback_parent; fallback_signature_is_good = rs_ctx->fallback_signature_is_good; /* clear saved state */ rs_ctx->parent = NULL; rs_ctx->fallback_parent = NULL; rs_ctx->fallback_signature_is_good = 0; /* resume where we left */ goto check_signature; } #endif fallback_parent = NULL; fallback_signature_is_good = 0; for( parent = candidates; parent != NULL; parent = parent->next ) { /* basic parenting skills (name, CA bit, key usage) */ if( x509_crt_check_parent( child, parent, top ) != 0 ) continue; /* +1 because stored max_pathlen is 1 higher that the actual value */ if( parent->max_pathlen > 0 && (size_t) parent->max_pathlen < 1 + path_cnt - self_cnt ) { continue; } /* Signature */ #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) check_signature: #endif ret = x509_crt_check_signature( child, parent, rs_ctx ); #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) { /* save state */ rs_ctx->parent = parent; rs_ctx->fallback_parent = fallback_parent; rs_ctx->fallback_signature_is_good = fallback_signature_is_good; return( ret ); } #else (void) ret; #endif signature_is_good = ret == 0; if( top && ! signature_is_good ) continue; /* optional time check */ if( mbedtls_x509_time_is_past( &parent->valid_to ) || mbedtls_x509_time_is_future( &parent->valid_from ) ) { if( fallback_parent == NULL ) { fallback_parent = parent; fallback_signature_is_good = signature_is_good; } continue; } *r_parent = parent; *r_signature_is_good = signature_is_good; break; } if( parent == NULL ) { *r_parent = fallback_parent; *r_signature_is_good = fallback_signature_is_good; } return( 0 ); } /* * Find a parent in trusted CAs or the provided chain, or return NULL. * * Searches in trusted CAs first, and return the first suitable parent found * (see find_parent_in() for definition of suitable). * * Arguments: * - [in] child: certificate for which we're looking for a parent, followed * by a chain of possible intermediates * - [in] trust_ca: list of locally trusted certificates * - [out] parent: parent found (or NULL) * - [out] parent_is_trusted: 1 if returned `parent` is trusted, or 0 * - [out] signature_is_good: 1 if child signature by parent is valid, or 0 * - [in] path_cnt: number of links in the chain so far (EE -> ... -> child) * - [in] self_cnt: number of self-signed certs in the chain so far * (will always be no greater than path_cnt) * - [in-out] rs_ctx: context for restarting operations * * Return value: * - 0 on success * - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise */ static int x509_crt_find_parent( mbedtls_x509_crt *child, mbedtls_x509_crt *trust_ca, mbedtls_x509_crt **parent, int *parent_is_trusted, int *signature_is_good, unsigned path_cnt, unsigned self_cnt, mbedtls_x509_crt_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_x509_crt *search_list; *parent_is_trusted = 1; #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* restore then clear saved state if we have some stored */ if( rs_ctx != NULL && rs_ctx->parent_is_trusted != -1 ) { *parent_is_trusted = rs_ctx->parent_is_trusted; rs_ctx->parent_is_trusted = -1; } #endif while( 1 ) { search_list = *parent_is_trusted ? trust_ca : child->next; ret = x509_crt_find_parent_in( child, search_list, parent, signature_is_good, *parent_is_trusted, path_cnt, self_cnt, rs_ctx ); #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) { /* save state */ rs_ctx->parent_is_trusted = *parent_is_trusted; return( ret ); } #else (void) ret; #endif /* stop here if found or already in second iteration */ if( *parent != NULL || *parent_is_trusted == 0 ) break; /* prepare second iteration */ *parent_is_trusted = 0; } /* extra precaution against mistakes in the caller */ if( *parent == NULL ) { *parent_is_trusted = 0; *signature_is_good = 0; } return( 0 ); } /* * Check if an end-entity certificate is locally trusted * * Currently we require such certificates to be self-signed (actually only * check for self-issued as self-signatures are not checked) */ static int x509_crt_check_ee_locally_trusted( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca ) { mbedtls_x509_crt *cur; /* must be self-issued */ if( x509_name_cmp( &crt->issuer, &crt->subject ) != 0 ) return( -1 ); /* look for an exact match with trusted cert */ for( cur = trust_ca; cur != NULL; cur = cur->next ) { if( crt->raw.len == cur->raw.len && memcmp( crt->raw.p, cur->raw.p, crt->raw.len ) == 0 ) { return( 0 ); } } /* too bad */ return( -1 ); } /* * Build and verify a certificate chain * * Given a peer-provided list of certificates EE, C1, ..., Cn and * a list of trusted certs R1, ... Rp, try to build and verify a chain * EE, Ci1, ... Ciq [, Rj] * such that every cert in the chain is a child of the next one, * jumping to a trusted root as early as possible. * * Verify that chain and return it with flags for all issues found. * * Special cases: * - EE == Rj -> return a one-element list containing it * - EE, Ci1, ..., Ciq cannot be continued with a trusted root * -> return that chain with NOT_TRUSTED set on Ciq * * Tests for (aspects of) this function should include at least: * - trusted EE * - EE -> trusted root * - EE -> intermediate CA -> trusted root * - if relevant: EE untrusted * - if relevant: EE -> intermediate, untrusted * with the aspect under test checked at each relevant level (EE, int, root). * For some aspects longer chains are required, but usually length 2 is * enough (but length 1 is not in general). * * Arguments: * - [in] crt: the cert list EE, C1, ..., Cn * - [in] trust_ca: the trusted list R1, ..., Rp * - [in] ca_crl, profile: as in verify_with_profile() * - [out] ver_chain: the built and verified chain * Only valid when return value is 0, may contain garbage otherwise! * Restart note: need not be the same when calling again to resume. * - [in-out] rs_ctx: context for restarting operations * * Return value: * - non-zero if the chain could not be fully built and examined * - 0 is the chain was successfully built and examined, * even if it was found to be invalid */ static int x509_crt_verify_chain( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, mbedtls_x509_crt_ca_cb_t f_ca_cb, void *p_ca_cb, const mbedtls_x509_crt_profile *profile, mbedtls_x509_crt_verify_chain *ver_chain, mbedtls_x509_crt_restart_ctx *rs_ctx ) { /* Don't initialize any of those variables here, so that the compiler can * catch potential issues with jumping ahead when restarting */ int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; uint32_t *flags; mbedtls_x509_crt_verify_chain_item *cur; mbedtls_x509_crt *child; mbedtls_x509_crt *parent; int parent_is_trusted; int child_is_trusted; int signature_is_good; unsigned self_cnt; mbedtls_x509_crt *cur_trust_ca = NULL; #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* resume if we had an operation in progress */ if( rs_ctx != NULL && rs_ctx->in_progress == x509_crt_rs_find_parent ) { /* restore saved state */ *ver_chain = rs_ctx->ver_chain; /* struct copy */ self_cnt = rs_ctx->self_cnt; /* restore derived state */ cur = &ver_chain->items[ver_chain->len - 1]; child = cur->crt; flags = &cur->flags; goto find_parent; } #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ child = crt; self_cnt = 0; parent_is_trusted = 0; child_is_trusted = 0; while( 1 ) { /* Add certificate to the verification chain */ cur = &ver_chain->items[ver_chain->len]; cur->crt = child; cur->flags = 0; ver_chain->len++; flags = &cur->flags; /* Check time-validity (all certificates) */ if( mbedtls_x509_time_is_past( &child->valid_to ) ) *flags |= MBEDTLS_X509_BADCERT_EXPIRED; if( mbedtls_x509_time_is_future( &child->valid_from ) ) *flags |= MBEDTLS_X509_BADCERT_FUTURE; /* Stop here for trusted roots (but not for trusted EE certs) */ if( child_is_trusted ) return( 0 ); /* Check signature algorithm: MD & PK algs */ if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_MD; if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_PK; /* Special case: EE certs that are locally trusted */ if( ver_chain->len == 1 && x509_crt_check_ee_locally_trusted( child, trust_ca ) == 0 ) { return( 0 ); } #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) find_parent: #endif /* Obtain list of potential trusted signers from CA callback, * or use statically provided list. */ #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) if( f_ca_cb != NULL ) { mbedtls_x509_crt_free( ver_chain->trust_ca_cb_result ); mbedtls_free( ver_chain->trust_ca_cb_result ); ver_chain->trust_ca_cb_result = NULL; ret = f_ca_cb( p_ca_cb, child, &ver_chain->trust_ca_cb_result ); if( ret != 0 ) return( MBEDTLS_ERR_X509_FATAL_ERROR ); cur_trust_ca = ver_chain->trust_ca_cb_result; } else #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ { ((void) f_ca_cb); ((void) p_ca_cb); cur_trust_ca = trust_ca; } /* Look for a parent in trusted CAs or up the chain */ ret = x509_crt_find_parent( child, cur_trust_ca, &parent, &parent_is_trusted, &signature_is_good, ver_chain->len - 1, self_cnt, rs_ctx ); #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) { /* save state */ rs_ctx->in_progress = x509_crt_rs_find_parent; rs_ctx->self_cnt = self_cnt; rs_ctx->ver_chain = *ver_chain; /* struct copy */ return( ret ); } #else (void) ret; #endif /* No parent? We're done here */ if( parent == NULL ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; return( 0 ); } /* Count intermediate self-issued (not necessarily self-signed) certs. * These can occur with some strategies for key rollover, see [SIRO], * and should be excluded from max_pathlen checks. */ if( ver_chain->len != 1 && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) { self_cnt++; } /* path_cnt is 0 for the first intermediate CA, * and if parent is trusted it's not an intermediate CA */ if( ! parent_is_trusted && ver_chain->len > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) { /* return immediately to avoid overflow the chain array */ return( MBEDTLS_ERR_X509_FATAL_ERROR ); } /* signature was checked while searching parent */ if( ! signature_is_good ) *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; /* check size of signing key */ if( x509_profile_check_key( profile, &parent->pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; #if defined(MBEDTLS_X509_CRL_PARSE_C) /* Check trusted CA's CRL for the given crt */ *flags |= x509_crt_verifycrl( child, parent, ca_crl, profile ); #else (void) ca_crl; #endif /* prepare for next iteration */ child = parent; parent = NULL; child_is_trusted = parent_is_trusted; signature_is_good = 0; } } /* * Check for CN match */ static int x509_crt_check_cn( const mbedtls_x509_buf *name, const char *cn, size_t cn_len ) { /* try exact match */ if( name->len == cn_len && x509_memcasecmp( cn, name->p, cn_len ) == 0 ) { return( 0 ); } /* try wildcard match */ if( x509_check_wildcard( cn, name ) == 0 ) { return( 0 ); } return( -1 ); } /* * Check for SAN match, see RFC 5280 Section 4.2.1.6 */ static int x509_crt_check_san( const mbedtls_x509_buf *name, const char *cn, size_t cn_len ) { const unsigned char san_type = (unsigned char) name->tag & MBEDTLS_ASN1_TAG_VALUE_MASK; /* dNSName */ if( san_type == MBEDTLS_X509_SAN_DNS_NAME ) return( x509_crt_check_cn( name, cn, cn_len ) ); /* (We may handle other types here later.) */ /* Unrecognized type */ return( -1 ); } /* * Verify the requested CN - only call this if cn is not NULL! */ static void x509_crt_verify_name( const mbedtls_x509_crt *crt, const char *cn, uint32_t *flags ) { const mbedtls_x509_name *name; const mbedtls_x509_sequence *cur; size_t cn_len = strlen( cn ); if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME ) { for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next ) { if( x509_crt_check_san( &cur->buf, cn, cn_len ) == 0 ) break; } if( cur == NULL ) *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } else { for( name = &crt->subject; name != NULL; name = name->next ) { if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 && x509_crt_check_cn( &name->val, cn, cn_len ) == 0 ) { break; } } if( name == NULL ) *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } } /* * Merge the flags for all certs in the chain, after calling callback */ static int x509_crt_merge_flags_with_cb( uint32_t *flags, const mbedtls_x509_crt_verify_chain *ver_chain, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned i; uint32_t cur_flags; const mbedtls_x509_crt_verify_chain_item *cur; for( i = ver_chain->len; i != 0; --i ) { cur = &ver_chain->items[i-1]; cur_flags = cur->flags; if( NULL != f_vrfy ) if( ( ret = f_vrfy( p_vrfy, cur->crt, (int) i-1, &cur_flags ) ) != 0 ) return( ret ); *flags |= cur_flags; } return( 0 ); } /* * Verify the certificate validity, with profile, restartable version * * This function: * - checks the requested CN (if any) * - checks the type and size of the EE cert's key, * as that isn't done as part of chain building/verification currently * - builds and verifies the chain * - then calls the callback and merges the flags * * The parameters pairs `trust_ca`, `ca_crl` and `f_ca_cb`, `p_ca_cb` * are mutually exclusive: If `f_ca_cb != NULL`, it will be used by the * verification routine to search for trusted signers, and CRLs will * be disabled. Otherwise, `trust_ca` will be used as the static list * of trusted signers, and `ca_crl` will be use as the static list * of CRLs. */ static int x509_crt_verify_restartable_ca_cb( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, mbedtls_x509_crt_ca_cb_t f_ca_cb, void *p_ca_cb, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy, mbedtls_x509_crt_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_pk_type_t pk_type; mbedtls_x509_crt_verify_chain ver_chain; uint32_t ee_flags; *flags = 0; ee_flags = 0; x509_crt_verify_chain_reset( &ver_chain ); if( profile == NULL ) { ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA; goto exit; } /* check name if requested */ if( cn != NULL ) x509_crt_verify_name( crt, cn, &ee_flags ); /* Check the type and size of the key */ pk_type = mbedtls_pk_get_type( &crt->pk ); if( x509_profile_check_pk_alg( profile, pk_type ) != 0 ) ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK; if( x509_profile_check_key( profile, &crt->pk ) != 0 ) ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY; /* Check the chain */ ret = x509_crt_verify_chain( crt, trust_ca, ca_crl, f_ca_cb, p_ca_cb, profile, &ver_chain, rs_ctx ); if( ret != 0 ) goto exit; /* Merge end-entity flags */ ver_chain.items[0].flags |= ee_flags; /* Build final flags, calling callback on the way if any */ ret = x509_crt_merge_flags_with_cb( flags, &ver_chain, f_vrfy, p_vrfy ); exit: #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) mbedtls_x509_crt_free( ver_chain.trust_ca_cb_result ); mbedtls_free( ver_chain.trust_ca_cb_result ); ver_chain.trust_ca_cb_result = NULL; #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) mbedtls_x509_crt_restart_free( rs_ctx ); #endif /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by * the SSL module for authmode optional, but non-zero return from the * callback means a fatal error so it shouldn't be ignored */ if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ) ret = MBEDTLS_ERR_X509_FATAL_ERROR; if( ret != 0 ) { *flags = (uint32_t) -1; return( ret ); } if( *flags != 0 ) return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); return( 0 ); } /* * Verify the certificate validity (default profile, not restartable) */ int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { return( x509_crt_verify_restartable_ca_cb( crt, trust_ca, ca_crl, NULL, NULL, &mbedtls_x509_crt_profile_default, cn, flags, f_vrfy, p_vrfy, NULL ) ); } /* * Verify the certificate validity (user-chosen profile, not restartable) */ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { return( x509_crt_verify_restartable_ca_cb( crt, trust_ca, ca_crl, NULL, NULL, profile, cn, flags, f_vrfy, p_vrfy, NULL ) ); } #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) /* * Verify the certificate validity (user-chosen profile, CA callback, * not restartable). */ int mbedtls_x509_crt_verify_with_ca_cb( mbedtls_x509_crt *crt, mbedtls_x509_crt_ca_cb_t f_ca_cb, void *p_ca_cb, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { return( x509_crt_verify_restartable_ca_cb( crt, NULL, NULL, f_ca_cb, p_ca_cb, profile, cn, flags, f_vrfy, p_vrfy, NULL ) ); } #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy, mbedtls_x509_crt_restart_ctx *rs_ctx ) { return( x509_crt_verify_restartable_ca_cb( crt, trust_ca, ca_crl, NULL, NULL, profile, cn, flags, f_vrfy, p_vrfy, rs_ctx ) ); } /* * Initialize a certificate chain */ void mbedtls_x509_crt_init( mbedtls_x509_crt *crt ) { memset( crt, 0, sizeof(mbedtls_x509_crt) ); } /* * Unallocate all certificate data */ void mbedtls_x509_crt_free( mbedtls_x509_crt *crt ) { mbedtls_x509_crt *cert_cur = crt; mbedtls_x509_crt *cert_prv; mbedtls_x509_name *name_cur; mbedtls_x509_name *name_prv; mbedtls_x509_sequence *seq_cur; mbedtls_x509_sequence *seq_prv; if( crt == NULL ) return; do { mbedtls_pk_free( &cert_cur->pk ); #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) mbedtls_free( cert_cur->sig_opts ); #endif name_cur = cert_cur->issuer.next; while( name_cur != NULL ) { name_prv = name_cur; name_cur = name_cur->next; mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } name_cur = cert_cur->subject.next; while( name_cur != NULL ) { name_prv = name_cur; name_cur = name_cur->next; mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } seq_cur = cert_cur->ext_key_usage.next; while( seq_cur != NULL ) { seq_prv = seq_cur; seq_cur = seq_cur->next; mbedtls_platform_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) ); mbedtls_free( seq_prv ); } seq_cur = cert_cur->subject_alt_names.next; while( seq_cur != NULL ) { seq_prv = seq_cur; seq_cur = seq_cur->next; mbedtls_platform_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) ); mbedtls_free( seq_prv ); } seq_cur = cert_cur->certificate_policies.next; while( seq_cur != NULL ) { seq_prv = seq_cur; seq_cur = seq_cur->next; mbedtls_platform_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) ); mbedtls_free( seq_prv ); } if( cert_cur->raw.p != NULL && cert_cur->own_buffer ) { mbedtls_platform_zeroize( cert_cur->raw.p, cert_cur->raw.len ); mbedtls_free( cert_cur->raw.p ); } cert_cur = cert_cur->next; } while( cert_cur != NULL ); cert_cur = crt; do { cert_prv = cert_cur; cert_cur = cert_cur->next; mbedtls_platform_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) ); if( cert_prv != crt ) mbedtls_free( cert_prv ); } while( cert_cur != NULL ); } #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* * Initialize a restart context */ void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx ) { mbedtls_pk_restart_init( &ctx->pk ); ctx->parent = NULL; ctx->fallback_parent = NULL; ctx->fallback_signature_is_good = 0; ctx->parent_is_trusted = -1; ctx->in_progress = x509_crt_rs_none; ctx->self_cnt = 0; x509_crt_verify_chain_reset( &ctx->ver_chain ); } /* * Free the components of a restart context */ void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx ) { if( ctx == NULL ) return; mbedtls_pk_restart_free( &ctx->pk ); mbedtls_x509_crt_restart_init( ctx ); } #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\x509_csr.c
/* * X.509 Certificate Signing Request (CSR) parsing * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The ITU-T X.509 standard defines a certificate format for PKI. * * http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs) * http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs) * http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10) * * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf */ #include "common.h" #if defined(MBEDTLS_X509_CSR_PARSE_C) #include "mbedtls/x509_csr.h" #include "mbedtls/error.h" #include "mbedtls/oid.h" #include "mbedtls/platform_util.h" #include <string.h> #if defined(MBEDTLS_PEM_PARSE_C) #include "mbedtls/pem.h" #endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #include <stdio.h> #define mbedtls_free free #define mbedtls_calloc calloc #define mbedtls_snprintf snprintf #endif #if defined(MBEDTLS_FS_IO) || defined(EFIX64) || defined(EFI32) #include <stdio.h> #endif /* * Version ::= INTEGER { v1(0) } */ static int x509_csr_get_version( unsigned char **p, const unsigned char *end, int *ver ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) { *ver = 0; return( 0 ); } return( MBEDTLS_ERR_X509_INVALID_VERSION + ret ); } return( 0 ); } /* * Parse a CSR in DER format */ int mbedtls_x509_csr_parse_der( mbedtls_x509_csr *csr, const unsigned char *buf, size_t buflen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; unsigned char *p, *end; mbedtls_x509_buf sig_params; memset( &sig_params, 0, sizeof( mbedtls_x509_buf ) ); /* * Check for valid input */ if( csr == NULL || buf == NULL || buflen == 0 ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); mbedtls_x509_csr_init( csr ); /* * first copy the raw DER data */ p = mbedtls_calloc( 1, len = buflen ); if( p == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); memcpy( p, buf, buflen ); csr->raw.p = p; csr->raw.len = len; end = p + len; /* * CertificationRequest ::= SEQUENCE { * certificationRequestInfo CertificationRequestInfo, * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING * } */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT ); } if( len != (size_t) ( end - p ) ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } /* * CertificationRequestInfo ::= SEQUENCE { */ csr->cri.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } end = p + len; csr->cri.len = end - csr->cri.p; /* * Version ::= INTEGER { v1(0) } */ if( ( ret = x509_csr_get_version( &p, end, &csr->version ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( ret ); } if( csr->version != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_UNKNOWN_VERSION ); } csr->version++; /* * subject Name */ csr->subject_raw.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } if( ( ret = mbedtls_x509_get_name( &p, p + len, &csr->subject ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( ret ); } csr->subject_raw.len = p - csr->subject_raw.p; /* * subjectPKInfo SubjectPublicKeyInfo */ if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &csr->pk ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( ret ); } /* * attributes [0] Attributes * * The list of possible attributes is open-ended, though RFC 2985 * (PKCS#9) defines a few in section 5.4. We currently don't support any, * so we just ignore them. This is a safe thing to do as the worst thing * that could happen is that we issue a certificate that does not match * the requester's expectations - this cannot cause a violation of our * signature policies. */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } p += len; end = csr->raw.p + csr->raw.len; /* * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING */ if( ( ret = mbedtls_x509_get_alg( &p, end, &csr->sig_oid, &sig_params ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( ret ); } if( ( ret = mbedtls_x509_get_sig_alg( &csr->sig_oid, &sig_params, &csr->sig_md, &csr->sig_pk, &csr->sig_opts ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG ); } if( ( ret = mbedtls_x509_get_sig( &p, end, &csr->sig ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( ret ); } if( p != end ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } return( 0 ); } /* * Parse a CSR, allowing for PEM or raw DER encoding */ int mbedtls_x509_csr_parse( mbedtls_x509_csr *csr, const unsigned char *buf, size_t buflen ) { #if defined(MBEDTLS_PEM_PARSE_C) int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t use_len; mbedtls_pem_context pem; #endif /* * Check for valid input */ if( csr == NULL || buf == NULL || buflen == 0 ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); #if defined(MBEDTLS_PEM_PARSE_C) /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */ if( buf[buflen - 1] == '\0' ) { mbedtls_pem_init( &pem ); ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN CERTIFICATE REQUEST-----", "-----END CERTIFICATE REQUEST-----", buf, NULL, 0, &use_len ); if( ret == MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) { ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN NEW CERTIFICATE REQUEST-----", "-----END NEW CERTIFICATE REQUEST-----", buf, NULL, 0, &use_len ); } if( ret == 0 ) { /* * Was PEM encoded, parse the result */ ret = mbedtls_x509_csr_parse_der( csr, pem.buf, pem.buflen ); } mbedtls_pem_free( &pem ); if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) return( ret ); } #endif /* MBEDTLS_PEM_PARSE_C */ return( mbedtls_x509_csr_parse_der( csr, buf, buflen ) ); } #if defined(MBEDTLS_FS_IO) /* * Load a CSR into the structure */ int mbedtls_x509_csr_parse_file( mbedtls_x509_csr *csr, const char *path ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n; unsigned char *buf; if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 ) return( ret ); ret = mbedtls_x509_csr_parse( csr, buf, n ); mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); } #endif /* MBEDTLS_FS_IO */ #define BEFORE_COLON 14 #define BC "14" /* * Return an informational string about the CSR. */ int mbedtls_x509_csr_info( char *buf, size_t size, const char *prefix, const mbedtls_x509_csr *csr ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n; char *p; char key_size_str[BEFORE_COLON]; p = buf; n = size; ret = mbedtls_snprintf( p, n, "%sCSR version : %d", prefix, csr->version ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%ssubject name : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_dn_gets( p, n, &csr->subject ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%ssigned using : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_sig_alg_gets( p, n, &csr->sig_oid, csr->sig_pk, csr->sig_md, csr->sig_opts ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON, mbedtls_pk_get_name( &csr->pk ) ) ) != 0 ) { return( ret ); } ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits\n", prefix, key_size_str, (int) mbedtls_pk_get_bitlen( &csr->pk ) ); MBEDTLS_X509_SAFE_SNPRINTF; return( (int) ( size - n ) ); } /* * Initialize a CSR */ void mbedtls_x509_csr_init( mbedtls_x509_csr *csr ) { memset( csr, 0, sizeof(mbedtls_x509_csr) ); } /* * Unallocate all CSR data */ void mbedtls_x509_csr_free( mbedtls_x509_csr *csr ) { mbedtls_x509_name *name_cur; mbedtls_x509_name *name_prv; if( csr == NULL ) return; mbedtls_pk_free( &csr->pk ); #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) mbedtls_free( csr->sig_opts ); #endif name_cur = csr->subject.next; while( name_cur != NULL ) { name_prv = name_cur; name_cur = name_cur->next; mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } if( csr->raw.p != NULL ) { mbedtls_platform_zeroize( csr->raw.p, csr->raw.len ); mbedtls_free( csr->raw.p ); } mbedtls_platform_zeroize( csr, sizeof( mbedtls_x509_csr ) ); } #endif /* MBEDTLS_X509_CSR_PARSE_C */
0
D://workCode//uploadProject\awtk\3rd\mbedtls
D://workCode//uploadProject\awtk\3rd\mbedtls\library\xtea.c
/* * An 32-bit implementation of the XTEA algorithm * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #if defined(MBEDTLS_XTEA_C) #include "mbedtls/xtea.h" #include "mbedtls/platform_util.h" #include <string.h> #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #define mbedtls_printf printf #endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_SELF_TEST */ #if !defined(MBEDTLS_XTEA_ALT) /* * 32-bit integer manipulation macros (big endian) */ #ifndef GET_UINT32_BE #define GET_UINT32_BE(n,b,i) \ { \ (n) = ( (uint32_t) (b)[(i) ] << 24 ) \ | ( (uint32_t) (b)[(i) + 1] << 16 ) \ | ( (uint32_t) (b)[(i) + 2] << 8 ) \ | ( (uint32_t) (b)[(i) + 3] ); \ } #endif #ifndef PUT_UINT32_BE #define PUT_UINT32_BE(n,b,i) \ { \ (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ (b)[(i) + 3] = (unsigned char) ( (n) ); \ } #endif void mbedtls_xtea_init( mbedtls_xtea_context *ctx ) { memset( ctx, 0, sizeof( mbedtls_xtea_context ) ); } void mbedtls_xtea_free( mbedtls_xtea_context *ctx ) { if( ctx == NULL ) return; mbedtls_platform_zeroize( ctx, sizeof( mbedtls_xtea_context ) ); } /* * XTEA key schedule */ void mbedtls_xtea_setup( mbedtls_xtea_context *ctx, const unsigned char key[16] ) { int i; memset( ctx, 0, sizeof(mbedtls_xtea_context) ); for( i = 0; i < 4; i++ ) { GET_UINT32_BE( ctx->k[i], key, i << 2 ); } } /* * XTEA encrypt function */ int mbedtls_xtea_crypt_ecb( mbedtls_xtea_context *ctx, int mode, const unsigned char input[8], unsigned char output[8]) { uint32_t *k, v0, v1, i; k = ctx->k; GET_UINT32_BE( v0, input, 0 ); GET_UINT32_BE( v1, input, 4 ); if( mode == MBEDTLS_XTEA_ENCRYPT ) { uint32_t sum = 0, delta = 0x9E3779B9; for( i = 0; i < 32; i++ ) { v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]); sum += delta; v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]); } } else /* MBEDTLS_XTEA_DECRYPT */ { uint32_t delta = 0x9E3779B9, sum = delta * 32; for( i = 0; i < 32; i++ ) { v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]); sum -= delta; v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]); } } PUT_UINT32_BE( v0, output, 0 ); PUT_UINT32_BE( v1, output, 4 ); return( 0 ); } #if defined(MBEDTLS_CIPHER_MODE_CBC) /* * XTEA-CBC buffer encryption/decryption */ int mbedtls_xtea_crypt_cbc( mbedtls_xtea_context *ctx, int mode, size_t length, unsigned char iv[8], const unsigned char *input, unsigned char *output) { int i; unsigned char temp[8]; if( length % 8 ) return( MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH ); if( mode == MBEDTLS_XTEA_DECRYPT ) { while( length > 0 ) { memcpy( temp, input, 8 ); mbedtls_xtea_crypt_ecb( ctx, mode, input, output ); for( i = 0; i < 8; i++ ) output[i] = (unsigned char)( output[i] ^ iv[i] ); memcpy( iv, temp, 8 ); input += 8; output += 8; length -= 8; } } else { while( length > 0 ) { for( i = 0; i < 8; i++ ) output[i] = (unsigned char)( input[i] ^ iv[i] ); mbedtls_xtea_crypt_ecb( ctx, mode, output, output ); memcpy( iv, output, 8 ); input += 8; output += 8; length -= 8; } } return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* !MBEDTLS_XTEA_ALT */ #if defined(MBEDTLS_SELF_TEST) /* * XTEA tests vectors (non-official) */ static const unsigned char xtea_test_key[6][16] = { { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }; static const unsigned char xtea_test_pt[6][8] = { { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48 }, { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 }, { 0x5a, 0x5b, 0x6e, 0x27, 0x89, 0x48, 0xd7, 0x7f }, { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48 }, { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 }, { 0x70, 0xe1, 0x22, 0x5d, 0x6e, 0x4e, 0x76, 0x55 } }; static const unsigned char xtea_test_ct[6][8] = { { 0x49, 0x7d, 0xf3, 0xd0, 0x72, 0x61, 0x2c, 0xb5 }, { 0xe7, 0x8f, 0x2d, 0x13, 0x74, 0x43, 0x41, 0xd8 }, { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 }, { 0xa0, 0x39, 0x05, 0x89, 0xf8, 0xb8, 0xef, 0xa5 }, { 0xed, 0x23, 0x37, 0x5a, 0x82, 0x1a, 0x8c, 0x2d }, { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 } }; /* * Checkup routine */ int mbedtls_xtea_self_test( int verbose ) { int i, ret = 0; unsigned char buf[8]; mbedtls_xtea_context ctx; mbedtls_xtea_init( &ctx ); for( i = 0; i < 6; i++ ) { if( verbose != 0 ) mbedtls_printf( " XTEA test #%d: ", i + 1 ); memcpy( buf, xtea_test_pt[i], 8 ); mbedtls_xtea_setup( &ctx, xtea_test_key[i] ); mbedtls_xtea_crypt_ecb( &ctx, MBEDTLS_XTEA_ENCRYPT, buf, buf ); if( memcmp( buf, xtea_test_ct[i], 8 ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto exit; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); exit: mbedtls_xtea_free( &ctx ); return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_XTEA_C */
0
D://workCode//uploadProject\awtk\3rd
D://workCode//uploadProject\awtk\3rd\miniz\miniz.c
/************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include "miniz.h" typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; #ifdef __cplusplus extern "C" { #endif /* ------------------- zlib-style API's */ mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } /* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ #if 0 mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } #elif defined(USE_EXTERNAL_MZCRC) /* If USE_EXTERNAL_CRC is defined, an external module will export the * mz_crc32() symbol for us to use, e.g. an SSE-accelerated version. * Depending on the impl, it may be necessary to ~ the input/output crc values. */ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len); #else /* Faster, but larger CPU cache footprint. */ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc_table[256] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; while (buf_len >= 4) { crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; pByte_buf += 4; buf_len -= 4; } while (buf_len) { crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; ++pByte_buf; --buf_len; } return ~crc32; } #endif void mz_free(void *p) { MZ_FREE(p); } MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } const char *mz_version(void) { return MZ_VERSION; } #ifndef MINIZ_NO_ZLIB_APIS int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = miniz_def_alloc_func; if (!pStream->zfree) pStream->zfree = miniz_def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for (;;) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; /* Can't make forward progress without some input. */ } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; /* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */ return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); /* In case mz_ulong is 64-bits (argh I hate longs). */ if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = miniz_def_alloc_func; if (!pStream->zfree) pStream->zfree = miniz_def_free_func; pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflateReset(mz_streamp pStream) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; pDecomp = (inflate_state *)pStream->state; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; /* pDecomp->m_window_bits = window_bits */; return MZ_OK; } int mz_inflate(mz_streamp pStream, int flush) { inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state *)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } /* flush != MZ_FINISH then we must assume there's more input. */ if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for (;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ else if (flush == MZ_FINISH) { /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); /* In case mz_ulong is 64-bits (argh I hate longs). */ if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = { { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } }; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif /*MINIZ_NO_ZLIB_APIS */ #ifdef __cplusplus } #endif /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> */
0
D://workCode//uploadProject\awtk\3rd
D://workCode//uploadProject\awtk\3rd\miniz\miniz.h
/* miniz.c 2.1.0 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateReset/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #pragma once #include "miniz_export.h" /* Defines to completely disable specific portions of miniz.c: If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. */ /* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ /*#define MINIZ_NO_STDIO */ /* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ /* get/set file times, and the C run-time funcs that get/set times won't be called. */ /* The current downside is the times written to your archives will be from 1979. */ /*#define MINIZ_NO_TIME */ /* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ /*#define MINIZ_NO_ARCHIVE_APIS */ /* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ /*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ /* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ /*#define MINIZ_NO_ZLIB_APIS */ /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ /*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ /* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ /*#define MINIZ_NO_MALLOC */ #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) /* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ #define MINIZ_NO_TIME #endif #include <stddef.h> #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) #include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) /* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ #define MINIZ_X86_OR_X64_CPU 1 #else #define MINIZ_X86_OR_X64_CPU 0 #endif #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU /* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ #define MINIZ_LITTLE_ENDIAN 1 #else #define MINIZ_LITTLE_ENDIAN 0 #endif /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ #if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) #if MINIZ_X86_OR_X64_CPU /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_UNALIGNED_USE_MEMCPY #else #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 #endif #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) /* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ #define MINIZ_HAS_64BIT_REGISTERS 1 #else #define MINIZ_HAS_64BIT_REGISTERS 0 #endif #ifdef __cplusplus extern "C" { #endif /* ------------------- zlib-style API Definitions. */ /* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ typedef unsigned long mz_ulong; /* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ MINIZ_EXPORT void mz_free(void *p); #define MZ_ADLER32_INIT (1) /* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ MINIZ_EXPORT mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) /* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ MINIZ_EXPORT mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); /* Compression strategies. */ enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; /* Method */ #define MZ_DEFLATED 8 /* Heap allocation callbacks. Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. */ typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); /* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; #define MZ_VERSION "10.1.0" #define MZ_VERNUM 0xA100 #define MZ_VER_MAJOR 10 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 0 #define MZ_VER_SUBREVISION 0 #ifndef MINIZ_NO_ZLIB_APIS /* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; /* Return status codes. MZ_PARAM_ERROR is non-standard. */ enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; /* Window bits */ #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; /* Compression/decompression stream struct. */ typedef struct mz_stream_s { const unsigned char *next_in; /* pointer to next byte to read */ unsigned int avail_in; /* number of bytes available at next_in */ mz_ulong total_in; /* total number of bytes consumed so far */ unsigned char *next_out; /* pointer to next byte to write */ unsigned int avail_out; /* number of bytes that can be written to next_out */ mz_ulong total_out; /* total number of bytes produced so far */ char *msg; /* error msg (unused) */ struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ mz_free_func zfree; /* optional heap free function (defaults to free) */ void *opaque; /* heap alloc function user pointer */ int data_type; /* data_type (unused) */ mz_ulong adler; /* adler32 of the source or uncompressed data */ mz_ulong reserved; /* not used */ } mz_stream; typedef mz_stream *mz_streamp; /* Returns the version string of miniz.c. */ MINIZ_EXPORT const char *mz_version(void); /* mz_deflateInit() initializes a compressor with default options: */ /* Parameters: */ /* pStream must point to an initialized mz_stream struct. */ /* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ /* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ /* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ /* Return values: */ /* MZ_OK on success. */ /* MZ_STREAM_ERROR if the stream is bogus. */ /* MZ_PARAM_ERROR if the input parameters are bogus. */ /* MZ_MEM_ERROR on out of memory. */ MINIZ_EXPORT int mz_deflateInit(mz_streamp pStream, int level); /* mz_deflateInit2() is like mz_deflate(), except with more control: */ /* Additional parameters: */ /* method must be MZ_DEFLATED */ /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ /* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ MINIZ_EXPORT int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); /* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ MINIZ_EXPORT int mz_deflateReset(mz_streamp pStream); /* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ /* Parameters: */ /* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ /* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ /* Return values: */ /* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ /* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ /* MZ_STREAM_ERROR if the stream is bogus. */ /* MZ_PARAM_ERROR if one of the parameters is invalid. */ /* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ MINIZ_EXPORT int mz_deflate(mz_streamp pStream, int flush); /* mz_deflateEnd() deinitializes a compressor: */ /* Return values: */ /* MZ_OK on success. */ /* MZ_STREAM_ERROR if the stream is bogus. */ MINIZ_EXPORT int mz_deflateEnd(mz_streamp pStream); /* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ MINIZ_EXPORT mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); /* Single-call compression functions mz_compress() and mz_compress2(): */ /* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ MINIZ_EXPORT int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); MINIZ_EXPORT int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); /* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ MINIZ_EXPORT mz_ulong mz_compressBound(mz_ulong source_len); /* Initializes a decompressor. */ MINIZ_EXPORT int mz_inflateInit(mz_streamp pStream); /* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ MINIZ_EXPORT int mz_inflateInit2(mz_streamp pStream, int window_bits); /* Quickly resets a compressor without having to reallocate anything. Same as calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */ MINIZ_EXPORT int mz_inflateReset(mz_streamp pStream); /* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ /* Parameters: */ /* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ /* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ /* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ /* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ /* Return values: */ /* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ /* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ /* MZ_STREAM_ERROR if the stream is bogus. */ /* MZ_DATA_ERROR if the deflate stream is invalid. */ /* MZ_PARAM_ERROR if one of the parameters is invalid. */ /* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ /* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ MINIZ_EXPORT int mz_inflate(mz_streamp pStream, int flush); /* Deinitializes a decompressor. */ MINIZ_EXPORT int mz_inflateEnd(mz_streamp pStream); /* Single-call decompression. */ /* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ MINIZ_EXPORT int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); /* Returns a string description of the specified error code, or NULL if the error code is invalid. */ MINIZ_EXPORT const char *mz_error(int err); /* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflateReset mz_inflateReset #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ #endif /* MINIZ_NO_ZLIB_APIS */ #ifdef __cplusplus } #endif #include "miniz_common.h" #include "miniz_tdef.h" #include "miniz_tinfl.h" #include "miniz_zip.h"
0
D://workCode//uploadProject\awtk\3rd
D://workCode//uploadProject\awtk\3rd\miniz\miniz_common.h
#pragma once #include <assert.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "miniz_export.h" /* ------------------- Types and macros */ typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef int64_t mz_int64; typedef uint64_t mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) /* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #define MZ_FILE FILE #endif /* #ifdef MINIZ_NO_STDIO */ #ifdef MINIZ_NO_TIME typedef struct mz_dummy_time_t_tag { int m_dummy; } mz_dummy_time_t; #define MZ_TIME_T mz_dummy_time_t #else #define MZ_TIME_T time_t #endif #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif extern MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); extern MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address); extern MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); #define MZ_UINT16_MAX (0xFFFFU) #define MZ_UINT32_MAX (0xFFFFFFFFU) #ifdef __cplusplus } #endif
0
D://workCode//uploadProject\awtk\3rd
D://workCode//uploadProject\awtk\3rd\miniz\miniz_export.h
#ifndef MINIZ_EXPORT_H #define MINIZ_EXPORT_H #define MINIZ_STATIC_DEFINE #ifdef MINIZ_STATIC_DEFINE # define MINIZ_EXPORT # define MINIZ_NO_EXPORT #else # ifndef MINIZ_EXPORT # ifdef miniz_EXPORTS /* We are building this library */ # define MINIZ_EXPORT __declspec(dllexport) # else /* We are using this library */ # define MINIZ_EXPORT __declspec(dllimport) # endif # endif # ifndef MINIZ_NO_EXPORT # define MINIZ_NO_EXPORT # endif #endif #ifndef MINIZ_DEPRECATED # define MINIZ_DEPRECATED __declspec(deprecated) #endif #ifndef MINIZ_DEPRECATED_EXPORT # define MINIZ_DEPRECATED_EXPORT MINIZ_EXPORT MINIZ_DEPRECATED #endif #ifndef MINIZ_DEPRECATED_NO_EXPORT # define MINIZ_DEPRECATED_NO_EXPORT MINIZ_NO_EXPORT MINIZ_DEPRECATED #endif #if 0 /* DEFINE_NO_DEPRECATED */ # ifndef MINIZ_NO_DEPRECATED # define MINIZ_NO_DEPRECATED # endif #endif #endif /* MINIZ_EXPORT_H */
0
D://workCode//uploadProject\awtk\3rd
D://workCode//uploadProject\awtk\3rd\miniz\miniz_tdef.c
/************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include "miniz.h" #ifdef __cplusplus extern "C" { #endif /* ------------------- Low-level Compression (independent from all decompression API's) */ /* Purposely making these tables static for faster init and thread safety. */ static const mz_uint16 s_tdefl_len_sym[256] = { 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285 }; static const mz_uint8 s_tdefl_len_extra[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 }; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 }; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 }; /* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. */ typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq *t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } /* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. */ static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n == 0) return; else if (n == 1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next = 1; next < n - 1; next++) { if (leaf >= n || A[root].m_key < A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n - 2].m_key = 0; for (next = n - 3; next >= 0; next--) A[next].m_key = A[A[next].m_key].m_key + 1; avbl = 1; used = dpth = 0; root = n - 2; next = n - 1; while (avbl > 0) { while (root >= 0 && (int)A[root].m_key == dpth) { used++; root--; } while (avbl > used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2 * used; dpth++; used = 0; } } /* Limits canonical Huffman code table's max code size. */ enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) \ do \ { \ mz_uint bits = b; \ mz_uint len = l; \ MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); \ d->m_bits_in += len; \ while (d->m_bits_in >= 8) \ { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } \ MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() \ { \ if (rle_repeat_count) \ { \ if (rle_repeat_count < 3) \ { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) \ packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } \ else \ { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 16; \ packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ } \ rle_repeat_count = 0; \ } \ } #define TDEFL_RLE_ZERO_CODE_SIZE() \ { \ if (rle_z_count) \ { \ if (rle_z_count < 3) \ { \ d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ while (rle_z_count--) \ packed_code_sizes[num_packed_code_sizes++] = 0; \ } \ else if (rle_z_count <= 10) \ { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 17; \ packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ } \ else \ { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 18; \ packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ } \ rle_z_count = 0; \ } \ } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) \ { \ bit_buffer |= (((mz_uint64)(b)) << bits_in); \ bits_in += (l); \ } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); /* This sequence coaxes MSVC into using cmov's vs. jmp's. */ s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64 *)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS */ static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); /* If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. */ if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } /* Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. */ else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #ifdef MINIZ_UNALIGNED_USE_MEMCPY static mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8* p) { mz_uint16 ret; memcpy(&ret, p, sizeof(mz_uint16)); return ret; } static mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16* p) { mz_uint16 ret; memcpy(&ret, p, sizeof(mz_uint16)); return ret; } #else #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) #define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p) #endif static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD2(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; q = (const mz_uint16 *)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD2(q) != s01) continue; p = s; probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */ #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #ifdef MINIZ_UNALIGNED_USE_MEMCPY static mz_uint32 TDEFL_READ_UNALIGNED_WORD32(const mz_uint8* p) { mz_uint32 ret; memcpy(&ret, p, sizeof(mz_uint32)); return ret; } #else #define TDEFL_READ_UNALIGNED_WORD32(p) *(const mz_uint32 *)(p) #endif static mz_bool tdefl_compress_fast(tdefl_compressor *d) { /* Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. */ mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = TDEFL_READ_UNALIGNED_WORD32(pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((TDEFL_READ_UNALIGNED_WORD32(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); #ifdef MINIZ_UNALIGNED_USE_MEMCPY memcpy(&pLZ_code_buf[1], &cur_match_dist, sizeof(cur_match_dist)); #else *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; #endif pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; /* Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. */ if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; /* Simple lazy/greedy parsing state machine. */ len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } /* Move the lookahead forward by len_to_move bytes. */ d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); /* Check if it's time to flush the current LZ codes to the internal output buffer. */ if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_dict); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8 *)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; /* level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). */ mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) /* nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) */ #endif /* Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. */ void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) { /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. */ static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } /* write dummy header */ for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); /* compress image data */ tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } /* write real header */ *pLen_out = out_buf.m_size - 41; { static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 }; mz_uint8 pnghdr[41] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x44, 0x41, 0x54 }; pnghdr[18] = (mz_uint8)(w >> 8); pnghdr[19] = (mz_uint8)w; pnghdr[22] = (mz_uint8)(h >> 8); pnghdr[23] = (mz_uint8)h; pnghdr[25] = chans[num_chans]; pnghdr[33] = (mz_uint8)(*pLen_out >> 24); pnghdr[34] = (mz_uint8)(*pLen_out >> 16); pnghdr[35] = (mz_uint8)(*pLen_out >> 8); pnghdr[36] = (mz_uint8)*pLen_out; c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); for (i = 0; i < 4; ++i, c <<= 8) ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); memcpy(out_buf.m_pBuf, pnghdr, 41); } /* write footer (IDAT CRC-32, followed by IEND chunk) */ if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); for (i = 0; i < 4; ++i, c <<= 8) (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); /* compute final size of file, grab compressed data buffer and return */ *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) */ return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); } #ifndef MINIZ_NO_MALLOC /* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that */ /* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */ /* structure size and allocation mechanism. */ tdefl_compressor *tdefl_compressor_alloc() { return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); } void tdefl_compressor_free(tdefl_compressor *pComp) { MZ_FREE(pComp); } #endif #ifdef _MSC_VER #pragma warning(pop) #endif #ifdef __cplusplus } #endif
0
D://workCode//uploadProject\awtk\3rd
D://workCode//uploadProject\awtk\3rd\miniz\miniz_tdef.h
#pragma once #include "miniz_common.h" #ifdef __cplusplus extern "C" { #endif /* ------------------- Low-level Compression API Definitions */ /* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ #define TDEFL_LESS_MEMORY 0 /* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ /* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; /* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ /* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ /* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ /* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ /* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ /* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ /* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ /* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ /* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; /* High level compression functions: */ /* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ /* On entry: */ /* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ /* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ /* On return: */ /* Function returns a pointer to the compressed data, or NULL on failure. */ /* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ /* The caller must free() the returned block when it's no longer needed. */ MINIZ_EXPORT void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); /* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ /* Returns 0 on failure. */ MINIZ_EXPORT size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); /* Compresses an image to a compressed PNG file in memory. */ /* On entry: */ /* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ /* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ /* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ /* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ /* On return: */ /* Function returns a pointer to the compressed data, or NULL on failure. */ /* *pLen_out will be set to the size of the PNG image file. */ /* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); /* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); /* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ MINIZ_EXPORT mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; /* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif /* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1 } tdefl_status; /* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; /* tdefl's compression state structure. */ typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; /* Initializes the compressor. */ /* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ /* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ /* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ /* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ MINIZ_EXPORT tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); /* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ MINIZ_EXPORT tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); /* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ /* tdefl_compress_buffer() always consumes the entire input buffer. */ MINIZ_EXPORT tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); MINIZ_EXPORT tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); MINIZ_EXPORT mz_uint32 tdefl_get_adler32(tdefl_compressor *d); /* Create tdefl_compress() flags given zlib-style compression parameters. */ /* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ /* window_bits may be -15 (raw deflate) or 15 (zlib) */ /* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ MINIZ_EXPORT mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #ifndef MINIZ_NO_MALLOC /* Allocate the tdefl_compressor structure in C so that */ /* non-C language bindings to tdefl_ API don't need to worry about */ /* structure size and allocation mechanism. */ MINIZ_EXPORT tdefl_compressor *tdefl_compressor_alloc(void); MINIZ_EXPORT void tdefl_compressor_free(tdefl_compressor *pComp); #endif #ifdef __cplusplus } #endif
0
D://workCode//uploadProject\awtk\3rd
D://workCode//uploadProject\awtk\3rd\miniz\miniz_tinfl.c
/************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include "miniz.h" #ifdef __cplusplus extern "C" { #endif /* ------------------- Low-level Decompression (completely independent from all compression API's) */ #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN \ switch (r->m_state) \ { \ case 0: #define TINFL_CR_RETURN(state_index, result) \ do \ { \ status = result; \ r->m_state = state_index; \ goto common_exit; \ case state_index:; \ } \ MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) \ do \ { \ for (;;) \ { \ TINFL_CR_RETURN(state_index, result); \ } \ } \ MZ_MACRO_END #define TINFL_CR_FINISH } #define TINFL_GET_BYTE(state_index, c) \ do \ { \ while (pIn_buf_cur >= pIn_buf_end) \ { \ TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ } \ c = *pIn_buf_cur++; \ } \ MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) \ do \ { \ mz_uint c; \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) \ do \ { \ if (num_bits < (mz_uint)(n)) \ { \ TINFL_NEED_BITS(state_index, n); \ } \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) \ do \ { \ if (num_bits < (mz_uint)(n)) \ { \ TINFL_NEED_BITS(state_index, n); \ } \ b = bit_buf & ((1 << (n)) - 1); \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END /* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */ /* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */ /* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */ /* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do \ { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) \ { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) \ break; \ } \ else if (num_bits > TINFL_FAST_LOOKUP_BITS) \ { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do \ { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); \ if (temp >= 0) \ break; \ } \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < 15); /* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */ /* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */ /* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */ /* The slow path is only executed at the very end of the input buffer. */ /* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */ /* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */ #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ do \ { \ int temp; \ mz_uint code_len, c; \ if (num_bits < 15) \ { \ if ((pIn_buf_end - pIn_buf_cur) < 2) \ { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } \ else \ { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ pIn_buf_cur += 2; \ num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ code_len = temp >> 9, temp &= 511; \ else \ { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do \ { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while (temp < 0); \ } \ sym = temp; \ bit_buf >>= code_len; \ num_bits -= code_len; \ } \ MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; static const int s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 }; static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 }; static const int s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static const int s_min_table_sizes[3] = { 257, 1, 4 }; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */ if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for (; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for (;;) { mz_uint8 *pSrc; for (;;) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { #ifdef MINIZ_UNALIGNED_USE_MEMCPY memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32)*2); #else ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; #endif pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif while(counter>2) { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; counter -= 3; } if (counter > 0) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */ TINFL_SKIP_BITS(32, num_bits & 7); while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) { --pIn_buf_cur; num_bits -= 8; } bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */ if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: /* As long as we aren't telling the caller that we NEED more input to make forward progress: */ /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */ if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) { while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) { --pIn_buf_cur; num_bits -= 8; } } r->m_num_bits = num_bits; r->m_bit_buf = bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } /* Higher level helper functions. */ void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for (;;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); for (;;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } #ifndef MINIZ_NO_MALLOC tinfl_decompressor *tinfl_decompressor_alloc() { tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); if (pDecomp) tinfl_init(pDecomp); return pDecomp; } void tinfl_decompressor_free(tinfl_decompressor *pDecomp) { MZ_FREE(pDecomp); } #endif #ifdef __cplusplus } #endif
0
D://workCode//uploadProject\awtk\3rd
D://workCode//uploadProject\awtk\3rd\miniz\miniz_tinfl.h
#pragma once #include "miniz_common.h" /* ------------------- Low-level Decompression API Definitions */ #ifdef __cplusplus extern "C" { #endif /* Decompression flags used by tinfl_decompress(). */ /* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ /* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ /* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ /* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; /* High level decompression functions: */ /* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ /* On entry: */ /* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ /* On return: */ /* Function returns a pointer to the decompressed data, or NULL on failure. */ /* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ /* The caller must call mz_free() on the returned block when it's no longer needed. */ MINIZ_EXPORT void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); /* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ /* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) MINIZ_EXPORT size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); /* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ /* Returns 1 on success or 0 on failure. */ typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); MINIZ_EXPORT int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; #ifndef MINIZ_NO_MALLOC /* Allocate the tinfl_decompressor structure in C so that */ /* non-C language bindings to tinfl_ API don't need to worry about */ /* structure size and allocation mechanism. */ MINIZ_EXPORT tinfl_decompressor *tinfl_decompressor_alloc(void); MINIZ_EXPORT void tinfl_decompressor_free(tinfl_decompressor *pDecomp); #endif /* Max size of LZ dictionary. */ #define TINFL_LZ_DICT_SIZE 32768 /* Return status. */ typedef enum { /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ TINFL_STATUS_BAD_PARAM = -3, /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ TINFL_STATUS_ADLER32_MISMATCH = -2, /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ TINFL_STATUS_FAILED = -1, /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ TINFL_STATUS_DONE = 0, /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ TINFL_STATUS_NEEDS_MORE_INPUT = 1, /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ /* so I may need to add some code to address this. */ TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; /* Initializes the decompressor to its initial state. */ #define tinfl_init(r) \ do \ { \ (r)->m_state = 0; \ } \ MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 /* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ /* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ MINIZ_EXPORT tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); /* Internal/private bits follow. */ enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #else #define TINFL_USE_64BIT_BITBUF 0 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; #ifdef __cplusplus } #endif
0
D://workCode//uploadProject\awtk\3rd
D://workCode//uploadProject\awtk\3rd\miniz\miniz_zip.c
/************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC * Copyright 2016 Martin Raiber * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include "miniz.h" #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus extern "C" { #endif /* ------------------- .ZIP archive reading */ #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW64__) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE *pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE *pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat64 #define MZ_FILE_STAT _stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__USE_LARGEFILE64) // gcc, clang #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #elif defined(__APPLE__) #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen(p, m, s) #define MZ_DELETE_FILE remove #else #pragma message("Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.") #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #ifdef __STRICT_ANSI__ #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #else #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #endif #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif /* #ifdef _MSC_VER */ #endif /* #ifdef MINIZ_NO_STDIO */ #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) /* Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. */ enum { /* ZIP archive identifiers and record sizes */ MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, /* ZIP64 archive identifier and record sizes */ MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, /* Central directory header record offsets */ MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, /* Local directory header offsets */ MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, /* End of central directory offsets */ MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, /* ZIP64 End of central directory locator offsets */ MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ /* ZIP64 End of central directory header offsets */ MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; /* The flags passed in when the archive is initially opened. */ uint32_t m_init_flags; /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. */ mz_bool m_zip64; /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 will also be slammed to true too, even if we didn't find a zip64 end of central dir header, etc.) */ mz_bool m_zip64_has_extended_info_fields; /* These fields are used by the file, FILE, memory, and memory/heap read/write helpers. */ MZ_FILE *m_pFile; mz_uint64 m_file_archive_start_ofs; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size #if defined(DEBUG) || defined(_DEBUG) || defined(NDEBUG) static MZ_FORCEINLINE mz_uint mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) { MZ_ASSERT(index < pArray->m_size); return index; } #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[mz_zip_array_range_check(array_ptr, index)] #else #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] #endif static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray, mz_uint32 element_size) { memset(pArray, 0, sizeof(mz_zip_array)); pArray->m_element_size = element_size; } static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; if (n > 0) memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif /* #ifdef _MSC_VER */ *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */ #ifndef MINIZ_NO_STDIO #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static mz_bool mz_zip_get_file_modified_time(const char *pFilename, MZ_TIME_T *pTime) { struct MZ_FILE_STAT_STRUCT file_stat; /* On Linux with x86 glibc, this call will fail on large files (I think >= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; *pTime = file_stat.st_mtime; return MZ_TRUE; } #endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/ static mz_bool mz_zip_set_file_times(const char *pFilename, MZ_TIME_T access_time, MZ_TIME_T modified_time) { struct utimbuf t; memset(&t, 0, sizeof(t)); t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif /* #ifndef MINIZ_NO_STDIO */ #endif /* #ifndef MINIZ_NO_TIME */ static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num) { if (pZip) pZip->m_last_error = err_num; return MZ_FALSE; } static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (!pZip->m_pAlloc) pZip->m_pAlloc = miniz_def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = miniz_def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = miniz_def_realloc_func; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; pZip->m_last_error = MZ_ZIP_NO_ERROR; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); pZip->m_pState->m_init_flags = flags; pZip->m_pState->m_zip64 = MZ_FALSE; pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; pZip->m_zip_mode = MZ_ZIP_MODE_READING; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) \ do \ { \ mz_uint32 t = a; \ a = b; \ b = t; \ } \ MZ_MACRO_END /* Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) */ static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices; mz_uint32 start, end; const mz_uint32 size = pZip->m_total_files; if (size <= 1U) return; pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); start = (size - 2U) >> 1U; for (;;) { mz_uint64 child, root = start; for (;;) { if ((child = (root << 1U) + 1U) >= size) break; child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } if (!start) break; start--; } end = size - 1; while (end > 0) { mz_uint64 child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for (;;) { if ((child = (root << 1U) + 1U) >= end) break; child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 record_sig, mz_uint32 record_size, mz_int64 *pOfs) { mz_int64 cur_file_ofs; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; /* Basic sanity checks - reject files which are too small */ if (pZip->m_archive_size < record_size) return MZ_FALSE; /* Find the record by scanning the file from the end towards the beginning. */ cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for (;;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) { mz_uint s = MZ_READ_LE32(pBuf + i); if (s == record_sig) { if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) break; } } if (i >= 0) { cur_file_ofs += i; break; } /* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */ if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } *pOfs = cur_file_ofs; return MZ_TRUE; } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flags) { mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, cdir_disk_index = 0; mz_uint64 cdir_ofs = 0; mz_int64 cur_file_ofs = 0; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); mz_uint32 zip64_end_of_central_dir_locator_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32; mz_uint32 zip64_end_of_central_dir_header_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pZip64_end_of_central_dir = (mz_uint8 *)zip64_end_of_central_dir_header_u32; mz_uint64 zip64_end_of_central_dir_ofs = 0; /* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */ if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); /* Read and verify the end of central directory record. */ if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) { if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) { if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) { zip64_end_of_central_dir_ofs = MZ_READ_LE64(pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); if (zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) { if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) { pZip->m_pState->m_zip64 = MZ_TRUE; } } } } } pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); cdir_entries_on_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if (pZip->m_pState->m_zip64) { mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if (zip64_total_num_of_disks != 1U) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); /* Check for miniz's practical limits */ if (zip64_cdir_total_entries > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk; /* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */ if (zip64_size_of_central_directory > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); cdir_size = (mz_uint32)zip64_size_of_central_directory; num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); } if (pZip->m_total_files != cdir_entries_on_this_disk) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; /* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */ if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); /* Now create an index into the central directory file records, do some basic sanity checking on each record */ p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size; mz_uint64 comp_size, decomp_size, local_header_ofs; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && (ext_data_size) && (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX)) { /* Attempt to find zip64 extended information field in the entry's extra data */ mz_uint32 extra_size_remaining = ext_data_size; if (extra_size_remaining) { const mz_uint8 *pExtra_data; void* buf = NULL; if (MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + ext_data_size > n) { buf = MZ_MALLOC(ext_data_size); if(buf==NULL) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size, buf, ext_data_size) != ext_data_size) { MZ_FREE(buf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); } pExtra_data = (mz_uint8*)buf; } else { pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; } do { mz_uint32 field_id; mz_uint32 field_data_size; if (extra_size_remaining < (sizeof(mz_uint16) * 2)) { MZ_FREE(buf); return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } field_id = MZ_READ_LE16(pExtra_data); field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) { MZ_FREE(buf); return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { /* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */ pZip->m_pState->m_zip64 = MZ_TRUE; pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; break; } pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; } while (extra_size_remaining); MZ_FREE(buf); } } /* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */ if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) { if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); if (comp_size != MZ_UINT32_MAX) { if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } void mz_zip_zero_struct(mz_zip_archive *pZip) { if (pZip) MZ_CLEAR_OBJ(*pZip); } static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) { mz_bool status = MZ_TRUE; if (!pZip) return MZ_FALSE; if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) { if (set_last_error) pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; return MZ_FALSE; } if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { if (MZ_FCLOSE(pState->m_pFile) == EOF) { if (set_last_error) pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; status = MZ_FALSE; } } pState->m_pFile = NULL; } #endif /* #ifndef MINIZ_NO_STDIO */ pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { return mz_zip_reader_end_internal(pZip, MZ_TRUE); } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags) { if ((!pZip) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_zip_type = MZ_ZIP_TYPE_USER; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end_internal(pZip, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags) { if (!pMem) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pNeeds_keepalive = NULL; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end_internal(pZip, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); file_ofs += pZip->m_pState->m_file_archive_start_ofs; if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0); } mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size) { mz_uint64 file_size; MZ_FILE *pFile; if ((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); file_size = archive_size; if (!file_size) { if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); } file_size = MZ_FTELL64(pFile); } /* TODO: Better sanity check archive_size and the # of actual remaining bytes */ if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) { MZ_FCLOSE(pFile); return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); } if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_zip_type = MZ_ZIP_TYPE_FILE; pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end_internal(pZip, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags) { mz_uint64 cur_file_ofs; if ((!pZip) || (!pFile)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); cur_file_ofs = MZ_FTELL64(pFile); if (!archive_size) { if (MZ_FSEEK64(pFile, 0, SEEK_END)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); archive_size = MZ_FTELL64(pFile) - cur_file_ofs; if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); } if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = archive_size; pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end_internal(pZip, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } #endif /* #ifndef MINIZ_NO_STDIO */ static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); if (!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; } m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; } mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index) { mz_uint bit_flag; mz_uint method; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); if (!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; } method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); if ((method != 0) && (method != MZ_DEFLATED)) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); return MZ_FALSE; } if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); return MZ_FALSE; } if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); return MZ_FALSE; } return MZ_TRUE; } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, attribute_mapping_id, external_attr; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); if (!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; } filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } /* Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. */ /* Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. */ /* FIXME: Remove this check? Is it necessary - we already check the filename. */ attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; (void)attribute_mapping_id; external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) { return MZ_TRUE; } return MZ_FALSE; } static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_index, const mz_uint8 *pCentral_dir_header, mz_zip_archive_file_stat *pStat, mz_bool *pFound_zip64_extra_data) { mz_uint n; const mz_uint8 *p = pCentral_dir_header; if (pFound_zip64_extra_data) *pFound_zip64_extra_data = MZ_FALSE; if ((!p) || (!pStat)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* Extract fields from the central directory record. */ pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); /* Copy as much of the filename and comment as possible. */ n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; /* Set some flags for convienance */ pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); /* See if we need to read any zip64 extended information fields. */ /* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */ if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) { /* Attempt to find zip64 extended information field in the entry's extra data */ mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); if (extra_size_remaining) { const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); do { mz_uint32 field_id; mz_uint32 field_data_size; if (extra_size_remaining < (sizeof(mz_uint16) * 2)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); field_id = MZ_READ_LE16(pExtra_data); field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; mz_uint32 field_data_remaining = field_data_size; if (pFound_zip64_extra_data) *pFound_zip64_extra_data = MZ_TRUE; if (pStat->m_uncomp_size == MZ_UINT32_MAX) { if (field_data_remaining < sizeof(mz_uint64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pStat->m_uncomp_size = MZ_READ_LE64(pField_data); pField_data += sizeof(mz_uint64); field_data_remaining -= sizeof(mz_uint64); } if (pStat->m_comp_size == MZ_UINT32_MAX) { if (field_data_remaining < sizeof(mz_uint64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pStat->m_comp_size = MZ_READ_LE64(pField_data); pField_data += sizeof(mz_uint64); field_data_remaining -= sizeof(mz_uint64); } if (pStat->m_local_header_ofs == MZ_UINT32_MAX) { if (field_data_remaining < sizeof(mz_uint64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); pField_data += sizeof(mz_uint64); field_data_remaining -= sizeof(mz_uint64); } break; } pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; } while (extra_size_remaining); } } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if (*pR != '\\' || *pL != '/') { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; } pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename, mz_uint32 *pIndex) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); const uint32_t size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); if (pIndex) *pIndex = 0; if (size) { /* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */ /* honestly the major expense here on 32-bit CPU's will still be the filename compare */ mz_int64 l = 0, h = (mz_int64)size - 1; while (l <= h) { mz_int64 m = l + ((h - l) >> 1); uint32_t file_index = pIndices[(uint32_t)m]; int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) { if (pIndex) *pIndex = file_index; return MZ_TRUE; } else if (comp < 0) l = m + 1; else h = m - 1; } } return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint32 index; if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) return -1; else return (int)index; } mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex) { mz_uint file_index; size_t name_len, comment_len; if (pIndex) *pIndex = 0; if ((!pZip) || (!pZip->m_pState) || (!pName)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* See if we can use a binary search */ if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) { return mz_zip_locate_file_binary_search(pZip, pName, pIndex); } /* Locate the entry by scanning the entire central directory */ name_len = strlen(pName); if (name_len > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); comment_len = pComment ? strlen(pComment) : 0; if (comment_len > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) { if (pIndex) *pIndex = file_index; return MZ_TRUE; } } return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; /* A directory or zero length file */ if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) return MZ_TRUE; /* Encryption and patch files are not supported. */ if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); /* This function only supports decompressing stored and deflate. */ if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); /* Ensure supplied output buffer is large enough. */ needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); /* Read and parse the local directory entry. */ cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { /* The file is stored or the caller has requested the compressed data. */ if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) { if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); } #endif return MZ_TRUE; } /* Decompress the file either directly from memory or from a file input buffer. */ tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { /* Read directly from the archive in memory. */ pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { /* Use a user provided read buffer. */ if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { /* Temporarily allocate a read buffer. */ read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { /* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */ size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { /* Make sure the entire file was decompressed, and check its CRC. */ if (out_buf_ofs != file_stat.m_uncomp_size) { mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); status = TINFL_STATUS_FAILED; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) { mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); status = TINFL_STATUS_FAILED; } #endif } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { mz_uint32 file_index; if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); void *pBuf; if (pSize) *pSize = 0; if (!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return NULL; } comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) { mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); return NULL; } if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); return NULL; } if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { mz_uint32 file_index; if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) { if (pSize) *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; /* A directory or zero length file */ if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) return MZ_TRUE; /* Encryption and patch files are not supported. */ if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); /* This function only supports decompressing stored and deflate. */ if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); /* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */ cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); /* Decompress the file either directly from memory or from a file input buffer. */ if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { /* The file is stored or the caller has requested the compressed data. */ if (pZip->m_pState->m_pMem) { if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) { mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); status = TINFL_STATUS_FAILED; } else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); #endif } cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); status = TINFL_STATUS_FAILED; break; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); } #endif if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); status = TINFL_STATUS_FAILED; } else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); status = TINFL_STATUS_FAILED; break; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); #endif if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { /* Make sure the entire file was decompressed, and check its CRC. */ if (out_buf_ofs != file_stat.m_uncomp_size) { mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); status = TINFL_STATUS_FAILED; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS else if (file_crc32 != file_stat.m_crc32) { mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); status = TINFL_STATUS_FAILED; } #endif } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { mz_uint32 file_index; if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) { mz_zip_reader_extract_iter_state *pState; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; /* Argument sanity check */ if ((!pZip) || (!pZip->m_pState)) return NULL; /* Allocate an iterator status structure */ pState = (mz_zip_reader_extract_iter_state*)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state)); if (!pState) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); return NULL; } /* Fetch file details */ if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState); return NULL; } /* Encryption and patch files are not supported. */ if (pState->file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); pZip->m_pFree(pZip->m_pAlloc_opaque, pState); return NULL; } /* This function only supports decompressing stored and deflate. */ if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (pState->file_stat.m_method != 0) && (pState->file_stat.m_method != MZ_DEFLATED)) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); pZip->m_pFree(pZip->m_pAlloc_opaque, pState); return NULL; } /* Init state - save args */ pState->pZip = pZip; pState->flags = flags; /* Init state - reset variables to defaults */ pState->status = TINFL_STATUS_DONE; #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS pState->file_crc32 = MZ_CRC32_INIT; #endif pState->read_buf_ofs = 0; pState->out_buf_ofs = 0; pState->pRead_buf = NULL; pState->pWrite_buf = NULL; pState->out_blk_remain = 0; /* Read and parse the local directory entry. */ pState->cur_file_ofs = pState->file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); pZip->m_pFree(pZip->m_pAlloc_opaque, pState); return NULL; } if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pZip->m_pFree(pZip->m_pAlloc_opaque, pState); return NULL; } pState->cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) > pZip->m_archive_size) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pZip->m_pFree(pZip->m_pAlloc_opaque, pState); return NULL; } /* Decompress the file either directly from memory or from a file input buffer. */ if (pZip->m_pState->m_pMem) { pState->pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + pState->cur_file_ofs; pState->read_buf_size = pState->read_buf_avail = pState->file_stat.m_comp_size; pState->comp_remaining = pState->file_stat.m_comp_size; } else { if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) { /* Decompression required, therefore intermediate read buffer required */ pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)pState->read_buf_size))) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); pZip->m_pFree(pZip->m_pAlloc_opaque, pState); return NULL; } } else { /* Decompression not required - we will be reading directly into user buffer, no temp buf required */ pState->read_buf_size = 0; } pState->read_buf_avail = 0; pState->comp_remaining = pState->file_stat.m_comp_size; } if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) { /* Decompression required, init decompressor */ tinfl_init( &pState->inflator ); /* Allocate write buffer */ if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); if (pState->pRead_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf); pZip->m_pFree(pZip->m_pAlloc_opaque, pState); return NULL; } } return pState; } mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) { mz_uint32 file_index; /* Locate file index by name */ if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) return NULL; /* Construct iterator */ return mz_zip_reader_extract_iter_new(pZip, file_index, flags); } size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size) { size_t copied_to_caller = 0; /* Argument sanity check */ if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf)) return 0; if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method)) { /* The file is stored or the caller has requested the compressed data, calc amount to return. */ copied_to_caller = (size_t)MZ_MIN( buf_size, pState->comp_remaining ); /* Zip is in memory....or requires reading from a file? */ if (pState->pZip->m_pState->m_pMem) { /* Copy data to caller's buffer */ memcpy( pvBuf, pState->pRead_buf, copied_to_caller ); pState->pRead_buf = ((mz_uint8*)pState->pRead_buf) + copied_to_caller; } else { /* Read directly into caller's buffer */ if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pvBuf, copied_to_caller) != copied_to_caller) { /* Failed to read all that was asked for, flag failure and alert user */ mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); pState->status = TINFL_STATUS_FAILED; copied_to_caller = 0; } } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS /* Compute CRC if not returning compressed data only */ if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, (const mz_uint8 *)pvBuf, copied_to_caller); #endif /* Advance offsets, dec counters */ pState->cur_file_ofs += copied_to_caller; pState->out_buf_ofs += copied_to_caller; pState->comp_remaining -= copied_to_caller; } else { do { /* Calc ptr to write buffer - given current output pos and block size */ mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pState->pWrite_buf + (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); /* Calc max output size - given current output pos and block size */ size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if (!pState->out_blk_remain) { /* Read more data from file if none available (and reading from file) */ if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem)) { /* Calc read size */ pState->read_buf_avail = MZ_MIN(pState->read_buf_size, pState->comp_remaining); if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pState->pRead_buf, (size_t)pState->read_buf_avail) != pState->read_buf_avail) { mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); pState->status = TINFL_STATUS_FAILED; break; } /* Advance offsets, dec counters */ pState->cur_file_ofs += pState->read_buf_avail; pState->comp_remaining -= pState->read_buf_avail; pState->read_buf_ofs = 0; } /* Perform decompression */ in_buf_size = (size_t)pState->read_buf_avail; pState->status = tinfl_decompress(&pState->inflator, (const mz_uint8 *)pState->pRead_buf + pState->read_buf_ofs, &in_buf_size, (mz_uint8 *)pState->pWrite_buf, pWrite_buf_cur, &out_buf_size, pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); pState->read_buf_avail -= in_buf_size; pState->read_buf_ofs += in_buf_size; /* Update current output block size remaining */ pState->out_blk_remain = out_buf_size; } if (pState->out_blk_remain) { /* Calc amount to return. */ size_t to_copy = MZ_MIN( (buf_size - copied_to_caller), pState->out_blk_remain ); /* Copy data to caller's buffer */ memcpy( (uint8_t*)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy ); #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS /* Perform CRC */ pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy); #endif /* Decrement data consumed from block */ pState->out_blk_remain -= to_copy; /* Inc output offset, while performing sanity check */ if ((pState->out_buf_ofs += to_copy) > pState->file_stat.m_uncomp_size) { mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); pState->status = TINFL_STATUS_FAILED; break; } /* Increment counter of data copied to caller */ copied_to_caller += to_copy; } } while ( (copied_to_caller < buf_size) && ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) || (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT)) ); } /* Return how many bytes were copied into user buffer */ return copied_to_caller; } mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState) { int status; /* Argument sanity check */ if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState)) return MZ_FALSE; /* Was decompression completed and requested? */ if ((pState->status == TINFL_STATUS_DONE) && (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { /* Make sure the entire file was decompressed, and check its CRC. */ if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size) { mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); pState->status = TINFL_STATUS_FAILED; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS else if (pState->file_crc32 != pState->file_stat.m_crc32) { mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); pState->status = TINFL_STATUS_FAILED; } #endif } /* Free buffers */ if (!pState->pZip->m_pState->m_pMem) pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf); if (pState->pWrite_buf) pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf); /* Save status */ status = pState->status; /* Free context */ pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState); return status == TINFL_STATUS_DONE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) { if (status) mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); status = MZ_FALSE; } #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) if (status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif return status; } mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { mz_uint32 file_index; if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *pFile, mz_uint flags) { mz_zip_archive_file_stat file_stat; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); return mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); } mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags) { mz_uint32 file_index; if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) return MZ_FALSE; return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); } #endif /* #ifndef MINIZ_NO_STDIO */ static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_uint32 *p = (mz_uint32 *)pOpaque; (void)file_ofs; *p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n); return n; } mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) { mz_zip_archive_file_stat file_stat; mz_zip_internal_state *pState; const mz_uint8 *pCentral_dir_header; mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE; mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint64 local_header_ofs = 0; mz_uint32 local_header_filename_len, local_header_extra_len, local_header_crc32; mz_uint64 local_header_comp_size, local_header_uncomp_size; mz_uint32 uncomp_crc32 = MZ_CRC32_INIT; mz_bool has_data_descriptor; mz_uint32 local_header_bit_flags; mz_zip_array file_data_array; mz_zip_array_init(&file_data_array, 1); if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (file_index > pZip->m_total_files) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir)) return MZ_FALSE; /* A directory or zero length file */ if ((file_stat.m_is_directory) || (!file_stat.m_uncomp_size)) return MZ_TRUE; /* Encryption and patch files are not supported. */ if (file_stat.m_is_encrypted) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); /* This function only supports stored and deflate. */ if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); if (!file_stat.m_is_supported) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); /* Read and parse the local directory entry. */ local_header_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); local_header_filename_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS); local_header_bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); has_data_descriptor = (local_header_bit_flags & 8) != 0; if (local_header_filename_len != strlen(file_stat.m_filename)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if (!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); if (local_header_filename_len) { if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); goto handle_failure; } /* I've seen 1 archive that had the same pathname, but used backslashes in the local dir and forward slashes in the central dir. Do we care about this? For now, this case will fail validation. */ if (memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0) { mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); goto handle_failure; } } if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) { mz_uint32 extra_size_remaining = local_header_extra_len; const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p; if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); goto handle_failure; } do { mz_uint32 field_id, field_data_size, field_total_size; if (extra_size_remaining < (sizeof(mz_uint16) * 2)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); field_id = MZ_READ_LE16(pExtra_data); field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); field_total_size = field_data_size + sizeof(mz_uint16) * 2; if (field_total_size > extra_size_remaining) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); if (field_data_size < sizeof(mz_uint64) * 2) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); goto handle_failure; } local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); found_zip64_ext_data_in_ldir = MZ_TRUE; break; } pExtra_data += field_total_size; extra_size_remaining -= field_total_size; } while (extra_size_remaining); } /* TODO: parse local header extra data when local_header_comp_size is 0xFFFFFFFF! (big_descriptor.zip) */ /* I've seen zips in the wild with the data descriptor bit set, but proper local header values and bogus data descriptors */ if ((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32)) { mz_uint8 descriptor_buf[32]; mz_bool has_id; const mz_uint8 *pSrc; mz_uint32 file_crc32; mz_uint64 comp_size = 0, uncomp_size = 0; mz_uint32 num_descriptor_uint32s = ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s)) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); goto handle_failure; } has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID); pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf; file_crc32 = MZ_READ_LE32(pSrc); if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) { comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); } else { comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32)); uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); } if ((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size)) { mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); goto handle_failure; } } else { if ((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size)) { mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); goto handle_failure; } } mz_zip_array_clear(pZip, &file_data_array); if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) { if (!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) return MZ_FALSE; /* 1 more check to be sure, although the extract checks too. */ if (uncomp_crc32 != file_stat.m_crc32) { mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); return MZ_FALSE; } } return MZ_TRUE; handle_failure: mz_zip_array_clear(pZip, &file_data_array); return MZ_FALSE; } mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) { mz_zip_internal_state *pState; uint32_t i; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; /* Basic sanity checks */ if (!pState->m_zip64) { if (pZip->m_total_files > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); if (pZip->m_archive_size > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); } else { if (pZip->m_total_files >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); } for (i = 0; i < pZip->m_total_files; i++) { if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) { mz_uint32 found_index; mz_zip_archive_file_stat stat; if (!mz_zip_reader_file_stat(pZip, i, &stat)) return MZ_FALSE; if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index)) return MZ_FALSE; /* This check can fail if there are duplicate filenames in the archive (which we don't check for when writing - that's up to the user) */ if (found_index != i) return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); } if (!mz_zip_validate_file(pZip, i, flags)) return MZ_FALSE; } return MZ_TRUE; } mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr) { mz_bool success = MZ_TRUE; mz_zip_archive zip; mz_zip_error actual_err = MZ_ZIP_NO_ERROR; if ((!pMem) || (!size)) { if (pErr) *pErr = MZ_ZIP_INVALID_PARAMETER; return MZ_FALSE; } mz_zip_zero_struct(&zip); if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) { if (pErr) *pErr = zip.m_last_error; return MZ_FALSE; } if (!mz_zip_validate_archive(&zip, flags)) { actual_err = zip.m_last_error; success = MZ_FALSE; } if (!mz_zip_reader_end_internal(&zip, success)) { if (!actual_err) actual_err = zip.m_last_error; success = MZ_FALSE; } if (pErr) *pErr = actual_err; return success; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr) { mz_bool success = MZ_TRUE; mz_zip_archive zip; mz_zip_error actual_err = MZ_ZIP_NO_ERROR; if (!pFilename) { if (pErr) *pErr = MZ_ZIP_INVALID_PARAMETER; return MZ_FALSE; } mz_zip_zero_struct(&zip); if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) { if (pErr) *pErr = zip.m_last_error; return MZ_FALSE; } if (!mz_zip_validate_archive(&zip, flags)) { actual_err = zip.m_last_error; success = MZ_FALSE; } if (!mz_zip_reader_end_internal(&zip, success)) { if (!actual_err) actual_err = zip.m_last_error; success = MZ_FALSE; } if (pErr) *pErr = actual_err; return success; } #endif /* #ifndef MINIZ_NO_STDIO */ /* ------------------- .ZIP archive writing */ #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v) { mz_write_le32(p, (mz_uint32)v); mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32)); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) #define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v)) static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); if (!n) return 0; /* An allocation this big is likely to just fail on 32-bit systems, so don't even go there. */ if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) { mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); return 0; } if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); return 0; } pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) { if (set_last_error) mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; } pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { if (MZ_FCLOSE(pState->m_pFile) == EOF) { if (set_last_error) mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); status = MZ_FALSE; } } pState->m_pFile = NULL; } #endif /* #ifndef MINIZ_NO_STDIO */ if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags) { mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) { if (!pZip->m_pRead) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); } if (pZip->m_file_offset_alignment) { /* Ensure user specified file offset alignment is a power of 2. */ if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); } if (!pZip->m_pAlloc) pZip->m_pAlloc = miniz_def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = miniz_def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = miniz_def_realloc_func; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); pZip->m_pState->m_zip64 = zip64; pZip->m_pState->m_zip64_has_extended_info_fields = zip64; pZip->m_zip_type = MZ_ZIP_TYPE_USER; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; return MZ_TRUE; } mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { return mz_zip_writer_init_v2(pZip, existing_size, 0); } mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pNeeds_keepalive = NULL; if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) return MZ_FALSE; pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end_internal(pZip, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, initial_allocation_size, 0); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); file_ofs += pZip->m_pState->m_file_archive_start_ofs; if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) { mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); return 0; } return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { return mz_zip_writer_init_file_v2(pZip, pFilename, size_to_reserve_at_beginning, 0); } mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pNeeds_keepalive = NULL; if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) return MZ_FALSE; if (NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) { mz_zip_writer_end(pZip); return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); } pZip->m_pState->m_pFile = pFile; pZip->m_zip_type = MZ_ZIP_TYPE_FILE; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags) { pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pNeeds_keepalive = NULL; if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init_v2(pZip, 0, flags)) return MZ_FALSE; pZip->m_pState->m_pFile = pFile; pZip->m_pState->m_file_archive_start_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; return MZ_TRUE; } #endif /* #ifndef MINIZ_NO_STDIO */ mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) { /* We don't support converting a non-zip64 file to zip64 - this seems like more trouble than it's worth. (What about the existing 32-bit data descriptors that could follow the compressed data?) */ if (!pZip->m_pState->m_zip64) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); } /* No sense in trying to write to an archive that's already at the support max size */ if (pZip->m_pState->m_zip64) { if (pZip->m_total_files == MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } else { if (pZip->m_total_files == MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); } pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO (void)pFilename; return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); #else if (pZip->m_pIO_opaque != pZip) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { if (!pFilename) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* Archive is being read from stdio and was originally opened only for reading. Try to reopen as writable. */ if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { /* The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. */ mz_zip_reader_end_internal(pZip, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); } } pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pNeeds_keepalive = NULL; #endif /* #ifdef MINIZ_NO_STDIO */ } else if (pState->m_pMem) { /* Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. */ if (pZip->m_pIO_opaque != pZip) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pNeeds_keepalive = NULL; } /* Archive is being read via a user provided read function - make sure the user has specified a write function too. */ else if (!pZip->m_pWrite) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* Start writing new files at the archive's current central directory location. */ /* TODO: We could add a flag that lets the user start writing immediately AFTER the existing central dir - this would be safer. */ pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_central_directory_file_ofs = 0; /* Clear the sorted central dir offsets, they aren't useful or maintained now. */ /* Even though we're now in write mode, files can still be extracted and verified, but file locates will be slow. */ /* TODO: We could easily maintain the sorted central directory offsets. */ mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; return MZ_TRUE; } mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0); } /* TODO: pArchive_name is a terrible name here! */ mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } #define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2) #define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3) static mz_uint32 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size, mz_uint64 *pComp_size, mz_uint64 *pLocal_header_ofs) { mz_uint8 *pDst = pBuf; mz_uint32 field_size = 0; MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); MZ_WRITE_LE16(pDst + 2, 0); pDst += sizeof(mz_uint16) * 2; if (pUncomp_size) { MZ_WRITE_LE64(pDst, *pUncomp_size); pDst += sizeof(mz_uint64); field_size += sizeof(mz_uint64); } if (pComp_size) { MZ_WRITE_LE64(pDst, *pComp_size); pDst += sizeof(mz_uint64); field_size += sizeof(mz_uint64); } if (pLocal_header_ofs) { MZ_WRITE_LE64(pDst, *pLocal_header_ofs); pDst += sizeof(mz_uint64); field_size += sizeof(mz_uint64); } MZ_WRITE_LE16(pBuf + 2, field_size); return (mz_uint32)(pDst - pBuf); } static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_MIN(local_header_ofs, MZ_UINT32_MAX)); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes, const char *user_extra_data, mz_uint user_extra_data_len) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; if (!pZip->m_pState->m_zip64) { if (local_header_ofs > 0xFFFFFFFF) return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); } /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, (mz_uint16)(extra_size + user_extra_data_len), comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, user_extra_data_len)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { /* Try to resize the central directory array back into its original state. */ mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { /* Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. */ if (*pArchive_name == '/') return MZ_FALSE; /* Making sure the name does not contain drive letters or DOS style backward slashes is the responsibility of the program using miniz*/ return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (mz_uint)((pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1)); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { return mz_zip_writer_add_mem_ex_v2(pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0); } mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; mz_uint8 *pExtra_data = NULL; mz_uint32 extra_size = 0; mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; mz_uint16 bit_flags = 0; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if (uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; if (pState->m_zip64) { if (pZip->m_total_files == MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } else { if (pZip->m_total_files == MZ_UINT16_MAX) { pState->m_zip64 = MZ_TRUE; /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ } if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) { pState->m_zip64 = MZ_TRUE; /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ } } if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (!mz_zip_writer_validate_archive_name(pArchive_name)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); #ifndef MINIZ_NO_TIME if (last_modified != NULL) { mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); } else { MZ_TIME_T cur_time; time(&cur_time); mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); } #endif /* #ifndef MINIZ_NO_TIME */ if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } archive_name_size = strlen(pArchive_name); if (archive_name_size > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); if (!pState->m_zip64) { /* Bail early if the archive would obviously become too large */ if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + user_extra_data_len + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len + MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF) { pState->m_zip64 = MZ_TRUE; /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ } } if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { /* Set DOS Subdirectory attribute bit. */ ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; /* Subdirectories cannot contain data. */ if ((buf_size) || (uncomp_size)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); } /* Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) */ if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes; MZ_CLEAR_OBJ(local_dir_header); if (!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { method = MZ_DEFLATED; } if (pState->m_zip64) { if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) { pExtra_data = extra_data; extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); } if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, bit_flags, dos_time, dos_date)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += sizeof(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_archive_file_ofs += archive_name_size; if (pExtra_data != NULL) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += extra_size; } } else { if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += sizeof(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_archive_file_ofs += archive_name_size; } if (user_extra_data_len > 0) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += user_extra_data_len; } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_archive_file_ofs += buf_size; comp_size = buf_size; } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; if (uncomp_size) { mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); if (pExtra_data == NULL) { if (comp_size > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); MZ_WRITE_LE32(local_dir_footer + 8, comp_size); MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); } else { MZ_WRITE_LE64(local_dir_footer + 8, comp_size); MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) return MZ_FALSE; cur_archive_file_ofs += local_dir_footer_size; } if (pExtra_data != NULL) { extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); } if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, user_extra_data_central, user_extra_data_central_len)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) { mz_uint16 gen_flags = MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = size_to_add, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; mz_uint8 *pExtra_data = NULL; mz_uint32 extra_size = 0; mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; mz_zip_internal_state *pState; mz_uint64 file_ofs = 0; if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; /* Sanity checks */ if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; if ((!pState->m_zip64) && (uncomp_size > MZ_UINT32_MAX)) { /* Source file is too large for non-zip64 */ /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ pState->m_zip64 = MZ_TRUE; } /* We could support this, but why? */ if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (!mz_zip_writer_validate_archive_name(pArchive_name)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); if (pState->m_zip64) { if (pZip->m_total_files == MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } else { if (pZip->m_total_files == MZ_UINT16_MAX) { pState->m_zip64 = MZ_TRUE; /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ } } archive_name_size = strlen(pArchive_name); if (archive_name_size > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); if (!pState->m_zip64) { /* Bail early if the archive would obviously become too large */ if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + user_extra_data_len + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024 + MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) > 0xFFFFFFFF) { pState->m_zip64 = MZ_TRUE; /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ } } #ifndef MINIZ_NO_TIME if (pFile_time) { mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); } #endif if (uncomp_size <= 3) level = 0; if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) { return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_archive_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_archive_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (uncomp_size && level) { method = MZ_DEFLATED; } MZ_CLEAR_OBJ(local_dir_header); if (pState->m_zip64) { if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) { pExtra_data = extra_data; extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); } if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, gen_flags, dos_time, dos_date)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += sizeof(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_archive_file_ofs += archive_name_size; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += extra_size; } else { if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += sizeof(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_archive_file_ofs += archive_name_size; } if (user_extra_data_len > 0) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += user_extra_data_len; } if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((read_callback(callback_opaque, file_ofs, pRead_buf, n) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); } file_ofs += n; uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); } for (;;) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; tdefl_flush flush = TDEFL_NO_FLUSH; if (read_callback(callback_opaque, file_ofs, pRead_buf, in_buf_size)!= in_buf_size) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); break; } file_ofs += in_buf_size; uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; if (pZip->m_pNeeds_keepalive != NULL && pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque)) flush = TDEFL_FULL_FLUSH; status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? flush : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) { mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); break; } } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } { mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); if (pExtra_data == NULL) { if (comp_size > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); MZ_WRITE_LE32(local_dir_footer + 8, comp_size); MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); } else { MZ_WRITE_LE64(local_dir_footer + 8, comp_size); MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) return MZ_FALSE; cur_archive_file_ofs += local_dir_footer_size; } if (pExtra_data != NULL) { extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); } if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, gen_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, user_extra_data_central, user_extra_data_central_len)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_file_read_func_stdio(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { MZ_FILE *pSrc_file = (MZ_FILE *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pSrc_file); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pSrc_file, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pSrc_file); } mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) { return mz_zip_writer_add_read_buf_callback(pZip, pArchive_name, mz_file_read_func_stdio, pSrc_file, size_to_add, pFile_time, pComment, comment_size, level_and_flags, user_extra_data, user_extra_data_len, user_extra_data_central, user_extra_data_central_len); } mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { MZ_FILE *pSrc_file = NULL; mz_uint64 uncomp_size = 0; MZ_TIME_T file_modified_time; MZ_TIME_T *pFile_time = NULL; mz_bool status; memset(&file_modified_time, 0, sizeof(file_modified_time)); #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) pFile_time = &file_modified_time; if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); #endif pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); status = mz_zip_writer_add_cfile(pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, comment_size, level_and_flags, NULL, 0, NULL, 0); MZ_FCLOSE(pSrc_file); return status; } #endif /* #ifndef MINIZ_NO_STDIO */ static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, uint32_t ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) { /* + 64 should be enough for any new zip64 data */ if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) { mz_uint8 new_ext_block[64]; mz_uint8 *pDst = new_ext_block; mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); mz_write_le16(pDst + sizeof(mz_uint16), 0); pDst += sizeof(mz_uint16) * 2; if (pUncomp_size) { mz_write_le64(pDst, *pUncomp_size); pDst += sizeof(mz_uint64); } if (pComp_size) { mz_write_le64(pDst, *pComp_size); pDst += sizeof(mz_uint64); } if (pLocal_header_ofs) { mz_write_le64(pDst, *pLocal_header_ofs); pDst += sizeof(mz_uint64); } if (pDisk_start) { mz_write_le32(pDst, *pDisk_start); pDst += sizeof(mz_uint32); } mz_write_le16(new_ext_block + sizeof(mz_uint16), (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } if ((pExt) && (ext_len)) { mz_uint32 extra_size_remaining = ext_len; const mz_uint8 *pExtra_data = pExt; do { mz_uint32 field_id, field_data_size, field_total_size; if (extra_size_remaining < (sizeof(mz_uint16) * 2)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); field_id = MZ_READ_LE16(pExtra_data); field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); field_total_size = field_data_size + sizeof(mz_uint16) * 2; if (field_total_size > extra_size_remaining) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } pExtra_data += field_total_size; extra_size_remaining -= field_total_size; } while (extra_size_remaining); } return MZ_TRUE; } /* TODO: This func is now pretty freakin complex due to zip64, split it up? */ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes, src_central_dir_following_data_size; mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; mz_zip_archive_file_stat src_file_stat; mz_uint32 src_filename_len, src_comment_len, src_ext_len; mz_uint32 local_header_filename_size, local_header_extra_len; mz_uint64 local_header_comp_size, local_header_uncomp_size; mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; /* Sanity checks */ if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; /* Don't support copying files from zip64 archives to non-zip64, even though in some cases this is possible */ if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* Get pointer to the source central dir header and crack it */ if (NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); src_filename_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); src_comment_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS); src_central_dir_following_data_size = src_filename_len + src_ext_len + src_comment_len; /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 fudge factor in case we need to add more extra data) */ if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); if (!pState->m_zip64) { if (pZip->m_total_files == MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } else { /* TODO: Our zip64 support still has some 32-bit limits that may not be worth fixing. */ if (pZip->m_total_files == MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL)) return MZ_FALSE; cur_src_file_ofs = src_file_stat.m_local_header_ofs; cur_dst_file_ofs = pZip->m_archive_size; /* Read the source archive's local dir header */ if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; /* Compute the total size we need to copy (filename+extra data+compressed data) */ local_header_filename_size = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); src_archive_bytes_remaining = local_header_filename_size + local_header_extra_len + src_file_stat.m_comp_size; /* Try to find a zip64 extended information field */ if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) { mz_zip_array file_data_array; const mz_uint8 *pExtra_data; mz_uint32 extra_size_remaining = local_header_extra_len; mz_zip_array_init(&file_data_array, 1); if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE)) { return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) { mz_zip_array_clear(pZip, &file_data_array); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); } pExtra_data = (const mz_uint8 *)file_data_array.m_p; do { mz_uint32 field_id, field_data_size, field_total_size; if (extra_size_remaining < (sizeof(mz_uint16) * 2)) { mz_zip_array_clear(pZip, &file_data_array); return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } field_id = MZ_READ_LE16(pExtra_data); field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); field_total_size = field_data_size + sizeof(mz_uint16) * 2; if (field_total_size > extra_size_remaining) { mz_zip_array_clear(pZip, &file_data_array); return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); if (field_data_size < sizeof(mz_uint64) * 2) { mz_zip_array_clear(pZip, &file_data_array); return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); /* may be 0 if there's a descriptor */ found_zip64_ext_data_in_ldir = MZ_TRUE; break; } pExtra_data += field_total_size; extra_size_remaining -= field_total_size; } while (extra_size_remaining); mz_zip_array_clear(pZip, &file_data_array); } if (!pState->m_zip64) { /* Try to detect if the new archive will most likely wind up too big and bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which could be present, +64 is a fudge factor). */ /* We also check when the archive is finalized so this doesn't need to be perfect. */ mz_uint64 approx_new_archive_size = cur_dst_file_ofs + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + (sizeof(mz_uint32) * 4) + pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; if (approx_new_archive_size >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); } /* Write dest archive padding */ if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } /* The original zip's local header+ext block doesn't change, even with zip64, so we can just copy it over to the dest zip */ if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; /* Copy over the source archive bytes to the dest archive, also ensure we have enough buf space to handle optional data descriptor */ if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining))))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); while (src_archive_bytes_remaining) { n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_dst_file_ofs += n; src_archive_bytes_remaining -= n; } /* Now deal with the optional data descriptor */ bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { /* Copy data descriptor */ if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) { /* src is zip64, dest must be zip64 */ /* name uint32_t's */ /* id 1 (optional in zip64?) */ /* crc 1 */ /* comp_size 2 */ /* uncomp_size 2 */ if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5); } else { /* src is NOT zip64 */ mz_bool has_id; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); } has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); if (pZip->m_pState->m_zip64) { /* dest is zip64, so upgrade the data descriptor */ const mz_uint32 *pSrc_descriptor = (const mz_uint32 *)((const mz_uint8 *)pBuf + (has_id ? sizeof(mz_uint32) : 0)); const mz_uint32 src_crc32 = pSrc_descriptor[0]; const mz_uint64 src_comp_size = pSrc_descriptor[1]; const mz_uint64 src_uncomp_size = pSrc_descriptor[2]; mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID); mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32); mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size); mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4, src_uncomp_size); n = sizeof(mz_uint32) * 6; } else { /* dest is NOT zip64, just copy it as-is */ n = sizeof(mz_uint32) * (has_id ? 4 : 3); } } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); /* Finally, add the new central dir header */ orig_central_dir_size = pState->m_central_dir.m_size; memcpy(new_central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); if (pState->m_zip64) { /* This is the painful part: We need to write a new central dir header + ext block with updated zip64 fields, and ensure the old fields (if any) are not included. */ const mz_uint8 *pSrc_ext = pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; mz_zip_array new_ext_block; mz_zip_array_init(&new_ext_block, sizeof(mz_uint8)); MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_UINT32_MAX); MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_UINT32_MAX); MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_UINT32_MAX); if (!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL)) { mz_zip_array_clear(pZip, &new_ext_block); return MZ_FALSE; } MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, new_ext_block.m_size); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) { mz_zip_array_clear(pZip, &new_ext_block); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len)) { mz_zip_array_clear(pZip, &new_ext_block); mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size)) { mz_zip_array_clear(pZip, &new_ext_block); mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len)) { mz_zip_array_clear(pZip, &new_ext_block); mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } mz_zip_array_clear(pZip, &new_ext_block); } else { /* sanity checks */ if (cur_dst_file_ofs > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); if (local_dir_header_ofs >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } } /* This shouldn't trigger unless we screwed up during the initial sanity checks */ if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) { /* TODO: Support central dirs >= 32-bits in size */ mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); } n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[256]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; if (pState->m_zip64) { if ((pZip->m_total_files > MZ_UINT32_MAX) || (pState->m_central_dir.m_size >= MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } else { if ((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { /* Write central directory */ central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); pZip->m_archive_size += central_dir_size; } if (pState->m_zip64) { /* Write zip64 end of central directory header */ mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - sizeof(mz_uint64)); MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, 0x031E); /* TODO: always Unix */ MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D); MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; /* Write zip64 end of central directory locator */ MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, rel_ofs_to_zip64_ecdr); MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; } /* Write end of central directory record */ MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_size)); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); #endif /* #ifndef MINIZ_NO_STDIO */ pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize) { if ((!ppBuf) || (!pSize)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); *ppBuf = NULL; *pSize = 0; if ((!pZip) || (!pZip->m_pState)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (pZip->m_pWrite != mz_zip_heap_write_func) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *ppBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { return mz_zip_writer_end_internal(pZip, MZ_TRUE); } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { return mz_zip_add_mem_to_archive_file_in_place_v2(pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, NULL); } mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; mz_zip_error actual_err = MZ_ZIP_NO_ERROR; mz_zip_zero_struct(&zip_archive); if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) { if (pErr) *pErr = MZ_ZIP_INVALID_PARAMETER; return MZ_FALSE; } if (!mz_zip_writer_validate_archive_name(pArchive_name)) { if (pErr) *pErr = MZ_ZIP_INVALID_FILENAME; return MZ_FALSE; } /* Important: The regular non-64 bit version of stat() can fail here if the file is very large, which could cause the archive to be overwritten. */ /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { /* Create a new archive. */ if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags)) { if (pErr) *pErr = zip_archive.m_last_error; return MZ_FALSE; } created_new_archive = MZ_TRUE; } else { /* Append to an existing archive. */ if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) { if (pErr) *pErr = zip_archive.m_last_error; return MZ_FALSE; } if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags)) { if (pErr) *pErr = zip_archive.m_last_error; mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); actual_err = zip_archive.m_last_error; /* Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) */ if (!mz_zip_writer_finalize_archive(&zip_archive)) { if (!actual_err) actual_err = zip_archive.m_last_error; status = MZ_FALSE; } if (!mz_zip_writer_end_internal(&zip_archive, status)) { if (!actual_err) actual_err = zip_archive.m_last_error; status = MZ_FALSE; } if ((!status) && (created_new_archive)) { /* It's a new archive and something went wrong, so just delete it. */ int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } if (pErr) *pErr = actual_err; return status; } void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr) { mz_uint32 file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) *pSize = 0; if ((!pZip_filename) || (!pArchive_name)) { if (pErr) *pErr = MZ_ZIP_INVALID_PARAMETER; return NULL; } mz_zip_zero_struct(&zip_archive); if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) { if (pErr) *pErr = zip_archive.m_last_error; return NULL; } if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index)) { p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); } mz_zip_reader_end_internal(&zip_archive, p != NULL); if (pErr) *pErr = zip_archive.m_last_error; return p; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, NULL, pSize, flags, NULL); } #endif /* #ifndef MINIZ_NO_STDIO */ #endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ /* ------------------- Misc utils */ mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip) { return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID; } mz_zip_type mz_zip_get_type(mz_zip_archive *pZip) { return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID; } mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) { mz_zip_error prev_err; if (!pZip) return MZ_ZIP_INVALID_PARAMETER; prev_err = pZip->m_last_error; pZip->m_last_error = err_num; return prev_err; } mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) { if (!pZip) return MZ_ZIP_INVALID_PARAMETER; return pZip->m_last_error; } mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip) { return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR); } mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) { mz_zip_error prev_err; if (!pZip) return MZ_ZIP_INVALID_PARAMETER; prev_err = pZip->m_last_error; pZip->m_last_error = MZ_ZIP_NO_ERROR; return prev_err; } const char *mz_zip_get_error_string(mz_zip_error mz_err) { switch (mz_err) { case MZ_ZIP_NO_ERROR: return "no error"; case MZ_ZIP_UNDEFINED_ERROR: return "undefined error"; case MZ_ZIP_TOO_MANY_FILES: return "too many files"; case MZ_ZIP_FILE_TOO_LARGE: return "file too large"; case MZ_ZIP_UNSUPPORTED_METHOD: return "unsupported method"; case MZ_ZIP_UNSUPPORTED_ENCRYPTION: return "unsupported encryption"; case MZ_ZIP_UNSUPPORTED_FEATURE: return "unsupported feature"; case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: return "failed finding central directory"; case MZ_ZIP_NOT_AN_ARCHIVE: return "not a ZIP archive"; case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: return "invalid header or archive is corrupted"; case MZ_ZIP_UNSUPPORTED_MULTIDISK: return "unsupported multidisk archive"; case MZ_ZIP_DECOMPRESSION_FAILED: return "decompression failed or archive is corrupted"; case MZ_ZIP_COMPRESSION_FAILED: return "compression failed"; case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: return "unexpected decompressed size"; case MZ_ZIP_CRC_CHECK_FAILED: return "CRC-32 check failed"; case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: return "unsupported central directory size"; case MZ_ZIP_ALLOC_FAILED: return "allocation failed"; case MZ_ZIP_FILE_OPEN_FAILED: return "file open failed"; case MZ_ZIP_FILE_CREATE_FAILED: return "file create failed"; case MZ_ZIP_FILE_WRITE_FAILED: return "file write failed"; case MZ_ZIP_FILE_READ_FAILED: return "file read failed"; case MZ_ZIP_FILE_CLOSE_FAILED: return "file close failed"; case MZ_ZIP_FILE_SEEK_FAILED: return "file seek failed"; case MZ_ZIP_FILE_STAT_FAILED: return "file stat failed"; case MZ_ZIP_INVALID_PARAMETER: return "invalid parameter"; case MZ_ZIP_INVALID_FILENAME: return "invalid filename"; case MZ_ZIP_BUF_TOO_SMALL: return "buffer too small"; case MZ_ZIP_INTERNAL_ERROR: return "internal error"; case MZ_ZIP_FILE_NOT_FOUND: return "file not found"; case MZ_ZIP_ARCHIVE_TOO_LARGE: return "archive is too large"; case MZ_ZIP_VALIDATION_FAILED: return "validation failed"; case MZ_ZIP_WRITE_CALLBACK_FAILED: return "write calledback failed"; default: break; } return "unknown error"; } /* Note: Just because the archive is not zip64 doesn't necessarily mean it doesn't have Zip64 extended information extra field, argh. */ mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState)) return MZ_FALSE; return pZip->m_pState->m_zip64; } size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState)) return 0; return pZip->m_pState->m_central_dir.m_size; } mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) { if (!pZip) return 0; return pZip->m_archive_size; } mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState)) return 0; return pZip->m_pState->m_file_archive_start_ofs; } MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState)) return 0; return pZip->m_pState->m_pFile; } size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { return mz_zip_file_stat_internal(pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); } mz_bool mz_zip_end(mz_zip_archive *pZip) { if (!pZip) return MZ_FALSE; if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) return mz_zip_reader_end(pZip); #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) return mz_zip_writer_end(pZip); #endif return MZ_FALSE; } #ifdef __cplusplus } #endif #endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/
0
D://workCode//uploadProject\awtk\3rd
D://workCode//uploadProject\awtk\3rd\miniz\miniz_zip.h
#pragma once #include "miniz_common.h" /* ------------------- ZIP archive reading/writing */ #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus extern "C" { #endif enum { /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 }; typedef struct { /* Central directory file index. */ mz_uint32 m_file_index; /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ mz_uint64 m_central_dir_ofs; /* These fields are copied directly from the zip's central dir. */ mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME MZ_TIME_T m_time; #endif /* CRC-32 of uncompressed data. */ mz_uint32 m_crc32; /* File's compressed size. */ mz_uint64 m_comp_size; /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ mz_uint64 m_uncomp_size; /* Zip internal and external file attributes. */ mz_uint16 m_internal_attr; mz_uint32 m_external_attr; /* Entry's local header file offset in bytes. */ mz_uint64 m_local_header_ofs; /* Size of comment in bytes. */ mz_uint32 m_comment_size; /* MZ_TRUE if the entry appears to be a directory. */ mz_bool m_is_directory; /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ mz_bool m_is_encrypted; /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ mz_bool m_is_supported; /* Filename. If string ends in '/' it's a subdirectory entry. */ /* Guaranteed to be zero terminated, may be truncated to fit. */ char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; /* Comment field. */ /* Guaranteed to be zero terminated, may be truncated to fit. */ char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000 } mz_zip_flags; typedef enum { MZ_ZIP_TYPE_INVALID = 0, MZ_ZIP_TYPE_USER, MZ_ZIP_TYPE_MEMORY, MZ_ZIP_TYPE_HEAP, MZ_ZIP_TYPE_FILE, MZ_ZIP_TYPE_CFILE, MZ_ZIP_TOTAL_TYPES } mz_zip_type; /* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ typedef enum { MZ_ZIP_NO_ERROR = 0, MZ_ZIP_UNDEFINED_ERROR, MZ_ZIP_TOO_MANY_FILES, MZ_ZIP_FILE_TOO_LARGE, MZ_ZIP_UNSUPPORTED_METHOD, MZ_ZIP_UNSUPPORTED_ENCRYPTION, MZ_ZIP_UNSUPPORTED_FEATURE, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, MZ_ZIP_NOT_AN_ARCHIVE, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, MZ_ZIP_UNSUPPORTED_MULTIDISK, MZ_ZIP_DECOMPRESSION_FAILED, MZ_ZIP_COMPRESSION_FAILED, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, MZ_ZIP_CRC_CHECK_FAILED, MZ_ZIP_UNSUPPORTED_CDIR_SIZE, MZ_ZIP_ALLOC_FAILED, MZ_ZIP_FILE_OPEN_FAILED, MZ_ZIP_FILE_CREATE_FAILED, MZ_ZIP_FILE_WRITE_FAILED, MZ_ZIP_FILE_READ_FAILED, MZ_ZIP_FILE_CLOSE_FAILED, MZ_ZIP_FILE_SEEK_FAILED, MZ_ZIP_FILE_STAT_FAILED, MZ_ZIP_INVALID_PARAMETER, MZ_ZIP_INVALID_FILENAME, MZ_ZIP_BUF_TOO_SMALL, MZ_ZIP_INTERNAL_ERROR, MZ_ZIP_FILE_NOT_FOUND, MZ_ZIP_ARCHIVE_TOO_LARGE, MZ_ZIP_VALIDATION_FAILED, MZ_ZIP_WRITE_CALLBACK_FAILED, MZ_ZIP_TOTAL_ERRORS } mz_zip_error; typedef struct { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; /* We only support up to UINT32_MAX files in zip64 mode. */ mz_uint32 m_total_files; mz_zip_mode m_zip_mode; mz_zip_type m_zip_type; mz_zip_error m_last_error; mz_uint64 m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; mz_file_needs_keepalive m_pNeeds_keepalive; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef struct { mz_zip_archive *pZip; mz_uint flags; int status; #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS mz_uint file_crc32; #endif mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf; void *pWrite_buf; size_t out_blk_remain; tinfl_decompressor inflator; } mz_zip_reader_extract_iter_state; /* -------- ZIP reading */ /* Inits a ZIP archive reader. */ /* These functions read and validate the archive's central directory. */ MINIZ_EXPORT mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); MINIZ_EXPORT mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); #ifndef MINIZ_NO_STDIO /* Read a archive from a disk file. */ /* file_start_ofs is the file offset where the archive actually begins, or 0. */ /* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ MINIZ_EXPORT mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); MINIZ_EXPORT mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); /* Read an archive from an already opened FILE, beginning at the current file position. */ /* The archive is assumed to be archive_size bytes long. If archive_size is 0, then the entire rest of the file is assumed to contain the archive. */ /* The FILE will NOT be closed when mz_zip_reader_end() is called. */ MINIZ_EXPORT mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); #endif /* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ MINIZ_EXPORT mz_bool mz_zip_reader_end(mz_zip_archive *pZip); /* -------- ZIP reading or writing */ /* Clears a mz_zip_archive struct to all zeros. */ /* Important: This must be done before passing the struct to any mz_zip functions. */ MINIZ_EXPORT void mz_zip_zero_struct(mz_zip_archive *pZip); MINIZ_EXPORT mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); MINIZ_EXPORT mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); /* Returns the total number of files in the archive. */ MINIZ_EXPORT mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); MINIZ_EXPORT mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); MINIZ_EXPORT mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); MINIZ_EXPORT MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); /* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ MINIZ_EXPORT size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); /* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ /* Note that the m_last_error functionality is not thread safe. */ MINIZ_EXPORT mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); MINIZ_EXPORT mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); MINIZ_EXPORT mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); MINIZ_EXPORT mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); MINIZ_EXPORT const char *mz_zip_get_error_string(mz_zip_error mz_err); /* MZ_TRUE if the archive file entry is a directory entry. */ MINIZ_EXPORT mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); /* MZ_TRUE if the file is encrypted/strong encrypted. */ MINIZ_EXPORT mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); /* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ MINIZ_EXPORT mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); /* Retrieves the filename of an archive file entry. */ /* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ MINIZ_EXPORT mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); /* Attempts to locates a file in the archive's central directory. */ /* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ /* Returns -1 if the file cannot be found. */ MINIZ_EXPORT int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); MINIZ_EXPORT mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); /* Returns detailed information about an archive file entry. */ MINIZ_EXPORT mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); /* MZ_TRUE if the file is in zip64 format. */ /* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ MINIZ_EXPORT mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); /* Returns the total central directory size in bytes. */ /* The current max supported size is <= MZ_UINT32_MAX. */ MINIZ_EXPORT size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); /* Extracts a archive file to a memory buffer using no memory allocation. */ /* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); /* Extracts a archive file to a memory buffer. */ MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); /* Extracts a archive file to a dynamically allocated heap buffer. */ /* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ /* Returns NULL and sets the last error on failure. */ MINIZ_EXPORT void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); MINIZ_EXPORT void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); /* Extracts a archive file using a callback function to output the file's data. */ MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); /* Extract a file iteratively */ MINIZ_EXPORT mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); MINIZ_EXPORT mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); MINIZ_EXPORT size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size); MINIZ_EXPORT mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState); #ifndef MINIZ_NO_STDIO /* Extracts a archive file to a disk file and sets its last accessed and modified times. */ /* This function only extracts files, not archive directory records. */ MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); /* Extracts a archive file starting at the current position in the destination FILE stream. */ MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); #endif #if 0 /* TODO */ typedef void *mz_zip_streaming_extract_state_ptr; mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); #endif /* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ /* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ MINIZ_EXPORT mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); /* Validates an entire archive by calling mz_zip_validate_file() on each file. */ MINIZ_EXPORT mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); /* Misc utils/helpers, valid for ZIP reading or writing */ MINIZ_EXPORT mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); MINIZ_EXPORT mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); /* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ MINIZ_EXPORT mz_bool mz_zip_end(mz_zip_archive *pZip); /* -------- ZIP writing */ #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS /* Inits a ZIP archive writer. */ /*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/ /*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/ MINIZ_EXPORT mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); MINIZ_EXPORT mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); MINIZ_EXPORT mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); MINIZ_EXPORT mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); #ifndef MINIZ_NO_STDIO MINIZ_EXPORT mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); MINIZ_EXPORT mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); MINIZ_EXPORT mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); #endif /* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ /* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ /* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ /* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ /* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ /* the archive is finalized the file's central directory will be hosed. */ MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); /* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ /* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ MINIZ_EXPORT mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); /* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ /* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len); /* Adds the contents of a file to an archive. This function also records the disk file's modified time into the archive. */ /* File data is supplied via a read callback function. User mz_zip_writer_add_(c)file to add a file directly.*/ MINIZ_EXPORT mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len); #ifndef MINIZ_NO_STDIO /* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ MINIZ_EXPORT mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); /* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ MINIZ_EXPORT mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len); #endif /* Adds a file to an archive by fully cloning the data from another archive. */ /* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ MINIZ_EXPORT mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); /* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ /* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ /* An archive must be manually finalized by calling this function for it to be valid. */ MINIZ_EXPORT mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); /* Finalizes a heap archive, returning a poiner to the heap block and its size. */ /* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ MINIZ_EXPORT mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); /* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ /* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ MINIZ_EXPORT mz_bool mz_zip_writer_end(mz_zip_archive *pZip); /* -------- Misc. high-level helper functions: */ /* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ /* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ /* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); /* Reads a single file from an archive into a heap block. */ /* If pComment is not NULL, only the file with the specified comment will be extracted. */ /* Returns NULL on failure. */ MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); #endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ #ifdef __cplusplus } #endif #endif /* MINIZ_NO_ARCHIVE_APIS */
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\agg\nanovg_agg.h
#ifndef NANOVG_AGG_H #define NANOVG_AGG_H #include <math.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include "nanovg.h" #ifndef M_PI #define M_PI 3.1415926f #endif /*M_PI*/ #ifdef __cplusplus extern "C" { #endif NVGcontext* nvgCreateAGG(uint32_t w, uint32_t h, uint32_t stride, enum NVGtexture format, uint8_t* data); void nvgReinitAgge(NVGcontext* ctx, uint32_t w, uint32_t h, uint32_t stride, enum NVGtexture, uint8_t* data); void nvgDeleteAGG(NVGcontext* ctx); #ifdef __cplusplus } #endif #endif /* NANOVG_AGG_H */
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\agg\nanovg_vertex.h
#pragma once #include "nanovg.h" #include "agg_basics.h" namespace agg { class nanovg_vertex { public: class iterator; public: nanovg_vertex(NVGvertex* vertex, int n) { _n = n; _index = 0; _vertex = vertex; } void rewind(unsigned) { _index = 0; } unsigned vertex(double* x, double* y) { int index = _index++; NVGvertex* p = _vertex + index; if (index < _n) { *x = p->x; *y = p->y; if (index == 0) { return path_cmd_move_to; } else if (index == (_n - 1)) { if (p->x == _vertex[0].x && p->y == _vertex[0].y) { return (path_cmd_end_poly | path_flags_close); } else { return path_cmd_line_to; } } else { return path_cmd_line_to; } } else { return path_cmd_stop; } } private: int _n; int _index; NVGvertex* _vertex; }; } // namespace agg
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\agge\nanovg_agge.h
#ifndef NANOVG_AGGE_H #define NANOVG_AGGE_H #include <math.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include "nanovg.h" #ifndef M_PI #define M_PI 3.1415926f #endif /*M_PI*/ #ifdef __cplusplus extern "C" { #endif NVGcontext* nvgCreateAGGE(uint32_t w, uint32_t h, uint32_t stride, enum NVGtexture format, uint8_t* data); void nvgReinitAgge(NVGcontext* ctx, uint32_t w, uint32_t h, uint32_t stride, enum NVGtexture format, uint8_t* data); void nvgDeleteAGGE(NVGcontext* ctx); #ifdef __cplusplus } #endif #endif /* NANOVG_AGGE_H */
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\agge\nanovg_image_blender.h
#pragma once #include "agge/math.h" #include "agge/pixel.h" #include "nanovg.h" namespace agge { template <typename PixelT, typename BitmapT> class nanovg_image_blender { public: typedef PixelT pixel; typedef uint8_t cover_type; public: nanovg_image_blender(BitmapT* bitmap, float* matrix); nanovg_image_blender(BitmapT* bitmap, float* matrix, float alpha); bool get_pixel(float x, float y, pixel32_rgba& ref) const; void operator()(pixel* pixels, int x, int y, count_t n) const; void operator()(pixel* pixels, int x, int y, count_t n, const cover_type* covers) const; private: void get_physical_image_point(int& x, int& y) const; private: BitmapT* _bitmap; float* _matrix; float _alpha; int w; int h; }; template <typename PixelT, typename BitmapT> inline nanovg_image_blender<PixelT, BitmapT>::nanovg_image_blender(BitmapT* bitmap, float* matrix) : _bitmap(bitmap), _matrix(matrix), _alpha(1.0f) { this->w = bitmap->width(); this->h = bitmap->height(); } template <typename PixelT, typename BitmapT> inline nanovg_image_blender<PixelT, BitmapT>::nanovg_image_blender(BitmapT* bitmap, float* matrix, float alpha) : _bitmap(bitmap), _matrix(matrix), _alpha(alpha) { this->w = bitmap->width(); this->h = bitmap->height(); } template <typename PixelTargetT, typename PixelSrcT> inline void pixel_linear(PixelTargetT& t, const PixelSrcT& s, float a) { float ma = 1 - a; t.r = s.r*a + t.r*ma; t.g = s.g*a + t.g*ma; t.b = s.b*a + t.b*ma; t.a = s.a*a + t.a*ma; } template <typename PixelT, typename BitmapT> inline void nanovg_image_blender<PixelT, BitmapT>::get_physical_image_point(int& x, int& y) const { int tmp_x = x; int tmp_y = y; unsigned int width = _bitmap->width(); unsigned int height = _bitmap->height(); switch (_bitmap->orientation()) { case 90: x = tmp_y; y = width - tmp_x - 1; break; case 180: x = width - tmp_x - 1; y = height - tmp_y - 1; break; case 270: y = tmp_x; x = height - tmp_y - 1; break; default: break; } } template <typename PixelT, typename BitmapT> inline bool nanovg_image_blender<PixelT, BitmapT>::get_pixel(float x, float y, pixel32_rgba& ref) const { float ox = 0; float oy = 0; nvgTransformPoint(&ox, &oy, _matrix, x, y); pixel32_rgba p[4]; //default is zero int x1 = floor(ox); int x2 = ceil(ox); int y1 = floor(oy); int y2 = ceil(oy); if (x1 >= 0 && x1 < this->w){ if (y1 >= 0 && y1 < this->h){ int px = x1; int py = y1; p[0].a = 0xff; get_physical_image_point(px, py); pixel_convert<pixel32_rgba, typename BitmapT::pixel>(p[0], _bitmap->row_ptr(py)[px]); } if (y2 >= 0 && y2 < this->h) { int px = x1; int py = y2; p[2].a = 0xff; get_physical_image_point(px, py); pixel_convert<pixel32_rgba, typename BitmapT::pixel>(p[2], _bitmap->row_ptr(py)[px]); } } if (x2 >= 0 && x2 < this->w) { if (y1 >= 0 && y1 < this->h) { int px = x2; int py = y1; p[1].a = 0xff; get_physical_image_point(px, py); pixel_convert<pixel32_rgba, typename BitmapT::pixel>(p[1], _bitmap->row_ptr(py)[px]); } if (y2 >= 0 && y2 < this->h) { int px = x2; int py = y2; p[3].a = 0xff; get_physical_image_point(px, py); pixel_convert<pixel32_rgba, typename BitmapT::pixel>(p[3], _bitmap->row_ptr(py)[px]); } } pixel_linear(p[0], p[1], ox - x1); pixel_linear(p[2], p[3], ox - x1); pixel_linear(p[0], p[2], oy - y1); ref = p[0]; ref.a *= _alpha; if (_bitmap->flags() & NVG_IMAGE_PREMULTIPLIED) { ref.r = ref.r * _alpha; ref.g = ref.g * _alpha; ref.b = ref.b * _alpha; } return true; } template <typename PixelT, typename BitmapT> inline void nanovg_image_blender<PixelT, BitmapT>::operator()(pixel* pixels, int x, int y, count_t n) const { pixel32_rgba p(0xff, 0xff, 0xff, 0xff); for (count_t i = 0; i < n; i++, ++pixels) { if (!this->get_pixel((float)x + i, (float)y, p)) { continue; } if (_bitmap->flags() & NVG_IMAGE_PREMULTIPLIED) { pixel_blend_premulti_alpha<PixelT, pixel32_rgba>(*pixels, p, p.a, 1); } else { pixel_blend<PixelT, pixel32_rgba>(*pixels, p, p.a); } } } template <typename PixelT, typename BitmapT> inline void nanovg_image_blender<PixelT, BitmapT>::operator()(pixel* pixels, int x, int y, count_t n, const cover_type* covers) const { pixel32_rgba p(0xff, 0xff, 0xff, 0xff); for (count_t i = 0; i < n; i++, ++pixels, ++covers) { if (!this->get_pixel((float)x + i, (float)y, p)) { continue; } uint8_t a = pixel_a(p, covers[0]); if (_bitmap->flags() & NVG_IMAGE_PREMULTIPLIED) { pixel_blend_premulti_alpha<PixelT, pixel32_rgba>(*pixels, p, a, covers[0]); } else { pixel_blend<PixelT, pixel32_rgba>(*pixels, p, a); } } } } // namespace agge
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\agge\nanovg_vertex.h
#pragma once #include "agge/types.h" #include "nanovg.h" namespace agge { class nanovg_vertex { public: class iterator; public: nanovg_vertex(NVGvertex* vertex, int n); iterator iterate() const; private: int _n; NVGvertex* _vertex; }; class nanovg_vertex::iterator { public: iterator(NVGvertex* vertex, int n); int vertex(real_t* x, real_t* y); private: int _n; int _index; NVGvertex* _vertex; }; } // namespace agge
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\agge\raw_bitmap.h
#pragma once #include <string.h> #include <stdint.h> #include <agge/config.h> #include <agge/pixel.h> typedef uint8_t* image_handle; namespace agge { class raw_bitmap : noncopyable { public: // General raw_bitmap(count_t width, count_t height, count_t stride, count_t flags, bits_per_pixel bpp, uint8_t* data); raw_bitmap(count_t width, count_t height, count_t stride, count_t flags, count_t orientation, bits_per_pixel bpp, uint8_t* data); ~raw_bitmap() { } count_t flags() const; count_t width() const; count_t height() const; count_t orientation() const; void* row_ptr(count_t y); const void* row_ptr(count_t y) const; public: image_handle native() const; void blit(int x, int y, count_t width, count_t height) const; private: uint8_t* _memory; count_t _width, _height; count_t _stride; count_t _flags; count_t _orientation; const bits_per_pixel _bpp; image_handle _native; }; inline raw_bitmap::raw_bitmap(count_t width, count_t height, count_t stride, count_t flags, bits_per_pixel bpp, uint8_t* data) : _memory(data), _width(width), _height(height), _stride(stride), _flags(flags), _orientation(0), _bpp(bpp), _native(0) { } inline raw_bitmap::raw_bitmap(count_t width, count_t height, count_t stride, count_t flags, count_t orientation, bits_per_pixel bpp, uint8_t* data) : _memory(data), _width(width), _height(height), _stride(stride), _flags(flags), _orientation(orientation), _bpp(bpp), _native(0) { } inline count_t raw_bitmap::flags() const { return _flags; } inline count_t raw_bitmap::width() const { return _width; } inline count_t raw_bitmap::height() const { return _height; } inline count_t raw_bitmap::orientation() const { return _orientation; } inline void* raw_bitmap::row_ptr(count_t y) { return _memory + y * _stride; } inline const void* raw_bitmap::row_ptr(count_t y) const { return _memory + y * _stride; } inline image_handle raw_bitmap::native() const { return _native; } } // namespace agge
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\base\fontstash.h
// // Copyright (c) 2009-2013 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #ifndef FONS_H #define FONS_H #define FONS_INVALID -1 enum FONSflags { FONS_ZERO_TOPLEFT = 1, FONS_ZERO_BOTTOMLEFT = 2, }; enum FONSalign { // Horizontal align FONS_ALIGN_LEFT = 1<<0, // Default FONS_ALIGN_CENTER = 1<<1, FONS_ALIGN_RIGHT = 1<<2, // Vertical align FONS_ALIGN_TOP = 1<<3, FONS_ALIGN_MIDDLE = 1<<4, FONS_ALIGN_BOTTOM = 1<<5, FONS_ALIGN_BASELINE = 1<<6, // Default }; enum FONSglyphBitmap { FONS_GLYPH_BITMAP_OPTIONAL = 1, FONS_GLYPH_BITMAP_REQUIRED = 2, }; enum FONSerrorCode { // Font atlas is full. FONS_ATLAS_FULL = 1, // Scratch memory used to render glyphs is full, requested size reported in 'val', you may need to bump up FONS_SCRATCH_BUF_SIZE. FONS_SCRATCH_FULL = 2, // Calls to fonsPushState has created too large stack, if you need deep state stack bump up FONS_MAX_STATES. FONS_STATES_OVERFLOW = 3, // Trying to pop too many states fonsPopState(). FONS_STATES_UNDERFLOW = 4, }; struct FONSparams { int width, height; unsigned char flags; void* userPtr; int (*renderCreate)(void* uptr, int width, int height); int (*renderResize)(void* uptr, int width, int height); void (*renderUpdate)(void* uptr, int* rect, const unsigned char* data); void (*renderDraw)(void* uptr, const float* verts, const float* tcoords, const unsigned int* colors, int nverts); void (*renderDelete)(void* uptr); }; typedef struct FONSparams FONSparams; struct FONSquad { float x0,y0,s0,t0; float x1,y1,s1,t1; }; typedef struct FONSquad FONSquad; struct FONStextIter { float x, y, nextx, nexty, scale, spacing; unsigned int codepoint; short isize, iblur; struct FONSfont* font; int prevGlyphIndex; const char* str; const char* next; const char* end; unsigned int utf8state; int bitmapOption; }; typedef struct FONStextIter FONStextIter; typedef struct FONScontext FONScontext; // Constructor and destructor. FONScontext* fonsCreateInternal(FONSparams* params); void fonsDeleteInternal(FONScontext* s); void fontsDeleteFontByName(FONScontext* stash, const char* name); void fonsSetErrorCallback(FONScontext* s, void (*callback)(void* uptr, int error, int val), void* uptr); // Returns current atlas size. void fonsGetAtlasSize(FONScontext* s, int* width, int* height); // Expands the atlas size. int fonsExpandAtlas(FONScontext* s, int width, int height); // Resets the whole stash. int fonsResetAtlas(FONScontext* stash, int width, int height); // Add fonts int fonsAddFont(FONScontext* s, const char* name, const char* path); int fonsAddFontMem(FONScontext* s, const char* name, unsigned char* data, int ndata, int freeData); int fonsGetFontByName(FONScontext* s, const char* name); // State handling void fonsPushState(FONScontext* s); void fonsPopState(FONScontext* s); void fonsClearState(FONScontext* s); // State setting void fonsSetSize(FONScontext* s, float size); void fonsSetColor(FONScontext* s, unsigned int color); void fonsSetSpacing(FONScontext* s, float spacing); void fonsSetBlur(FONScontext* s, float blur); void fonsSetAlign(FONScontext* s, int align); void fonsSetFont(FONScontext* s, int font); // Draw text float fonsDrawText(FONScontext* s, float x, float y, const char* string, const char* end); // Measure text float fonsTextBounds(FONScontext* s, float x, float y, const char* string, const char* end, float* bounds); void fonsLineBounds(FONScontext* s, float y, float* miny, float* maxy); void fonsVertMetrics(FONScontext* s, float* ascender, float* descender, float* lineh); // Text iterator int fonsTextIterInit(FONScontext* stash, FONStextIter* iter, float x, float y, const char* str, const char* end, int bitmapOption); int fonsTextIterNext(FONScontext* stash, FONStextIter* iter, struct FONSquad* quad); // Pull texture changes const unsigned char* fonsGetTextureData(FONScontext* stash, int* width, int* height); int fonsValidateTexture(FONScontext* s, int* dirty); // Draws the stash texture for debugging void fonsDrawDebug(FONScontext* s, float x, float y); #endif // FONTSTASH_H #ifdef FONTSTASH_IMPLEMENTATION #define FONS_NOTUSED(v) (void)sizeof(v) #ifdef FONS_USE_FREETYPE #include <ft2build.h> #include FT_FREETYPE_H #include FT_ADVANCES_H #include <math.h> struct FONSttFontImpl { FT_Face font; }; typedef struct FONSttFontImpl FONSttFontImpl; static FT_Library ftLibrary; int fons__tt_init(FONScontext *context) { FT_Error ftError; FONS_NOTUSED(context); ftError = FT_Init_FreeType(&ftLibrary); return ftError == 0; } int fons__tt_done(FONScontext *context) { FT_Error ftError; FONS_NOTUSED(context); ftError = FT_Done_FreeType(ftLibrary); return ftError == 0; } int fons__tt_loadFont(FONScontext *context, FONSttFontImpl *font, unsigned char *data, int dataSize) { FT_Error ftError; FONS_NOTUSED(context); //font->font.userdata = stash; ftError = FT_New_Memory_Face(ftLibrary, (const FT_Byte*)data, dataSize, 0, &font->font); return ftError == 0; } void fons__tt_getFontVMetrics(FONSttFontImpl *font, int *ascent, int *descent, int *lineGap) { *ascent = font->font->ascender; *descent = font->font->descender; *lineGap = font->font->height - (*ascent - *descent); } float fons__tt_getPixelHeightScale(FONSttFontImpl *font, float size) { return size / (font->font->ascender - font->font->descender); } int fons__tt_getGlyphIndex(FONSttFontImpl *font, int codepoint) { return FT_Get_Char_Index(font->font, codepoint); } int fons__tt_buildGlyphBitmap(FONSttFontImpl *font, int glyph, float size, float scale, int *advance, int *lsb, int *x0, int *y0, int *x1, int *y1) { FT_Error ftError; FT_GlyphSlot ftGlyph; FT_Fixed advFixed; FONS_NOTUSED(scale); ftError = FT_Set_Pixel_Sizes(font->font, 0, (FT_UInt)(size * (float)font->font->units_per_EM / (float)(font->font->ascender - font->font->descender))); if (ftError) return 0; ftError = FT_Load_Glyph(font->font, glyph, FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT); if (ftError) return 0; ftError = FT_Get_Advance(font->font, glyph, FT_LOAD_NO_SCALE, &advFixed); if (ftError) return 0; ftGlyph = font->font->glyph; *advance = (int)advFixed; *lsb = (int)ftGlyph->metrics.horiBearingX; *x0 = ftGlyph->bitmap_left; *x1 = *x0 + ftGlyph->bitmap.width; *y0 = -ftGlyph->bitmap_top; *y1 = *y0 + ftGlyph->bitmap.rows; return 1; } void fons__tt_renderGlyphBitmap(FONSttFontImpl *font, unsigned char *output, int outWidth, int outHeight, int outStride, float scaleX, float scaleY, int glyph) { FT_GlyphSlot ftGlyph = font->font->glyph; int ftGlyphOffset = 0; int x, y; FONS_NOTUSED(outWidth); FONS_NOTUSED(outHeight); FONS_NOTUSED(scaleX); FONS_NOTUSED(scaleY); FONS_NOTUSED(glyph); // glyph has already been loaded by fons__tt_buildGlyphBitmap for ( y = 0; y < ftGlyph->bitmap.rows; y++ ) { for ( x = 0; x < ftGlyph->bitmap.width; x++ ) { output[(y * outStride) + x] = ftGlyph->bitmap.buffer[ftGlyphOffset++]; } } } int fons__tt_getGlyphKernAdvance(FONSttFontImpl *font, int glyph1, int glyph2) { FT_Vector ftKerning; FT_Get_Kerning(font->font, glyph1, glyph2, FT_KERNING_DEFAULT, &ftKerning); return (int)((ftKerning.x + 32) >> 6); // Round up and convert to integer } #else #define STB_TRUETYPE_IMPLEMENTATION // static void* fons__tmpalloc(size_t size, void* up); // static void fons__tmpfree(void* ptr, void* up); // #define STBTT_malloc(x,u) fons__tmpalloc(x,u) // #define STBTT_free(x,u) fons__tmpfree(x,u) #include "stb/stb_truetype.h" struct FONSttFontImpl { stbtt_fontinfo font; }; typedef struct FONSttFontImpl FONSttFontImpl; int fons__tt_init(FONScontext *context) { FONS_NOTUSED(context); return 1; } int fons__tt_done(FONScontext *context) { FONS_NOTUSED(context); return 1; } int fons__tt_loadFont(FONScontext *context, FONSttFontImpl *font, unsigned char *data, int dataSize) { int stbError; FONS_NOTUSED(dataSize); font->font.userdata = context; stbError = stbtt_InitFont(&font->font, data, 0); return stbError; } void fons__tt_getFontVMetrics(FONSttFontImpl *font, int *ascent, int *descent, int *lineGap) { stbtt_GetFontVMetrics(&font->font, ascent, descent, lineGap); if(*ascent == 0 && *descent == 0) { float scale = stbtt_ScaleForMappingEmToPixels(&font->font, 18); *ascent = (int)(18 / scale); *descent = 0; *lineGap = 0; } } float fons__tt_getPixelHeightScale(FONSttFontImpl *font, float size) { float scale = stbtt_ScaleForPixelHeight(&font->font, size); if (scale == INFINITY) { scale = stbtt_ScaleForMappingEmToPixels(&font->font, size); } return scale; } int fons__tt_getGlyphIndex(FONSttFontImpl *font, int codepoint) { return stbtt_FindGlyphIndex(&font->font, codepoint); } int fons__tt_buildGlyphBitmap(FONSttFontImpl *font, int glyph, float size, float scale, int *advance, int *lsb, int *x0, int *y0, int *x1, int *y1) { FONS_NOTUSED(size); stbtt_GetGlyphHMetrics(&font->font, glyph, advance, lsb); stbtt_GetGlyphBitmapBox(&font->font, glyph, scale, scale, x0, y0, x1, y1); return 1; } void fons__tt_renderGlyphBitmap(FONSttFontImpl *font, unsigned char *output, int outWidth, int outHeight, int outStride, float scaleX, float scaleY, int glyph) { stbtt_MakeGlyphBitmap(&font->font, output, outWidth, outHeight, outStride, scaleX, scaleY, glyph); } int fons__tt_getGlyphKernAdvance(FONSttFontImpl *font, int glyph1, int glyph2) { return stbtt_GetGlyphKernAdvance(&font->font, glyph1, glyph2); } #endif #ifndef FONS_SCRATCH_BUF_SIZE # define FONS_SCRATCH_BUF_SIZE 1 #endif #ifndef FONS_HASH_LUT_SIZE # define FONS_HASH_LUT_SIZE 256 #endif #ifndef FONS_INIT_FONTS # define FONS_INIT_FONTS 4 #endif #ifndef FONS_INIT_GLYPHS # define FONS_INIT_GLYPHS 256 #endif #ifndef FONS_INIT_ATLAS_NODES # define FONS_INIT_ATLAS_NODES 256 #endif #ifndef FONS_VERTEX_COUNT # define FONS_VERTEX_COUNT 1024 #endif #ifndef FONS_MAX_STATES # define FONS_MAX_STATES 20 #endif #ifndef FONS_MAX_FALLBACKS # define FONS_MAX_FALLBACKS 20 #endif static unsigned int fons__hashint(unsigned int a) { a += ~(a<<15); a ^= (a>>10); a += (a<<3); a ^= (a>>6); a += ~(a<<11); a ^= (a>>16); return a; } static int fons__mini(int a, int b) { return a < b ? a : b; } static int fons__maxi(int a, int b) { return a > b ? a : b; } struct FONSglyph { unsigned int codepoint; int index; int next; short size, blur; short x0,y0,x1,y1; short xadv,xoff,yoff; }; typedef struct FONSglyph FONSglyph; struct FONSfont { FONSttFontImpl font; char name[64]; unsigned char* data; int dataSize; unsigned char freeData; float ascender; float descender; float lineh; FONSglyph* glyphs; int cglyphs; int nglyphs; int lut[FONS_HASH_LUT_SIZE]; int fallbacks[FONS_MAX_FALLBACKS]; int nfallbacks; }; typedef struct FONSfont FONSfont; struct FONSstate { int font; int align; float size; unsigned int color; float blur; float spacing; }; typedef struct FONSstate FONSstate; struct FONSatlasNode { short x, y, width; }; typedef struct FONSatlasNode FONSatlasNode; struct FONSatlas { int width, height; FONSatlasNode* nodes; int nnodes; int cnodes; }; typedef struct FONSatlas FONSatlas; struct FONScontext { FONSparams params; float itw,ith; unsigned char* texData; int dirtyRect[4]; FONSfont** fonts; FONSatlas* atlas; int cfonts; int nfonts; float verts[FONS_VERTEX_COUNT*2]; float tcoords[FONS_VERTEX_COUNT*2]; unsigned int colors[FONS_VERTEX_COUNT]; int nverts; unsigned char* scratch; int nscratch; FONSstate states[FONS_MAX_STATES]; int nstates; void (*handleError)(void* uptr, int error, int val); void* errorUptr; }; #ifdef STB_TRUETYPE_IMPLEMENTATION static void* fons__tmpalloc(size_t size, void* up) { unsigned char* ptr; FONScontext* stash = (FONScontext*)up; // 16-byte align the returned pointer size = (size + 0xf) & ~0xf; if (stash->nscratch+(int)size > FONS_SCRATCH_BUF_SIZE) { if (stash->handleError) stash->handleError(stash->errorUptr, FONS_SCRATCH_FULL, stash->nscratch+(int)size); return NULL; } ptr = stash->scratch + stash->nscratch; stash->nscratch += (int)size; return ptr; } static void fons__tmpfree(void* ptr, void* up) { (void)ptr; (void)up; // empty } #endif // STB_TRUETYPE_IMPLEMENTATION // Copyright (c) 2008-2010 Bjoern Hoehrmann <bjoern@hoehrmann.de> // See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. #define FONS_UTF8_ACCEPT 0 #define FONS_UTF8_REJECT 12 static unsigned int fons__decutf8(unsigned int* state, unsigned int* codep, unsigned int byte) { static const unsigned char utf8d[] = { // The first part of the table maps bytes to character classes that // to reduce the size of the transition table and create bitmasks. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, // The second part is a transition table that maps a combination // of a state of the automaton and a character class to a state. 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12, 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,12,12,12,12,12, }; unsigned int type = utf8d[byte]; *codep = (*state != FONS_UTF8_ACCEPT) ? (byte & 0x3fu) | (*codep << 6) : (0xff >> type) & (byte); *state = utf8d[256 + *state + type]; return *state; } // Atlas based on Skyline Bin Packer by Jukka Jylänki static void fons__deleteAtlas(FONSatlas* atlas) { if (atlas == NULL) return; if (atlas->nodes != NULL) free(atlas->nodes); free(atlas); } static FONSatlas* fons__allocAtlas(int w, int h, int nnodes) { FONSatlas* atlas = NULL; // Allocate memory for the font stash. atlas = (FONSatlas*)malloc(sizeof(FONSatlas)); if (atlas == NULL) goto error; memset(atlas, 0, sizeof(FONSatlas)); atlas->width = w; atlas->height = h; // Allocate space for skyline nodes atlas->nodes = (FONSatlasNode*)malloc(sizeof(FONSatlasNode) * nnodes); if (atlas->nodes == NULL) goto error; memset(atlas->nodes, 0, sizeof(FONSatlasNode) * nnodes); atlas->nnodes = 0; atlas->cnodes = nnodes; // Init root node. atlas->nodes[0].x = 0; atlas->nodes[0].y = 0; atlas->nodes[0].width = (short)w; atlas->nnodes++; return atlas; error: if (atlas) fons__deleteAtlas(atlas); return NULL; } static int fons__atlasInsertNode(FONSatlas* atlas, int idx, int x, int y, int w) { int i; // Insert node if (atlas->nnodes+1 > atlas->cnodes) { atlas->cnodes = atlas->cnodes == 0 ? 8 : atlas->cnodes * 2; atlas->nodes = (FONSatlasNode*)realloc(atlas->nodes, sizeof(FONSatlasNode) * atlas->cnodes); if (atlas->nodes == NULL) return 0; } for (i = atlas->nnodes; i > idx; i--) atlas->nodes[i] = atlas->nodes[i-1]; atlas->nodes[idx].x = (short)x; atlas->nodes[idx].y = (short)y; atlas->nodes[idx].width = (short)w; atlas->nnodes++; return 1; } static void fons__atlasRemoveNode(FONSatlas* atlas, int idx) { int i; if (atlas->nnodes == 0) return; for (i = idx; i < atlas->nnodes-1; i++) atlas->nodes[i] = atlas->nodes[i+1]; atlas->nnodes--; } static void fons__atlasExpand(FONSatlas* atlas, int w, int h) { // Insert node for empty space if (w > atlas->width) fons__atlasInsertNode(atlas, atlas->nnodes, atlas->width, 0, w - atlas->width); atlas->width = w; atlas->height = h; } static void fons__atlasReset(FONSatlas* atlas, int w, int h) { atlas->width = w; atlas->height = h; atlas->nnodes = 0; // Init root node. atlas->nodes[0].x = 0; atlas->nodes[0].y = 0; atlas->nodes[0].width = (short)w; atlas->nnodes++; } static int fons__atlasAddSkylineLevel(FONSatlas* atlas, int idx, int x, int y, int w, int h) { int i; // Insert new node if (fons__atlasInsertNode(atlas, idx, x, y+h, w) == 0) return 0; // Delete skyline segments that fall under the shadow of the new segment. for (i = idx+1; i < atlas->nnodes; i++) { if (atlas->nodes[i].x < atlas->nodes[i-1].x + atlas->nodes[i-1].width) { int shrink = atlas->nodes[i-1].x + atlas->nodes[i-1].width - atlas->nodes[i].x; atlas->nodes[i].x += (short)shrink; atlas->nodes[i].width -= (short)shrink; if (atlas->nodes[i].width <= 0) { fons__atlasRemoveNode(atlas, i); i--; } else { break; } } else { break; } } // Merge same height skyline segments that are next to each other. for (i = 0; i < atlas->nnodes-1; i++) { if (atlas->nodes[i].y == atlas->nodes[i+1].y) { atlas->nodes[i].width += atlas->nodes[i+1].width; fons__atlasRemoveNode(atlas, i+1); i--; } } return 1; } static int fons__atlasRectFits(FONSatlas* atlas, int i, int w, int h) { // Checks if there is enough space at the location of skyline span 'i', // and return the max height of all skyline spans under that at that location, // (think tetris block being dropped at that position). Or -1 if no space found. int x = atlas->nodes[i].x; int y = atlas->nodes[i].y; int spaceLeft; if (x + w > atlas->width) return -1; spaceLeft = w; while (spaceLeft > 0) { if (i == atlas->nnodes) return -1; y = fons__maxi(y, atlas->nodes[i].y); if (y + h > atlas->height) return -1; spaceLeft -= atlas->nodes[i].width; ++i; } return y; } static int fons__atlasAddRect(FONSatlas* atlas, int rw, int rh, int* rx, int* ry) { int besth = atlas->height, bestw = atlas->width, besti = -1; int bestx = -1, besty = -1, i; // Bottom left fit heuristic. for (i = 0; i < atlas->nnodes; i++) { int y = fons__atlasRectFits(atlas, i, rw, rh); if (y != -1) { if (y + rh < besth || (y + rh == besth && atlas->nodes[i].width < bestw)) { besti = i; bestw = atlas->nodes[i].width; besth = y + rh; bestx = atlas->nodes[i].x; besty = y; } } } if (besti == -1) return 0; // Perform the actual packing. if (fons__atlasAddSkylineLevel(atlas, besti, bestx, besty, rw, rh) == 0) return 0; *rx = bestx; *ry = besty; return 1; } static void fons__addWhiteRect(FONScontext* stash, int w, int h) { int x, y, gx, gy; unsigned char* dst; if (fons__atlasAddRect(stash->atlas, w, h, &gx, &gy) == 0) return; // Rasterize dst = &stash->texData[gx + gy * stash->params.width]; for (y = 0; y < h; y++) { for (x = 0; x < w; x++) dst[x] = 0xff; dst += stash->params.width; } stash->dirtyRect[0] = fons__mini(stash->dirtyRect[0], gx); stash->dirtyRect[1] = fons__mini(stash->dirtyRect[1], gy); stash->dirtyRect[2] = fons__maxi(stash->dirtyRect[2], gx+w); stash->dirtyRect[3] = fons__maxi(stash->dirtyRect[3], gy+h); } FONScontext* fonsCreateInternal(FONSparams* params) { FONScontext* stash = NULL; // Allocate memory for the font stash. stash = (FONScontext*)malloc(sizeof(FONScontext)); if (stash == NULL) goto error; memset(stash, 0, sizeof(FONScontext)); stash->params = *params; // Allocate scratch buffer. stash->scratch = (unsigned char*)malloc(FONS_SCRATCH_BUF_SIZE); if (stash->scratch == NULL) goto error; // Initialize implementation library if (!fons__tt_init(stash)) goto error; if (stash->params.renderCreate != NULL) { if (stash->params.renderCreate(stash->params.userPtr, stash->params.width, stash->params.height) == 0) goto error; } stash->atlas = fons__allocAtlas(stash->params.width, stash->params.height, FONS_INIT_ATLAS_NODES); if (stash->atlas == NULL) goto error; // Allocate space for fonts. stash->fonts = (FONSfont**)malloc(sizeof(FONSfont*) * FONS_INIT_FONTS); if (stash->fonts == NULL) goto error; memset(stash->fonts, 0, sizeof(FONSfont*) * FONS_INIT_FONTS); stash->cfonts = FONS_INIT_FONTS; stash->nfonts = 0; // Create texture for the cache. stash->itw = 1.0f/stash->params.width; stash->ith = 1.0f/stash->params.height; stash->texData = (unsigned char*)malloc(stash->params.width * stash->params.height); if (stash->texData == NULL) goto error; memset(stash->texData, 0, stash->params.width * stash->params.height); stash->dirtyRect[0] = stash->params.width; stash->dirtyRect[1] = stash->params.height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; // Add white rect at 0,0 for debug drawing. fons__addWhiteRect(stash, 2,2); fonsPushState(stash); fonsClearState(stash); return stash; error: fonsDeleteInternal(stash); return NULL; } static FONSstate* fons__getState(FONScontext* stash) { return &stash->states[stash->nstates-1]; } int fonsAddFallbackFont(FONScontext* stash, int base, int fallback) { FONSfont* baseFont = stash->fonts[base]; if (baseFont->nfallbacks < FONS_MAX_FALLBACKS) { baseFont->fallbacks[baseFont->nfallbacks++] = fallback; return 1; } return 0; } void fonsSetSize(FONScontext* stash, float size) { fons__getState(stash)->size = size; } void fonsSetColor(FONScontext* stash, unsigned int color) { fons__getState(stash)->color = color; } void fonsSetSpacing(FONScontext* stash, float spacing) { fons__getState(stash)->spacing = spacing; } void fonsSetBlur(FONScontext* stash, float blur) { fons__getState(stash)->blur = blur; } void fonsSetAlign(FONScontext* stash, int align) { fons__getState(stash)->align = align; } void fonsSetFont(FONScontext* stash, int font) { fons__getState(stash)->font = font; } void fonsPushState(FONScontext* stash) { if (stash->nstates >= FONS_MAX_STATES) { if (stash->handleError) stash->handleError(stash->errorUptr, FONS_STATES_OVERFLOW, 0); return; } if (stash->nstates > 0) memcpy(&stash->states[stash->nstates], &stash->states[stash->nstates-1], sizeof(FONSstate)); stash->nstates++; } void fonsPopState(FONScontext* stash) { if (stash->nstates <= 1) { if (stash->handleError) stash->handleError(stash->errorUptr, FONS_STATES_UNDERFLOW, 0); return; } stash->nstates--; } void fonsClearState(FONScontext* stash) { FONSstate* state = fons__getState(stash); state->size = 12.0f; state->color = 0xffffffff; state->font = 0; state->blur = 0; state->spacing = 0; state->align = FONS_ALIGN_LEFT | FONS_ALIGN_BASELINE; } static void fons__freeFont(FONSfont* font) { if (font == NULL) return; if (font->glyphs) free(font->glyphs); if (font->freeData && font->data) free(font->data); free(font); } static int fons__allocFont(FONScontext* stash) { FONSfont* font = NULL; if (stash->nfonts+1 > stash->cfonts) { stash->cfonts = stash->cfonts == 0 ? 8 : stash->cfonts * 2; stash->fonts = (FONSfont**)realloc(stash->fonts, sizeof(FONSfont*) * stash->cfonts); if (stash->fonts == NULL) return -1; } font = (FONSfont*)malloc(sizeof(FONSfont)); if (font == NULL) goto error; memset(font, 0, sizeof(FONSfont)); font->glyphs = (FONSglyph*)malloc(sizeof(FONSglyph) * FONS_INIT_GLYPHS); if (font->glyphs == NULL) goto error; font->cglyphs = FONS_INIT_GLYPHS; font->nglyphs = 0; stash->fonts[stash->nfonts++] = font; return stash->nfonts-1; error: fons__freeFont(font); return FONS_INVALID; } int fonsAddFont(FONScontext* stash, const char* name, const char* path) { FILE* fp = 0; int dataSize = 0; size_t readed; unsigned char* data = NULL; // Read in the font data. fp = fopen(path, "rb"); if (fp == NULL) goto error; fseek(fp,0,SEEK_END); dataSize = (int)ftell(fp); fseek(fp,0,SEEK_SET); data = (unsigned char*)malloc(dataSize); if (data == NULL) goto error; readed = fread(data, 1, dataSize, fp); fclose(fp); fp = 0; if (readed != dataSize) goto error; return fonsAddFontMem(stash, name, data, dataSize, 1); error: if (data) free(data); if (fp) fclose(fp); return FONS_INVALID; } int fonsAddFontMem(FONScontext* stash, const char* name, unsigned char* data, int dataSize, int freeData) { int i, ascent, descent, fh, lineGap; FONSfont* font; int idx = fons__allocFont(stash); if (idx == FONS_INVALID) return FONS_INVALID; font = stash->fonts[idx]; strncpy(font->name, name, sizeof(font->name)); font->name[sizeof(font->name)-1] = '\0'; // Init hash lookup. for (i = 0; i < FONS_HASH_LUT_SIZE; ++i) font->lut[i] = -1; // Read in the font data. font->dataSize = dataSize; font->data = data; font->freeData = (unsigned char)freeData; // Init font stash->nscratch = 0; if (!fons__tt_loadFont(stash, &font->font, data, dataSize)) goto error; // Store normalized line height. The real line height is got // by multiplying the lineh by font size. fons__tt_getFontVMetrics( &font->font, &ascent, &descent, &lineGap); fh = ascent - descent; font->ascender = (float)ascent / (float)fh; font->descender = (float)descent / (float)fh; font->lineh = (float)(fh + lineGap) / (float)fh; return idx; error: fons__freeFont(font); stash->nfonts--; return FONS_INVALID; } int fonsGetFontByName(FONScontext* s, const char* name) { int i; for (i = 0; i < s->nfonts; i++) { if (strcmp(s->fonts[i]->name, name) == 0) return i; } return FONS_INVALID; } static FONSglyph* fons__allocGlyph(FONSfont* font) { if (font->nglyphs+1 > font->cglyphs) { font->cglyphs = font->cglyphs == 0 ? 8 : font->cglyphs * 2; font->glyphs = (FONSglyph*)realloc(font->glyphs, sizeof(FONSglyph) * font->cglyphs); if (font->glyphs == NULL) return NULL; } font->nglyphs++; return &font->glyphs[font->nglyphs-1]; } // Based on Exponential blur, Jani Huhtanen, 2006 #define APREC 16 #define ZPREC 7 static void fons__blurCols(unsigned char* dst, int w, int h, int dstStride, int alpha) { int x, y; for (y = 0; y < h; y++) { int z = 0; // force zero border for (x = 1; x < w; x++) { z += (alpha * (((int)(dst[x]) << ZPREC) - z)) >> APREC; dst[x] = (unsigned char)(z >> ZPREC); } dst[w-1] = 0; // force zero border z = 0; for (x = w-2; x >= 0; x--) { z += (alpha * (((int)(dst[x]) << ZPREC) - z)) >> APREC; dst[x] = (unsigned char)(z >> ZPREC); } dst[0] = 0; // force zero border dst += dstStride; } } static void fons__blurRows(unsigned char* dst, int w, int h, int dstStride, int alpha) { int x, y; for (x = 0; x < w; x++) { int z = 0; // force zero border for (y = dstStride; y < h*dstStride; y += dstStride) { z += (alpha * (((int)(dst[y]) << ZPREC) - z)) >> APREC; dst[y] = (unsigned char)(z >> ZPREC); } dst[(h-1)*dstStride] = 0; // force zero border z = 0; for (y = (h-2)*dstStride; y >= 0; y -= dstStride) { z += (alpha * (((int)(dst[y]) << ZPREC) - z)) >> APREC; dst[y] = (unsigned char)(z >> ZPREC); } dst[0] = 0; // force zero border dst++; } } static void fons__blur(FONScontext* stash, unsigned char* dst, int w, int h, int dstStride, int blur) { int alpha; float sigma; (void)stash; if (blur < 1) return; // Calculate the alpha such that 90% of the kernel is within the radius. (Kernel extends to infinity) sigma = (float)blur * 0.57735f; // 1 / sqrt(3) alpha = (int)((1<<APREC) * (1.0f - expf(-2.3f / (sigma+1.0f)))); fons__blurRows(dst, w, h, dstStride, alpha); fons__blurCols(dst, w, h, dstStride, alpha); fons__blurRows(dst, w, h, dstStride, alpha); fons__blurCols(dst, w, h, dstStride, alpha); // fons__blurrows(dst, w, h, dstStride, alpha); // fons__blurcols(dst, w, h, dstStride, alpha); } static FONSglyph* fons__getGlyph(FONScontext* stash, FONSfont* font, unsigned int codepoint, short isize, short iblur, int bitmapOption) { int i, g, advance, lsb, x0, y0, x1, y1, gw, gh, gx, gy, x, y; float scale; FONSglyph* glyph = NULL; unsigned int h; float size = isize/10.0f; int pad, added; unsigned char* bdst; unsigned char* dst; FONSfont* renderFont = font; if (isize < 2) return NULL; if (iblur > 20) iblur = 20; pad = iblur+2; // Reset allocator. stash->nscratch = 0; // Find code point and size. h = fons__hashint(codepoint) & (FONS_HASH_LUT_SIZE-1); i = font->lut[h]; while (i != -1) { if (font->glyphs[i].codepoint == codepoint && font->glyphs[i].size == isize && font->glyphs[i].blur == iblur) { glyph = &font->glyphs[i]; if (bitmapOption == FONS_GLYPH_BITMAP_OPTIONAL || (glyph->x0 >= 0 && glyph->y0 >= 0)) { return glyph; } // At this point, glyph exists but the bitmap data is not yet created. break; } i = font->glyphs[i].next; } // Create a new glyph or rasterize bitmap data for a cached glyph. g = fons__tt_getGlyphIndex(&font->font, codepoint); // Try to find the glyph in fallback fonts. if (g == 0) { for (i = 0; i < font->nfallbacks; ++i) { FONSfont* fallbackFont = stash->fonts[font->fallbacks[i]]; int fallbackIndex = fons__tt_getGlyphIndex(&fallbackFont->font, codepoint); if (fallbackIndex != 0) { g = fallbackIndex; renderFont = fallbackFont; break; } } // It is possible that we did not find a fallback glyph. // In that case the glyph index 'g' is 0, and we'll proceed below and cache empty glyph. } scale = fons__tt_getPixelHeightScale(&renderFont->font, size); fons__tt_buildGlyphBitmap(&renderFont->font, g, size, scale, &advance, &lsb, &x0, &y0, &x1, &y1); gw = x1-x0 + pad*2; gh = y1-y0 + pad*2; // Determines the spot to draw glyph in the atlas. if (bitmapOption == FONS_GLYPH_BITMAP_REQUIRED) { // Find free spot for the rect in the atlas added = fons__atlasAddRect(stash->atlas, gw, gh, &gx, &gy); if (added == 0 && stash->handleError != NULL) { // Atlas is full, let the user to resize the atlas (or not), and try again. stash->handleError(stash->errorUptr, FONS_ATLAS_FULL, 0); added = fons__atlasAddRect(stash->atlas, gw, gh, &gx, &gy); } if (added == 0) return NULL; } else { // Negative coordinate indicates there is no bitmap data created. gx = -1; gy = -1; } // Init glyph. if (glyph == NULL) { glyph = fons__allocGlyph(font); glyph->codepoint = codepoint; glyph->size = isize; glyph->blur = iblur; glyph->next = 0; // Insert char to hash lookup. glyph->next = font->lut[h]; font->lut[h] = font->nglyphs-1; } glyph->index = g; glyph->x0 = (short)gx; glyph->y0 = (short)gy; glyph->x1 = (short)(glyph->x0+gw); glyph->y1 = (short)(glyph->y0+gh); glyph->xadv = (short)(scale * advance * 10.0f); glyph->xoff = (short)(x0 - pad); glyph->yoff = (short)(y0 - pad); if (bitmapOption == FONS_GLYPH_BITMAP_OPTIONAL) { return glyph; } // Rasterize dst = &stash->texData[(glyph->x0+pad) + (glyph->y0+pad) * stash->params.width]; fons__tt_renderGlyphBitmap(&renderFont->font, dst, gw-pad*2,gh-pad*2, stash->params.width, scale, scale, g); // Make sure there is one pixel empty border. dst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width]; for (y = 0; y < gh; y++) { dst[y*stash->params.width] = 0; dst[gw-1 + y*stash->params.width] = 0; } for (x = 0; x < gw; x++) { dst[x] = 0; dst[x + (gh-1)*stash->params.width] = 0; } // Debug code to color the glyph background /* unsigned char* fdst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width]; for (y = 0; y < gh; y++) { for (x = 0; x < gw; x++) { int a = (int)fdst[x+y*stash->params.width] + 20; if (a > 255) a = 255; fdst[x+y*stash->params.width] = a; } }*/ // Blur if (iblur > 0) { stash->nscratch = 0; bdst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width]; fons__blur(stash, bdst, gw, gh, stash->params.width, iblur); } stash->dirtyRect[0] = fons__mini(stash->dirtyRect[0], glyph->x0); stash->dirtyRect[1] = fons__mini(stash->dirtyRect[1], glyph->y0); stash->dirtyRect[2] = fons__maxi(stash->dirtyRect[2], glyph->x1); stash->dirtyRect[3] = fons__maxi(stash->dirtyRect[3], glyph->y1); return glyph; } static void fons__getQuad(FONScontext* stash, FONSfont* font, int prevGlyphIndex, FONSglyph* glyph, float scale, float spacing, float* x, float* y, FONSquad* q) { float rx,ry,xoff,yoff,x0,y0,x1,y1; if (prevGlyphIndex != -1) { float adv = fons__tt_getGlyphKernAdvance(&font->font, prevGlyphIndex, glyph->index) * scale; *x += (int)(adv + spacing + 0.5f); } // Each glyph has 2px border to allow good interpolation, // one pixel to prevent leaking, and one to allow good interpolation for rendering. // Inset the texture region by one pixel for correct interpolation. xoff = (short)(glyph->xoff+1); yoff = (short)(glyph->yoff+1); x0 = (float)(glyph->x0+1); y0 = (float)(glyph->y0+1); x1 = (float)(glyph->x1-1); y1 = (float)(glyph->y1-1); if (stash->params.flags & FONS_ZERO_TOPLEFT) { rx = (float)(int)(*x + xoff); ry = (float)(int)(*y + yoff); q->x0 = rx; q->y0 = ry; q->x1 = rx + x1 - x0; q->y1 = ry + y1 - y0; q->s0 = x0 * stash->itw; q->t0 = y0 * stash->ith; q->s1 = x1 * stash->itw; q->t1 = y1 * stash->ith; } else { rx = (float)(int)(*x + xoff); ry = (float)(int)(*y - yoff); q->x0 = rx; q->y0 = ry; q->x1 = rx + x1 - x0; q->y1 = ry - y1 + y0; q->s0 = x0 * stash->itw; q->t0 = y0 * stash->ith; q->s1 = x1 * stash->itw; q->t1 = y1 * stash->ith; } *x += (int)(glyph->xadv / 10.0f + 0.5f); } static void fons__flush(FONScontext* stash) { // Flush texture if (stash->dirtyRect[0] < stash->dirtyRect[2] && stash->dirtyRect[1] < stash->dirtyRect[3]) { if (stash->params.renderUpdate != NULL) stash->params.renderUpdate(stash->params.userPtr, stash->dirtyRect, stash->texData); // Reset dirty rect stash->dirtyRect[0] = stash->params.width; stash->dirtyRect[1] = stash->params.height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; } // Flush triangles if (stash->nverts > 0) { if (stash->params.renderDraw != NULL) stash->params.renderDraw(stash->params.userPtr, stash->verts, stash->tcoords, stash->colors, stash->nverts); stash->nverts = 0; } } static __inline void fons__vertex(FONScontext* stash, float x, float y, float s, float t, unsigned int c) { stash->verts[stash->nverts*2+0] = x; stash->verts[stash->nverts*2+1] = y; stash->tcoords[stash->nverts*2+0] = s; stash->tcoords[stash->nverts*2+1] = t; stash->colors[stash->nverts] = c; stash->nverts++; } static float fons__getVertAlign(FONScontext* stash, FONSfont* font, int align, short isize) { if (stash->params.flags & FONS_ZERO_TOPLEFT) { if (align & FONS_ALIGN_TOP) { return font->ascender * (float)isize/10.0f; } else if (align & FONS_ALIGN_MIDDLE) { return (font->ascender + font->descender) / 2.0f * (float)isize/10.0f; } else if (align & FONS_ALIGN_BASELINE) { return 0.0f; } else if (align & FONS_ALIGN_BOTTOM) { return font->descender * (float)isize/10.0f; } } else { if (align & FONS_ALIGN_TOP) { return -font->ascender * (float)isize/10.0f; } else if (align & FONS_ALIGN_MIDDLE) { return -(font->ascender + font->descender) / 2.0f * (float)isize/10.0f; } else if (align & FONS_ALIGN_BASELINE) { return 0.0f; } else if (align & FONS_ALIGN_BOTTOM) { return -font->descender * (float)isize/10.0f; } } return 0.0; } float fonsDrawText(FONScontext* stash, float x, float y, const char* str, const char* end) { FONSstate* state = fons__getState(stash); unsigned int codepoint; unsigned int utf8state = 0; FONSglyph* glyph = NULL; FONSquad q; int prevGlyphIndex = -1; short isize = (short)(state->size*10.0f); short iblur = (short)state->blur; float scale; FONSfont* font; float width; if (stash == NULL) return x; if (state->font < 0 || state->font >= stash->nfonts) return x; font = stash->fonts[state->font]; if (font->data == NULL) return x; scale = fons__tt_getPixelHeightScale(&font->font, (float)isize/10.0f); if (end == NULL) end = str + strlen(str); // Align horizontally if (state->align & FONS_ALIGN_LEFT) { // empty } else if (state->align & FONS_ALIGN_RIGHT) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width; } else if (state->align & FONS_ALIGN_CENTER) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width * 0.5f; } // Align vertically. y += fons__getVertAlign(stash, font, state->align, isize); for (; str != end; ++str) { if (fons__decutf8(&utf8state, &codepoint, *(const unsigned char*)str)) continue; glyph = fons__getGlyph(stash, font, codepoint, isize, iblur, FONS_GLYPH_BITMAP_REQUIRED); if (glyph != NULL) { fons__getQuad(stash, font, prevGlyphIndex, glyph, scale, state->spacing, &x, &y, &q); if (stash->nverts+6 > FONS_VERTEX_COUNT) fons__flush(stash); fons__vertex(stash, q.x0, q.y0, q.s0, q.t0, state->color); fons__vertex(stash, q.x1, q.y1, q.s1, q.t1, state->color); fons__vertex(stash, q.x1, q.y0, q.s1, q.t0, state->color); fons__vertex(stash, q.x0, q.y0, q.s0, q.t0, state->color); fons__vertex(stash, q.x0, q.y1, q.s0, q.t1, state->color); fons__vertex(stash, q.x1, q.y1, q.s1, q.t1, state->color); } prevGlyphIndex = glyph != NULL ? glyph->index : -1; } fons__flush(stash); return x; } int fonsTextIterInit(FONScontext* stash, FONStextIter* iter, float x, float y, const char* str, const char* end, int bitmapOption) { FONSstate* state = fons__getState(stash); float width; memset(iter, 0, sizeof(*iter)); if (stash == NULL) return 0; if (state->font < 0 || state->font >= stash->nfonts) return 0; iter->font = stash->fonts[state->font]; if (iter->font->data == NULL) return 0; iter->isize = (short)(state->size*10.0f); iter->iblur = (short)state->blur; iter->scale = fons__tt_getPixelHeightScale(&iter->font->font, (float)iter->isize/10.0f); // Align horizontally if (state->align & FONS_ALIGN_LEFT) { // empty } else if (state->align & FONS_ALIGN_RIGHT) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width; } else if (state->align & FONS_ALIGN_CENTER) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width * 0.5f; } // Align vertically. y += fons__getVertAlign(stash, iter->font, state->align, iter->isize); if (end == NULL) end = str + strlen(str); iter->x = iter->nextx = x; iter->y = iter->nexty = y; iter->spacing = state->spacing; iter->str = str; iter->next = str; iter->end = end; iter->codepoint = 0; iter->prevGlyphIndex = -1; iter->bitmapOption = bitmapOption; return 1; } int fonsTextIterNext(FONScontext* stash, FONStextIter* iter, FONSquad* quad) { FONSglyph* glyph = NULL; const char* str = iter->next; iter->str = iter->next; if (str == iter->end) return 0; for (; str != iter->end; str++) { if (fons__decutf8(&iter->utf8state, &iter->codepoint, *(const unsigned char*)str)) continue; str++; // Get glyph and quad iter->x = iter->nextx; iter->y = iter->nexty; glyph = fons__getGlyph(stash, iter->font, iter->codepoint, iter->isize, iter->iblur, iter->bitmapOption); // If the iterator was initialized with FONS_GLYPH_BITMAP_OPTIONAL, then the UV coordinates of the quad will be invalid. if (glyph != NULL) fons__getQuad(stash, iter->font, iter->prevGlyphIndex, glyph, iter->scale, iter->spacing, &iter->nextx, &iter->nexty, quad); iter->prevGlyphIndex = glyph != NULL ? glyph->index : -1; break; } iter->next = str; return 1; } void fonsDrawDebug(FONScontext* stash, float x, float y) { int i; int w = stash->params.width; int h = stash->params.height; float u = w == 0 ? 0 : (1.0f / w); float v = h == 0 ? 0 : (1.0f / h); if (stash->nverts+6+6 > FONS_VERTEX_COUNT) fons__flush(stash); // Draw background fons__vertex(stash, x+0, y+0, u, v, 0x0fffffff); fons__vertex(stash, x+w, y+h, u, v, 0x0fffffff); fons__vertex(stash, x+w, y+0, u, v, 0x0fffffff); fons__vertex(stash, x+0, y+0, u, v, 0x0fffffff); fons__vertex(stash, x+0, y+h, u, v, 0x0fffffff); fons__vertex(stash, x+w, y+h, u, v, 0x0fffffff); // Draw texture fons__vertex(stash, x+0, y+0, 0, 0, 0xffffffff); fons__vertex(stash, x+w, y+h, 1, 1, 0xffffffff); fons__vertex(stash, x+w, y+0, 1, 0, 0xffffffff); fons__vertex(stash, x+0, y+0, 0, 0, 0xffffffff); fons__vertex(stash, x+0, y+h, 0, 1, 0xffffffff); fons__vertex(stash, x+w, y+h, 1, 1, 0xffffffff); // Drawbug draw atlas for (i = 0; i < stash->atlas->nnodes; i++) { FONSatlasNode* n = &stash->atlas->nodes[i]; if (stash->nverts+6 > FONS_VERTEX_COUNT) fons__flush(stash); fons__vertex(stash, x+n->x+0, y+n->y+0, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+n->width, y+n->y+1, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+n->width, y+n->y+0, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+0, y+n->y+0, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+0, y+n->y+1, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+n->width, y+n->y+1, u, v, 0xc00000ff); } fons__flush(stash); } float fonsTextBounds(FONScontext* stash, float x, float y, const char* str, const char* end, float* bounds) { FONSstate* state = fons__getState(stash); unsigned int codepoint; unsigned int utf8state = 0; FONSquad q; FONSglyph* glyph = NULL; int prevGlyphIndex = -1; short isize = (short)(state->size*10.0f); short iblur = (short)state->blur; float scale; FONSfont* font; float startx, advance; float minx, miny, maxx, maxy; if (stash == NULL) return 0; if (state->font < 0 || state->font >= stash->nfonts) return 0; font = stash->fonts[state->font]; if (font->data == NULL) return 0; scale = fons__tt_getPixelHeightScale(&font->font, (float)isize/10.0f); // Align vertically. y += fons__getVertAlign(stash, font, state->align, isize); minx = maxx = x; miny = maxy = y; startx = x; if (end == NULL) end = str + strlen(str); for (; str != end; ++str) { if (fons__decutf8(&utf8state, &codepoint, *(const unsigned char*)str)) continue; glyph = fons__getGlyph(stash, font, codepoint, isize, iblur, FONS_GLYPH_BITMAP_OPTIONAL); if (glyph != NULL) { fons__getQuad(stash, font, prevGlyphIndex, glyph, scale, state->spacing, &x, &y, &q); if (q.x0 < minx) minx = q.x0; if (q.x1 > maxx) maxx = q.x1; if (stash->params.flags & FONS_ZERO_TOPLEFT) { if (q.y0 < miny) miny = q.y0; if (q.y1 > maxy) maxy = q.y1; } else { if (q.y1 < miny) miny = q.y1; if (q.y0 > maxy) maxy = q.y0; } } prevGlyphIndex = glyph != NULL ? glyph->index : -1; } advance = x - startx; // Align horizontally if (state->align & FONS_ALIGN_LEFT) { // empty } else if (state->align & FONS_ALIGN_RIGHT) { minx -= advance; maxx -= advance; } else if (state->align & FONS_ALIGN_CENTER) { minx -= advance * 0.5f; maxx -= advance * 0.5f; } if (bounds) { bounds[0] = minx; bounds[1] = miny; bounds[2] = maxx; bounds[3] = maxy; } return advance; } void fonsVertMetrics(FONScontext* stash, float* ascender, float* descender, float* lineh) { FONSfont* font; FONSstate* state = fons__getState(stash); short isize; if (stash == NULL) return; if (state->font < 0 || state->font >= stash->nfonts) return; font = stash->fonts[state->font]; isize = (short)(state->size*10.0f); if (font->data == NULL) return; if (ascender) *ascender = font->ascender*isize/10.0f; if (descender) *descender = font->descender*isize/10.0f; if (lineh) *lineh = font->lineh*isize/10.0f; } void fonsLineBounds(FONScontext* stash, float y, float* miny, float* maxy) { FONSfont* font; FONSstate* state = fons__getState(stash); short isize; if (stash == NULL) return; if (state->font < 0 || state->font >= stash->nfonts) return; font = stash->fonts[state->font]; isize = (short)(state->size*10.0f); if (font->data == NULL) return; y += fons__getVertAlign(stash, font, state->align, isize); if (stash->params.flags & FONS_ZERO_TOPLEFT) { *miny = y - font->ascender * (float)isize/10.0f; *maxy = *miny + font->lineh*isize/10.0f; } else { *maxy = y + font->descender * (float)isize/10.0f; *miny = *maxy - font->lineh*isize/10.0f; } } const unsigned char* fonsGetTextureData(FONScontext* stash, int* width, int* height) { if (width != NULL) *width = stash->params.width; if (height != NULL) *height = stash->params.height; return stash->texData; } int fonsValidateTexture(FONScontext* stash, int* dirty) { if (stash->dirtyRect[0] < stash->dirtyRect[2] && stash->dirtyRect[1] < stash->dirtyRect[3]) { dirty[0] = stash->dirtyRect[0]; dirty[1] = stash->dirtyRect[1]; dirty[2] = stash->dirtyRect[2]; dirty[3] = stash->dirtyRect[3]; // Reset dirty rect stash->dirtyRect[0] = stash->params.width; stash->dirtyRect[1] = stash->params.height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; return 1; } return 0; } void fontsDeleteFontByName(FONScontext* stash, const char* name) { int id = 0; if (stash == NULL) return; if(name == NULL) { for (id = 0; id < stash->nfonts; ++id) { fons__freeFont(stash->fonts[id]); } stash->nfonts = 0; } else { id = fonsGetFontByName(stash, name); if(id >= 0) { fons__freeFont(stash->fonts[id]); for(; id < stash->nfonts; id++) { if(id + 1 < stash->nfonts) { stash->fonts[id] = stash->fonts[id + 1]; } else { stash->fonts[id] = NULL; break; } } stash->nfonts--; } } } void fonsDeleteInternal(FONScontext* stash) { int i; if (stash == NULL) return; if (stash->params.renderDelete) stash->params.renderDelete(stash->params.userPtr); for (i = 0; i < stash->nfonts; ++i) fons__freeFont(stash->fonts[i]); if (stash->atlas) fons__deleteAtlas(stash->atlas); if (stash->fonts) free(stash->fonts); if (stash->texData) free(stash->texData); if (stash->scratch) free(stash->scratch); free(stash); fons__tt_done(stash); } void fonsSetErrorCallback(FONScontext* stash, void (*callback)(void* uptr, int error, int val), void* uptr) { if (stash == NULL) return; stash->handleError = callback; stash->errorUptr = uptr; } void fonsGetAtlasSize(FONScontext* stash, int* width, int* height) { if (stash == NULL) return; *width = stash->params.width; *height = stash->params.height; } int fonsExpandAtlas(FONScontext* stash, int width, int height) { int i, maxy = 0; unsigned char* data = NULL; if (stash == NULL) return 0; width = fons__maxi(width, stash->params.width); height = fons__maxi(height, stash->params.height); if (width == stash->params.width && height == stash->params.height) return 1; // Flush pending glyphs. fons__flush(stash); // Create new texture if (stash->params.renderResize != NULL) { if (stash->params.renderResize(stash->params.userPtr, width, height) == 0) return 0; } // Copy old texture data over. data = (unsigned char*)malloc(width * height); if (data == NULL) return 0; for (i = 0; i < stash->params.height; i++) { unsigned char* dst = &data[i*width]; unsigned char* src = &stash->texData[i*stash->params.width]; memcpy(dst, src, stash->params.width); if (width > stash->params.width) memset(dst+stash->params.width, 0, width - stash->params.width); } if (height > stash->params.height) memset(&data[stash->params.height * width], 0, (height - stash->params.height) * width); free(stash->texData); stash->texData = data; // Increase atlas size fons__atlasExpand(stash->atlas, width, height); // Add existing data as dirty. for (i = 0; i < stash->atlas->nnodes; i++) maxy = fons__maxi(maxy, stash->atlas->nodes[i].y); stash->dirtyRect[0] = 0; stash->dirtyRect[1] = 0; stash->dirtyRect[2] = stash->params.width; stash->dirtyRect[3] = maxy; stash->params.width = width; stash->params.height = height; stash->itw = 1.0f/stash->params.width; stash->ith = 1.0f/stash->params.height; return 1; } int fonsResetAtlas(FONScontext* stash, int width, int height) { int i, j; if (stash == NULL) return 0; // Flush pending glyphs. fons__flush(stash); // Create new texture if (stash->params.renderResize != NULL) { if (stash->params.renderResize(stash->params.userPtr, width, height) == 0) return 0; } // Reset atlas fons__atlasReset(stash->atlas, width, height); // Clear texture data. stash->texData = (unsigned char*)realloc(stash->texData, width * height); if (stash->texData == NULL) return 0; memset(stash->texData, 0, width * height); // Reset dirty rect stash->dirtyRect[0] = width; stash->dirtyRect[1] = height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; // Reset cached glyphs for (i = 0; i < stash->nfonts; i++) { FONSfont* font = stash->fonts[i]; font->nglyphs = 0; for (j = 0; j < FONS_HASH_LUT_SIZE; j++) font->lut[j] = -1; } stash->params.width = width; stash->params.height = height; stash->itw = 1.0f/stash->params.width; stash->ith = 1.0f/stash->params.height; // Add white rect at 0,0 for debug drawing. fons__addWhiteRect(stash, 2,2); return 1; } #endif
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\base\nanovg.c
// // Copyright (c) 2013 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #include <stdlib.h> #include <math.h> #include "nanovg.h" #ifdef WITH_NANOVG_GPU #include <stdio.h> #include <memory.h> #define FONTSTASH_IMPLEMENTATION #include "fontstash.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #else #include <string.h> #define printf(...) #endif/*WITH_NANOVG_GPU*/ #ifdef _MSC_VER #pragma warning(disable: 4100) // unreferenced formal parameter #pragma warning(disable: 4127) // conditional expression is constant #pragma warning(disable: 4204) // nonstandard extension used : non-constant aggregate initializer #pragma warning(disable: 4706) // assignment within conditional expression #endif #define NVG_INIT_FONTIMAGE_SIZE 512 #define NVG_MAX_FONTIMAGE_SIZE 2048 #define NVG_MAX_FONTIMAGES 4 #define NVG_INIT_COMMANDS_SIZE 256 #define NVG_INIT_POINTS_SIZE 128 #define NVG_INIT_PATHS_SIZE 16 #define NVG_INIT_VERTS_SIZE 256 #define NVG_MAX_STATES 32 #define NVG_KAPPA90 0.5522847493f // Length proportional to radius of a cubic bezier handle for 90deg arcs. #define NVG_COUNTOF(arr) (sizeof(arr) / sizeof(0[arr])) enum NVGcommands { NVG_MOVETO = 0, NVG_LINETO = 1, NVG_BEZIERTO = 2, NVG_CLOSE = 3, NVG_WINDING = 4, }; enum NVGpointFlags { NVG_PT_CORNER = 0x01, NVG_PT_LEFT = 0x02, NVG_PT_BEVEL = 0x04, NVG_PR_INNERBEVEL = 0x08, }; struct NVGstate { NVGcompositeOperationState compositeOperation; int shapeAntiAlias; NVGpaint fill; NVGpaint stroke; float strokeWidth; float miterLimit; int lineJoin; int lineCap; float alpha; float xform[6]; NVGscissor scissor; float fontSize; float letterSpacing; float lineHeight; float fontBlur; int textAlign; int fontId; }; typedef struct NVGstate NVGstate; struct NVGpoint { float x,y; float dx, dy; float len; float dmx, dmy; unsigned char flags; }; typedef struct NVGpoint NVGpoint; struct NVGpathCache { NVGpoint* points; int npoints; int cpoints; NVGpath* paths; int npaths; int cpaths; NVGvertex* verts; int nverts; int cverts; float bounds[4]; }; typedef struct NVGpathCache NVGpathCache; struct NVGcontext { NVGparams params; float* commands; int ccommands; int ncommands; float commandx, commandy; NVGstate states[NVG_MAX_STATES]; int nstates; NVGpathCache* cache; float tessTol; float distTol; float fringeWidth; float devicePxRatio; float windowWidth; float windowHeight; struct FONScontext* fs; int fontImages[NVG_MAX_FONTIMAGES]; int fontImageIdx; int drawCallCount; int fillTriCount; int strokeTriCount; int textTriCount; }; static float nvg__sqrtf(float a) { return sqrtf(a); } static float nvg__modf(float a, float b) { return fmodf(a, b); } static float nvg__sinf(float a) { return sinf(a); } static float nvg__cosf(float a) { return cosf(a); } static float nvg__tanf(float a) { return tanf(a); } static float nvg__atan2f(float a,float b) { return atan2f(a, b); } static float nvg__acosf(float a) { return acosf(a); } static int nvg__mini(int a, int b) { return a < b ? a : b; } static int nvg__maxi(int a, int b) { return a > b ? a : b; } static int nvg__clampi(int a, int mn, int mx) { return a < mn ? mn : (a > mx ? mx : a); } static float nvg__minf(float a, float b) { return a < b ? a : b; } static float nvg__maxf(float a, float b) { return a > b ? a : b; } static float nvg__absf(float a) { return a >= 0.0f ? a : -a; } static float nvg__signf(float a) { return a >= 0.0f ? 1.0f : -1.0f; } static float nvg__clampf(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); } static float nvg__cross(float dx0, float dy0, float dx1, float dy1) { return dx1*dy0 - dx0*dy1; } static int nvg__fequalf(float a, float b) { float t = a - b; return t > -1e-6 && t < 1e-6; } static float nvg__normalize(float *x, float* y) { float d = nvg__sqrtf((*x)*(*x) + (*y)*(*y)); if (d > 1e-6f) { float id = 1.0f / d; *x *= id; *y *= id; } return d; } static void nvg__deletePathCache(NVGpathCache* c) { if (c == NULL) return; if (c->points != NULL) free(c->points); if (c->paths != NULL) free(c->paths); if (c->verts != NULL) free(c->verts); free(c); } float nvgGetWidth(NVGcontext* ctx) { if (ctx != NULL) { return ctx->windowWidth; } return 0.0f; } float nvgGetHeight(NVGcontext* ctx) { if (ctx != NULL) { return ctx->windowHeight; } return 0.0f; } static NVGpathCache* nvg__allocPathCache(void) { NVGpathCache* c = (NVGpathCache*)malloc(sizeof(NVGpathCache)); if (c == NULL) goto error; memset(c, 0, sizeof(NVGpathCache)); c->points = (NVGpoint*)malloc(sizeof(NVGpoint)*NVG_INIT_POINTS_SIZE); if (!c->points) goto error; c->npoints = 0; c->cpoints = NVG_INIT_POINTS_SIZE; c->paths = (NVGpath*)malloc(sizeof(NVGpath)*NVG_INIT_PATHS_SIZE); if (!c->paths) goto error; c->npaths = 0; c->cpaths = NVG_INIT_PATHS_SIZE; c->verts = (NVGvertex*)malloc(sizeof(NVGvertex)*NVG_INIT_VERTS_SIZE); if (!c->verts) goto error; c->nverts = 0; c->cverts = NVG_INIT_VERTS_SIZE; return c; error: nvg__deletePathCache(c); return NULL; } static void nvg__setDevicePixelRatio(NVGcontext* ctx, float ratio) { ctx->tessTol = 0.25f / ratio; ctx->distTol = 0.01f / ratio; ctx->fringeWidth = 1.0f / ratio; ctx->devicePxRatio = ratio; } static NVGcompositeOperationState nvg__compositeOperationState(int op) { int sfactor, dfactor; if (op == NVG_SOURCE_OVER) { sfactor = NVG_ONE; dfactor = NVG_ONE_MINUS_SRC_ALPHA; } else if (op == NVG_SOURCE_IN) { sfactor = NVG_DST_ALPHA; dfactor = NVG_ZERO; } else if (op == NVG_SOURCE_OUT) { sfactor = NVG_ONE_MINUS_DST_ALPHA; dfactor = NVG_ZERO; } else if (op == NVG_ATOP) { sfactor = NVG_DST_ALPHA; dfactor = NVG_ONE_MINUS_SRC_ALPHA; } else if (op == NVG_DESTINATION_OVER) { sfactor = NVG_ONE_MINUS_DST_ALPHA; dfactor = NVG_ONE; } else if (op == NVG_DESTINATION_IN) { sfactor = NVG_ZERO; dfactor = NVG_SRC_ALPHA; } else if (op == NVG_DESTINATION_OUT) { sfactor = NVG_ZERO; dfactor = NVG_ONE_MINUS_SRC_ALPHA; } else if (op == NVG_DESTINATION_ATOP) { sfactor = NVG_ONE_MINUS_DST_ALPHA; dfactor = NVG_SRC_ALPHA; } else if (op == NVG_LIGHTER) { sfactor = NVG_ONE; dfactor = NVG_ONE; } else if (op == NVG_COPY) { sfactor = NVG_ONE; dfactor = NVG_ZERO; } else if (op == NVG_XOR) { sfactor = NVG_ONE_MINUS_DST_ALPHA; dfactor = NVG_ONE_MINUS_SRC_ALPHA; } else { sfactor = NVG_ONE; dfactor = NVG_ZERO; } NVGcompositeOperationState state; state.srcRGB = sfactor; state.dstRGB = dfactor; state.srcAlpha = sfactor; state.dstAlpha = dfactor; return state; } static NVGstate* nvg__getState(NVGcontext* ctx) { return &ctx->states[ctx->nstates-1]; } void nvgGetStateXfrom(NVGcontext* ctx, float* xform) { if(xform != NULL) { memcpy(xform, &(ctx->states[ctx->nstates-1].xform), sizeof(float) * 6); } } NVGcontext* nvgCreateInternal(NVGparams* params) { #ifdef WITH_NANOVG_GPU FONSparams fontParams; #endif/*WITH_NANOVG_GPU*/ NVGcontext* ctx = (NVGcontext*)malloc(sizeof(NVGcontext)); int i; if (ctx == NULL) goto error; memset(ctx, 0, sizeof(NVGcontext)); ctx->params = *params; for (i = 0; i < NVG_MAX_FONTIMAGES; i++) ctx->fontImages[i] = 0; ctx->commands = (float*)malloc(sizeof(float)*NVG_INIT_COMMANDS_SIZE); if (!ctx->commands) goto error; ctx->ncommands = 0; ctx->ccommands = NVG_INIT_COMMANDS_SIZE; ctx->cache = nvg__allocPathCache(); if (ctx->cache == NULL) goto error; nvgSave(ctx); nvgReset(ctx); nvg__setDevicePixelRatio(ctx, 1.0f); if (ctx->params.renderCreate(ctx->params.userPtr) == 0) goto error; #ifdef WITH_NANOVG_GPU // Init font rendering memset(&fontParams, 0, sizeof(fontParams)); fontParams.width = NVG_INIT_FONTIMAGE_SIZE; fontParams.height = NVG_INIT_FONTIMAGE_SIZE; fontParams.flags = FONS_ZERO_TOPLEFT; fontParams.renderCreate = NULL; fontParams.renderUpdate = NULL; fontParams.renderDraw = NULL; fontParams.renderDelete = NULL; fontParams.userPtr = NULL; ctx->fs = fonsCreateInternal(&fontParams); if (ctx->fs == NULL) goto error; // Create font texture ctx->fontImages[0] = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, fontParams.width, fontParams.height, 0, 0, NVG_ORIENTATION_0, NULL); if (ctx->fontImages[0] == 0) goto error; ctx->fontImageIdx = 0; #endif/*WITH_NANOVG_GPU*/ return ctx; error: nvgDeleteInternal(ctx); return 0; } NVGparams* nvgInternalParams(NVGcontext* ctx) { return &ctx->params; } void nvgDeleteInternal(NVGcontext* ctx) { int i; if (ctx == NULL) return; if (ctx->commands != NULL) free(ctx->commands); if (ctx->cache != NULL) nvg__deletePathCache(ctx->cache); #ifdef WITH_NANOVG_GPU if (ctx->fs) fonsDeleteInternal(ctx->fs); for (i = 0; i < NVG_MAX_FONTIMAGES; i++) { if (ctx->fontImages[i] != 0) { nvgDeleteImage(ctx, ctx->fontImages[i]); ctx->fontImages[i] = 0; } } #else (void)i; #endif/*WITH_NANOVG_GPU*/ if (ctx->params.renderDelete != NULL) ctx->params.renderDelete(ctx->params.userPtr); free(ctx); } void nvgBeginFrameEx(NVGcontext* ctx, float windowWidth, float windowHeight, float devicePixelRatio, int reset, enum NVGorientation orientation) { float angle = 0.0f; float anchor_x = 0.0f; float anchor_y = 0.0f; /* printf("Tris: draws:%d fill:%d stroke:%d text:%d TOT:%d\n", ctx->drawCallCount, ctx->fillTriCount, ctx->strokeTriCount, ctx->textTriCount, ctx->fillTriCount+ctx->strokeTriCount+ctx->textTriCount);*/ if (reset != 0) { ctx->nstates = 0; nvgSave(ctx); nvgReset(ctx); } ctx->windowWidth = windowWidth; ctx->windowHeight = windowHeight; nvg__setDevicePixelRatio(ctx, devicePixelRatio); ctx->params.renderViewport(ctx->params.userPtr, windowWidth, windowHeight, devicePixelRatio); ctx->drawCallCount = 0; ctx->fillTriCount = 0; ctx->strokeTriCount = 0; ctx->textTriCount = 0; if (ctx->params.globalSreenOrientation != NULL) { ctx->params.globalSreenOrientation(ctx->params.userPtr, orientation); } /* global sreen orientation is anti-clockwise */ switch (orientation) { case NVG_ORIENTATION_0: angle = 0.0f; break; case NVG_ORIENTATION_90: angle = nvgDegToRad(270); break; case NVG_ORIENTATION_180: angle = nvgDegToRad(180); break; case NVG_ORIENTATION_270: angle = nvgDegToRad(90); break; default : break; } anchor_x = windowWidth / 2.0f; anchor_y = windowHeight / 2.0f; if (orientation == 90 || orientation == 270) { nvgTranslate(ctx, anchor_x, anchor_y); nvgRotate(ctx, angle); nvgTranslate(ctx, -anchor_y, -anchor_x); } else if (orientation == 180) { nvgTranslate(ctx, anchor_x, anchor_y); nvgRotate(ctx, angle); nvgTranslate(ctx, -anchor_x, -anchor_y); } } void nvgBeginFrame(NVGcontext* ctx, float windowWidth, float windowHeight, float devicePixelRatio, enum NVGorientation orientation) { nvgBeginFrameEx(ctx, windowWidth, windowHeight, devicePixelRatio, 1, orientation); } void nvgCancelFrame(NVGcontext* ctx) { ctx->params.renderCancel(ctx->params.userPtr); } void nvgEndFrame(NVGcontext* ctx) { ctx->params.renderFlush(ctx->params.userPtr); if (ctx->fontImageIdx != 0) { int fontImage = ctx->fontImages[ctx->fontImageIdx]; int i, j, iw, ih; // delete images that smaller than current one if (fontImage == 0) return; nvgImageSize(ctx, fontImage, &iw, &ih); for (i = j = 0; i < ctx->fontImageIdx; i++) { if (ctx->fontImages[i] != 0) { int nw, nh; nvgImageSize(ctx, ctx->fontImages[i], &nw, &nh); if (nw < iw || nh < ih) nvgDeleteImage(ctx, ctx->fontImages[i]); else ctx->fontImages[j++] = ctx->fontImages[i]; } } // make current font image to first ctx->fontImages[j++] = ctx->fontImages[0]; ctx->fontImages[0] = fontImage; ctx->fontImageIdx = 0; // clear all images after j for (i = j; i < NVG_MAX_FONTIMAGES; i++) ctx->fontImages[i] = 0; } } NVGcolor nvgRGB(unsigned char r, unsigned char g, unsigned char b) { return nvgRGBA(r,g,b,255); } NVGcolor nvgRGBf(float r, float g, float b) { return nvgRGBAf(r,g,b,1.0f); } NVGcolor nvgRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { NVGcolor color; // Use longer initialization to suppress warning. color.r = r / 255.0f; color.g = g / 255.0f; color.b = b / 255.0f; color.a = a / 255.0f; return color; } NVGcolor nvgRGBAf(float r, float g, float b, float a) { NVGcolor color; // Use longer initialization to suppress warning. color.r = r; color.g = g; color.b = b; color.a = a; return color; } NVGcolor nvgTransRGBA(NVGcolor c, unsigned char a) { c.a = a / 255.0f; return c; } NVGcolor nvgTransRGBAf(NVGcolor c, float a) { c.a = a; return c; } NVGcolor nvgLerpRGBA(NVGcolor c0, NVGcolor c1, float u) { int i; float oneminu; NVGcolor cint = {{{0}}}; u = nvg__clampf(u, 0.0f, 1.0f); oneminu = 1.0f - u; for( i = 0; i <4; i++ ) { cint.rgba[i] = c0.rgba[i] * oneminu + c1.rgba[i] * u; } return cint; } NVGcolor nvgHSL(float h, float s, float l) { return nvgHSLA(h,s,l,255); } static float nvg__hue(float h, float m1, float m2) { if (h < 0) h += 1; if (h > 1) h -= 1; if (h < 1.0f/6.0f) return m1 + (m2 - m1) * h * 6.0f; else if (h < 3.0f/6.0f) return m2; else if (h < 4.0f/6.0f) return m1 + (m2 - m1) * (2.0f/3.0f - h) * 6.0f; return m1; } NVGcolor nvgHSLA(float h, float s, float l, unsigned char a) { float m1, m2; NVGcolor col; h = nvg__modf(h, 1.0f); if (h < 0.0f) h += 1.0f; s = nvg__clampf(s, 0.0f, 1.0f); l = nvg__clampf(l, 0.0f, 1.0f); m2 = l <= 0.5f ? (l * (1 + s)) : (l + s - l * s); m1 = 2 * l - m2; col.r = nvg__clampf(nvg__hue(h + 1.0f/3.0f, m1, m2), 0.0f, 1.0f); col.g = nvg__clampf(nvg__hue(h, m1, m2), 0.0f, 1.0f); col.b = nvg__clampf(nvg__hue(h - 1.0f/3.0f, m1, m2), 0.0f, 1.0f); col.a = a/255.0f; return col; } void nvgTransformIdentity(float* t) { t[0] = 1.0f; t[1] = 0.0f; t[2] = 0.0f; t[3] = 1.0f; t[4] = 0.0f; t[5] = 0.0f; } void nvgTransformTranslate(float* t, float tx, float ty) { t[0] = 1.0f; t[1] = 0.0f; t[2] = 0.0f; t[3] = 1.0f; t[4] = tx; t[5] = ty; } void nvgTransformScale(float* t, float sx, float sy) { t[0] = sx; t[1] = 0.0f; t[2] = 0.0f; t[3] = sy; t[4] = 0.0f; t[5] = 0.0f; } void nvgTransformRotate(float* t, float a) { float cs = nvg__cosf(a), sn = nvg__sinf(a); t[0] = cs; t[1] = sn; t[2] = -sn; t[3] = cs; t[4] = 0.0f; t[5] = 0.0f; } void nvgTransformSkewX(float* t, float a) { t[0] = 1.0f; t[1] = 0.0f; t[2] = nvg__tanf(a); t[3] = 1.0f; t[4] = 0.0f; t[5] = 0.0f; } void nvgTransformSkewY(float* t, float a) { t[0] = 1.0f; t[1] = nvg__tanf(a); t[2] = 0.0f; t[3] = 1.0f; t[4] = 0.0f; t[5] = 0.0f; } void nvgTransformMultiply(float* t, const float* s) { float t0 = t[0] * s[0] + t[1] * s[2]; float t2 = t[2] * s[0] + t[3] * s[2]; float t4 = t[4] * s[0] + t[5] * s[2] + s[4]; t[1] = t[0] * s[1] + t[1] * s[3]; t[3] = t[2] * s[1] + t[3] * s[3]; t[5] = t[4] * s[1] + t[5] * s[3] + s[5]; t[0] = t0; t[2] = t2; t[4] = t4; } void nvgTransformPremultiply(float* t, const float* s) { float s2[6]; memcpy(s2, s, sizeof(float)*6); nvgTransformMultiply(s2, t); memcpy(t, s2, sizeof(float)*6); } int nvgTransformInverse(float* inv, const float* t) { double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1]; if (det > -1e-6 && det < 1e-6) { nvgTransformIdentity(inv); return 0; } invdet = 1.0 / det; inv[0] = (float)(t[3] * invdet); inv[2] = (float)(-t[2] * invdet); inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet); inv[1] = (float)(-t[1] * invdet); inv[3] = (float)(t[0] * invdet); inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet); return 1; } void nvgTransformPoint(float* dx, float* dy, const float* t, float sx, float sy) { *dx = sx*t[0] + sy*t[2] + t[4]; *dy = sx*t[1] + sy*t[3] + t[5]; } float nvgDegToRad(float deg) { return deg / 180.0f * NVG_PI; } float nvgRadToDeg(float rad) { return rad / NVG_PI * 180.0f; } static void nvg__setPaintColor(NVGpaint* p, NVGcolor color) { memset(p, 0, sizeof(*p)); nvgTransformIdentity(p->xform); p->radius = 0.0f; p->feather = 1.0f; p->innerColor = color; p->outerColor = color; } // State handling void nvgSave(NVGcontext* ctx) { if (ctx->nstates >= NVG_MAX_STATES) return; if (ctx->nstates > 0) memcpy(&ctx->states[ctx->nstates], &ctx->states[ctx->nstates-1], sizeof(NVGstate)); ctx->nstates++; } void nvgRestore(NVGcontext* ctx) { if (ctx->nstates <= 1) return; ctx->nstates--; } void nvgReset(NVGcontext* ctx) { NVGstate* state = nvg__getState(ctx); memset(state, 0, sizeof(*state)); nvg__setPaintColor(&state->fill, nvgRGBA(255,255,255,255)); nvg__setPaintColor(&state->stroke, nvgRGBA(0,0,0,255)); state->compositeOperation = nvg__compositeOperationState(NVG_SOURCE_OVER); state->shapeAntiAlias = 1; state->strokeWidth = 1.0f; state->miterLimit = 10.0f; state->lineCap = NVG_BUTT; state->lineJoin = NVG_MITER; state->alpha = 1.0f; nvgTransformIdentity(state->xform); state->scissor.extent[0] = -1.0f; state->scissor.extent[1] = -1.0f; state->fontSize = 16.0f; state->letterSpacing = 0.0f; state->lineHeight = 1.0f; state->fontBlur = 0.0f; state->textAlign = NVG_ALIGN_LEFT | NVG_ALIGN_BASELINE; state->fontId = 0; } // State setting void nvgShapeAntiAlias(NVGcontext* ctx, int enabled) { NVGstate* state = nvg__getState(ctx); state->shapeAntiAlias = enabled; } void nvgStrokeWidth(NVGcontext* ctx, float width) { NVGstate* state = nvg__getState(ctx); state->strokeWidth = width; } void nvgMiterLimit(NVGcontext* ctx, float limit) { NVGstate* state = nvg__getState(ctx); state->miterLimit = limit; } void nvgLineCap(NVGcontext* ctx, int cap) { NVGstate* state = nvg__getState(ctx); state->lineCap = cap; if(ctx->params.setLineCap != NULL) { ctx->params.setLineCap(ctx->params.userPtr, cap); } } void nvgLineJoin(NVGcontext* ctx, int join) { NVGstate* state = nvg__getState(ctx); state->lineJoin = join; if(ctx->params.setLineJoin != NULL) { ctx->params.setLineJoin(ctx->params.userPtr, join); } } void nvgGlobalAlpha(NVGcontext* ctx, float alpha) { NVGstate* state = nvg__getState(ctx); state->alpha = alpha; } void nvgTransform(NVGcontext* ctx, float a, float b, float c, float d, float e, float f) { NVGstate* state = nvg__getState(ctx); float t[6] = { a, b, c, d, e, f }; nvgTransformPremultiply(state->xform, t); } void nvgResetTransform(NVGcontext* ctx) { NVGstate* state = nvg__getState(ctx); nvgTransformIdentity(state->xform); } void nvgTranslate(NVGcontext* ctx, float x, float y) { NVGstate* state = nvg__getState(ctx); float t[6]; nvgTransformTranslate(t, x,y); nvgTransformPremultiply(state->xform, t); } void nvgRotate(NVGcontext* ctx, float angle) { NVGstate* state = nvg__getState(ctx); float t[6]; nvgTransformRotate(t, angle); nvgTransformPremultiply(state->xform, t); } void nvgSkewX(NVGcontext* ctx, float angle) { NVGstate* state = nvg__getState(ctx); float t[6]; nvgTransformSkewX(t, angle); nvgTransformPremultiply(state->xform, t); } void nvgSkewY(NVGcontext* ctx, float angle) { NVGstate* state = nvg__getState(ctx); float t[6]; nvgTransformSkewY(t, angle); nvgTransformPremultiply(state->xform, t); } void nvgScale(NVGcontext* ctx, float x, float y) { NVGstate* state = nvg__getState(ctx); float t[6]; nvgTransformScale(t, x,y); nvgTransformPremultiply(state->xform, t); } void nvgCurrentTransform(NVGcontext* ctx, float* xform) { NVGstate* state = nvg__getState(ctx); if (xform == NULL) return; memcpy(xform, state->xform, sizeof(float)*6); } void nvgStrokeColor(NVGcontext* ctx, NVGcolor color) { NVGstate* state = nvg__getState(ctx); nvg__setPaintColor(&state->stroke, color); } void nvgStrokePaint(NVGcontext* ctx, NVGpaint paint) { NVGstate* state = nvg__getState(ctx); state->stroke = paint; nvgTransformMultiply(state->stroke.xform, state->xform); } void nvgFillColor(NVGcontext* ctx, NVGcolor color) { NVGstate* state = nvg__getState(ctx); nvg__setPaintColor(&state->fill, color); } void nvgFillPaint(NVGcontext* ctx, NVGpaint paint) { NVGstate* state = nvg__getState(ctx); state->fill = paint; nvgTransformMultiply(state->fill.xform, state->xform); } #ifdef WITH_NANOVG_GPU int nvgCreateImage(NVGcontext* ctx, const char* filename, int imageFlags) { int w, h, n, image; unsigned char* img; stbi_set_unpremultiply_on_load(1); stbi_convert_iphone_png_to_rgb(1); img = stbi_load(filename, &w, &h, &n, 4); if (img == NULL) { // printf("Failed to load %s - %s\n", filename, stbi_failure_reason()); return 0; } image = nvgCreateImageRGBA(ctx, w, h, imageFlags, img); stbi_image_free(img); return image; } int nvgCreateImageMem(NVGcontext* ctx, int imageFlags, unsigned char* data, int ndata) { int w, h, n, image; unsigned char* img = stbi_load_from_memory(data, ndata, &w, &h, &n, 4); if (img == NULL) { // printf("Failed to load %s - %s\n", filename, stbi_failure_reason()); return 0; } image = nvgCreateImageRGBA(ctx, w, h, imageFlags, img); stbi_image_free(img); return image; } #else int nvgCreateImage(NVGcontext* ctx, const char* filename, int imageFlags) { return -1; } int nvgCreateImageMem(NVGcontext* ctx, int imageFlags, unsigned char* data, int ndata) { return -1; } #endif/*WITH_NANOVG_GPU*/ int nvgCreateImageRGBA(NVGcontext* ctx, int w, int h, int imageFlags, const unsigned char* data) { return ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_RGBA, w, h, w * 4, imageFlags, NVG_ORIENTATION_0, data); } void nvgUpdateImage(NVGcontext* ctx, int image, const unsigned char* data) { int w, h; ctx->params.renderGetTextureSize(ctx->params.userPtr, image, &w, &h); ctx->params.renderUpdateTexture(ctx->params.userPtr, image, 0,0, w,h, data); } void nvgImageSize(NVGcontext* ctx, int image, int* w, int* h) { ctx->params.renderGetTextureSize(ctx->params.userPtr, image, w, h); } void nvgDeleteFontByName(NVGcontext* ctx, const char* name) { #ifdef WITH_NANOVG_GPU if (ctx->fs) { fontsDeleteFontByName(ctx->fs, name); } #endif } void nvgDeleteImage(NVGcontext* ctx, int image) { ctx->params.renderDeleteTexture(ctx->params.userPtr, image); } NVGpaint nvgLinearGradient(NVGcontext* ctx, float sx, float sy, float ex, float ey, NVGcolor icol, NVGcolor ocol) { NVGpaint p; float dx, dy, d; const float large = 1e5; NVG_NOTUSED(ctx); memset(&p, 0, sizeof(p)); // Calculate transform aligned to the line dx = ex - sx; dy = ey - sy; d = sqrtf(dx*dx + dy*dy); if (d > 0.0001f) { dx /= d; dy /= d; } else { dx = 0; dy = 1; } p.xform[0] = dy; p.xform[1] = -dx; p.xform[2] = dx; p.xform[3] = dy; p.xform[4] = sx - dx*large; p.xform[5] = sy - dy*large; p.extent[0] = large; p.extent[1] = large + d*0.5f; p.radius = 0.0f; p.feather = nvg__maxf(1.0f, d); p.innerColor = icol; p.outerColor = ocol; return p; } NVGpaint nvgRadialGradient(NVGcontext* ctx, float cx, float cy, float inr, float outr, NVGcolor icol, NVGcolor ocol) { NVGpaint p; float r = (inr+outr)*0.5f; float f = (outr-inr); NVG_NOTUSED(ctx); memset(&p, 0, sizeof(p)); nvgTransformIdentity(p.xform); p.xform[4] = cx; p.xform[5] = cy; p.extent[0] = r; p.extent[1] = r; p.radius = r; p.feather = nvg__maxf(1.0f, f); p.innerColor = icol; p.outerColor = ocol; return p; } NVGpaint nvgBoxGradient(NVGcontext* ctx, float x, float y, float w, float h, float r, float f, NVGcolor icol, NVGcolor ocol) { NVGpaint p; NVG_NOTUSED(ctx); memset(&p, 0, sizeof(p)); nvgTransformIdentity(p.xform); p.xform[4] = x+w*0.5f; p.xform[5] = y+h*0.5f; p.extent[0] = w*0.5f; p.extent[1] = h*0.5f; p.radius = r; p.feather = nvg__maxf(1.0f, f); p.innerColor = icol; p.outerColor = ocol; return p; } NVGpaint nvgImagePattern(NVGcontext* ctx, float cx, float cy, float w, float h, float angle, int image, float alpha) { NVGpaint p; NVG_NOTUSED(ctx); memset(&p, 0, sizeof(p)); nvgTransformRotate(p.xform, angle); p.xform[4] = cx; p.xform[5] = cy; p.extent[0] = w; p.extent[1] = h; p.image = image; p.innerColor = p.outerColor = nvgRGBAf(1,1,1,alpha); return p; } // Scissoring void nvgScissor(NVGcontext* ctx, float x, float y, float w, float h) { NVGstate* state = nvg__getState(ctx); w = nvg__maxf(0.0f, w); h = nvg__maxf(0.0f, h); /* 消除着色器精度不够引起的漏出颜色的问题 */ if (w == 0.0f || h == 0.0f) { w = 0.0f; h = 0.0f; } nvgTransformIdentity(state->scissor.xform); state->scissor.xform[4] = x+w*0.5f; state->scissor.xform[5] = y+h*0.5f; nvgTransformMultiply(state->scissor.xform, state->xform); state->scissor.extent[0] = w*0.5f; state->scissor.extent[1] = h*0.5f; } static void nvg__isectRects(float* dst, float ax, float ay, float aw, float ah, float bx, float by, float bw, float bh) { float minx = nvg__maxf(ax, bx); float miny = nvg__maxf(ay, by); float maxx = nvg__minf(ax+aw, bx+bw); float maxy = nvg__minf(ay+ah, by+bh); dst[0] = minx; dst[1] = miny; dst[2] = nvg__maxf(0.0f, maxx - minx); dst[3] = nvg__maxf(0.0f, maxy - miny); } int nvgGetCurrScissor(NVGcontext* ctx, float* x, float* y, float* w, float* h) { NVGstate* state = nvg__getState(ctx); float pxform[6], invxorm[6]; float ex, ey, tex, tey; // If no previous scissor has been set, set the scissor as current scissor. if (state->scissor.extent[0] < 0) { *w = 0; *h = 0; return 0; } // Transform the current scissor rect into current transform space. // If there is difference in rotation, this will be approximation. memcpy(pxform, state->scissor.xform, sizeof(float)*6); ex = state->scissor.extent[0]; ey = state->scissor.extent[1]; nvgTransformInverse(invxorm, state->xform); nvgTransformMultiply(pxform, invxorm); tex = ex*nvg__absf(pxform[0]) + ey*nvg__absf(pxform[2]); tey = ex*nvg__absf(pxform[1]) + ey*nvg__absf(pxform[3]); *x = pxform[4] - tex; *y = pxform[5] - tey; *w = tex * 2; *h = tey * 2; return 1; } void nvgIntersectScissorForOtherRect(NVGcontext* ctx, float x, float y, float w, float h, float dx, float dy, float dw, float dh) { NVGstate* state = nvg__getState(ctx); float rect[4]; float invxorm[6]; float ex = 0.0f, ey = 0.0f, tex = 0.0f, tey = 0.0f; /* 因为脏矩形默认坐标系就是没有旋转没有缩放没有平移的状态 */ float pxform[6] = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }; ex = dw * 0.5f; ey = dh * 0.5f; pxform[4] = dx + dw * 0.5f; pxform[5] = dy + dh * 0.5f; memset(invxorm, 0, sizeof(float) * 6); nvgTransformInverse(invxorm, state->xform); nvgTransformMultiply(pxform, invxorm); tex = ex*nvg__absf(pxform[0]) + ey*nvg__absf(pxform[2]); tey = ex*nvg__absf(pxform[1]) + ey*nvg__absf(pxform[3]); // Intersect rects. nvg__isectRects(rect, pxform[4] - tex, pxform[5] - tey, tex * 2, tey * 2, x, y, w, h); nvgScissor(ctx, rect[0], rect[1], rect[2], rect[3]); } void nvgIntersectScissor_ex(NVGcontext* ctx, float* x, float* y, float* w, float* h) { NVGstate* state = nvg__getState(ctx); float pxform[6], invxorm[6]; float rect[4]; float ex, ey, tex, tey; // If no previous scissor has been set, set the scissor as current scissor. if (state->scissor.extent[0] < 0) { nvgScissor(ctx, *x, *y, *w, *h); return; } // Transform the current scissor rect into current transform space. // If there is difference in rotation, this will be approximation. memcpy(pxform, state->scissor.xform, sizeof(float)*6); ex = state->scissor.extent[0]; ey = state->scissor.extent[1]; nvgTransformInverse(invxorm, state->xform); nvgTransformMultiply(pxform, invxorm); tex = ex*nvg__absf(pxform[0]) + ey*nvg__absf(pxform[2]); tey = ex*nvg__absf(pxform[1]) + ey*nvg__absf(pxform[3]); // Intersect rects. nvg__isectRects(rect, pxform[4]-tex,pxform[5]-tey,tex*2,tey*2, *x, *y, *w, *h); *x = rect[0]; *y = rect[1]; *w = rect[2]; *h = rect[3]; nvgScissor(ctx, rect[0], rect[1], rect[2], rect[3]); } void nvgIntersectScissor(NVGcontext* ctx, float x, float y, float w, float h) { NVGstate* state = nvg__getState(ctx); float pxform[6], invxorm[6]; float rect[4]; float ex, ey, tex, tey; // If no previous scissor has been set, set the scissor as current scissor. if (state->scissor.extent[0] < 0) { nvgScissor(ctx, x, y, w, h); return; } // Transform the current scissor rect into current transform space. // If there is difference in rotation, this will be approximation. memcpy(pxform, state->scissor.xform, sizeof(float)*6); ex = state->scissor.extent[0]; ey = state->scissor.extent[1]; nvgTransformInverse(invxorm, state->xform); nvgTransformMultiply(pxform, invxorm); tex = ex*nvg__absf(pxform[0]) + ey*nvg__absf(pxform[2]); tey = ex*nvg__absf(pxform[1]) + ey*nvg__absf(pxform[3]); // Intersect rects. nvg__isectRects(rect, pxform[4]-tex,pxform[5]-tey,tex*2,tey*2, x,y,w,h); nvgScissor(ctx, rect[0], rect[1], rect[2], rect[3]); } void nvgResetScissor(NVGcontext* ctx) { NVGstate* state = nvg__getState(ctx); memset(state->scissor.xform, 0, sizeof(state->scissor.xform)); state->scissor.extent[0] = -1.0f; state->scissor.extent[1] = -1.0f; } // Global composite operation. void nvgGlobalCompositeOperation(NVGcontext* ctx, int op) { NVGstate* state = nvg__getState(ctx); state->compositeOperation = nvg__compositeOperationState(op); } void nvgGlobalCompositeBlendFunc(NVGcontext* ctx, int sfactor, int dfactor) { nvgGlobalCompositeBlendFuncSeparate(ctx, sfactor, dfactor, sfactor, dfactor); } void nvgGlobalCompositeBlendFuncSeparate(NVGcontext* ctx, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { NVGcompositeOperationState op; op.srcRGB = srcRGB; op.dstRGB = dstRGB; op.srcAlpha = srcAlpha; op.dstAlpha = dstAlpha; NVGstate* state = nvg__getState(ctx); state->compositeOperation = op; } static int nvg__ptEquals(float x1, float y1, float x2, float y2, float tol) { float dx = x2 - x1; float dy = y2 - y1; return dx*dx + dy*dy < tol*tol; } static float nvg__distPtSeg(float x, float y, float px, float py, float qx, float qy) { float pqx, pqy, dx, dy, d, t; pqx = qx-px; pqy = qy-py; dx = x-px; dy = y-py; d = pqx*pqx + pqy*pqy; t = pqx*dx + pqy*dy; if (d > 0) t /= d; if (t < 0) t = 0; else if (t > 1) t = 1; dx = px + t*pqx - x; dy = py + t*pqy - y; return dx*dx + dy*dy; } static void nvg__appendCommands(NVGcontext* ctx, float* vals, int nvals) { NVGstate* state = nvg__getState(ctx); int i; if (ctx->ncommands+nvals > ctx->ccommands) { float* commands; int ccommands = ctx->ncommands+nvals + ctx->ccommands/2; commands = (float*)realloc(ctx->commands, sizeof(float)*ccommands); if (commands == NULL) return; ctx->commands = commands; ctx->ccommands = ccommands; } if ((int)vals[0] != NVG_CLOSE && (int)vals[0] != NVG_WINDING) { ctx->commandx = vals[nvals-2]; ctx->commandy = vals[nvals-1]; } // transform commands i = 0; while (i < nvals) { int cmd = (int)vals[i]; switch (cmd) { case NVG_MOVETO: nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]); i += 3; break; case NVG_LINETO: nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]); i += 3; break; case NVG_BEZIERTO: nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]); nvgTransformPoint(&vals[i+3],&vals[i+4], state->xform, vals[i+3],vals[i+4]); nvgTransformPoint(&vals[i+5],&vals[i+6], state->xform, vals[i+5],vals[i+6]); i += 7; break; case NVG_CLOSE: i++; break; case NVG_WINDING: i += 2; break; default: i++; } } memcpy(&ctx->commands[ctx->ncommands], vals, nvals*sizeof(float)); ctx->ncommands += nvals; } static void nvg__clearPathCache(NVGcontext* ctx) { ctx->cache->npoints = 0; ctx->cache->npaths = 0; } static NVGpath* nvg__lastPath(NVGcontext* ctx) { if (ctx->cache->npaths > 0) return &ctx->cache->paths[ctx->cache->npaths-1]; return NULL; } static void nvg__addPath(NVGcontext* ctx) { NVGpath* path; if (ctx->cache->npaths+1 > ctx->cache->cpaths) { NVGpath* paths; int cpaths = ctx->cache->npaths+1 + ctx->cache->cpaths/2; paths = (NVGpath*)realloc(ctx->cache->paths, sizeof(NVGpath)*cpaths); if (paths == NULL) return; ctx->cache->paths = paths; ctx->cache->cpaths = cpaths; } path = &ctx->cache->paths[ctx->cache->npaths]; memset(path, 0, sizeof(*path)); path->first = ctx->cache->npoints; path->winding = NVG_CCW; ctx->cache->npaths++; } static NVGpoint* nvg__lastPoint(NVGcontext* ctx) { if (ctx->cache->npoints > 0) return &ctx->cache->points[ctx->cache->npoints-1]; return NULL; } static void nvg__addPoint(NVGcontext* ctx, float x, float y, int flags) { NVGpath* path = nvg__lastPath(ctx); NVGpoint* pt; if (path == NULL) return; if (path->count > 0 && ctx->cache->npoints > 0) { pt = nvg__lastPoint(ctx); if (nvg__ptEquals(pt->x,pt->y, x,y, ctx->distTol)) { pt->flags |= flags; return; } } if (ctx->cache->npoints+1 > ctx->cache->cpoints) { NVGpoint* points; int cpoints = ctx->cache->npoints+1 + ctx->cache->cpoints/2; points = (NVGpoint*)realloc(ctx->cache->points, sizeof(NVGpoint)*cpoints); if (points == NULL) return; ctx->cache->points = points; ctx->cache->cpoints = cpoints; } pt = &ctx->cache->points[ctx->cache->npoints]; memset(pt, 0, sizeof(*pt)); pt->x = x; pt->y = y; pt->flags = (unsigned char)flags; ctx->cache->npoints++; path->count++; } static void nvg__closePath(NVGcontext* ctx) { NVGpath* path = nvg__lastPath(ctx); if (path == NULL) return; path->closed = 1; } static void nvg__pathWinding(NVGcontext* ctx, int winding) { NVGpath* path = nvg__lastPath(ctx); if (path == NULL) return; path->winding = winding; } static float nvg__getAverageScale(float *t) { float sx = sqrtf(t[0]*t[0] + t[2]*t[2]); float sy = sqrtf(t[1]*t[1] + t[3]*t[3]); return (sx + sy) * 0.5f; } static NVGvertex* nvg__allocTempVerts(NVGcontext* ctx, int nverts) { if (nverts > ctx->cache->cverts) { NVGvertex* verts; int cverts = (nverts + 0xff) & ~0xff; // Round up to prevent allocations when things change just slightly. verts = (NVGvertex*)realloc(ctx->cache->verts, sizeof(NVGvertex)*cverts); if (verts == NULL) return NULL; ctx->cache->verts = verts; ctx->cache->cverts = cverts; } return ctx->cache->verts; } static float nvg__triarea2(float ax, float ay, float bx, float by, float cx, float cy) { float abx = bx - ax; float aby = by - ay; float acx = cx - ax; float acy = cy - ay; return acx*aby - abx*acy; } static float nvg__polyArea(NVGpoint* pts, int npts) { int i; float area = 0; for (i = 2; i < npts; i++) { NVGpoint* a = &pts[0]; NVGpoint* b = &pts[i-1]; NVGpoint* c = &pts[i]; area += nvg__triarea2(a->x,a->y, b->x,b->y, c->x,c->y); } return area * 0.5f; } static void nvg__polyReverse(NVGpoint* pts, int npts) { NVGpoint tmp; int i = 0, j = npts-1; while (i < j) { tmp = pts[i]; pts[i] = pts[j]; pts[j] = tmp; i++; j--; } } static void nvg__vset(NVGvertex* vtx, float x, float y, float u, float v) { vtx->x = x; vtx->y = y; vtx->u = u; vtx->v = v; } static void nvg__tesselateBezier(NVGcontext* ctx, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, int level, int type) { float x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234; float dx,dy,d2,d3; if (level > 10) return; x12 = (x1+x2)*0.5f; y12 = (y1+y2)*0.5f; x23 = (x2+x3)*0.5f; y23 = (y2+y3)*0.5f; x34 = (x3+x4)*0.5f; y34 = (y3+y4)*0.5f; x123 = (x12+x23)*0.5f; y123 = (y12+y23)*0.5f; dx = x4 - x1; dy = y4 - y1; d2 = nvg__absf(((x2 - x4) * dy - (y2 - y4) * dx)); d3 = nvg__absf(((x3 - x4) * dy - (y3 - y4) * dx)); if ((d2 + d3)*(d2 + d3) < ctx->tessTol * (dx*dx + dy*dy)) { nvg__addPoint(ctx, x4, y4, type); return; } /* if (nvg__absf(x1+x3-x2-x2) + nvg__absf(y1+y3-y2-y2) + nvg__absf(x2+x4-x3-x3) + nvg__absf(y2+y4-y3-y3) < ctx->tessTol) { nvg__addPoint(ctx, x4, y4, type); return; }*/ x234 = (x23+x34)*0.5f; y234 = (y23+y34)*0.5f; x1234 = (x123+x234)*0.5f; y1234 = (y123+y234)*0.5f; nvg__tesselateBezier(ctx, x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0); nvg__tesselateBezier(ctx, x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type); } static void nvg__flattenPaths(NVGcontext* ctx) { NVGpathCache* cache = ctx->cache; // NVGstate* state = nvg__getState(ctx); NVGpoint* last; NVGpoint* p0; NVGpoint* p1; NVGpoint* pts; NVGpath* path; int i, j; float* cp1; float* cp2; float* p; float area; if (cache->npaths > 0) return; // Flatten i = 0; while (i < ctx->ncommands) { int cmd = (int)ctx->commands[i]; switch (cmd) { case NVG_MOVETO: nvg__addPath(ctx); p = &ctx->commands[i+1]; nvg__addPoint(ctx, p[0], p[1], NVG_PT_CORNER); i += 3; break; case NVG_LINETO: p = &ctx->commands[i+1]; nvg__addPoint(ctx, p[0], p[1], NVG_PT_CORNER); i += 3; break; case NVG_BEZIERTO: last = nvg__lastPoint(ctx); if (last != NULL) { cp1 = &ctx->commands[i+1]; cp2 = &ctx->commands[i+3]; p = &ctx->commands[i+5]; nvg__tesselateBezier(ctx, last->x,last->y, cp1[0],cp1[1], cp2[0],cp2[1], p[0],p[1], 0, NVG_PT_CORNER); } i += 7; break; case NVG_CLOSE: nvg__closePath(ctx); i++; break; case NVG_WINDING: nvg__pathWinding(ctx, (int)ctx->commands[i+1]); i += 2; break; default: i++; } } cache->bounds[0] = cache->bounds[1] = 1e6f; cache->bounds[2] = cache->bounds[3] = -1e6f; // Calculate the direction and length of line segments. for (j = 0; j < cache->npaths; j++) { path = &cache->paths[j]; pts = &cache->points[path->first]; // If the first and last points are the same, remove the last, mark as closed path. p0 = &pts[path->count-1]; p1 = &pts[0]; if (nvg__ptEquals(p0->x,p0->y, p1->x,p1->y, ctx->distTol)) { path->count--; p0 = &pts[path->count-1]; path->closed = 1; } // Enforce winding. if (path->count > 2) { area = nvg__polyArea(pts, path->count); if (path->winding == NVG_CCW && area < 0.0f) nvg__polyReverse(pts, path->count); if (path->winding == NVG_CW && area > 0.0f) nvg__polyReverse(pts, path->count); } for(i = 0; i < path->count; i++) { // Calculate segment direction and length p0->dx = p1->x - p0->x; p0->dy = p1->y - p0->y; p0->len = nvg__normalize(&p0->dx, &p0->dy); // Update bounds cache->bounds[0] = nvg__minf(cache->bounds[0], p0->x); cache->bounds[1] = nvg__minf(cache->bounds[1], p0->y); cache->bounds[2] = nvg__maxf(cache->bounds[2], p0->x); cache->bounds[3] = nvg__maxf(cache->bounds[3], p0->y); // Advance p0 = p1++; } } } static int nvg__curveDivs(float r, float arc, float tol) { float da = acosf(r / (r + tol)) * 2.0f; return nvg__maxi(2, (int)ceilf(arc / da)); } #ifdef WITH_NANOVG_GPU static void nvg__chooseBevel(int bevel, NVGpoint* p0, NVGpoint* p1, float w, float* x0, float* y0, float* x1, float* y1) { if (bevel) { *x0 = p1->x + p0->dy * w; *y0 = p1->y - p0->dx * w; *x1 = p1->x + p1->dy * w; *y1 = p1->y - p1->dx * w; } else { *x0 = p1->x + p1->dmx * w; *y0 = p1->y + p1->dmy * w; *x1 = p1->x + p1->dmx * w; *y1 = p1->y + p1->dmy * w; } } static NVGvertex* nvg__roundJoin(NVGvertex* dst, NVGpoint* p0, NVGpoint* p1, float lw, float rw, float lu, float ru, int ncap, float fringe) { int i, n; float dlx0 = p0->dy; float dly0 = -p0->dx; float dlx1 = p1->dy; float dly1 = -p1->dx; NVG_NOTUSED(fringe); if (p1->flags & NVG_PT_LEFT) { float lx0,ly0,lx1,ly1,a0,a1; nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1); a0 = atan2f(-dly0, -dlx0); a1 = atan2f(-dly1, -dlx1); if (a1 > a0) a1 -= NVG_PI*2; nvg__vset(dst, lx0, ly0, lu,1); dst++; nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++; n = nvg__clampi((int)ceilf(((a0 - a1) / NVG_PI) * ncap), 2, ncap); for (i = 0; i < n; i++) { float u = i/(float)(n-1); float a = a0 + u*(a1-a0); float rx = p1->x + cosf(a) * rw; float ry = p1->y + sinf(a) * rw; nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++; nvg__vset(dst, rx, ry, ru,1); dst++; } nvg__vset(dst, lx1, ly1, lu,1); dst++; nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++; } else { float rx0,ry0,rx1,ry1,a0,a1; nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1); a0 = atan2f(dly0, dlx0); a1 = atan2f(dly1, dlx1); if (a1 < a0) a1 += NVG_PI*2; nvg__vset(dst, p1->x + dlx0*rw, p1->y + dly0*rw, lu,1); dst++; nvg__vset(dst, rx0, ry0, ru,1); dst++; n = nvg__clampi((int)ceilf(((a1 - a0) / NVG_PI) * ncap), 2, ncap); for (i = 0; i < n; i++) { float u = i/(float)(n-1); float a = a0 + u*(a1-a0); float lx = p1->x + cosf(a) * lw; float ly = p1->y + sinf(a) * lw; nvg__vset(dst, lx, ly, lu,1); dst++; nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++; } nvg__vset(dst, p1->x + dlx1*rw, p1->y + dly1*rw, lu,1); dst++; nvg__vset(dst, rx1, ry1, ru,1); dst++; } return dst; } static NVGvertex* nvg__bevelJoin(NVGvertex* dst, NVGpoint* p0, NVGpoint* p1, float lw, float rw, float lu, float ru, float fringe) { float rx0,ry0,rx1,ry1; float lx0,ly0,lx1,ly1; float dlx0 = p0->dy; float dly0 = -p0->dx; float dlx1 = p1->dy; float dly1 = -p1->dx; NVG_NOTUSED(fringe); if (p1->flags & NVG_PT_LEFT) { nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1); nvg__vset(dst, lx0, ly0, lu,1); dst++; nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++; if (p1->flags & NVG_PT_BEVEL) { nvg__vset(dst, lx0, ly0, lu,1); dst++; nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++; nvg__vset(dst, lx1, ly1, lu,1); dst++; nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++; } else { rx0 = p1->x - p1->dmx * rw; ry0 = p1->y - p1->dmy * rw; nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++; nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++; nvg__vset(dst, rx0, ry0, ru,1); dst++; nvg__vset(dst, rx0, ry0, ru,1); dst++; nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++; nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++; } nvg__vset(dst, lx1, ly1, lu,1); dst++; nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++; } else { nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1); nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++; nvg__vset(dst, rx0, ry0, ru,1); dst++; if (p1->flags & NVG_PT_BEVEL) { nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++; nvg__vset(dst, rx0, ry0, ru,1); dst++; nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++; nvg__vset(dst, rx1, ry1, ru,1); dst++; } else { lx0 = p1->x + p1->dmx * lw; ly0 = p1->y + p1->dmy * lw; nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++; nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++; nvg__vset(dst, lx0, ly0, lu,1); dst++; nvg__vset(dst, lx0, ly0, lu,1); dst++; nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++; nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++; } nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++; nvg__vset(dst, rx1, ry1, ru,1); dst++; } return dst; } static NVGvertex* nvg__buttCapStart(NVGvertex* dst, NVGpoint* p, float dx, float dy, float w, float d, float aa, float u0, float u1) { float px = p->x - dx*d; float py = p->y - dy*d; float dlx = dy; float dly = -dx; nvg__vset(dst, px + dlx*w - dx*aa, py + dly*w - dy*aa, u0,0); dst++; nvg__vset(dst, px - dlx*w - dx*aa, py - dly*w - dy*aa, u1,0); dst++; nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++; nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++; return dst; } static NVGvertex* nvg__buttCapEnd(NVGvertex* dst, NVGpoint* p, float dx, float dy, float w, float d, float aa, float u0, float u1) { float px = p->x + dx*d; float py = p->y + dy*d; float dlx = dy; float dly = -dx; nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++; nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++; nvg__vset(dst, px + dlx*w + dx*aa, py + dly*w + dy*aa, u0,0); dst++; nvg__vset(dst, px - dlx*w + dx*aa, py - dly*w + dy*aa, u1,0); dst++; return dst; } static NVGvertex* nvg__roundCapStart(NVGvertex* dst, NVGpoint* p, float dx, float dy, float w, int ncap, float aa, float u0, float u1) { int i; float px = p->x; float py = p->y; float dlx = dy; float dly = -dx; NVG_NOTUSED(aa); for (i = 0; i < ncap; i++) { float a = i/(float)(ncap-1)*NVG_PI; float ax = cosf(a) * w, ay = sinf(a) * w; nvg__vset(dst, px - dlx*ax - dx*ay, py - dly*ax - dy*ay, u0,1); dst++; nvg__vset(dst, px, py, 0.5f,1); dst++; } nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++; nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++; return dst; } static NVGvertex* nvg__roundCapEnd(NVGvertex* dst, NVGpoint* p, float dx, float dy, float w, int ncap, float aa, float u0, float u1) { int i; float px = p->x; float py = p->y; float dlx = dy; float dly = -dx; NVG_NOTUSED(aa); nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++; nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++; for (i = 0; i < ncap; i++) { float a = i/(float)(ncap-1)*NVG_PI; float ax = cosf(a) * w, ay = sinf(a) * w; nvg__vset(dst, px, py, 0.5f,1); dst++; nvg__vset(dst, px - dlx*ax + dx*ay, py - dly*ax + dy*ay, u0,1); dst++; } return dst; } static void nvg__calculateJoins(NVGcontext* ctx, float w, int lineJoin, float miterLimit) { NVGpathCache* cache = ctx->cache; int i, j; float iw = 0.0f; if (w > 0.0f) iw = 1.0f / w; // Calculate which joins needs extra vertices to append, and gather vertex count. for (i = 0; i < cache->npaths; i++) { NVGpath* path = &cache->paths[i]; NVGpoint* pts = &cache->points[path->first]; NVGpoint* p0 = &pts[path->count-1]; NVGpoint* p1 = &pts[0]; int nleft = 0; path->nbevel = 0; for (j = 0; j < path->count; j++) { float dlx0, dly0, dlx1, dly1, dmr2, cross, limit; dlx0 = p0->dy; dly0 = -p0->dx; dlx1 = p1->dy; dly1 = -p1->dx; // Calculate extrusions p1->dmx = (dlx0 + dlx1) * 0.5f; p1->dmy = (dly0 + dly1) * 0.5f; dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy; if (dmr2 > 0.000001f) { float scale = 1.0f / dmr2; if (scale > 600.0f) { scale = 600.0f; } p1->dmx *= scale; p1->dmy *= scale; } // Clear flags, but keep the corner. p1->flags = (p1->flags & NVG_PT_CORNER) ? NVG_PT_CORNER : 0; // Keep track of left turns. cross = p1->dx * p0->dy - p0->dx * p1->dy; if (cross > 0.0f) { nleft++; p1->flags |= NVG_PT_LEFT; } // Calculate if we should use bevel or miter for inner join. limit = nvg__maxf(1.01f, nvg__minf(p0->len, p1->len) * iw); if ((dmr2 * limit*limit) < 1.0f) p1->flags |= NVG_PR_INNERBEVEL; // Check to see if the corner needs to be beveled. if (p1->flags & NVG_PT_CORNER) { if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == NVG_BEVEL || lineJoin == NVG_ROUND) { p1->flags |= NVG_PT_BEVEL; } } if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) path->nbevel++; p0 = p1++; } path->convex = (nleft == path->count) ? 1 : 0; } } static int nvg__expandStroke(NVGcontext* ctx, float w, float fringe, int lineCap, int lineJoin, float miterLimit) { NVGpathCache* cache = ctx->cache; NVGvertex* verts; NVGvertex* dst; int cverts, i, j; float aa = fringe;//ctx->fringeWidth; float u0 = 0.0f, u1 = 1.0f; int ncap = nvg__curveDivs(w, NVG_PI, ctx->tessTol); // Calculate divisions per half circle. w += aa * 0.5f; // Disable the gradient used for antialiasing when antialiasing is not used. if (aa == 0.0f) { u0 = 0.5f; u1 = 0.5f; } nvg__calculateJoins(ctx, w, lineJoin, miterLimit); // Calculate max vertex usage. cverts = 0; for (i = 0; i < cache->npaths; i++) { NVGpath* path = &cache->paths[i]; int loop = (path->closed == 0) ? 0 : 1; if (lineJoin == NVG_ROUND) cverts += (path->count + path->nbevel*(ncap+2) + 1) * 2; // plus one for loop else cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop if (loop == 0) { // space for caps if (lineCap == NVG_ROUND) { cverts += (ncap*2 + 2)*2; } else { cverts += (3+3)*2; } } } verts = nvg__allocTempVerts(ctx, cverts); if (verts == NULL) return 0; for (i = 0; i < cache->npaths; i++) { NVGpath* path = &cache->paths[i]; NVGpoint* pts = &cache->points[path->first]; NVGpoint* p0; NVGpoint* p1; int s, e, loop; float dx, dy; path->fill = 0; path->nfill = 0; // Calculate fringe or stroke loop = (path->closed == 0) ? 0 : 1; dst = verts; path->stroke = dst; if (loop) { // Looping p0 = &pts[path->count-1]; p1 = &pts[0]; s = 0; e = path->count; } else { // Add cap p0 = &pts[0]; p1 = &pts[1]; s = 1; e = path->count-1; } if (loop == 0) { // Add cap dx = p1->x - p0->x; dy = p1->y - p0->y; nvg__normalize(&dx, &dy); if (lineCap == NVG_BUTT) dst = nvg__buttCapStart(dst, p0, dx, dy, w, -aa*0.5f, aa, u0, u1); else if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE) dst = nvg__buttCapStart(dst, p0, dx, dy, w, w-aa, aa, u0, u1); else if (lineCap == NVG_ROUND) dst = nvg__roundCapStart(dst, p0, dx, dy, w, ncap, aa, u0, u1); } for (j = s; j < e; ++j) { if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) { if (lineJoin == NVG_ROUND) { dst = nvg__roundJoin(dst, p0, p1, w, w, u0, u1, ncap, aa); } else { dst = nvg__bevelJoin(dst, p0, p1, w, w, u0, u1, aa); } } else { nvg__vset(dst, p1->x + (p1->dmx * w), p1->y + (p1->dmy * w), u0,1); dst++; nvg__vset(dst, p1->x - (p1->dmx * w), p1->y - (p1->dmy * w), u1,1); dst++; } p0 = p1++; } if (loop) { // Loop it nvg__vset(dst, verts[0].x, verts[0].y, u0,1); dst++; nvg__vset(dst, verts[1].x, verts[1].y, u1,1); dst++; } else { // Add cap dx = p1->x - p0->x; dy = p1->y - p0->y; nvg__normalize(&dx, &dy); if (lineCap == NVG_BUTT) dst = nvg__buttCapEnd(dst, p1, dx, dy, w, -aa*0.5f, aa, u0, u1); else if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE) dst = nvg__buttCapEnd(dst, p1, dx, dy, w, w-aa, aa, u0, u1); else if (lineCap == NVG_ROUND) dst = nvg__roundCapEnd(dst, p1, dx, dy, w, ncap, aa, u0, u1); } path->nstroke = (int)(dst - verts); verts = dst; } return 1; } static int nvg__expandFill(NVGcontext* ctx, float w, int lineJoin, float miterLimit) { NVGpathCache* cache = ctx->cache; NVGvertex* verts; NVGvertex* dst; int cverts, convex, i, j; float aa = ctx->fringeWidth; int fringe = w > 0.0f; nvg__calculateJoins(ctx, w, lineJoin, miterLimit); // Calculate max vertex usage. cverts = 0; for (i = 0; i < cache->npaths; i++) { NVGpath* path = &cache->paths[i]; cverts += path->count + path->nbevel + 1; if (fringe) cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop } verts = nvg__allocTempVerts(ctx, cverts); if (verts == NULL) return 0; convex = cache->npaths == 1 && cache->paths[0].convex; for (i = 0; i < cache->npaths; i++) { NVGpath* path = &cache->paths[i]; NVGpoint* pts = &cache->points[path->first]; NVGpoint* p0; NVGpoint* p1; float rw, lw, woff; float ru, lu; // Calculate shape vertices. woff = 0.5f*aa; dst = verts; path->fill = dst; if (fringe) { // Looping p0 = &pts[path->count-1]; p1 = &pts[0]; for (j = 0; j < path->count; ++j) { if (p1->flags & NVG_PT_BEVEL) { float dlx0 = p0->dy; float dly0 = -p0->dx; float dlx1 = p1->dy; float dly1 = -p1->dx; if (p1->flags & NVG_PT_LEFT) { float lx = p1->x + p1->dmx * woff; float ly = p1->y + p1->dmy * woff; nvg__vset(dst, lx, ly, 0.5f,1); dst++; } else { float lx0 = p1->x + dlx0 * woff; float ly0 = p1->y + dly0 * woff; float lx1 = p1->x + dlx1 * woff; float ly1 = p1->y + dly1 * woff; nvg__vset(dst, lx0, ly0, 0.5f,1); dst++; nvg__vset(dst, lx1, ly1, 0.5f,1); dst++; } } else { nvg__vset(dst, p1->x + (p1->dmx * woff), p1->y + (p1->dmy * woff), 0.5f,1); dst++; } p0 = p1++; } } else { for (j = 0; j < path->count; ++j) { nvg__vset(dst, pts[j].x, pts[j].y, 0.5f,1); dst++; } } path->nfill = (int)(dst - verts); verts = dst; // Calculate fringe if (fringe) { lw = w + woff; rw = w - woff; lu = 0; ru = 1; dst = verts; path->stroke = dst; // Create only half a fringe for convex shapes so that // the shape can be rendered without stenciling. if (convex) { lw = woff; // This should generate the same vertex as fill inset above. lu = 0.5f; // Set outline fade at middle. } // Looping p0 = &pts[path->count-1]; p1 = &pts[0]; for (j = 0; j < path->count; ++j) { if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) { dst = nvg__bevelJoin(dst, p0, p1, lw, rw, lu, ru, ctx->fringeWidth); } else { nvg__vset(dst, p1->x + (p1->dmx * lw), p1->y + (p1->dmy * lw), lu,1); dst++; nvg__vset(dst, p1->x - (p1->dmx * rw), p1->y - (p1->dmy * rw), ru,1); dst++; } p0 = p1++; } // Loop it nvg__vset(dst, verts[0].x, verts[0].y, lu,1); dst++; nvg__vset(dst, verts[1].x, verts[1].y, ru,1); dst++; path->nstroke = (int)(dst - verts); verts = dst; } else { path->stroke = NULL; path->nstroke = 0; } } return 1; } #else static int nvg__expandStroke(NVGcontext* ctx, float w, float fringe, int lineCap, int lineJoin, float miterLimit) { NVGpathCache* cache = ctx->cache; NVGvertex* verts; NVGvertex* dst; int cverts, i, j; float aa = fringe;//ctx->fringeWidth; float u0 = 0.0f, u1 = 1.0f; int ncap = nvg__curveDivs(w, NVG_PI, ctx->tessTol); // Calculate divisions per half circle. w += aa * 0.5f; // Disable the gradient used for antialiasing when antialiasing is not used. if (aa == 0.0f) { u0 = 0.5f; u1 = 0.5f; } // Calculate max vertex usage. cverts = 0; for (i = 0; i < cache->npaths; i++) { NVGpath* path = &cache->paths[i]; int loop = (path->closed == 0) ? 0 : 1; cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop if (loop == 0) { // space for caps if (lineCap == NVG_ROUND) { cverts += (ncap*2 + 2)*2; } else { cverts += (3+3)*2; } } } verts = nvg__allocTempVerts(ctx, cverts); if (verts == NULL) return 0; for (i = 0; i < cache->npaths; i++) { NVGpath* path = &cache->paths[i]; NVGpoint* pts = &cache->points[path->first]; NVGpoint* p0; NVGpoint* p1; int s, e, loop; float dx, dy; path->fill = 0; path->nfill = 0; // Calculate fringe or stroke loop = (path->closed == 0) ? 0 : 1; dst = verts; path->stroke = dst; if (loop) { // Looping p0 = &pts[path->count-1]; p1 = &pts[0]; s = 0; e = path->count; } else { // Add cap p0 = &pts[0]; p1 = &pts[1]; s = 1; e = path->count-1; } if (loop == 0) { // Add cap nvg__vset(dst, p0->x, p0->y, u0,1); dst++; } for (j = s; j < e; ++j) { nvg__vset(dst, p1->x + (p1->dmx * w), p1->y + (p1->dmy * w), u0,1); dst++; nvg__vset(dst, p1->x - (p1->dmx * w), p1->y - (p1->dmy * w), u1,1); dst++; p0 = p1++; } if (loop) { // Loop it nvg__vset(dst, verts[0].x, verts[0].y, u0,1); dst++; nvg__vset(dst, verts[1].x, verts[1].y, u1,1); dst++; } else { // Add cap nvg__vset(dst, p1->x, p1->y, u0,1); dst++; } path->nstroke = (int)(dst - verts); verts = dst; } return 1; } static int nvg__expandFill(NVGcontext* ctx, float w, int lineJoin, float miterLimit) { NVGpathCache* cache = ctx->cache; NVGvertex* verts; NVGvertex* dst; int cverts, convex, i, j; float aa = ctx->fringeWidth; int fringe = w > 0.0f; // Calculate max vertex usage. cverts = 0; for (i = 0; i < cache->npaths; i++) { NVGpath* path = &cache->paths[i]; cverts += path->count + path->nbevel + 1; if (fringe) cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop } verts = nvg__allocTempVerts(ctx, cverts); if (verts == NULL) return 0; convex = cache->npaths == 1 && cache->paths[0].convex; for (i = 0; i < cache->npaths; i++) { NVGpath* path = &cache->paths[i]; NVGpoint* pts = &cache->points[path->first]; NVGpoint* p0; NVGpoint* p1; float rw, lw, woff; float ru, lu; // Calculate shape vertices. woff = 0.5f*aa; dst = verts; path->fill = dst; if (fringe) { // Looping p0 = &pts[path->count-1]; p1 = &pts[0]; for (j = 0; j < path->count; ++j) { nvg__vset(dst, p1->x + (p1->dmx * woff), p1->y + (p1->dmy * woff), 0.5f,1); dst++; p0 = p1++; } } else { for (j = 0; j < path->count; ++j) { nvg__vset(dst, pts[j].x, pts[j].y, 0.5f,1); dst++; } } path->nfill = (int)(dst - verts); verts = dst; // Calculate fringe if (fringe) { lw = w + woff; rw = w - woff; lu = 0; ru = 1; dst = verts; path->stroke = dst; // Create only half a fringe for convex shapes so that // the shape can be rendered without stenciling. if (convex) { lw = woff; // This should generate the same vertex as fill inset above. lu = 0.5f; // Set outline fade at middle. } // Looping p0 = &pts[path->count-1]; p1 = &pts[0]; for (j = 0; j < path->count; ++j) { nvg__vset(dst, p1->x + (p1->dmx * lw), p1->y + (p1->dmy * lw), lu,1); dst++; nvg__vset(dst, p1->x - (p1->dmx * rw), p1->y - (p1->dmy * rw), ru,1); dst++; p0 = p1++; } // Loop it nvg__vset(dst, verts[0].x, verts[0].y, lu,1); dst++; nvg__vset(dst, verts[1].x, verts[1].y, ru,1); dst++; path->nstroke = (int)(dst - verts); verts = dst; } else { path->stroke = NULL; path->nstroke = 0; } } return 1; } #endif/*WITH_NANOVG_GPU*/ // Draw void nvgBeginPath(NVGcontext* ctx) { ctx->ncommands = 0; nvg__clearPathCache(ctx); } void nvgMoveTo(NVGcontext* ctx, float x, float y) { float vals[] = { NVG_MOVETO, x, y }; nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); } void nvgLineTo(NVGcontext* ctx, float x, float y) { float vals[] = { NVG_LINETO, x, y }; nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); } void nvgBezierTo(NVGcontext* ctx, float c1x, float c1y, float c2x, float c2y, float x, float y) { float vals[] = { NVG_BEZIERTO, c1x, c1y, c2x, c2y, x, y }; nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); } void nvgQuadTo(NVGcontext* ctx, float cx, float cy, float x, float y) { float x0 = ctx->commandx; float y0 = ctx->commandy; float vals[] = { NVG_BEZIERTO, x0 + 2.0f/3.0f*(cx - x0), y0 + 2.0f/3.0f*(cy - y0), x + 2.0f/3.0f*(cx - x), y + 2.0f/3.0f*(cy - y), x, y }; nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); } void nvgArcTo(NVGcontext* ctx, float x1, float y1, float x2, float y2, float radius) { float x0 = ctx->commandx; float y0 = ctx->commandy; float dx0,dy0, dx1,dy1, a, d, cx,cy, a0,a1; int dir; if (ctx->ncommands == 0) { return; } // Handle degenerate cases. if (nvg__ptEquals(x0,y0, x1,y1, ctx->distTol) || nvg__ptEquals(x1,y1, x2,y2, ctx->distTol) || nvg__distPtSeg(x1,y1, x0,y0, x2,y2) < ctx->distTol*ctx->distTol || radius < ctx->distTol) { nvgLineTo(ctx, x1,y1); return; } // Calculate tangential circle to lines (x0,y0)-(x1,y1) and (x1,y1)-(x2,y2). dx0 = x0-x1; dy0 = y0-y1; dx1 = x2-x1; dy1 = y2-y1; nvg__normalize(&dx0,&dy0); nvg__normalize(&dx1,&dy1); a = nvg__acosf(dx0*dx1 + dy0*dy1); d = radius / nvg__tanf(a/2.0f); // printf("a=%f° d=%f\n", a/NVG_PI*180.0f, d); if (d > 10000.0f) { nvgLineTo(ctx, x1,y1); return; } if (nvg__cross(dx0,dy0, dx1,dy1) > 0.0f) { cx = x1 + dx0*d + dy0*radius; cy = y1 + dy0*d + -dx0*radius; a0 = nvg__atan2f(dx0, -dy0); a1 = nvg__atan2f(-dx1, dy1); dir = NVG_CW; // printf("CW c=(%f, %f) a0=%f° a1=%f°\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f); } else { cx = x1 + dx0*d + -dy0*radius; cy = y1 + dy0*d + dx0*radius; a0 = nvg__atan2f(-dx0, dy0); a1 = nvg__atan2f(dx1, -dy1); dir = NVG_CCW; // printf("CCW c=(%f, %f) a0=%f° a1=%f°\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f); } nvgArc(ctx, cx, cy, radius, a0, a1, dir); } void nvgClosePath(NVGcontext* ctx) { float vals[] = { NVG_CLOSE }; nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); } void nvgPathWinding(NVGcontext* ctx, int dir) { float vals[] = { NVG_WINDING, (float)dir }; nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); } void nvgArc(NVGcontext* ctx, float cx, float cy, float r, float a0, float a1, int dir) { float ads_da = 0; float a = 0, da = 0, hda = 0, kappa = 0; float dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0; float px = 0, py = 0, ptanx = 0, ptany = 0; float vals[3 + 5*7 + 100]; int i, ndivs, nvals; int move = ctx->ncommands > 0 ? NVG_LINETO : NVG_MOVETO; // Clamp angles da = a1 - a0; ads_da = nvg__absf(da); if (dir == NVG_CW) { if (ads_da > NVG_PI*2 || nvg__fequalf(ads_da, NVG_PI*2)) { da = NVG_PI*2; } else { while (da < 0.0f) da += NVG_PI*2; } } else { if (ads_da > NVG_PI*2 || nvg__fequalf(ads_da, NVG_PI*2)) { da = -NVG_PI*2; } else { while (da > 0.0f) da -= NVG_PI*2; } } // Split arc into max 90 degree segments. ndivs = nvg__maxi(1, nvg__mini((int)(nvg__absf(da) / (NVG_PI*0.5f) + 0.5f), 5)); hda = (da / (float)ndivs) / 2.0f; kappa = nvg__absf(4.0f / 3.0f * (1.0f - nvg__cosf(hda)) / nvg__sinf(hda)); if (dir == NVG_CCW) kappa = -kappa; nvals = 0; for (i = 0; i <= ndivs; i++) { a = a0 + da * (i/(float)ndivs); dx = nvg__cosf(a); dy = nvg__sinf(a); x = cx + dx*r; y = cy + dy*r; tanx = -dy*r*kappa; tany = dx*r*kappa; if (i == 0) { vals[nvals++] = (float)move; vals[nvals++] = x; vals[nvals++] = y; } else { vals[nvals++] = NVG_BEZIERTO; vals[nvals++] = px+ptanx; vals[nvals++] = py+ptany; vals[nvals++] = x-tanx; vals[nvals++] = y-tany; vals[nvals++] = x; vals[nvals++] = y; } px = x; py = y; ptanx = tanx; ptany = tany; } nvg__appendCommands(ctx, vals, nvals); } void nvgRect(NVGcontext* ctx, float x, float y, float w, float h) { float vals[] = { NVG_MOVETO, x,y, NVG_LINETO, x,y+h, NVG_LINETO, x+w,y+h, NVG_LINETO, x+w,y, NVG_CLOSE }; nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); } void nvgRoundedRect(NVGcontext* ctx, float x, float y, float w, float h, float r) { nvgRoundedRectVarying(ctx, x, y, w, h, r, r, r, r); } void nvgRoundedRectVarying(NVGcontext* ctx, float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft) { if(radTopLeft < 0.1f && radTopRight < 0.1f && radBottomRight < 0.1f && radBottomLeft < 0.1f) { nvgRect(ctx, x, y, w, h); return; } else { float halfw = nvg__absf(w)*0.5f; float halfh = nvg__absf(h)*0.5f; float rxBL = nvg__minf(radBottomLeft, halfw) * nvg__signf(w), ryBL = nvg__minf(radBottomLeft, halfh) * nvg__signf(h); float rxBR = nvg__minf(radBottomRight, halfw) * nvg__signf(w), ryBR = nvg__minf(radBottomRight, halfh) * nvg__signf(h); float rxTR = nvg__minf(radTopRight, halfw) * nvg__signf(w), ryTR = nvg__minf(radTopRight, halfh) * nvg__signf(h); float rxTL = nvg__minf(radTopLeft, halfw) * nvg__signf(w), ryTL = nvg__minf(radTopLeft, halfh) * nvg__signf(h); float vals[] = { NVG_MOVETO, x, y + ryTL, NVG_LINETO, x, y + h - ryBL, NVG_BEZIERTO, x, y + h - ryBL*(1 - NVG_KAPPA90), x + rxBL*(1 - NVG_KAPPA90), y + h, x + rxBL, y + h, NVG_LINETO, x + w - rxBR, y + h, NVG_BEZIERTO, x + w - rxBR*(1 - NVG_KAPPA90), y + h, x + w, y + h - ryBR*(1 - NVG_KAPPA90), x + w, y + h - ryBR, NVG_LINETO, x + w, y + ryTR, NVG_BEZIERTO, x + w, y + ryTR*(1 - NVG_KAPPA90), x + w - rxTR*(1 - NVG_KAPPA90), y, x + w - rxTR, y, NVG_LINETO, x + rxTL, y, NVG_BEZIERTO, x + rxTL*(1 - NVG_KAPPA90), y, x, y + ryTL*(1 - NVG_KAPPA90), x, y + ryTL, NVG_CLOSE }; nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); } } void nvgEllipse(NVGcontext* ctx, float cx, float cy, float rx, float ry) { float vals[] = { NVG_MOVETO, cx-rx, cy, NVG_BEZIERTO, cx-rx, cy+ry*NVG_KAPPA90, cx-rx*NVG_KAPPA90, cy+ry, cx, cy+ry, NVG_BEZIERTO, cx+rx*NVG_KAPPA90, cy+ry, cx+rx, cy+ry*NVG_KAPPA90, cx+rx, cy, NVG_BEZIERTO, cx+rx, cy-ry*NVG_KAPPA90, cx+rx*NVG_KAPPA90, cy-ry, cx, cy-ry, NVG_BEZIERTO, cx-rx*NVG_KAPPA90, cy-ry, cx-rx, cy-ry*NVG_KAPPA90, cx-rx, cy, NVG_CLOSE }; nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); } void nvgCircle(NVGcontext* ctx, float cx, float cy, float r) { nvgEllipse(ctx, cx,cy, r,r); } int nvgClearCache(NVGcontext* ctx) { if(ctx->params.clearCache != NULL) { ctx->params.clearCache(ctx->params.userPtr); } return 0; } #ifdef WITH_NANOVG_GPU void nvgDebugDumpPathCache(NVGcontext* ctx) { const NVGpath* path; int i, j; printf("Dumping %d cached paths\n", ctx->cache->npaths); for (i = 0; i < ctx->cache->npaths; i++) { path = &ctx->cache->paths[i]; printf(" - Path %d\n", i); if (path->nfill) { printf(" - fill: %d\n", path->nfill); for (j = 0; j < path->nfill; j++) printf("%f\t%f\n", path->fill[j].x, path->fill[j].y); } if (path->nstroke) { printf(" - stroke: %d\n", path->nstroke); for (j = 0; j < path->nstroke; j++) printf("%f\t%f\n", path->stroke[j].x, path->stroke[j].y); } } } #endif/*WITH_NANOVG_GPU*/ void nvgFill(NVGcontext* ctx) { NVGstate* state = nvg__getState(ctx); const NVGpath* path; NVGpaint fillPaint = state->fill; int i; nvg__flattenPaths(ctx); if (ctx->params.edgeAntiAlias && state->shapeAntiAlias) nvg__expandFill(ctx, ctx->fringeWidth, NVG_MITER, 2.4f); else nvg__expandFill(ctx, 0.0f, NVG_MITER, 2.4f); // Apply global alpha fillPaint.innerColor.a *= state->alpha; fillPaint.outerColor.a *= state->alpha; /* 把 nanovg 的坐标系传入到适量画布算法中 */ if(ctx->params.setStateXfrom != NULL) { ctx->params.setStateXfrom(ctx->params.userPtr, state->xform); } ctx->params.renderFill(ctx->params.userPtr, &fillPaint, state->compositeOperation, &state->scissor, ctx->fringeWidth, ctx->cache->bounds, ctx->cache->paths, ctx->cache->npaths); // Count triangles for (i = 0; i < ctx->cache->npaths; i++) { path = &ctx->cache->paths[i]; ctx->fillTriCount += path->nfill-2; ctx->fillTriCount += path->nstroke-2; ctx->drawCallCount += 2; } } void nvgStroke(NVGcontext* ctx) { NVGstate* state = nvg__getState(ctx); float scale = nvg__getAverageScale(state->xform); float strokeWidth = nvg__clampf(state->strokeWidth * scale, 0.0f, 200.0f); NVGpaint strokePaint = state->stroke; const NVGpath* path; int i; if (strokeWidth < ctx->fringeWidth) { // If the stroke width is less than pixel size, use alpha to emulate coverage. // Since coverage is area, scale by alpha*alpha. float alpha = nvg__clampf(strokeWidth / ctx->fringeWidth, 0.0f, 1.0f); strokePaint.innerColor.a *= alpha*alpha; strokePaint.outerColor.a *= alpha*alpha; strokeWidth = ctx->fringeWidth; } // Apply global alpha strokePaint.innerColor.a *= state->alpha; strokePaint.outerColor.a *= state->alpha; nvg__flattenPaths(ctx); if (ctx->params.edgeAntiAlias && state->shapeAntiAlias) nvg__expandStroke(ctx, strokeWidth*0.5f, ctx->fringeWidth, state->lineCap, state->lineJoin, state->miterLimit); else nvg__expandStroke(ctx, strokeWidth*0.5f, 0.0f, state->lineCap, state->lineJoin, state->miterLimit); /* 把 nanovg 的坐标系传入到适量画布算法中 */ if(ctx->params.setStateXfrom != NULL) { ctx->params.setStateXfrom(ctx->params.userPtr, state->xform); } ctx->params.renderStroke(ctx->params.userPtr, &strokePaint, state->compositeOperation, &state->scissor, ctx->fringeWidth, strokeWidth, ctx->cache->paths, ctx->cache->npaths); // Count triangles for (i = 0; i < ctx->cache->npaths; i++) { path = &ctx->cache->paths[i]; ctx->strokeTriCount += path->nstroke-2; ctx->drawCallCount++; } } #ifdef WITH_NANOVG_GPU // Add fonts int nvgCreateFont(NVGcontext* ctx, const char* name, const char* path) { return fonsAddFont(ctx->fs, name, path); } int nvgCreateFontMem(NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData) { return fonsAddFontMem(ctx->fs, name, data, ndata, freeData); } int nvgFindFont(NVGcontext* ctx, const char* name) { if (name == NULL) return -1; return fonsGetFontByName(ctx->fs, name); } int nvgAddFallbackFontId(NVGcontext* ctx, int baseFont, int fallbackFont) { if(baseFont == -1 || fallbackFont == -1) return 0; return fonsAddFallbackFont(ctx->fs, baseFont, fallbackFont); } int nvgAddFallbackFont(NVGcontext* ctx, const char* baseFont, const char* fallbackFont) { return nvgAddFallbackFontId(ctx, nvgFindFont(ctx, baseFont), nvgFindFont(ctx, fallbackFont)); } // State setting void nvgFontSize(NVGcontext* ctx, float size) { NVGstate* state = nvg__getState(ctx); state->fontSize = size; } void nvgFontBlur(NVGcontext* ctx, float blur) { NVGstate* state = nvg__getState(ctx); state->fontBlur = blur; } void nvgTextLetterSpacing(NVGcontext* ctx, float spacing) { NVGstate* state = nvg__getState(ctx); state->letterSpacing = spacing; } void nvgTextLineHeight(NVGcontext* ctx, float lineHeight) { NVGstate* state = nvg__getState(ctx); state->lineHeight = lineHeight; } void nvgTextAlign(NVGcontext* ctx, int align) { NVGstate* state = nvg__getState(ctx); state->textAlign = align; } void nvgFontFaceId(NVGcontext* ctx, int font) { NVGstate* state = nvg__getState(ctx); state->fontId = font; } void nvgFontFace(NVGcontext* ctx, const char* font) { NVGstate* state = nvg__getState(ctx); state->fontId = fonsGetFontByName(ctx->fs, font); } static float nvg__quantize(float a, float d) { return ((int)(a / d + 0.5f)) * d; } static float nvg__getFontScale(NVGstate* state) { return nvg__minf(nvg__quantize(nvg__getAverageScale(state->xform), 0.01f), 4.0f); } static void nvg__flushTextTexture(NVGcontext* ctx) { int dirty[4]; if (fonsValidateTexture(ctx->fs, dirty)) { int fontImage = ctx->fontImages[ctx->fontImageIdx]; // Update texture if (fontImage != 0) { int iw, ih; const unsigned char* data = fonsGetTextureData(ctx->fs, &iw, &ih); int x = dirty[0]; int y = dirty[1]; int w = dirty[2] - dirty[0]; int h = dirty[3] - dirty[1]; ctx->params.renderUpdateTexture(ctx->params.userPtr, fontImage, x,y, w,h, data); } } } static int nvg__allocTextAtlas(NVGcontext* ctx) { int iw, ih; nvg__flushTextTexture(ctx); if (ctx->fontImageIdx >= NVG_MAX_FONTIMAGES-1) return 0; // if next fontImage already have a texture if (ctx->fontImages[ctx->fontImageIdx+1] != 0) nvgImageSize(ctx, ctx->fontImages[ctx->fontImageIdx+1], &iw, &ih); else { // calculate the new font image size and create it. nvgImageSize(ctx, ctx->fontImages[ctx->fontImageIdx], &iw, &ih); if (iw > ih) ih *= 2; else iw *= 2; if (iw > NVG_MAX_FONTIMAGE_SIZE || ih > NVG_MAX_FONTIMAGE_SIZE) iw = ih = NVG_MAX_FONTIMAGE_SIZE; ctx->fontImages[ctx->fontImageIdx+1] = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, iw, ih, 0, 0, NVG_ORIENTATION_0, NULL); } ++ctx->fontImageIdx; fonsResetAtlas(ctx->fs, iw, ih); return 1; } static void nvg__renderText(NVGcontext* ctx, NVGvertex* verts, int nverts) { NVGstate* state = nvg__getState(ctx); NVGpaint paint = state->fill; // Render triangles. paint.image = ctx->fontImages[ctx->fontImageIdx]; // Apply global alpha paint.innerColor.a *= state->alpha; paint.outerColor.a *= state->alpha; ctx->params.renderTriangles(ctx->params.userPtr, &paint, state->compositeOperation, &state->scissor, verts, nverts); ctx->drawCallCount++; ctx->textTriCount += nverts/3; } float nvgText(NVGcontext* ctx, float x, float y, const char* string, const char* end) { NVGstate* state = nvg__getState(ctx); FONStextIter iter, prevIter; FONSquad q; NVGvertex* verts; float scale = nvg__getFontScale(state) * ctx->devicePxRatio; float invscale = 1.0f / scale; int cverts = 0; int nverts = 0; if (end == NULL) end = string + strlen(string); if (state->fontId == FONS_INVALID) return x; fonsSetSize(ctx->fs, state->fontSize*scale); fonsSetSpacing(ctx->fs, state->letterSpacing*scale); fonsSetBlur(ctx->fs, state->fontBlur*scale); fonsSetAlign(ctx->fs, state->textAlign); fonsSetFont(ctx->fs, state->fontId); cverts = nvg__maxi(2, (int)(end - string)) * 6; // conservative estimate. verts = nvg__allocTempVerts(ctx, cverts); if (verts == NULL) return x; fonsTextIterInit(ctx->fs, &iter, x*scale, y*scale, string, end, FONS_GLYPH_BITMAP_REQUIRED); prevIter = iter; while (fonsTextIterNext(ctx->fs, &iter, &q)) { float c[4*2]; if (iter.prevGlyphIndex == -1) { // can not retrieve glyph? if (nverts != 0) { nvg__renderText(ctx, verts, nverts); nverts = 0; } if (!nvg__allocTextAtlas(ctx)) break; // no memory :( iter = prevIter; fonsTextIterNext(ctx->fs, &iter, &q); // try again if (iter.prevGlyphIndex == -1) // still can not find glyph? break; } prevIter = iter; // Transform corners. nvgTransformPoint(&c[0],&c[1], state->xform, q.x0*invscale, q.y0*invscale); nvgTransformPoint(&c[2],&c[3], state->xform, q.x1*invscale, q.y0*invscale); nvgTransformPoint(&c[4],&c[5], state->xform, q.x1*invscale, q.y1*invscale); nvgTransformPoint(&c[6],&c[7], state->xform, q.x0*invscale, q.y1*invscale); // Create triangles if (nverts+6 <= cverts) { nvg__vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++; nvg__vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++; nvg__vset(&verts[nverts], c[2], c[3], q.s1, q.t0); nverts++; nvg__vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++; nvg__vset(&verts[nverts], c[6], c[7], q.s0, q.t1); nverts++; nvg__vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++; } } // TODO: add back-end bit to do this just once per frame. nvg__flushTextTexture(ctx); nvg__renderText(ctx, verts, nverts); return iter.nextx / scale; } void nvgTextBox(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end) { NVGstate* state = nvg__getState(ctx); NVGtextRow rows[2]; int nrows = 0, i; int oldAlign = state->textAlign; int haling = state->textAlign & (NVG_ALIGN_LEFT | NVG_ALIGN_CENTER | NVG_ALIGN_RIGHT); int valign = state->textAlign & (NVG_ALIGN_TOP | NVG_ALIGN_MIDDLE | NVG_ALIGN_BOTTOM | NVG_ALIGN_BASELINE); float lineh = 0; if (state->fontId == FONS_INVALID) return; nvgTextMetrics(ctx, NULL, NULL, &lineh); state->textAlign = NVG_ALIGN_LEFT | valign; while ((nrows = nvgTextBreakLines(ctx, string, end, breakRowWidth, rows, 2))) { for (i = 0; i < nrows; i++) { NVGtextRow* row = &rows[i]; if (haling & NVG_ALIGN_LEFT) nvgText(ctx, x, y, row->start, row->end); else if (haling & NVG_ALIGN_CENTER) nvgText(ctx, x + breakRowWidth*0.5f - row->width*0.5f, y, row->start, row->end); else if (haling & NVG_ALIGN_RIGHT) nvgText(ctx, x + breakRowWidth - row->width, y, row->start, row->end); y += lineh * state->lineHeight; } string = rows[nrows-1].next; } state->textAlign = oldAlign; } int nvgTextGlyphPositions(NVGcontext* ctx, float x, float y, const char* string, const char* end, NVGglyphPosition* positions, int maxPositions) { NVGstate* state = nvg__getState(ctx); float scale = nvg__getFontScale(state) * ctx->devicePxRatio; float invscale = 1.0f / scale; FONStextIter iter, prevIter; FONSquad q; int npos = 0; if (state->fontId == FONS_INVALID) return 0; if (end == NULL) end = string + strlen(string); if (string == end) return 0; fonsSetSize(ctx->fs, state->fontSize*scale); fonsSetSpacing(ctx->fs, state->letterSpacing*scale); fonsSetBlur(ctx->fs, state->fontBlur*scale); fonsSetAlign(ctx->fs, state->textAlign); fonsSetFont(ctx->fs, state->fontId); fonsTextIterInit(ctx->fs, &iter, x*scale, y*scale, string, end, FONS_GLYPH_BITMAP_OPTIONAL); prevIter = iter; while (fonsTextIterNext(ctx->fs, &iter, &q)) { if (iter.prevGlyphIndex < 0 && nvg__allocTextAtlas(ctx)) { // can not retrieve glyph? iter = prevIter; fonsTextIterNext(ctx->fs, &iter, &q); // try again } prevIter = iter; positions[npos].str = iter.str; positions[npos].x = iter.x * invscale; positions[npos].minx = nvg__minf(iter.x, q.x0) * invscale; positions[npos].maxx = nvg__maxf(iter.nextx, q.x1) * invscale; npos++; if (npos >= maxPositions) break; } return npos; } enum NVGcodepointType { NVG_SPACE, NVG_NEWLINE, NVG_CHAR, NVG_CJK_CHAR, }; int nvgTextBreakLines(NVGcontext* ctx, const char* string, const char* end, float breakRowWidth, NVGtextRow* rows, int maxRows) { NVGstate* state = nvg__getState(ctx); float scale = nvg__getFontScale(state) * ctx->devicePxRatio; float invscale = 1.0f / scale; FONStextIter iter, prevIter; FONSquad q; int nrows = 0; float rowStartX = 0; float rowWidth = 0; float rowMinX = 0; float rowMaxX = 0; const char* rowStart = NULL; const char* rowEnd = NULL; const char* wordStart = NULL; float wordStartX = 0; float wordMinX = 0; const char* breakEnd = NULL; float breakWidth = 0; float breakMaxX = 0; int type = NVG_SPACE, ptype = NVG_SPACE; unsigned int pcodepoint = 0; if (maxRows == 0) return 0; if (state->fontId == FONS_INVALID) return 0; if (end == NULL) end = string + strlen(string); if (string == end) return 0; fonsSetSize(ctx->fs, state->fontSize*scale); fonsSetSpacing(ctx->fs, state->letterSpacing*scale); fonsSetBlur(ctx->fs, state->fontBlur*scale); fonsSetAlign(ctx->fs, state->textAlign); fonsSetFont(ctx->fs, state->fontId); breakRowWidth *= scale; fonsTextIterInit(ctx->fs, &iter, 0, 0, string, end, FONS_GLYPH_BITMAP_OPTIONAL); prevIter = iter; while (fonsTextIterNext(ctx->fs, &iter, &q)) { if (iter.prevGlyphIndex < 0 && nvg__allocTextAtlas(ctx)) { // can not retrieve glyph? iter = prevIter; fonsTextIterNext(ctx->fs, &iter, &q); // try again } prevIter = iter; switch (iter.codepoint) { case 9: // \t case 11: // \v case 12: // \f case 32: // space case 0x00a0: // NBSP type = NVG_SPACE; break; case 10: // \n type = pcodepoint == 13 ? NVG_SPACE : NVG_NEWLINE; break; case 13: // \r type = pcodepoint == 10 ? NVG_SPACE : NVG_NEWLINE; break; case 0x0085: // NEL type = NVG_NEWLINE; break; default: if ((iter.codepoint >= 0x4E00 && iter.codepoint <= 0x9FFF) || (iter.codepoint >= 0x3000 && iter.codepoint <= 0x30FF) || (iter.codepoint >= 0xFF00 && iter.codepoint <= 0xFFEF) || (iter.codepoint >= 0x1100 && iter.codepoint <= 0x11FF) || (iter.codepoint >= 0x3130 && iter.codepoint <= 0x318F) || (iter.codepoint >= 0xAC00 && iter.codepoint <= 0xD7AF)) type = NVG_CJK_CHAR; else type = NVG_CHAR; break; } if (type == NVG_NEWLINE) { // Always handle new lines. rows[nrows].start = rowStart != NULL ? rowStart : iter.str; rows[nrows].end = rowEnd != NULL ? rowEnd : iter.str; rows[nrows].width = rowWidth * invscale; rows[nrows].minx = rowMinX * invscale; rows[nrows].maxx = rowMaxX * invscale; rows[nrows].next = iter.next; nrows++; if (nrows >= maxRows) return nrows; // Set null break point breakEnd = rowStart; breakWidth = 0.0; breakMaxX = 0.0; // Indicate to skip the white space at the beginning of the row. rowStart = NULL; rowEnd = NULL; rowWidth = 0; rowMinX = rowMaxX = 0; } else { if (rowStart == NULL) { // Skip white space until the beginning of the line if (type == NVG_CHAR || type == NVG_CJK_CHAR) { // The current char is the row so far rowStartX = iter.x; rowStart = iter.str; rowEnd = iter.next; rowWidth = iter.nextx - rowStartX; // q.x1 - rowStartX; rowMinX = q.x0 - rowStartX; rowMaxX = q.x1 - rowStartX; wordStart = iter.str; wordStartX = iter.x; wordMinX = q.x0 - rowStartX; // Set null break point breakEnd = rowStart; breakWidth = 0.0; breakMaxX = 0.0; } } else { float nextWidth = iter.nextx - rowStartX; // track last non-white space character if (type == NVG_CHAR || type == NVG_CJK_CHAR) { rowEnd = iter.next; rowWidth = iter.nextx - rowStartX; rowMaxX = q.x1 - rowStartX; } // track last end of a word if (((ptype == NVG_CHAR || ptype == NVG_CJK_CHAR) && type == NVG_SPACE) || type == NVG_CJK_CHAR) { breakEnd = iter.str; breakWidth = rowWidth; breakMaxX = rowMaxX; } // track last beginning of a word if ((ptype == NVG_SPACE && (type == NVG_CHAR || type == NVG_CJK_CHAR)) || type == NVG_CJK_CHAR) { wordStart = iter.str; wordStartX = iter.x; wordMinX = q.x0 - rowStartX; } // Break to new line when a character is beyond break width. if ((type == NVG_CHAR || type == NVG_CJK_CHAR) && nextWidth > breakRowWidth) { // The run length is too long, need to break to new line. if (breakEnd == rowStart) { // The current word is longer than the row length, just break it from here. rows[nrows].start = rowStart; rows[nrows].end = iter.str; rows[nrows].width = rowWidth * invscale; rows[nrows].minx = rowMinX * invscale; rows[nrows].maxx = rowMaxX * invscale; rows[nrows].next = iter.str; nrows++; if (nrows >= maxRows) return nrows; rowStartX = iter.x; rowStart = iter.str; rowEnd = iter.next; rowWidth = iter.nextx - rowStartX; rowMinX = q.x0 - rowStartX; rowMaxX = q.x1 - rowStartX; wordStart = iter.str; wordStartX = iter.x; wordMinX = q.x0 - rowStartX; } else { // Break the line from the end of the last word, and start new line from the beginning of the new. rows[nrows].start = rowStart; rows[nrows].end = breakEnd; rows[nrows].width = breakWidth * invscale; rows[nrows].minx = rowMinX * invscale; rows[nrows].maxx = breakMaxX * invscale; rows[nrows].next = wordStart; nrows++; if (nrows >= maxRows) return nrows; rowStartX = wordStartX; rowStart = wordStart; rowEnd = iter.next; rowWidth = iter.nextx - rowStartX; rowMinX = wordMinX; rowMaxX = q.x1 - rowStartX; // No change to the word start } // Set null break point breakEnd = rowStart; breakWidth = 0.0; breakMaxX = 0.0; } } } pcodepoint = iter.codepoint; ptype = type; } // Break the line from the end of the last word, and start new line from the beginning of the new. if (rowStart != NULL) { rows[nrows].start = rowStart; rows[nrows].end = rowEnd; rows[nrows].width = rowWidth * invscale; rows[nrows].minx = rowMinX * invscale; rows[nrows].maxx = rowMaxX * invscale; rows[nrows].next = end; nrows++; } return nrows; } float nvgTextBounds(NVGcontext* ctx, float x, float y, const char* string, const char* end, float* bounds) { NVGstate* state = nvg__getState(ctx); float scale = nvg__getFontScale(state) * ctx->devicePxRatio; float invscale = 1.0f / scale; float width; if (state->fontId == FONS_INVALID) return 0; fonsSetSize(ctx->fs, state->fontSize*scale); fonsSetSpacing(ctx->fs, state->letterSpacing*scale); fonsSetBlur(ctx->fs, state->fontBlur*scale); fonsSetAlign(ctx->fs, state->textAlign); fonsSetFont(ctx->fs, state->fontId); width = fonsTextBounds(ctx->fs, x*scale, y*scale, string, end, bounds); if (bounds != NULL) { // Use line bounds for height. fonsLineBounds(ctx->fs, y*scale, &bounds[1], &bounds[3]); bounds[0] *= invscale; bounds[1] *= invscale; bounds[2] *= invscale; bounds[3] *= invscale; } return width * invscale; } void nvgTextBoxBounds(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds) { NVGstate* state = nvg__getState(ctx); NVGtextRow rows[2]; float scale = nvg__getFontScale(state) * ctx->devicePxRatio; float invscale = 1.0f / scale; int nrows = 0, i; int oldAlign = state->textAlign; int haling = state->textAlign & (NVG_ALIGN_LEFT | NVG_ALIGN_CENTER | NVG_ALIGN_RIGHT); int valign = state->textAlign & (NVG_ALIGN_TOP | NVG_ALIGN_MIDDLE | NVG_ALIGN_BOTTOM | NVG_ALIGN_BASELINE); float lineh = 0, rminy = 0, rmaxy = 0; float minx, miny, maxx, maxy; if (state->fontId == FONS_INVALID) { if (bounds != NULL) bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0f; return; } nvgTextMetrics(ctx, NULL, NULL, &lineh); state->textAlign = NVG_ALIGN_LEFT | valign; minx = maxx = x; miny = maxy = y; fonsSetSize(ctx->fs, state->fontSize*scale); fonsSetSpacing(ctx->fs, state->letterSpacing*scale); fonsSetBlur(ctx->fs, state->fontBlur*scale); fonsSetAlign(ctx->fs, state->textAlign); fonsSetFont(ctx->fs, state->fontId); fonsLineBounds(ctx->fs, 0, &rminy, &rmaxy); rminy *= invscale; rmaxy *= invscale; while ((nrows = nvgTextBreakLines(ctx, string, end, breakRowWidth, rows, 2))) { for (i = 0; i < nrows; i++) { NVGtextRow* row = &rows[i]; float rminx, rmaxx, dx = 0; // Horizontal bounds if (haling & NVG_ALIGN_LEFT) dx = 0; else if (haling & NVG_ALIGN_CENTER) dx = breakRowWidth*0.5f - row->width*0.5f; else if (haling & NVG_ALIGN_RIGHT) dx = breakRowWidth - row->width; rminx = x + row->minx + dx; rmaxx = x + row->maxx + dx; minx = nvg__minf(minx, rminx); maxx = nvg__maxf(maxx, rmaxx); // Vertical bounds. miny = nvg__minf(miny, y + rminy); maxy = nvg__maxf(maxy, y + rmaxy); y += lineh * state->lineHeight; } string = rows[nrows-1].next; } state->textAlign = oldAlign; if (bounds != NULL) { bounds[0] = minx; bounds[1] = miny; bounds[2] = maxx; bounds[3] = maxy; } } void nvgTextMetrics(NVGcontext* ctx, float* ascender, float* descender, float* lineh) { NVGstate* state = nvg__getState(ctx); float scale = nvg__getFontScale(state) * ctx->devicePxRatio; float invscale = 1.0f / scale; if (state->fontId == FONS_INVALID) return; fonsSetSize(ctx->fs, state->fontSize*scale); fonsSetSpacing(ctx->fs, state->letterSpacing*scale); fonsSetBlur(ctx->fs, state->fontBlur*scale); fonsSetAlign(ctx->fs, state->textAlign); fonsSetFont(ctx->fs, state->fontId); fonsVertMetrics(ctx->fs, ascender, descender, lineh); if (ascender != NULL) *ascender *= invscale; if (descender != NULL) *descender *= invscale; if (lineh != NULL) *lineh *= invscale; } #else // State setting void nvgFontSize(NVGcontext* ctx, float size) { NVGstate* state = nvg__getState(ctx); state->fontSize = size; } void nvgFontBlur(NVGcontext* ctx, float blur) { } void nvgTextLetterSpacing(NVGcontext* ctx, float spacing) { } void nvgTextLineHeight(NVGcontext* ctx, float lineHeight) { } void nvgTextAlign(NVGcontext* ctx, int align) { } void nvgFontFaceId(NVGcontext* ctx, int font) { } void nvgFontFace(NVGcontext* ctx, const char* font) { } int nvgCreateFontMem(NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData) { return 0; } int nvgFindFont(NVGcontext* ctx, const char* name) { return 0; } float nvgText(NVGcontext* ctx, float x, float y, const char* string, const char* end) { return 0; } float nvgTextBounds(NVGcontext* ctx, float x, float y, const char* string, const char* end, float* bounds) { return 0; } #endif/*WITH_NANOVG_GPU*/ NVGparams* nvgGetParams(NVGcontext* ctx) { return &(ctx->params); } int nvgCreateImageRaw(NVGcontext* ctx, int w, int h, int format, int stride, int imageFlags, enum NVGorientation orientation, const unsigned char* data) { return ctx->params.renderCreateTexture(ctx->params.userPtr, format, w, h, stride, imageFlags, orientation, data); } int nvgFindTextureRaw(NVGcontext* ctx, const void* data) { if(ctx->params.findTexture != NULL) { return ctx->params.findTexture(ctx->params.userPtr, data); } return -1; } // vim: ft=c nu noet ts=4
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\base\nanovg.h
// // Copyright (c) 2013 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #ifndef NANOVG_H #define NANOVG_H #ifdef __cplusplus extern "C" { #endif #define NVG_PI 3.14159265358979323846264338327f #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4201) // nonstandard extension used : nameless struct/union #endif typedef struct NVGcontext NVGcontext; struct NVGcolor { union { float rgba[4]; struct { float r,g,b,a; }; }; }; typedef struct NVGcolor NVGcolor; struct NVGpaint { float xform[6]; float extent[2]; float radius; float feather; NVGcolor innerColor; NVGcolor outerColor; int image; }; typedef struct NVGpaint NVGpaint; enum NVGwinding { NVG_CCW = 1, // Winding for solid shapes NVG_CW = 2, // Winding for holes }; enum NVGsolidity { NVG_SOLID = 1, // CCW NVG_HOLE = 2, // CW }; enum NVGlineCap { NVG_BUTT, NVG_ROUND, NVG_SQUARE, NVG_BEVEL, NVG_MITER, }; enum NVGalign { // Horizontal align NVG_ALIGN_LEFT = 1<<0, // Default, align text horizontally to left. NVG_ALIGN_CENTER = 1<<1, // Align text horizontally to center. NVG_ALIGN_RIGHT = 1<<2, // Align text horizontally to right. // Vertical align NVG_ALIGN_TOP = 1<<3, // Align text vertically to top. NVG_ALIGN_MIDDLE = 1<<4, // Align text vertically to middle. NVG_ALIGN_BOTTOM = 1<<5, // Align text vertically to bottom. NVG_ALIGN_BASELINE = 1<<6, // Default, align text vertically to baseline. }; enum NVGblendFactor { NVG_ZERO = 1<<0, NVG_ONE = 1<<1, NVG_SRC_COLOR = 1<<2, NVG_ONE_MINUS_SRC_COLOR = 1<<3, NVG_DST_COLOR = 1<<4, NVG_ONE_MINUS_DST_COLOR = 1<<5, NVG_SRC_ALPHA = 1<<6, NVG_ONE_MINUS_SRC_ALPHA = 1<<7, NVG_DST_ALPHA = 1<<8, NVG_ONE_MINUS_DST_ALPHA = 1<<9, NVG_SRC_ALPHA_SATURATE = 1<<10, }; enum NVGcompositeOperation { NVG_SOURCE_OVER, NVG_SOURCE_IN, NVG_SOURCE_OUT, NVG_ATOP, NVG_DESTINATION_OVER, NVG_DESTINATION_IN, NVG_DESTINATION_OUT, NVG_DESTINATION_ATOP, NVG_LIGHTER, NVG_COPY, NVG_XOR, }; struct NVGcompositeOperationState { int srcRGB; int dstRGB; int srcAlpha; int dstAlpha; }; typedef struct NVGcompositeOperationState NVGcompositeOperationState; struct NVGglyphPosition { const char* str; // Position of the glyph in the input string. float x; // The x-coordinate of the logical glyph position. float minx, maxx; // The bounds of the glyph shape. }; typedef struct NVGglyphPosition NVGglyphPosition; struct NVGtextRow { const char* start; // Pointer to the input text where the row starts. const char* end; // Pointer to the input text where the row ends (one past the last character). const char* next; // Pointer to the beginning of the next row. float width; // Logical width of the row. float minx, maxx; // Actual bounds of the row. Logical with and bounds can differ because of kerning and some parts over extending. }; typedef struct NVGtextRow NVGtextRow; enum NVGimageFlags { NVG_IMAGE_GENERATE_MIPMAPS = 1<<0, // Generate mipmaps during creation of the image. NVG_IMAGE_REPEATX = 1<<1, // Repeat image in X direction. NVG_IMAGE_REPEATY = 1<<2, // Repeat image in Y direction. NVG_IMAGE_FLIPY = 1<<3, // Flips (inverses) image in Y direction when rendered. NVG_IMAGE_PREMULTIPLIED = 1<<4, // Image data has premultiplied alpha. NVG_IMAGE_NEAREST = 1<<5, // Image interpolation is Nearest instead Linear }; enum NVGorientation { NVG_ORIENTATION_0 = 0, NVG_ORIENTATION_90 = 90, NVG_ORIENTATION_180 = 180, NVG_ORIENTATION_270 = 270 }; // Begin drawing a new frame // Calls to nanovg drawing API should be wrapped in nvgBeginFrame() & nvgEndFrame() // nvgBeginFrame() defines the size of the window to render to in relation currently // set viewport (i.e. glViewport on GL backends). Device pixel ration allows to // control the rendering on Hi-DPI devices. // For example, GLFW returns two dimension for an opened window: window size and // frame buffer size. In that case you would set windowWidth/Height to the window size // devicePixelRatio to: frameBufferWidth / windowWidth. void nvgBeginFrame(NVGcontext* ctx, float windowWidth, float windowHeight, float devicePixelRatio, enum NVGorientation orientation); void nvgBeginFrameEx(NVGcontext* ctx, float windowWidth, float windowHeight, float devicePixelRatio, int reset, enum NVGorientation orientation); float nvgGetHeight(NVGcontext* ctx); float nvgGetWidth(NVGcontext* ctx); // Cancels drawing the current frame. void nvgCancelFrame(NVGcontext* ctx); // Ends drawing flushing remaining render state. void nvgEndFrame(NVGcontext* ctx); // // Composite operation // // The composite operations in NanoVG are modeled after HTML Canvas API, and // the blend func is based on OpenGL (see corresponding manuals for more info). // The colors in the blending state have premultiplied alpha. // Sets the composite operation. The op parameter should be one of NVGcompositeOperation. void nvgGlobalCompositeOperation(NVGcontext* ctx, int op); // Sets the composite operation with custom pixel arithmetic. The parameters should be one of NVGblendFactor. void nvgGlobalCompositeBlendFunc(NVGcontext* ctx, int sfactor, int dfactor); // Sets the composite operation with custom pixel arithmetic for RGB and alpha components separately. The parameters should be one of NVGblendFactor. void nvgGlobalCompositeBlendFuncSeparate(NVGcontext* ctx, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha); // // Color utils // // Colors in NanoVG are stored as unsigned ints in ABGR format. // Returns a color value from red, green, blue values. Alpha will be set to 255 (1.0f). NVGcolor nvgRGB(unsigned char r, unsigned char g, unsigned char b); // Returns a color value from red, green, blue values. Alpha will be set to 1.0f. NVGcolor nvgRGBf(float r, float g, float b); // Returns a color value from red, green, blue and alpha values. NVGcolor nvgRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Returns a color value from red, green, blue and alpha values. NVGcolor nvgRGBAf(float r, float g, float b, float a); // Linearly interpolates from color c0 to c1, and returns resulting color value. NVGcolor nvgLerpRGBA(NVGcolor c0, NVGcolor c1, float u); // Sets transparency of a color value. NVGcolor nvgTransRGBA(NVGcolor c0, unsigned char a); // Sets transparency of a color value. NVGcolor nvgTransRGBAf(NVGcolor c0, float a); // Returns color value specified by hue, saturation and lightness. // HSL values are all in range [0..1], alpha will be set to 255. NVGcolor nvgHSL(float h, float s, float l); // Returns color value specified by hue, saturation and lightness and alpha. // HSL values are all in range [0..1], alpha in range [0..255] NVGcolor nvgHSLA(float h, float s, float l, unsigned char a); // // State Handling // // NanoVG contains state which represents how paths will be rendered. // The state contains transform, fill and stroke styles, text and font styles, // and scissor clipping. // Pushes and saves the current render state into a state stack. // A matching nvgRestore() must be used to restore the state. void nvgSave(NVGcontext* ctx); // Pops and restores current render state. void nvgRestore(NVGcontext* ctx); // Resets current render state to default values. Does not affect the render state stack. void nvgReset(NVGcontext* ctx); // // Render styles // // Fill and stroke render style can be either a solid color or a paint which is a gradient or a pattern. // Solid color is simply defined as a color value, different kinds of paints can be created // using nvgLinearGradient(), nvgBoxGradient(), nvgRadialGradient() and nvgImagePattern(). // // Current render style can be saved and restored using nvgSave() and nvgRestore(). // Sets whether to draw antialias for nvgStroke() and nvgFill(). It's enabled by default. void nvgShapeAntiAlias(NVGcontext* ctx, int enabled); // Sets current stroke style to a solid color. void nvgStrokeColor(NVGcontext* ctx, NVGcolor color); // Sets current stroke style to a paint, which can be a one of the gradients or a pattern. void nvgStrokePaint(NVGcontext* ctx, NVGpaint paint); // Sets current fill style to a solid color. void nvgFillColor(NVGcontext* ctx, NVGcolor color); // Sets current fill style to a paint, which can be a one of the gradients or a pattern. void nvgFillPaint(NVGcontext* ctx, NVGpaint paint); // Sets the miter limit of the stroke style. // Miter limit controls when a sharp corner is beveled. void nvgMiterLimit(NVGcontext* ctx, float limit); // Sets the stroke width of the stroke style. void nvgStrokeWidth(NVGcontext* ctx, float size); // Sets how the end of the line (cap) is drawn, // Can be one of: NVG_BUTT (default), NVG_ROUND, NVG_SQUARE. void nvgLineCap(NVGcontext* ctx, int cap); // Sets how sharp path corners are drawn. // Can be one of NVG_MITER (default), NVG_ROUND, NVG_BEVEL. void nvgLineJoin(NVGcontext* ctx, int join); // Sets the transparency applied to all rendered shapes. // Already transparent paths will get proportionally more transparent as well. void nvgGlobalAlpha(NVGcontext* ctx, float alpha); // // Transforms // // The paths, gradients, patterns and scissor region are transformed by an transformation // matrix at the time when they are passed to the API. // The current transformation matrix is a affine matrix: // [sx kx tx] // [ky sy ty] // [ 0 0 1] // Where: sx,sy define scaling, kx,ky skewing, and tx,ty translation. // The last row is assumed to be 0,0,1 and is not stored. // // Apart from nvgResetTransform(), each transformation function first creates // specific transformation matrix and pre-multiplies the current transformation by it. // // Current coordinate system (transformation) can be saved and restored using nvgSave() and nvgRestore(). // Resets current transform to a identity matrix. void nvgResetTransform(NVGcontext* ctx); // Premultiplies current coordinate system by specified matrix. // The parameters are interpreted as matrix as follows: // [a c e] // [b d f] // [0 0 1] void nvgTransform(NVGcontext* ctx, float a, float b, float c, float d, float e, float f); // Translates current coordinate system. void nvgTranslate(NVGcontext* ctx, float x, float y); // Rotates current coordinate system. Angle is specified in radians. void nvgRotate(NVGcontext* ctx, float angle); // Skews the current coordinate system along X axis. Angle is specified in radians. void nvgSkewX(NVGcontext* ctx, float angle); // Skews the current coordinate system along Y axis. Angle is specified in radians. void nvgSkewY(NVGcontext* ctx, float angle); // Scales the current coordinate system. void nvgScale(NVGcontext* ctx, float x, float y); // Stores the top part (a-f) of the current transformation matrix in to the specified buffer. // [a c e] // [b d f] // [0 0 1] // There should be space for 6 floats in the return buffer for the values a-f. void nvgCurrentTransform(NVGcontext* ctx, float* xform); // The following functions can be used to make calculations on 2x3 transformation matrices. // A 2x3 matrix is represented as float[6]. // Sets the transform to identity matrix. void nvgTransformIdentity(float* dst); // Sets the transform to translation matrix matrix. void nvgTransformTranslate(float* dst, float tx, float ty); // Sets the transform to scale matrix. void nvgTransformScale(float* dst, float sx, float sy); // Sets the transform to rotate matrix. Angle is specified in radians. void nvgTransformRotate(float* dst, float a); // Sets the transform to skew-x matrix. Angle is specified in radians. void nvgTransformSkewX(float* dst, float a); // Sets the transform to skew-y matrix. Angle is specified in radians. void nvgTransformSkewY(float* dst, float a); // Sets the transform to the result of multiplication of two transforms, of A = A*B. void nvgTransformMultiply(float* dst, const float* src); // Sets the transform to the result of multiplication of two transforms, of A = B*A. void nvgTransformPremultiply(float* dst, const float* src); // Sets the destination to inverse of specified transform. // Returns 1 if the inverse could be calculated, else 0. int nvgTransformInverse(float* dst, const float* src); // Transform a point by given transform. void nvgTransformPoint(float* dstx, float* dsty, const float* xform, float srcx, float srcy); // Converts degrees to radians and vice versa. float nvgDegToRad(float deg); float nvgRadToDeg(float rad); // // Images // // NanoVG allows you to load jpg, png, psd, tga, pic and gif files to be used for rendering. // In addition you can upload your own image. The image loading is provided by stb_image. // The parameter imageFlags is combination of flags defined in NVGimageFlags. // Creates image by loading it from the disk from specified file name. // Returns handle to the image. int nvgCreateImage(NVGcontext* ctx, const char* filename, int imageFlags); // Creates image by loading it from the specified chunk of memory. // Returns handle to the image. int nvgCreateImageMem(NVGcontext* ctx, int imageFlags, unsigned char* data, int ndata); // Creates image from specified image data. // Returns handle to the image. int nvgCreateImageRGBA(NVGcontext* ctx, int w, int h, int imageFlags, const unsigned char* data); // Updates image data specified by image handle. void nvgUpdateImage(NVGcontext* ctx, int image, const unsigned char* data); // Returns the dimensions of a created image. void nvgImageSize(NVGcontext* ctx, int image, int* w, int* h); // Deletes created image. void nvgDeleteImage(NVGcontext* ctx, int image); // Deletes font's assets for font's name. void nvgDeleteFontByName(NVGcontext* ctx, const char* name); // // Paints // // NanoVG supports four types of paints: linear gradient, box gradient, radial gradient and image pattern. // These can be used as paints for strokes and fills. // Creates and returns a linear gradient. Parameters (sx,sy)-(ex,ey) specify the start and end coordinates // of the linear gradient, icol specifies the start color and ocol the end color. // The gradient is transformed by the current transform when it is passed to nvgFillPaint() or nvgStrokePaint(). NVGpaint nvgLinearGradient(NVGcontext* ctx, float sx, float sy, float ex, float ey, NVGcolor icol, NVGcolor ocol); // Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering // drop shadows or highlights for boxes. Parameters (x,y) define the top-left corner of the rectangle, // (w,h) define the size of the rectangle, r defines the corner radius, and f feather. Feather defines how blurry // the border of the rectangle is. Parameter icol specifies the inner color and ocol the outer color of the gradient. // The gradient is transformed by the current transform when it is passed to nvgFillPaint() or nvgStrokePaint(). NVGpaint nvgBoxGradient(NVGcontext* ctx, float x, float y, float w, float h, float r, float f, NVGcolor icol, NVGcolor ocol); // Creates and returns a radial gradient. Parameters (cx,cy) specify the center, inr and outr specify // the inner and outer radius of the gradient, icol specifies the start color and ocol the end color. // The gradient is transformed by the current transform when it is passed to nvgFillPaint() or nvgStrokePaint(). NVGpaint nvgRadialGradient(NVGcontext* ctx, float cx, float cy, float inr, float outr, NVGcolor icol, NVGcolor ocol); // Creates and returns an image patter. Parameters (ox,oy) specify the left-top location of the image pattern, // (ex,ey) the size of one image, angle rotation around the top-left corner, image is handle to the image to render. // The gradient is transformed by the current transform when it is passed to nvgFillPaint() or nvgStrokePaint(). NVGpaint nvgImagePattern(NVGcontext* ctx, float ox, float oy, float ex, float ey, float angle, int image, float alpha); // get xfrom data void nvgGetStateXfrom(NVGcontext* ctx, float* xform); // // Scissoring // // Scissoring allows you to clip the rendering into a rectangle. This is useful for various // user interface cases like rendering a text edit or a timeline. // Sets the current scissor rectangle. // The scissor rectangle is transformed by the current transform. void nvgScissor(NVGcontext* ctx, float x, float y, float w, float h); // Intersects current scissor rectangle with the specified rectangle. // The scissor rectangle is transformed by the current transform. // Note: in case the rotation of previous scissor rect differs from // the current one, the intersection will be done between the specified // rectangle and the previous scissor rectangle transformed in the current // transform space. The resulting shape is always rectangle. void nvgIntersectScissor(NVGcontext* ctx, float x, float y, float w, float h); /** * @method nvgIntersectScissor_ex * 设置一个与前一个裁剪区做交集的矩形裁剪区。 * 输入要设置的裁剪区,做交集后把新的裁剪区返回来给用户。 * * @annotation ["scriptable"] * @param {NVGcontext*} ctx nanovg的对象 * @param {float_t} x 裁剪区x坐标。 * @param {float_t} y 裁剪区y坐标。 * @param {float_t} w 裁剪区宽度。 * @param {float_t} h 裁剪区高度。 * */ void nvgIntersectScissor_ex(NVGcontext* ctx, float* x, float* y, float* w, float* h); // Reset and disables scissoring. void nvgResetScissor(NVGcontext* ctx); /** * @method nvgGetCurrScissor * 获取当前裁剪区 * * @annotation ["scriptable"] * @param {NVGcontext*} ctx nanovg的对象 * @param {float_t*} x 裁剪区x坐标。 * @param {float_t*} y 裁剪区y坐标。 * @param {float_t*} w 裁剪区宽度。 * @param {float_t*} h 裁剪区高度。 * * @return {int} 返回成功返回 1,失败返回 0。 */ int nvgGetCurrScissor(NVGcontext* ctx, float* x, float* y, float* w, float* h); /** * @method nvgIntersectScissorForOtherRect * 设置一个裁剪区,但是该裁剪区收到脏矩形的影响 * 首先会把脏矩形根据当前 nanovg 的坐标系转换为新的脏矩形区域,再和裁剪区做交集,把交集设为新的裁剪区 * * @annotation ["scriptable"] * @param {NVGcontext*} ctx nanovg的对象 * @param {float_t} x 裁剪区x坐标。 * @param {float_t} y 裁剪区y坐标。 * @param {float_t} w 裁剪区宽度。 * @param {float_t} h 裁剪区高度。 * @param {float_t} dx 脏矩形x坐标。 * @param {float_t} dy 脏矩形y坐标。 * @param {float_t} dw 脏矩形宽度。 * @param {float_t} dh 脏矩形高度。 * */ void nvgIntersectScissorForOtherRect(NVGcontext* ctx, float x, float y, float w, float h, float dx, float dy, float dw, float dh); // // Paths // // Drawing a new shape starts with nvgBeginPath(), it clears all the currently defined paths. // Then you define one or more paths and sub-paths which describe the shape. The are functions // to draw common shapes like rectangles and circles, and lower level step-by-step functions, // which allow to define a path curve by curve. // // NanoVG uses even-odd fill rule to draw the shapes. Solid shapes should have counter clockwise // winding and holes should have counter clockwise order. To specify winding of a path you can // call nvgPathWinding(). This is useful especially for the common shapes, which are drawn CCW. // // Finally you can fill the path using current fill style by calling nvgFill(), and stroke it // with current stroke style by calling nvgStroke(). // // The curve segments and sub-paths are transformed by the current transform. // Clears the current path and sub-paths. void nvgBeginPath(NVGcontext* ctx); // Starts new sub-path with specified point as first point. void nvgMoveTo(NVGcontext* ctx, float x, float y); // Adds line segment from the last point in the path to the specified point. void nvgLineTo(NVGcontext* ctx, float x, float y); // Adds cubic bezier segment from last point in the path via two control points to the specified point. void nvgBezierTo(NVGcontext* ctx, float c1x, float c1y, float c2x, float c2y, float x, float y); // Adds quadratic bezier segment from last point in the path via a control point to the specified point. void nvgQuadTo(NVGcontext* ctx, float cx, float cy, float x, float y); // Adds an arc segment at the corner defined by the last path point, and two specified points. void nvgArcTo(NVGcontext* ctx, float x1, float y1, float x2, float y2, float radius); // Closes current sub-path with a line segment. void nvgClosePath(NVGcontext* ctx); // Sets the current sub-path winding, see NVGwinding and NVGsolidity. void nvgPathWinding(NVGcontext* ctx, int dir); // Creates new circle arc shaped sub-path. The arc center is at cx,cy, the arc radius is r, // and the arc is drawn from angle a0 to a1, and swept in direction dir (NVG_CCW, or NVG_CW). // Angles are specified in radians. void nvgArc(NVGcontext* ctx, float cx, float cy, float r, float a0, float a1, int dir); // Creates new rectangle shaped sub-path. void nvgRect(NVGcontext* ctx, float x, float y, float w, float h); // Creates new rounded rectangle shaped sub-path. void nvgRoundedRect(NVGcontext* ctx, float x, float y, float w, float h, float r); // Creates new rounded rectangle shaped sub-path with varying radii for each corner. void nvgRoundedRectVarying(NVGcontext* ctx, float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft); // Creates new ellipse shaped sub-path. void nvgEllipse(NVGcontext* ctx, float cx, float cy, float rx, float ry); // Creates new circle shaped sub-path. void nvgCircle(NVGcontext* ctx, float cx, float cy, float r); // Fills the current path with current fill style. void nvgFill(NVGcontext* ctx); // Fills the current path with current stroke style. void nvgStroke(NVGcontext* ctx); // // Text // // NanoVG allows you to load .ttf files and use the font to render text. // // The appearance of the text can be defined by setting the current text style // and by specifying the fill color. Common text and font settings such as // font size, letter spacing and text align are supported. Font blur allows you // to create simple text effects such as drop shadows. // // At render time the font face can be set based on the font handles or name. // // Font measure functions return values in local space, the calculations are // carried in the same resolution as the final rendering. This is done because // the text glyph positions are snapped to the nearest pixels sharp rendering. // // The local space means that values are not rotated or scale as per the current // transformation. For example if you set font size to 12, which would mean that // line height is 16, then regardless of the current scaling and rotation, the // returned line height is always 16. Some measures may vary because of the scaling // since aforementioned pixel snapping. // // While this may sound a little odd, the setup allows you to always render the // same way regardless of scaling. I.e. following works regardless of scaling: // // const char* txt = "Text me up."; // nvgTextBounds(vg, x,y, txt, NULL, bounds); // nvgBeginPath(vg); // nvgRoundedRect(vg, bounds[0],bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1]); // nvgFill(vg); // // Note: currently only solid color fill is supported for text. // Creates font by loading it from the disk from specified file name. // Returns handle to the font. int nvgCreateFont(NVGcontext* ctx, const char* name, const char* filename); // Creates font by loading it from the specified memory chunk. // Returns handle to the font. int nvgCreateFontMem(NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData); // Finds a loaded font of specified name, and returns handle to it, or -1 if the font is not found. int nvgFindFont(NVGcontext* ctx, const char* name); // Adds a fallback font by handle. int nvgAddFallbackFontId(NVGcontext* ctx, int baseFont, int fallbackFont); // Adds a fallback font by name. int nvgAddFallbackFont(NVGcontext* ctx, const char* baseFont, const char* fallbackFont); // Sets the font size of current text style. void nvgFontSize(NVGcontext* ctx, float size); // Sets the blur of current text style. void nvgFontBlur(NVGcontext* ctx, float blur); // Sets the letter spacing of current text style. void nvgTextLetterSpacing(NVGcontext* ctx, float spacing); // Sets the proportional line height of current text style. The line height is specified as multiple of font size. void nvgTextLineHeight(NVGcontext* ctx, float lineHeight); // Sets the text align of current text style, see NVGalign for options. void nvgTextAlign(NVGcontext* ctx, int align); // Sets the font face based on specified id of current text style. void nvgFontFaceId(NVGcontext* ctx, int font); // Sets the font face based on specified name of current text style. void nvgFontFace(NVGcontext* ctx, const char* font); // Draws text string at specified location. If end is specified only the sub-string up to the end is drawn. float nvgText(NVGcontext* ctx, float x, float y, const char* string, const char* end); // Draws multi-line text string at specified location wrapped at the specified width. If end is specified only the sub-string up to the end is drawn. // White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. // Words longer than the max width are slit at nearest character (i.e. no hyphenation). void nvgTextBox(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end); // Measures the specified text string. Parameter bounds should be a pointer to float[4], // if the bounding box of the text should be returned. The bounds value are [xmin,ymin, xmax,ymax] // Returns the horizontal advance of the measured text (i.e. where the next character should drawn). // Measured values are returned in local coordinate space. float nvgTextBounds(NVGcontext* ctx, float x, float y, const char* string, const char* end, float* bounds); // Measures the specified multi-text string. Parameter bounds should be a pointer to float[4], // if the bounding box of the text should be returned. The bounds value are [xmin,ymin, xmax,ymax] // Measured values are returned in local coordinate space. void nvgTextBoxBounds(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds); // Calculates the glyph x positions of the specified text. If end is specified only the sub-string will be used. // Measured values are returned in local coordinate space. int nvgTextGlyphPositions(NVGcontext* ctx, float x, float y, const char* string, const char* end, NVGglyphPosition* positions, int maxPositions); // Returns the vertical metrics based on the current text style. // Measured values are returned in local coordinate space. void nvgTextMetrics(NVGcontext* ctx, float* ascender, float* descender, float* lineh); // Breaks the specified text into lines. If end is specified only the sub-string will be used. // White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. // Words longer than the max width are slit at nearest character (i.e. no hyphenation). int nvgTextBreakLines(NVGcontext* ctx, const char* string, const char* end, float breakRowWidth, NVGtextRow* rows, int maxRows); // // Internal Render API // enum NVGtexture { NVG_TEXTURE_ALPHA = 1, NVG_TEXTURE_RGBA = 2, NVG_TEXTURE_BGRA = 4, NVG_TEXTURE_RGB = 8, NVG_TEXTURE_BGR = 16, NVG_TEXTURE_RGB565 = 32, NVG_TEXTURE_BGR565 = 64, NVG_TEXTURE_ARGB = 128, NVG_TEXTURE_ABGR = 256, }; struct NVGscissor { float xform[6]; float extent[2]; }; typedef struct NVGscissor NVGscissor; struct NVGvertex { float x,y,u,v; }; typedef struct NVGvertex NVGvertex; struct NVGpath { int first; int count; unsigned char closed; int nbevel; NVGvertex* fill; int nfill; NVGvertex* stroke; int nstroke; int winding; int convex; }; typedef struct NVGpath NVGpath; struct NVGparams { void* userPtr; int edgeAntiAlias; void (*setLineCap)(void* uptr, int lineCap); void (*setLineJoin)(void* uptr, int lineJoin); int (*clearCache)(void* uptr); int (*renderCreate)(void* uptr); int (*findTexture)(void* uptr, const void* data); void (*setStateXfrom)(void* uptr, float* xform); int (*renderCreateTexture)(void* uptr, int type, int w, int h, int stride, int imageFlags, enum NVGorientation orientation, const unsigned char* data); int (*renderDeleteTexture)(void* uptr, int image); int (*renderUpdateTexture)(void* uptr, int image, int x, int y, int w, int h, const unsigned char* data); int (*renderGetTextureSize)(void* uptr, int image, int* w, int* h); void (*renderViewport)(void* uptr, float width, float height, float devicePixelRatio); void (*renderCancel)(void* uptr); void (*renderFlush)(void* uptr); void (*globalSreenOrientation)(void* uptr, enum NVGorientation orientation); void (*renderFill)(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, float fringe, const float* bounds, const NVGpath* paths, int npaths); void (*renderStroke)(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, float fringe, float strokeWidth, const NVGpath* paths, int npaths); void (*renderTriangles)(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, const NVGvertex* verts, int nverts); void (*renderDelete)(void* uptr); }; typedef struct NVGparams NVGparams; // Constructor and destructor, called by the render back-end. NVGcontext* nvgCreateInternal(NVGparams* params); void nvgDeleteInternal(NVGcontext* ctx); NVGparams* nvgInternalParams(NVGcontext* ctx); // Debug function to dump cached path data. void nvgDebugDumpPathCache(NVGcontext* ctx); #ifdef _MSC_VER #pragma warning(pop) #endif #define NVG_NOTUSED(v) for (;;) { (void)(1 ? (void)0 : ( (void)(v) ) ); break; } NVGparams* nvgGetParams(NVGcontext* ctx); int nvgCreateImageRaw(NVGcontext* ctx, int w, int h, int format, int stride, int imageFlags, enum NVGorientation orientation, const unsigned char* data); int nvgFindTextureRaw(NVGcontext* ctx, const void* data); int nvgClearCache(NVGcontext* ctx); #ifdef __cplusplus } #endif #endif // NANOVG_H
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\base\stb_image.h
/* stb_image - v2.10 - public domain image loader - http://nothings.org/stb_image.h no warranty implied; use at your own risk Do this: #define STB_IMAGE_IMPLEMENTATION before you include this file in *one* C or C++ file to create the implementation. // i.e. it should look like this: #include ... #include ... #include ... #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free QUICK NOTES: Primarily of interest to game developers and other people who can avoid problematic images and only need the trivial interface JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) PNG 1/2/4/8-bit-per-channel (16 bpc not supported) TGA (not sure what subset, if a subset) BMP non-1bpp, non-RLE PSD (composited view only, no extra channels, 8/16 bit-per-channel) GIF (*comp always reports as 4-channel) HDR (radiance rgbE format) PIC (Softimage PIC) PNM (PPM and PGM binary only) Animated GIF still needs a proper API, but here's one way to do it: http://gist.github.com/urraka/685d9a6340b26b830d49 - decode from memory or through FILE (define STBI_NO_STDIO to remove code) - decode from arbitrary I/O callbacks - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) Full documentation under "DOCUMENTATION" below. Revision 2.00 release notes: - Progressive JPEG is now supported. - PPM and PGM binary formats are now supported, thanks to Ken Miller. - x86 platforms now make use of SSE2 SIMD instructions for JPEG decoding, and ARM platforms can use NEON SIMD if requested. This work was done by Fabian "ryg" Giesen. SSE2 is used by default, but NEON must be enabled explicitly; see docs. With other JPEG optimizations included in this version, we see 2x speedup on a JPEG on an x86 machine, and a 1.5x speedup on a JPEG on an ARM machine, relative to previous versions of this library. The same results will not obtain for all JPGs and for all x86/ARM machines. (Note that progressive JPEGs are significantly slower to decode than regular JPEGs.) This doesn't mean that this is the fastest JPEG decoder in the land; rather, it brings it closer to parity with standard libraries. If you want the fastest decode, look elsewhere. (See "Philosophy" section of docs below.) See final bullet items below for more info on SIMD. - Added STBI_MALLOC, STBI_REALLOC, and STBI_FREE macros for replacing the memory allocator. Unlike other STBI libraries, these macros don't support a context parameter, so if you need to pass a context in to the allocator, you'll have to store it in a global or a thread-local variable. - Split existing STBI_NO_HDR flag into two flags, STBI_NO_HDR and STBI_NO_LINEAR. STBI_NO_HDR: suppress implementation of .hdr reader format STBI_NO_LINEAR: suppress high-dynamic-range light-linear float API - You can suppress implementation of any of the decoders to reduce your code footprint by #defining one or more of the following symbols before creating the implementation. STBI_NO_JPEG STBI_NO_PNG STBI_NO_BMP STBI_NO_PSD STBI_NO_TGA STBI_NO_GIF STBI_NO_HDR STBI_NO_PIC STBI_NO_PNM (.ppm and .pgm) - You can request *only* certain decoders and suppress all other ones (this will be more forward-compatible, as addition of new decoders doesn't require you to disable them explicitly): STBI_ONLY_JPEG STBI_ONLY_PNG STBI_ONLY_BMP STBI_ONLY_PSD STBI_ONLY_TGA STBI_ONLY_GIF STBI_ONLY_HDR STBI_ONLY_PIC STBI_ONLY_PNM (.ppm and .pgm) Note that you can define multiples of these, and you will get all of them ("only x" and "only y" is interpreted to mean "only x&y"). - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB - Compilation of all SIMD code can be suppressed with #define STBI_NO_SIMD It should not be necessary to disable SIMD unless you have issues compiling (e.g. using an x86 compiler which doesn't support SSE intrinsics or that doesn't support the method used to detect SSE2 support at run-time), and even those can be reported as bugs so I can refine the built-in compile-time checking to be smarter. - The old STBI_SIMD system which allowed installing a user-defined IDCT etc. has been removed. If you need this, don't upgrade. My assumption is that almost nobody was doing this, and those who were will find the built-in SIMD more satisfactory anyway. - RGB values computed for JPEG images are slightly different from previous versions of stb_image. (This is due to using less integer precision in SIMD.) The C code has been adjusted so that the same RGB values will be computed regardless of whether SIMD support is available, so your app should always produce consistent results. But these results are slightly different from previous versions. (Specifically, about 3% of available YCbCr values will compute different RGB results from pre-1.49 versions by +-1; most of the deviating values are one smaller in the G channel.) - If you must produce consistent results with previous versions of stb_image, #define STBI_JPEG_OLD and you will get the same results you used to; however, you will not get the SIMD speedups for the YCbCr-to-RGB conversion step (although you should still see significant JPEG speedup from the other changes). Please note that STBI_JPEG_OLD is a temporary feature; it will be removed in future versions of the library. It is only intended for near-term back-compatibility use. Latest revision history: 2.10 (2016-01-22) avoid warning introduced in 2.09 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA 2.07 (2015-09-13) partial animated GIF support limited 16-bit PSD support minor bugs, code cleanup, and compiler warnings 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit 2.03 (2015-04-12) additional corruption checking stbi_set_flip_vertically_on_load fix NEON support; fix mingw support 2.02 (2015-01-19) fix incorrect assert, fix warning 2.01 (2015-01-17) fix various warnings 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG 2.00 (2014-12-25) optimize JPEG, including x86 SSE2 & ARM NEON SIMD progressive JPEG PGM/PPM support STBI_MALLOC,STBI_REALLOC,STBI_FREE STBI_NO_*, STBI_ONLY_* GIF bugfix 1.48 (2014-12-14) fix incorrectly-named assert() 1.47 (2014-12-14) 1/2/4-bit PNG support (both grayscale and paletted) optimize PNG fix bug in interlaced PNG with user-specified channel count See end of file for full revision history. ============================ Contributors ========================= Image formats Extensions, features Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) urraka@github (animated gif) Junggon Kim (PNM comments) Daniel Gibson (16-bit TGA) Optimizations & bugfixes Fabian "ryg" Giesen Arseny Kapoulkine Bug & warning fixes Marc LeBlanc David Woo Guillaume George Martins Mozeiko Christpher Lloyd Martin Golini Jerry Jansson Joseph Thomson Dave Moore Roy Eltham Hayaki Saito Phil Jordan Won Chun Luke Graham Johan Duparc Nathan Reed the Horde3D community Thomas Ruf Ronny Chevalier Nick Verigakis Janez Zemva John Bartholomew Michal Cichon svdijk@github Jonathan Blow Ken Hamada Tero Hanninen Baldur Karlsson Laurent Gomila Cort Stratton Sergio Gonzalez romigrou@github Aruelien Pocheville Thibault Reuille Cass Everitt Ryamond Barbiero Paul Du Bois Engin Manap Blazej Dariusz Roszkowski Michaelangel007@github LICENSE This software is in the public domain. Where that dedication is not recognized, you are granted a perpetual, irrevocable license to copy, distribute, and modify this file as you see fit. */ #ifndef STBI_INCLUDE_STB_IMAGE_H #define STBI_INCLUDE_STB_IMAGE_H // DOCUMENTATION // // Limitations: // - no 16-bit-per-channel PNG // - no 12-bit-per-channel JPEG // - no JPEGs with arithmetic coding // - no 1-bit BMP // - GIF always returns *comp=4 // // Basic usage (see HDR discussion below for HDR usage): // int x,y,n; // unsigned char *data = stbi_load(filename, &x, &y, &n, 0); // // ... process data if not NULL ... // // ... x = width, y = height, n = # 8-bit components per pixel ... // // ... replace '0' with '1'..'4' to force that many components per pixel // // ... but 'n' will always be the number that it would have been if you said 0 // stbi_image_free(data) // // Standard parameters: // int *x -- outputs image width in pixels // int *y -- outputs image height in pixels // int *comp -- outputs # of image components in image file // int req_comp -- if non-zero, # of image components requested in result // // The return value from an image loader is an 'unsigned char *' which points // to the pixel data, or NULL on an allocation failure or if the image is // corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, // with each pixel consisting of N interleaved 8-bit components; the first // pixel pointed to is top-left-most in the image. There is no padding between // image scanlines or between pixels, regardless of format. The number of // components N is 'req_comp' if req_comp is non-zero, or *comp otherwise. // If req_comp is non-zero, *comp has the number of components that _would_ // have been output otherwise. E.g. if you set req_comp to 4, you will always // get RGBA output, but you can check *comp to see if it's trivially opaque // because e.g. there were only 3 channels in the source image. // // An output image with N components has the following components interleaved // in this order in each pixel: // // N=#comp components // 1 grey // 2 grey, alpha // 3 red, green, blue // 4 red, green, blue, alpha // // If image loading fails for any reason, the return value will be NULL, // and *x, *y, *comp will be unchanged. The function stbi_failure_reason() // can be queried for an extremely brief, end-user unfriendly explanation // of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid // compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly // more user-friendly ones. // // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. // // =========================================================================== // // Philosophy // // stb libraries are designed with the following priorities: // // 1. easy to use // 2. easy to maintain // 3. good performance // // Sometimes I let "good performance" creep up in priority over "easy to maintain", // and for best performance I may provide less-easy-to-use APIs that give higher // performance, in addition to the easy to use ones. Nevertheless, it's important // to keep in mind that from the standpoint of you, a client of this library, // all you care about is #1 and #3, and stb libraries do not emphasize #3 above all. // // Some secondary priorities arise directly from the first two, some of which // make more explicit reasons why performance can't be emphasized. // // - Portable ("ease of use") // - Small footprint ("easy to maintain") // - No dependencies ("ease of use") // // =========================================================================== // // I/O callbacks // // I/O callbacks allow you to read from arbitrary sources, like packaged // files or some other source. Data read from callbacks are processed // through a small internal buffer (currently 128 bytes) to try to reduce // overhead. // // The three functions you must define are "read" (reads some bytes of data), // "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). // // =========================================================================== // // SIMD support // // The JPEG decoder will try to automatically use SIMD kernels on x86 when // supported by the compiler. For ARM Neon support, you must explicitly // request it. // // (The old do-it-yourself SIMD API is no longer supported in the current // code.) // // On x86, SSE2 will automatically be used when available based on a run-time // test; if not, the generic C versions are used as a fall-back. On ARM targets, // the typical path is to have separate builds for NEON and non-NEON devices // (at least this is true for iOS and Android). Therefore, the NEON support is // toggled by a build flag: define STBI_NEON to get NEON loops. // // The output of the JPEG decoder is slightly different from versions where // SIMD support was introduced (that is, for versions before 1.49). The // difference is only +-1 in the 8-bit RGB channels, and only on a small // fraction of pixels. You can force the pre-1.49 behavior by defining // STBI_JPEG_OLD, but this will disable some of the SIMD decoding path // and hence cost some performance. // // If for some reason you do not want to use any of SIMD code, or if // you have issues compiling it, you can disable it entirely by // defining STBI_NO_SIMD. // // =========================================================================== // // HDR image support (disable by defining STBI_NO_HDR) // // stb_image now supports loading HDR images in general, and currently // the Radiance .HDR file format, although the support is provided // generically. You can still load any file through the existing interface; // if you attempt to load an HDR file, it will be automatically remapped to // LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; // both of these constants can be reconfigured through this interface: // // stbi_hdr_to_ldr_gamma(2.2f); // stbi_hdr_to_ldr_scale(1.0f); // // (note, do not use _inverse_ constants; stbi_image will invert them // appropriately). // // Additionally, there is a new, parallel interface for loading files as // (linear) floats to preserve the full dynamic range: // // float *data = stbi_loadf(filename, &x, &y, &n, 0); // // If you load LDR images through this interface, those images will // be promoted to floating point values, run through the inverse of // constants corresponding to the above: // // stbi_ldr_to_hdr_scale(1.0f); // stbi_ldr_to_hdr_gamma(2.2f); // // Finally, given a filename (or an open file or memory block--see header // file for details) containing image data, you can query for the "most // appropriate" interface to use (that is, whether the image is HDR or // not), using: // // stbi_is_hdr(char *filename); // // =========================================================================== // // iPhone PNG support: // // By default we convert iphone-formatted PNGs back to RGB, even though // they are internally encoded differently. You can disable this conversion // by by calling stbi_convert_iphone_png_to_rgb(0), in which case // you will always just get the native iphone "format" through (which // is BGR stored in RGB). // // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per // pixel to remove any premultiplied alpha *only* if the image file explicitly // says there's premultiplied data (currently only happens in iPhone images, // and only if iPhone convert-to-rgb processing is on). // #ifndef STBI_NO_STDIO #include <stdio.h> #endif // STBI_NO_STDIO #define STBI_VERSION 1 enum { STBI_default = 0, // only used for req_comp STBI_grey = 1, STBI_grey_alpha = 2, STBI_rgb = 3, STBI_rgb_alpha = 4 }; typedef unsigned char stbi_uc; #ifdef __cplusplus extern "C" { #endif #ifdef STB_IMAGE_STATIC #define STBIDEF static inline #else #define STBIDEF extern #endif ////////////////////////////////////////////////////////////////////////////// // // PRIMARY API - works on images of any type // // // load image by filename, open file, or memory buffer // typedef struct { int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative int (*eof) (void *user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp); STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *comp, int req_comp); STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *comp, int req_comp); #ifndef STBI_NO_STDIO STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); // for stbi_load_from_file, file pointer is left pointing immediately after image #endif #ifndef STBI_NO_LINEAR STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp); STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp); #ifndef STBI_NO_STDIO STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); #endif #endif #ifndef STBI_NO_HDR STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); STBIDEF void stbi_hdr_to_ldr_scale(float scale); #endif // STBI_NO_HDR #ifndef STBI_NO_LINEAR STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); STBIDEF void stbi_ldr_to_hdr_scale(float scale); #endif // STBI_NO_LINEAR // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr (char const *filename); STBIDEF int stbi_is_hdr_from_file(FILE *f); #endif // STBI_NO_STDIO // get a VERY brief reason for failure // NOT THREADSAFE STBIDEF const char *stbi_failure_reason (void); // free the loaded image -- this is just free() STBIDEF void stbi_image_free (void *retval_from_stbi_load); // get image dimensions & components without fully decoding STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); #ifndef STBI_NO_STDIO STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); #endif // for image formats that explicitly notate that they have premultiplied alpha, // we just return the colors as stored in the file. set this flag to force // unpremultiplication. results are undefined if the unpremultiply overflow. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); // indicate whether we should process iphone images back to canonical format, // or just pass them through "as-is" STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); // flip the image vertically, so the first pixel in the output array is the bottom left STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); // ZLIB client - used by PNG, available for other purposes STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); #ifdef __cplusplus } #endif // // //// end header file ///////////////////////////////////////////////////// #endif // STBI_INCLUDE_STB_IMAGE_H #ifdef STB_IMAGE_IMPLEMENTATION #if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ || defined(STBI_ONLY_ZLIB) #ifndef STBI_ONLY_JPEG #define STBI_NO_JPEG #endif #ifndef STBI_ONLY_PNG #define STBI_NO_PNG #endif #ifndef STBI_ONLY_BMP #define STBI_NO_BMP #endif #ifndef STBI_ONLY_PSD #define STBI_NO_PSD #endif #ifndef STBI_ONLY_TGA #define STBI_NO_TGA #endif #ifndef STBI_ONLY_GIF #define STBI_NO_GIF #endif #ifndef STBI_ONLY_HDR #define STBI_NO_HDR #endif #ifndef STBI_ONLY_PIC #define STBI_NO_PIC #endif #ifndef STBI_ONLY_PNM #define STBI_NO_PNM #endif #endif #if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) #define STBI_NO_ZLIB #endif #include <stdarg.h> #include <stddef.h> // ptrdiff_t on osx #include <stdlib.h> #include <string.h> #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) #include <math.h> // ldexp #endif #ifndef STBI_NO_STDIO #include <stdio.h> #endif #ifndef STBI_ASSERT #include <assert.h> #define STBI_ASSERT(x) assert(x) #endif #ifndef _MSC_VER #ifdef __cplusplus #define stbi_inline inline #else #define stbi_inline #endif #else #define stbi_inline __forceinline #endif #ifdef _MSC_VER typedef unsigned short stbi__uint16; typedef signed short stbi__int16; typedef unsigned int stbi__uint32; typedef signed int stbi__int32; #else #include <stdint.h> typedef uint16_t stbi__uint16; typedef int16_t stbi__int16; typedef uint32_t stbi__uint32; typedef int32_t stbi__int32; #endif // should produce compiler error if size is wrong typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #ifdef _MSC_VER #define STBI_NOTUSED(v) (void)(v) #else #define STBI_NOTUSED(v) (void)sizeof(v) #endif #ifdef _MSC_VER #define STBI_HAS_LROTL #endif #ifdef STBI_HAS_LROTL #define stbi_lrot(x,y) _lrotl(x,y) #else #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) #endif #if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) // ok #elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) // ok #else #error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." #endif #ifndef STBI_MALLOC #define STBI_MALLOC(sz) malloc(sz) #define STBI_REALLOC(p,newsz) realloc(p,newsz) #define STBI_FREE(p) free(p) #endif #ifndef STBI_REALLOC_SIZED #define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) #endif // x86/x64 detection #if defined(__x86_64__) || defined(_M_X64) #define STBI__X64_TARGET #elif defined(__i386) || defined(_M_IX86) #define STBI__X86_TARGET #endif #if defined(__GNUC__) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) // NOTE: not clear do we actually need this for the 64-bit path? // gcc doesn't support sse2 intrinsics unless you compile with -msse2, // (but compiling with -msse2 allows the compiler to use SSE2 everywhere; // this is just broken and gcc are jerks for not fixing it properly // http://www.virtualdub.org/blog/pivot/entry.php?id=363 ) #define STBI_NO_SIMD #endif #if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) // Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET // // 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the // Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. // As a result, enabling SSE2 on 32-bit MinGW is dangerous when not // simultaneously enabling "-mstackrealign". // // See https://github.com/nothings/stb/issues/81 for more information. // // So default to no SSE2 on 32-bit MinGW. If you've read this far and added // -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. #define STBI_NO_SIMD #endif #if !defined(STBI_NO_SIMD) && defined(STBI__X86_TARGET) #define STBI_SSE2 #include <emmintrin.h> #ifdef _MSC_VER #if _MSC_VER >= 1400 // not VC6 #include <intrin.h> // __cpuid static int stbi__cpuid3(void) { int info[4]; __cpuid(info,1); return info[3]; } #else static int stbi__cpuid3(void) { int res; __asm { mov eax,1 cpuid mov res,edx } return res; } #endif #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name static int stbi__sse2_available() { int info3 = stbi__cpuid3(); return ((info3 >> 26) & 1) != 0; } #else // assume GCC-style if not VC++ #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) static int stbi__sse2_available() { #if defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 408 // GCC 4.8 or later // GCC 4.8+ has a nice way to do this return __builtin_cpu_supports("sse2"); #else // portable way to do this, preferably without using GCC inline ASM? // just bail for now. return 0; #endif } #endif #endif // ARM NEON #if defined(STBI_NO_SIMD) && defined(STBI_NEON) #undef STBI_NEON #endif #ifdef STBI_NEON #include <arm_neon.h> // assume GCC or Clang on ARM targets #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #endif #ifndef STBI_SIMD_ALIGN #define STBI_SIMD_ALIGN(type, name) type name #endif /////////////////////////////////////////////// // // stbi__context struct and start_xxx functions // stbi__context structure is our basic context used by all images, so it // contains all the IO context, plus some basic image information typedef struct { stbi__uint32 img_x, img_y; int img_n, img_out_n; stbi_io_callbacks io; void *io_user_data; int read_from_callbacks; int buflen; stbi_uc buffer_start[128]; stbi_uc *img_buffer, *img_buffer_end; stbi_uc *img_buffer_original, *img_buffer_original_end; } stbi__context; static void stbi__refill_buffer(stbi__context *s); // initialize a memory-decode context static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) { s->io.read = NULL; s->read_from_callbacks = 0; s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; } // initialize a callback-based context static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) { s->io = *c; s->io_user_data = user; s->buflen = sizeof(s->buffer_start); s->read_from_callbacks = 1; s->img_buffer_original = s->buffer_start; stbi__refill_buffer(s); s->img_buffer_original_end = s->img_buffer_end; } #ifndef STBI_NO_STDIO static int stbi__stdio_read(void *user, char *data, int size) { return (int) fread(data,1,size,(FILE*) user); } static void stbi__stdio_skip(void *user, int n) { fseek((FILE*) user, n, SEEK_CUR); } static int stbi__stdio_eof(void *user) { return feof((FILE*) user); } static stbi_io_callbacks stbi__stdio_callbacks = { stbi__stdio_read, stbi__stdio_skip, stbi__stdio_eof, }; static void stbi__start_file(stbi__context *s, FILE *f) { stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); } //static void stop_file(stbi__context *s) { } #endif // !STBI_NO_STDIO static void stbi__rewind(stbi__context *s) { // conceptually rewind SHOULD rewind to the beginning of the stream, // but we just rewind to the beginning of the initial buffer, because // we only use it after doing 'test', which only ever looks at at most 92 bytes s->img_buffer = s->img_buffer_original; s->img_buffer_end = s->img_buffer_original_end; } #ifndef STBI_NO_JPEG static int stbi__jpeg_test(stbi__context *s); static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNG static int stbi__png_test(stbi__context *s); static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_BMP static int stbi__bmp_test(stbi__context *s); static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_TGA static int stbi__tga_test(stbi__context *s); static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s); static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_HDR static int stbi__hdr_test(stbi__context *s); static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PIC static int stbi__pic_test(stbi__context *s); static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_GIF static int stbi__gif_test(stbi__context *s); static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s); static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); #endif // this is not threadsafe static const char *stbi__g_failure_reason; STBIDEF const char *stbi_failure_reason(void) { return stbi__g_failure_reason; } static int stbi__err(const char *str) { stbi__g_failure_reason = str; return 0; } static void *stbi__malloc(size_t size) { return STBI_MALLOC(size); } // stbi__err - error // stbi__errpf - error returning pointer to float // stbi__errpuc - error returning pointer to unsigned char #ifdef STBI_NO_FAILURE_STRINGS #define stbi__err(x,y) 0 #elif defined(STBI_FAILURE_USERMSG) #define stbi__err(x,y) stbi__err(y) #else #define stbi__err(x,y) stbi__err(x) #endif #define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) #define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) STBIDEF void stbi_image_free(void *retval_from_stbi_load) { STBI_FREE(retval_from_stbi_load); } #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); #endif #ifndef STBI_NO_HDR static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); #endif static int stbi__vertically_flip_on_load = 0; STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) { stbi__vertically_flip_on_load = flag_true_if_should_flip; } static unsigned char *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) { #ifndef STBI_NO_JPEG if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp); #endif #ifndef STBI_NO_PNG if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp); #endif #ifndef STBI_NO_BMP if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp); #endif #ifndef STBI_NO_GIF if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp); #endif #ifndef STBI_NO_PSD if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp); #endif #ifndef STBI_NO_PIC if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp); #endif #ifndef STBI_NO_PNM if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp); #endif #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { float *hdr = stbi__hdr_load(s, x,y,comp,req_comp); return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); } #endif #ifndef STBI_NO_TGA // test tga last because it's a crappy test! if (stbi__tga_test(s)) return stbi__tga_load(s,x,y,comp,req_comp); #endif return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); } static unsigned char *stbi__load_flip(stbi__context *s, int *x, int *y, int *comp, int req_comp) { unsigned char *result = stbi__load_main(s, x, y, comp, req_comp); if (stbi__vertically_flip_on_load && result != NULL) { int w = *x, h = *y; int depth = req_comp ? req_comp : *comp; int row,col,z; stbi_uc temp; // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once for (row = 0; row < (h>>1); row++) { for (col = 0; col < w; col++) { for (z = 0; z < depth; z++) { temp = result[(row * w + col) * depth + z]; result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z]; result[((h - row - 1) * w + col) * depth + z] = temp; } } } } return result; } #ifndef STBI_NO_HDR static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) { if (stbi__vertically_flip_on_load && result != NULL) { int w = *x, h = *y; int depth = req_comp ? req_comp : *comp; int row,col,z; float temp; // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once for (row = 0; row < (h>>1); row++) { for (col = 0; col < w; col++) { for (z = 0; z < depth; z++) { temp = result[(row * w + col) * depth + z]; result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z]; result[((h - row - 1) * w + col) * depth + z] = temp; } } } } } #endif #ifndef STBI_NO_STDIO static FILE *stbi__fopen(char const *filename, char const *mode) { FILE *f; #if defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != fopen_s(&f, filename, mode)) f=0; #else f = fopen(filename, mode); #endif return f; } STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = stbi__fopen(filename, "rb"); unsigned char *result; if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); result = stbi_load_from_file(f,x,y,comp,req_comp); fclose(f); return result; } STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { unsigned char *result; stbi__context s; stbi__start_file(&s,f); result = stbi__load_flip(&s,x,y,comp,req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } #endif //!STBI_NO_STDIO STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__load_flip(&s,x,y,comp,req_comp); } STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__load_flip(&s,x,y,comp,req_comp); } #ifndef STBI_NO_LINEAR static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) { unsigned char *data; #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp); if (hdr_data) stbi__float_postprocess(hdr_data,x,y,comp,req_comp); return hdr_data; } #endif data = stbi__load_flip(s, x, y, comp, req_comp); if (data) return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); } STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__loadf_main(&s,x,y,comp,req_comp); } STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__loadf_main(&s,x,y,comp,req_comp); } #ifndef STBI_NO_STDIO STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) { float *result; FILE *f = stbi__fopen(filename, "rb"); if (!f) return stbi__errpf("can't fopen", "Unable to open file"); result = stbi_loadf_from_file(f,x,y,comp,req_comp); fclose(f); return result; } STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_file(&s,f); return stbi__loadf_main(&s,x,y,comp,req_comp); } #endif // !STBI_NO_STDIO #endif // !STBI_NO_LINEAR // these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is // defined, for API simplicity; if STBI_NO_LINEAR is defined, it always // reports false! STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__hdr_test(&s); #else STBI_NOTUSED(buffer); STBI_NOTUSED(len); return 0; #endif } #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr (char const *filename) { FILE *f = stbi__fopen(filename, "rb"); int result=0; if (f) { result = stbi_is_hdr_from_file(f); fclose(f); } return result; } STBIDEF int stbi_is_hdr_from_file(FILE *f) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_file(&s,f); return stbi__hdr_test(&s); #else STBI_NOTUSED(f); return 0; #endif } #endif // !STBI_NO_STDIO STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__hdr_test(&s); #else STBI_NOTUSED(clbk); STBI_NOTUSED(user); return 0; #endif } #ifndef STBI_NO_LINEAR static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } #endif static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } ////////////////////////////////////////////////////////////////////////////// // // Common code used by all image loaders // enum { STBI__SCAN_load=0, STBI__SCAN_type, STBI__SCAN_header }; static void stbi__refill_buffer(stbi__context *s) { int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); if (n == 0) { // at end of file, treat same as if from memory, but need to handle case // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file s->read_from_callbacks = 0; s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start+1; *s->img_buffer = 0; } else { s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start + n; } } stbi_inline static stbi_uc stbi__get8(stbi__context *s) { if (s->img_buffer < s->img_buffer_end) return *s->img_buffer++; if (s->read_from_callbacks) { stbi__refill_buffer(s); return *s->img_buffer++; } return 0; } stbi_inline static int stbi__at_eof(stbi__context *s) { if (s->io.read) { if (!(s->io.eof)(s->io_user_data)) return 0; // if feof() is true, check if buffer = end // special case: we've only got the special 0 character at the end if (s->read_from_callbacks == 0) return 1; } return s->img_buffer >= s->img_buffer_end; } static void stbi__skip(stbi__context *s, int n) { if (n < 0) { s->img_buffer = s->img_buffer_end; return; } if (s->io.read) { int blen = (int) (s->img_buffer_end - s->img_buffer); if (blen < n) { s->img_buffer = s->img_buffer_end; (s->io.skip)(s->io_user_data, n - blen); return; } } s->img_buffer += n; } static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) { if (s->io.read) { int blen = (int) (s->img_buffer_end - s->img_buffer); if (blen < n) { int res, count; memcpy(buffer, s->img_buffer, blen); count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); res = (count == (n-blen)); s->img_buffer = s->img_buffer_end; return res; } } if (s->img_buffer+n <= s->img_buffer_end) { memcpy(buffer, s->img_buffer, n); s->img_buffer += n; return 1; } else return 0; } static int stbi__get16be(stbi__context *s) { int z = stbi__get8(s); return (z << 8) + stbi__get8(s); } static stbi__uint32 stbi__get32be(stbi__context *s) { stbi__uint32 z = stbi__get16be(s); return (z << 16) + stbi__get16be(s); } #if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) // nothing #else static int stbi__get16le(stbi__context *s) { int z = stbi__get8(s); return z + (stbi__get8(s) << 8); } #endif #ifndef STBI_NO_BMP static stbi__uint32 stbi__get32le(stbi__context *s) { stbi__uint32 z = stbi__get16le(s); return z + (stbi__get16le(s) << 16); } #endif #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings ////////////////////////////////////////////////////////////////////////////// // // generic converter from built-in img_n to req_comp // individual types do this automatically as much as possible (e.g. jpeg // does all cases internally since it needs to colorspace convert anyway, // and it never has alpha, so very few cases ). png can automatically // interleave an alpha=255 channel, but falls back to this for other cases // // assume data buffer is malloced, so malloc a new one and free that one // only failure mode is malloc failing static stbi_uc stbi__compute_y(int r, int g, int b) { return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); } static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i,j; unsigned char *good; if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); good = (unsigned char *) stbi__malloc(req_comp * x * y); if (good == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } for (j=0; j < (int) y; ++j) { unsigned char *src = data + j * x * img_n ; unsigned char *dest = good + j * x * req_comp; #define COMBO(a,b) ((a)*8+(b)) #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch (COMBO(img_n, req_comp)) { CASE(1,2) dest[0]=src[0], dest[1]=255; break; CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break; CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break; CASE(2,1) dest[0]=src[0]; break; CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break; CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break; CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break; CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break; CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break; CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break; CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break; CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break; default: STBI_ASSERT(0); } #undef CASE } STBI_FREE(data); return good; } #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) { int i,k,n; float *output = (float *) stbi__malloc(x * y * comp * sizeof(float)); if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); } if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f; } STBI_FREE(data); return output; } #endif #ifndef STBI_NO_HDR #define stbi__float2int(x) ((int) (x)) static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) { int i,k,n; stbi_uc *output = (stbi_uc *) stbi__malloc(x * y * comp); if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (stbi_uc) stbi__float2int(z); } if (k < comp) { float z = data[i*comp+k] * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (stbi_uc) stbi__float2int(z); } } STBI_FREE(data); return output; } #endif ////////////////////////////////////////////////////////////////////////////// // // "baseline" JPEG/JFIF decoder // // simple implementation // - doesn't support delayed output of y-dimension // - simple interface (only one output format: 8-bit interleaved RGB) // - doesn't try to recover corrupt jpegs // - doesn't allow partial loading, loading multiple at once // - still fast on x86 (copying globals into locals doesn't help x86) // - allocates lots of intermediate memory (full size of all components) // - non-interleaved case requires this anyway // - allows good upsampling (see next) // high-quality // - upsampled channels are bilinearly interpolated, even across blocks // - quality integer IDCT derived from IJG's 'slow' // performance // - fast huffman; reasonable integer IDCT // - some SIMD kernels for common paths on targets with SSE2/NEON // - uses a lot of intermediate memory, could cache poorly #ifndef STBI_NO_JPEG // huffman decoding acceleration #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache typedef struct { stbi_uc fast[1 << FAST_BITS]; // weirdly, repacking this into AoS is a 10% speed loss, instead of a win stbi__uint16 code[256]; stbi_uc values[256]; stbi_uc size[257]; unsigned int maxcode[18]; int delta[17]; // old 'firstsymbol' - old 'firstcode' } stbi__huffman; typedef struct { stbi__context *s; stbi__huffman huff_dc[4]; stbi__huffman huff_ac[4]; stbi_uc dequant[4][64]; stbi__int16 fast_ac[4][1 << FAST_BITS]; // sizes for components, interleaved MCUs int img_h_max, img_v_max; int img_mcu_x, img_mcu_y; int img_mcu_w, img_mcu_h; // definition of jpeg image component struct { int id; int h,v; int tq; int hd,ha; int dc_pred; int x,y,w2,h2; stbi_uc *data; void *raw_data, *raw_coeff; stbi_uc *linebuf; short *coeff; // progressive only int coeff_w, coeff_h; // number of 8x8 coefficient blocks } img_comp[4]; stbi__uint32 code_buffer; // jpeg entropy-coded buffer int code_bits; // number of valid bits unsigned char marker; // marker seen while filling entropy buffer int nomore; // flag if we saw a marker so must stop int progressive; int spec_start; int spec_end; int succ_high; int succ_low; int eob_run; int scan_n, order[4]; int restart_interval, todo; // kernels void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); } stbi__jpeg; static int stbi__build_huffman(stbi__huffman *h, int *count) { int i,j,k=0,code; // build size list for each symbol (from JPEG spec) for (i=0; i < 16; ++i) for (j=0; j < count[i]; ++j) h->size[k++] = (stbi_uc) (i+1); h->size[k] = 0; // compute actual symbols (from jpeg spec) code = 0; k = 0; for(j=1; j <= 16; ++j) { // compute delta to add to code to compute symbol id h->delta[j] = k - code; if (h->size[k] == j) { while (h->size[k] == j) h->code[k++] = (stbi__uint16) (code++); if (code-1 >= (1 << j)) return stbi__err("bad code lengths","Corrupt JPEG"); } // compute largest code + 1 for this size, preshifted as needed later h->maxcode[j] = code << (16-j); code <<= 1; } h->maxcode[j] = 0xffffffff; // build non-spec acceleration table; 255 is flag for not-accelerated memset(h->fast, 255, 1 << FAST_BITS); for (i=0; i < k; ++i) { int s = h->size[i]; if (s <= FAST_BITS) { int c = h->code[i] << (FAST_BITS-s); int m = 1 << (FAST_BITS-s); for (j=0; j < m; ++j) { h->fast[c+j] = (stbi_uc) i; } } } return 1; } // build a table that decodes both magnitude and value of small ACs in // one go. static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) { int i; for (i=0; i < (1 << FAST_BITS); ++i) { stbi_uc fast = h->fast[i]; fast_ac[i] = 0; if (fast < 255) { int rs = h->values[fast]; int run = (rs >> 4) & 15; int magbits = rs & 15; int len = h->size[fast]; if (magbits && len + magbits <= FAST_BITS) { // magnitude code followed by receive_extend code int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); int m = 1 << (magbits - 1); if (k < m) k += (-1 << magbits) + 1; // if the result is small enough, we can fit it in fast_ac table if (k >= -128 && k <= 127) fast_ac[i] = (stbi__int16) ((k << 8) + (run << 4) + (len + magbits)); } } } } static void stbi__grow_buffer_unsafe(stbi__jpeg *j) { do { int b = j->nomore ? 0 : stbi__get8(j->s); if (b == 0xff) { int c = stbi__get8(j->s); if (c != 0) { j->marker = (unsigned char) c; j->nomore = 1; return; } } j->code_buffer |= b << (24 - j->code_bits); j->code_bits += 8; } while (j->code_bits <= 24); } // (1 << n) - 1 static stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; // decode a jpeg huffman value from the bitstream stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) { unsigned int temp; int c,k; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); // look at the top FAST_BITS and determine what symbol ID it is, // if the code is <= FAST_BITS c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); k = h->fast[c]; if (k < 255) { int s = h->size[k]; if (s > j->code_bits) return -1; j->code_buffer <<= s; j->code_bits -= s; return h->values[k]; } // naive test is to shift the code_buffer down so k bits are // valid, then test against maxcode. To speed this up, we've // preshifted maxcode left so that it has (16-k) 0s at the // end; in other words, regardless of the number of bits, it // wants to be compared against something shifted to have 16; // that way we don't need to shift inside the loop. temp = j->code_buffer >> 16; for (k=FAST_BITS+1 ; ; ++k) if (temp < h->maxcode[k]) break; if (k == 17) { // error! code not found j->code_bits -= 16; return -1; } if (k > j->code_bits) return -1; // convert the huffman code to the symbol id c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); // convert the id to a symbol j->code_bits -= k; j->code_buffer <<= k; return h->values[c]; } // bias[n] = (-1<<n) + 1 static int const stbi__jbias[16] = {0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767}; // combined JPEG 'receive' and JPEG 'extend', since baseline // always extends everything it receives. stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n) { unsigned int k; int sgn; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB k = stbi_lrot(j->code_buffer, n); STBI_ASSERT(n >= 0 && n < (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; return k + (stbi__jbias[n] & ~sgn); } // get some unsigned bits stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) { unsigned int k; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); k = stbi_lrot(j->code_buffer, n); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; return k; } stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) { unsigned int k; if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); k = j->code_buffer; j->code_buffer <<= 1; --j->code_bits; return k & 0x80000000; } // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? static stbi_uc stbi__jpeg_dezigzag[64+15] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, // let corrupt input sample past end 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 }; // decode one 64-entry block-- static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi_uc *dequant) { int diff,dc,k; int t; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); t = stbi__jpeg_huff_decode(j, hdc); if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG"); // 0 all the ac values now so we can do it 32-bits at a time memset(data,0,64*sizeof(data[0])); diff = t ? stbi__extend_receive(j, t) : 0; dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; data[0] = (short) (dc * dequant[0]); // decode AC components, see JPEG spec k = 1; do { unsigned int zig; int c,r,s; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); r = fac[c]; if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length j->code_buffer <<= s; j->code_bits -= s; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) * dequant[zig]); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (rs != 0xf0) break; // end block k += 16; } else { k += r; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); } } } while (k < 64); return 1; } static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) { int diff,dc; int t; if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); if (j->succ_high == 0) { // first scan for DC coefficient, must be first memset(data,0,64*sizeof(data[0])); // 0 all the ac values now t = stbi__jpeg_huff_decode(j, hdc); diff = t ? stbi__extend_receive(j, t) : 0; dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; data[0] = (short) (dc << j->succ_low); } else { // refinement scan for DC coefficient if (stbi__jpeg_get_bit(j)) data[0] += (short) (1 << j->succ_low); } return 1; } // @OPTIMIZE: store non-zigzagged during the decode passes, // and only de-zigzag when dequantizing static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) { int k; if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->succ_high == 0) { int shift = j->succ_low; if (j->eob_run) { --j->eob_run; return 1; } k = j->spec_start; do { unsigned int zig; int c,r,s; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); r = fac[c]; if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length j->code_buffer <<= s; j->code_bits -= s; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) << shift); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (r < 15) { j->eob_run = (1 << r); if (r) j->eob_run += stbi__jpeg_get_bits(j, r); --j->eob_run; break; } k += 16; } else { k += r; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) (stbi__extend_receive(j,s) << shift); } } } while (k <= j->spec_end); } else { // refinement scan for these AC coefficients short bit = (short) (1 << j->succ_low); if (j->eob_run) { --j->eob_run; for (k = j->spec_start; k <= j->spec_end; ++k) { short *p = &data[stbi__jpeg_dezigzag[k]]; if (*p != 0) if (stbi__jpeg_get_bit(j)) if ((*p & bit)==0) { if (*p > 0) *p += bit; else *p -= bit; } } } else { k = j->spec_start; do { int r,s; int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (r < 15) { j->eob_run = (1 << r) - 1; if (r) j->eob_run += stbi__jpeg_get_bits(j, r); r = 64; // force end of block } else { // r=15 s=0 should write 16 0s, so we just do // a run of 15 0s and then write s (which is 0), // so we don't have to do anything special here } } else { if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); // sign bit if (stbi__jpeg_get_bit(j)) s = bit; else s = -bit; } // advance by r while (k <= j->spec_end) { short *p = &data[stbi__jpeg_dezigzag[k++]]; if (*p != 0) { if (stbi__jpeg_get_bit(j)) if ((*p & bit)==0) { if (*p > 0) *p += bit; else *p -= bit; } } else { if (r == 0) { *p = (short) s; break; } --r; } } } while (k <= j->spec_end); } } return 1; } // take a -128..127 value and stbi__clamp it and convert to 0..255 stbi_inline static stbi_uc stbi__clamp(int x) { // trick to use a single test to catch both cases if ((unsigned int) x > 255) { if (x < 0) return 0; if (x > 255) return 255; } return (stbi_uc) x; } #define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) #define stbi__fsh(x) ((x) << 12) // derived from jidctint -- DCT_ISLOW #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ p2 = s2; \ p3 = s6; \ p1 = (p2+p3) * stbi__f2f(0.5411961f); \ t2 = p1 + p3*stbi__f2f(-1.847759065f); \ t3 = p1 + p2*stbi__f2f( 0.765366865f); \ p2 = s0; \ p3 = s4; \ t0 = stbi__fsh(p2+p3); \ t1 = stbi__fsh(p2-p3); \ x0 = t0+t3; \ x3 = t0-t3; \ x1 = t1+t2; \ x2 = t1-t2; \ t0 = s7; \ t1 = s5; \ t2 = s3; \ t3 = s1; \ p3 = t0+t2; \ p4 = t1+t3; \ p1 = t0+t3; \ p2 = t1+t2; \ p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ t0 = t0*stbi__f2f( 0.298631336f); \ t1 = t1*stbi__f2f( 2.053119869f); \ t2 = t2*stbi__f2f( 3.072711026f); \ t3 = t3*stbi__f2f( 1.501321110f); \ p1 = p5 + p1*stbi__f2f(-0.899976223f); \ p2 = p5 + p2*stbi__f2f(-2.562915447f); \ p3 = p3*stbi__f2f(-1.961570560f); \ p4 = p4*stbi__f2f(-0.390180644f); \ t3 += p1+p4; \ t2 += p2+p3; \ t1 += p2+p4; \ t0 += p1+p3; static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) { int i,val[64],*v=val; stbi_uc *o; short *d = data; // columns for (i=0; i < 8; ++i,++d, ++v) { // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 && d[40]==0 && d[48]==0 && d[56]==0) { // no shortcut 0 seconds // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds int dcterm = d[0] << 2; v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) // constants scaled things up by 1<<12; let's bring them back // down, but keep 2 extra bits of precision x0 += 512; x1 += 512; x2 += 512; x3 += 512; v[ 0] = (x0+t3) >> 10; v[56] = (x0-t3) >> 10; v[ 8] = (x1+t2) >> 10; v[48] = (x1-t2) >> 10; v[16] = (x2+t1) >> 10; v[40] = (x2-t1) >> 10; v[24] = (x3+t0) >> 10; v[32] = (x3-t0) >> 10; } } for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { // no fast case since the first 1D IDCT spread components out STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) // constants scaled things up by 1<<12, plus we had 1<<2 from first // loop, plus horizontal and vertical each scale by sqrt(8) so together // we've got an extra 1<<3, so 1<<17 total we need to remove. // so we want to round that, which means adding 0.5 * 1<<17, // aka 65536. Also, we'll end up with -128 to 127 that we want // to encode as 0..255 by adding 128, so we'll add that before the shift x0 += 65536 + (128<<17); x1 += 65536 + (128<<17); x2 += 65536 + (128<<17); x3 += 65536 + (128<<17); // tried computing the shifts into temps, or'ing the temps to see // if any were out of range, but that was slower o[0] = stbi__clamp((x0+t3) >> 17); o[7] = stbi__clamp((x0-t3) >> 17); o[1] = stbi__clamp((x1+t2) >> 17); o[6] = stbi__clamp((x1-t2) >> 17); o[2] = stbi__clamp((x2+t1) >> 17); o[5] = stbi__clamp((x2-t1) >> 17); o[3] = stbi__clamp((x3+t0) >> 17); o[4] = stbi__clamp((x3-t0) >> 17); } } #ifdef STBI_SSE2 // sse2 integer IDCT. not the fastest possible implementation but it // produces bit-identical results to the generic C version so it's // fully "transparent". static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) { // This is constructed to match our regular (generic) integer IDCT exactly. __m128i row0, row1, row2, row3, row4, row5, row6, row7; __m128i tmp; // dot product constant: even elems=x, odd elems=y #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) // out(1) = c1[even]*x + c1[odd]*y #define dct_rot(out0,out1, x,y,c0,c1) \ __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) // out = in << 12 (in 16-bit, out 32-bit) #define dct_widen(out, in) \ __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) // wide add #define dct_wadd(out, a, b) \ __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ __m128i out##_h = _mm_add_epi32(a##_h, b##_h) // wide sub #define dct_wsub(out, a, b) \ __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) // butterfly a/b, add bias, then shift by "s" and pack #define dct_bfly32o(out0, out1, a,b,bias,s) \ { \ __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ dct_wadd(sum, abiased, b); \ dct_wsub(dif, abiased, b); \ out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ } // 8-bit interleave step (for transposes) #define dct_interleave8(a, b) \ tmp = a; \ a = _mm_unpacklo_epi8(a, b); \ b = _mm_unpackhi_epi8(tmp, b) // 16-bit interleave step (for transposes) #define dct_interleave16(a, b) \ tmp = a; \ a = _mm_unpacklo_epi16(a, b); \ b = _mm_unpackhi_epi16(tmp, b) #define dct_pass(bias,shift) \ { \ /* even part */ \ dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ __m128i sum04 = _mm_add_epi16(row0, row4); \ __m128i dif04 = _mm_sub_epi16(row0, row4); \ dct_widen(t0e, sum04); \ dct_widen(t1e, dif04); \ dct_wadd(x0, t0e, t3e); \ dct_wsub(x3, t0e, t3e); \ dct_wadd(x1, t1e, t2e); \ dct_wsub(x2, t1e, t2e); \ /* odd part */ \ dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ __m128i sum17 = _mm_add_epi16(row1, row7); \ __m128i sum35 = _mm_add_epi16(row3, row5); \ dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ dct_wadd(x4, y0o, y4o); \ dct_wadd(x5, y1o, y5o); \ dct_wadd(x6, y2o, y5o); \ dct_wadd(x7, y3o, y4o); \ dct_bfly32o(row0,row7, x0,x7,bias,shift); \ dct_bfly32o(row1,row6, x1,x6,bias,shift); \ dct_bfly32o(row2,row5, x2,x5,bias,shift); \ dct_bfly32o(row3,row4, x3,x4,bias,shift); \ } __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); // rounding biases in column/row passes, see stbi__idct_block for explanation. __m128i bias_0 = _mm_set1_epi32(512); __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); // load row0 = _mm_load_si128((const __m128i *) (data + 0*8)); row1 = _mm_load_si128((const __m128i *) (data + 1*8)); row2 = _mm_load_si128((const __m128i *) (data + 2*8)); row3 = _mm_load_si128((const __m128i *) (data + 3*8)); row4 = _mm_load_si128((const __m128i *) (data + 4*8)); row5 = _mm_load_si128((const __m128i *) (data + 5*8)); row6 = _mm_load_si128((const __m128i *) (data + 6*8)); row7 = _mm_load_si128((const __m128i *) (data + 7*8)); // column pass dct_pass(bias_0, 10); { // 16bit 8x8 transpose pass 1 dct_interleave16(row0, row4); dct_interleave16(row1, row5); dct_interleave16(row2, row6); dct_interleave16(row3, row7); // transpose pass 2 dct_interleave16(row0, row2); dct_interleave16(row1, row3); dct_interleave16(row4, row6); dct_interleave16(row5, row7); // transpose pass 3 dct_interleave16(row0, row1); dct_interleave16(row2, row3); dct_interleave16(row4, row5); dct_interleave16(row6, row7); } // row pass dct_pass(bias_1, 17); { // pack __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 __m128i p1 = _mm_packus_epi16(row2, row3); __m128i p2 = _mm_packus_epi16(row4, row5); __m128i p3 = _mm_packus_epi16(row6, row7); // 8bit 8x8 transpose pass 1 dct_interleave8(p0, p2); // a0e0a1e1... dct_interleave8(p1, p3); // c0g0c1g1... // transpose pass 2 dct_interleave8(p0, p1); // a0c0e0g0... dct_interleave8(p2, p3); // b0d0f0h0... // transpose pass 3 dct_interleave8(p0, p2); // a0b0c0d0... dct_interleave8(p1, p3); // a4b4c4d4... // store _mm_storel_epi64((__m128i *) out, p0); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p2); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p1); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p3); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); } #undef dct_const #undef dct_rot #undef dct_widen #undef dct_wadd #undef dct_wsub #undef dct_bfly32o #undef dct_interleave8 #undef dct_interleave16 #undef dct_pass } #endif // STBI_SSE2 #ifdef STBI_NEON // NEON integer IDCT. should produce bit-identical // results to the generic C version. static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) { int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); #define dct_long_mul(out, inq, coeff) \ int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) #define dct_long_mac(out, acc, inq, coeff) \ int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) #define dct_widen(out, inq) \ int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) // wide add #define dct_wadd(out, a, b) \ int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ int32x4_t out##_h = vaddq_s32(a##_h, b##_h) // wide sub #define dct_wsub(out, a, b) \ int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ int32x4_t out##_h = vsubq_s32(a##_h, b##_h) // butterfly a/b, then shift using "shiftop" by "s" and pack #define dct_bfly32o(out0,out1, a,b,shiftop,s) \ { \ dct_wadd(sum, a, b); \ dct_wsub(dif, a, b); \ out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ } #define dct_pass(shiftop, shift) \ { \ /* even part */ \ int16x8_t sum26 = vaddq_s16(row2, row6); \ dct_long_mul(p1e, sum26, rot0_0); \ dct_long_mac(t2e, p1e, row6, rot0_1); \ dct_long_mac(t3e, p1e, row2, rot0_2); \ int16x8_t sum04 = vaddq_s16(row0, row4); \ int16x8_t dif04 = vsubq_s16(row0, row4); \ dct_widen(t0e, sum04); \ dct_widen(t1e, dif04); \ dct_wadd(x0, t0e, t3e); \ dct_wsub(x3, t0e, t3e); \ dct_wadd(x1, t1e, t2e); \ dct_wsub(x2, t1e, t2e); \ /* odd part */ \ int16x8_t sum15 = vaddq_s16(row1, row5); \ int16x8_t sum17 = vaddq_s16(row1, row7); \ int16x8_t sum35 = vaddq_s16(row3, row5); \ int16x8_t sum37 = vaddq_s16(row3, row7); \ int16x8_t sumodd = vaddq_s16(sum17, sum35); \ dct_long_mul(p5o, sumodd, rot1_0); \ dct_long_mac(p1o, p5o, sum17, rot1_1); \ dct_long_mac(p2o, p5o, sum35, rot1_2); \ dct_long_mul(p3o, sum37, rot2_0); \ dct_long_mul(p4o, sum15, rot2_1); \ dct_wadd(sump13o, p1o, p3o); \ dct_wadd(sump24o, p2o, p4o); \ dct_wadd(sump23o, p2o, p3o); \ dct_wadd(sump14o, p1o, p4o); \ dct_long_mac(x4, sump13o, row7, rot3_0); \ dct_long_mac(x5, sump24o, row5, rot3_1); \ dct_long_mac(x6, sump23o, row3, rot3_2); \ dct_long_mac(x7, sump14o, row1, rot3_3); \ dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ } // load row0 = vld1q_s16(data + 0*8); row1 = vld1q_s16(data + 1*8); row2 = vld1q_s16(data + 2*8); row3 = vld1q_s16(data + 3*8); row4 = vld1q_s16(data + 4*8); row5 = vld1q_s16(data + 5*8); row6 = vld1q_s16(data + 6*8); row7 = vld1q_s16(data + 7*8); // add DC bias row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); // column pass dct_pass(vrshrn_n_s32, 10); // 16bit 8x8 transpose { // these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. // whether compilers actually get this is another story, sadly. #define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } #define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } #define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } // pass 1 dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 dct_trn16(row2, row3); dct_trn16(row4, row5); dct_trn16(row6, row7); // pass 2 dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 dct_trn32(row1, row3); dct_trn32(row4, row6); dct_trn32(row5, row7); // pass 3 dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 dct_trn64(row1, row5); dct_trn64(row2, row6); dct_trn64(row3, row7); #undef dct_trn16 #undef dct_trn32 #undef dct_trn64 } // row pass // vrshrn_n_s32 only supports shifts up to 16, we need // 17. so do a non-rounding shift of 16 first then follow // up with a rounding shift by 1. dct_pass(vshrn_n_s32, 16); { // pack and round uint8x8_t p0 = vqrshrun_n_s16(row0, 1); uint8x8_t p1 = vqrshrun_n_s16(row1, 1); uint8x8_t p2 = vqrshrun_n_s16(row2, 1); uint8x8_t p3 = vqrshrun_n_s16(row3, 1); uint8x8_t p4 = vqrshrun_n_s16(row4, 1); uint8x8_t p5 = vqrshrun_n_s16(row5, 1); uint8x8_t p6 = vqrshrun_n_s16(row6, 1); uint8x8_t p7 = vqrshrun_n_s16(row7, 1); // again, these can translate into one instruction, but often don't. #define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } #define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } #define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } // sadly can't use interleaved stores here since we only write // 8 bytes to each scan line! // 8x8 8-bit transpose pass 1 dct_trn8_8(p0, p1); dct_trn8_8(p2, p3); dct_trn8_8(p4, p5); dct_trn8_8(p6, p7); // pass 2 dct_trn8_16(p0, p2); dct_trn8_16(p1, p3); dct_trn8_16(p4, p6); dct_trn8_16(p5, p7); // pass 3 dct_trn8_32(p0, p4); dct_trn8_32(p1, p5); dct_trn8_32(p2, p6); dct_trn8_32(p3, p7); // store vst1_u8(out, p0); out += out_stride; vst1_u8(out, p1); out += out_stride; vst1_u8(out, p2); out += out_stride; vst1_u8(out, p3); out += out_stride; vst1_u8(out, p4); out += out_stride; vst1_u8(out, p5); out += out_stride; vst1_u8(out, p6); out += out_stride; vst1_u8(out, p7); #undef dct_trn8_8 #undef dct_trn8_16 #undef dct_trn8_32 } #undef dct_long_mul #undef dct_long_mac #undef dct_widen #undef dct_wadd #undef dct_wsub #undef dct_bfly32o #undef dct_pass } #endif // STBI_NEON #define STBI__MARKER_none 0xff // if there's a pending marker from the entropy stream, return that // otherwise, fetch from the stream and get a marker. if there's no // marker, return 0xff, which is never a valid marker value static stbi_uc stbi__get_marker(stbi__jpeg *j) { stbi_uc x; if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } x = stbi__get8(j->s); if (x != 0xff) return STBI__MARKER_none; while (x == 0xff) x = stbi__get8(j->s); return x; } // in each scan, we'll have scan_n components, and the order // of the components is specified by order[] #define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) // after a restart interval, stbi__jpeg_reset the entropy decoder and // the dc prediction static void stbi__jpeg_reset(stbi__jpeg *j) { j->code_bits = 0; j->code_buffer = 0; j->nomore = 0; j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0; j->marker = STBI__MARKER_none; j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; j->eob_run = 0; // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, // since we don't even allow 1<<30 pixels } static int stbi__parse_entropy_coded_data(stbi__jpeg *z) { stbi__jpeg_reset(z); if (!z->progressive) { if (z->scan_n == 1) { int i,j; STBI_SIMD_ALIGN(short, data[64]); int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); // if it's NOT a restart, then just bail, so we get corrupt data // rather than no data if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } else { // interleaved int i,j,k,x,y; STBI_SIMD_ALIGN(short, data[64]); for (j=0; j < z->img_mcu_y; ++j) { for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x)*8; int y2 = (j*z->img_comp[n].v + y)*8; int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } } else { if (z->scan_n == 1) { int i,j; int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); if (z->spec_start == 0) { if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } else { int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) return 0; } // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } else { // interleaved int i,j,k,x,y; for (j=0; j < z->img_mcu_y; ++j) { for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x); int y2 = (j*z->img_comp[n].v + y); short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } } } static void stbi__jpeg_dequantize(short *data, stbi_uc *dequant) { int i; for (i=0; i < 64; ++i) data[i] *= dequant[i]; } static void stbi__jpeg_finish(stbi__jpeg *z) { if (z->progressive) { // dequantize and idct the data int i,j,n; for (n=0; n < z->s->img_n; ++n) { int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); } } } } } static int stbi__process_marker(stbi__jpeg *z, int m) { int L; switch (m) { case STBI__MARKER_none: // no marker found return stbi__err("expected marker","Corrupt JPEG"); case 0xDD: // DRI - specify restart interval if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); z->restart_interval = stbi__get16be(z->s); return 1; case 0xDB: // DQT - define quantization table L = stbi__get16be(z->s)-2; while (L > 0) { int q = stbi__get8(z->s); int p = q >> 4; int t = q & 15,i; if (p != 0) return stbi__err("bad DQT type","Corrupt JPEG"); if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); for (i=0; i < 64; ++i) z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8(z->s); L -= 65; } return L==0; case 0xC4: // DHT - define huffman table L = stbi__get16be(z->s)-2; while (L > 0) { stbi_uc *v; int sizes[16],i,n=0; int q = stbi__get8(z->s); int tc = q >> 4; int th = q & 15; if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); for (i=0; i < 16; ++i) { sizes[i] = stbi__get8(z->s); n += sizes[i]; } L -= 17; if (tc == 0) { if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; v = z->huff_dc[th].values; } else { if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; v = z->huff_ac[th].values; } for (i=0; i < n; ++i) v[i] = stbi__get8(z->s); if (tc != 0) stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); L -= n; } return L==0; } // check for comment block or APP blocks if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { stbi__skip(z->s, stbi__get16be(z->s)-2); return 1; } return 0; } // after we see SOS static int stbi__process_scan_header(stbi__jpeg *z) { int i; int Ls = stbi__get16be(z->s); z->scan_n = stbi__get8(z->s); if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); for (i=0; i < z->scan_n; ++i) { int id = stbi__get8(z->s), which; int q = stbi__get8(z->s); for (which = 0; which < z->s->img_n; ++which) if (z->img_comp[which].id == id) break; if (which == z->s->img_n) return 0; // no match z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); z->order[i] = which; } { int aa; z->spec_start = stbi__get8(z->s); z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 aa = stbi__get8(z->s); z->succ_high = (aa >> 4); z->succ_low = (aa & 15); if (z->progressive) { if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) return stbi__err("bad SOS", "Corrupt JPEG"); } else { if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); z->spec_end = 63; } } return 1; } static int stbi__process_frame_header(stbi__jpeg *z, int scan) { stbi__context *s = z->s; int Lf,p,i,q, h_max=1,v_max=1,c; Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires c = stbi__get8(s); if (c != 3 && c != 1) return stbi__err("bad component count","Corrupt JPEG"); // JFIF requires s->img_n = c; for (i=0; i < c; ++i) { z->img_comp[i].data = NULL; z->img_comp[i].linebuf = NULL; } if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); for (i=0; i < s->img_n; ++i) { z->img_comp[i].id = stbi__get8(s); if (z->img_comp[i].id != i+1) // JFIF requires if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files! return stbi__err("bad component ID","Corrupt JPEG"); q = stbi__get8(s); z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); } if (scan != STBI__SCAN_load) return 1; if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); for (i=0; i < s->img_n; ++i) { if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; } // compute interleaved mcu info z->img_h_max = h_max; z->img_v_max = v_max; z->img_mcu_w = h_max * 8; z->img_mcu_h = v_max * 8; z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; for (i=0; i < s->img_n; ++i) { // number of effective pixels (e.g. for non-interleaved MCU) z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; // to simplify generation, we'll allocate enough memory to decode // the bogus oversized data from using interleaved MCUs and their // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't // discard the extra data until colorspace conversion z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; z->img_comp[i].raw_data = stbi__malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15); if (z->img_comp[i].raw_data == NULL) { for(--i; i >= 0; --i) { STBI_FREE(z->img_comp[i].raw_data); z->img_comp[i].raw_data = NULL; } return stbi__err("outofmem", "Out of memory"); } // align blocks for idct using mmx/sse z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); z->img_comp[i].linebuf = NULL; if (z->progressive) { z->img_comp[i].coeff_w = (z->img_comp[i].w2 + 7) >> 3; z->img_comp[i].coeff_h = (z->img_comp[i].h2 + 7) >> 3; z->img_comp[i].raw_coeff = STBI_MALLOC(z->img_comp[i].coeff_w * z->img_comp[i].coeff_h * 64 * sizeof(short) + 15); z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); } else { z->img_comp[i].coeff = 0; z->img_comp[i].raw_coeff = 0; } } return 1; } // use comparisons since in some cases we handle more than one case (e.g. SOF) #define stbi__DNL(x) ((x) == 0xdc) #define stbi__SOI(x) ((x) == 0xd8) #define stbi__EOI(x) ((x) == 0xd9) #define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) #define stbi__SOS(x) ((x) == 0xda) #define stbi__SOF_progressive(x) ((x) == 0xc2) static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) { int m; z->marker = STBI__MARKER_none; // initialize cached marker to empty m = stbi__get_marker(z); if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); if (scan == STBI__SCAN_type) return 1; m = stbi__get_marker(z); while (!stbi__SOF(m)) { if (!stbi__process_marker(z,m)) return 0; m = stbi__get_marker(z); while (m == STBI__MARKER_none) { // some files have extra padding after their blocks, so ok, we'll scan if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); m = stbi__get_marker(z); } } z->progressive = stbi__SOF_progressive(m); if (!stbi__process_frame_header(z, scan)) return 0; return 1; } // decode image to YCbCr format static int stbi__decode_jpeg_image(stbi__jpeg *j) { int m; for (m = 0; m < 4; m++) { j->img_comp[m].raw_data = NULL; j->img_comp[m].raw_coeff = NULL; } j->restart_interval = 0; if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; m = stbi__get_marker(j); while (!stbi__EOI(m)) { if (stbi__SOS(m)) { if (!stbi__process_scan_header(j)) return 0; if (!stbi__parse_entropy_coded_data(j)) return 0; if (j->marker == STBI__MARKER_none ) { // handle 0s at the end of image data from IP Kamera 9060 while (!stbi__at_eof(j->s)) { int x = stbi__get8(j->s); if (x == 255) { j->marker = stbi__get8(j->s); break; } else if (x != 0) { return stbi__err("junk before marker", "Corrupt JPEG"); } } // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 } } else { if (!stbi__process_marker(j, m)) return 0; } m = stbi__get_marker(j); } if (j->progressive) stbi__jpeg_finish(j); return 1; } // static jfif-centered resampling (across block boundaries) typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, int w, int hs); #define stbi__div4(x) ((stbi_uc) ((x) >> 2)) static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { STBI_NOTUSED(out); STBI_NOTUSED(in_far); STBI_NOTUSED(w); STBI_NOTUSED(hs); return in_near; } static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate two samples vertically for every one in input int i; STBI_NOTUSED(hs); for (i=0; i < w; ++i) out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); return out; } static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate two samples horizontally for every one in input int i; stbi_uc *input = in_near; if (w == 1) { // if only one sample, can't do any interpolation out[0] = out[1] = input[0]; return out; } out[0] = input[0]; out[1] = stbi__div4(input[0]*3 + input[1] + 2); for (i=1; i < w-1; ++i) { int n = 3*input[i]+2; out[i*2+0] = stbi__div4(n+input[i-1]); out[i*2+1] = stbi__div4(n+input[i+1]); } out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); out[i*2+1] = input[w-1]; STBI_NOTUSED(in_far); STBI_NOTUSED(hs); return out; } #define stbi__div16(x) ((stbi_uc) ((x) >> 4)) static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i,t0,t1; if (w == 1) { out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); return out; } t1 = 3*in_near[0] + in_far[0]; out[0] = stbi__div4(t1+2); for (i=1; i < w; ++i) { t0 = t1; t1 = 3*in_near[i]+in_far[i]; out[i*2-1] = stbi__div16(3*t0 + t1 + 8); out[i*2 ] = stbi__div16(3*t1 + t0 + 8); } out[w*2-1] = stbi__div4(t1+2); STBI_NOTUSED(hs); return out; } #if defined(STBI_SSE2) || defined(STBI_NEON) static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i=0,t0,t1; if (w == 1) { out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); return out; } t1 = 3*in_near[0] + in_far[0]; // process groups of 8 pixels for as long as we can. // note we can't handle the last pixel in a row in this loop // because we need to handle the filter boundary conditions. for (; i < ((w-1) & ~7); i += 8) { #if defined(STBI_SSE2) // load and perform the vertical filtering pass // this uses 3*x + y = 4*x + (y - x) __m128i zero = _mm_setzero_si128(); __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); __m128i farw = _mm_unpacklo_epi8(farb, zero); __m128i nearw = _mm_unpacklo_epi8(nearb, zero); __m128i diff = _mm_sub_epi16(farw, nearw); __m128i nears = _mm_slli_epi16(nearw, 2); __m128i curr = _mm_add_epi16(nears, diff); // current row // horizontal filter works the same based on shifted vers of current // row. "prev" is current row shifted right by 1 pixel; we need to // insert the previous pixel value (from t1). // "next" is current row shifted left by 1 pixel, with first pixel // of next block of 8 pixels added in. __m128i prv0 = _mm_slli_si128(curr, 2); __m128i nxt0 = _mm_srli_si128(curr, 2); __m128i prev = _mm_insert_epi16(prv0, t1, 0); __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) // odd pixels = 3*cur + next = cur*4 + (next - cur) // note the shared term. __m128i bias = _mm_set1_epi16(8); __m128i curs = _mm_slli_epi16(curr, 2); __m128i prvd = _mm_sub_epi16(prev, curr); __m128i nxtd = _mm_sub_epi16(next, curr); __m128i curb = _mm_add_epi16(curs, bias); __m128i even = _mm_add_epi16(prvd, curb); __m128i odd = _mm_add_epi16(nxtd, curb); // interleave even and odd pixels, then undo scaling. __m128i int0 = _mm_unpacklo_epi16(even, odd); __m128i int1 = _mm_unpackhi_epi16(even, odd); __m128i de0 = _mm_srli_epi16(int0, 4); __m128i de1 = _mm_srli_epi16(int1, 4); // pack and write output __m128i outv = _mm_packus_epi16(de0, de1); _mm_storeu_si128((__m128i *) (out + i*2), outv); #elif defined(STBI_NEON) // load and perform the vertical filtering pass // this uses 3*x + y = 4*x + (y - x) uint8x8_t farb = vld1_u8(in_far + i); uint8x8_t nearb = vld1_u8(in_near + i); int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); int16x8_t curr = vaddq_s16(nears, diff); // current row // horizontal filter works the same based on shifted vers of current // row. "prev" is current row shifted right by 1 pixel; we need to // insert the previous pixel value (from t1). // "next" is current row shifted left by 1 pixel, with first pixel // of next block of 8 pixels added in. int16x8_t prv0 = vextq_s16(curr, curr, 7); int16x8_t nxt0 = vextq_s16(curr, curr, 1); int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) // odd pixels = 3*cur + next = cur*4 + (next - cur) // note the shared term. int16x8_t curs = vshlq_n_s16(curr, 2); int16x8_t prvd = vsubq_s16(prev, curr); int16x8_t nxtd = vsubq_s16(next, curr); int16x8_t even = vaddq_s16(curs, prvd); int16x8_t odd = vaddq_s16(curs, nxtd); // undo scaling and round, then store with even/odd phases interleaved uint8x8x2_t o; o.val[0] = vqrshrun_n_s16(even, 4); o.val[1] = vqrshrun_n_s16(odd, 4); vst2_u8(out + i*2, o); #endif // "previous" value for next iter t1 = 3*in_near[i+7] + in_far[i+7]; } t0 = t1; t1 = 3*in_near[i] + in_far[i]; out[i*2] = stbi__div16(3*t1 + t0 + 8); for (++i; i < w; ++i) { t0 = t1; t1 = 3*in_near[i]+in_far[i]; out[i*2-1] = stbi__div16(3*t0 + t1 + 8); out[i*2 ] = stbi__div16(3*t1 + t0 + 8); } out[w*2-1] = stbi__div4(t1+2); STBI_NOTUSED(hs); return out; } #endif static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // resample with nearest-neighbor int i,j; STBI_NOTUSED(in_far); for (i=0; i < w; ++i) for (j=0; j < hs; ++j) out[i*hs+j] = in_near[i]; return out; } #ifdef STBI_JPEG_OLD // this is the same YCbCr-to-RGB calculation that stb_image has used // historically before the algorithm changes in 1.49 #define float2fixed(x) ((int) ((x) * 65536 + 0.5)) static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) { int i; for (i=0; i < count; ++i) { int y_fixed = (y[i] << 16) + 32768; // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr*float2fixed(1.40200f); g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f); b = y_fixed + cb*float2fixed(1.77200f); r >>= 16; g >>= 16; b >>= 16; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #else // this is a reduced-precision calculation of YCbCr-to-RGB introduced // to make sure the code produces the same results in both SIMD and scalar #define float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) { int i; for (i=0; i < count; ++i) { int y_fixed = (y[i] << 20) + (1<<19); // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr* float2fixed(1.40200f); g = y_fixed + (cr*-float2fixed(0.71414f)) + ((cb*-float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #endif #if defined(STBI_SSE2) || defined(STBI_NEON) static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) { int i = 0; #ifdef STBI_SSE2 // step == 3 is pretty ugly on the final interleave, and i'm not convinced // it's useful in practice (you wouldn't use it for textures, for example). // so just accelerate step == 4 case. if (step == 4) { // this is a fairly straightforward implementation and not super-optimized. __m128i signflip = _mm_set1_epi8(-0x80); __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); __m128i xw = _mm_set1_epi16(255); // alpha channel for (; i+7 < count; i += 8) { // load __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 // unpack to short (and left-shift cr, cb by 8) __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); // color transform __m128i yws = _mm_srli_epi16(yw, 4); __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); __m128i rws = _mm_add_epi16(cr0, yws); __m128i gwt = _mm_add_epi16(cb0, yws); __m128i bws = _mm_add_epi16(yws, cb1); __m128i gws = _mm_add_epi16(gwt, cr1); // descale __m128i rw = _mm_srai_epi16(rws, 4); __m128i bw = _mm_srai_epi16(bws, 4); __m128i gw = _mm_srai_epi16(gws, 4); // back to byte, set up for transpose __m128i brb = _mm_packus_epi16(rw, bw); __m128i gxb = _mm_packus_epi16(gw, xw); // transpose to interleave channels __m128i t0 = _mm_unpacklo_epi8(brb, gxb); __m128i t1 = _mm_unpackhi_epi8(brb, gxb); __m128i o0 = _mm_unpacklo_epi16(t0, t1); __m128i o1 = _mm_unpackhi_epi16(t0, t1); // store _mm_storeu_si128((__m128i *) (out + 0), o0); _mm_storeu_si128((__m128i *) (out + 16), o1); out += 32; } } #endif #ifdef STBI_NEON // in this version, step=3 support would be easy to add. but is there demand? if (step == 4) { // this is a fairly straightforward implementation and not super-optimized. uint8x8_t signflip = vdup_n_u8(0x80); int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); for (; i+7 < count; i += 8) { // load uint8x8_t y_bytes = vld1_u8(y + i); uint8x8_t cr_bytes = vld1_u8(pcr + i); uint8x8_t cb_bytes = vld1_u8(pcb + i); int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); // expand to s16 int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); int16x8_t crw = vshll_n_s8(cr_biased, 7); int16x8_t cbw = vshll_n_s8(cb_biased, 7); // color transform int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); int16x8_t rws = vaddq_s16(yws, cr0); int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); int16x8_t bws = vaddq_s16(yws, cb1); // undo scaling, round, convert to byte uint8x8x4_t o; o.val[0] = vqrshrun_n_s16(rws, 4); o.val[1] = vqrshrun_n_s16(gws, 4); o.val[2] = vqrshrun_n_s16(bws, 4); o.val[3] = vdup_n_u8(255); // store, interleaving r/g/b/a vst4_u8(out, o); out += 8*4; } } #endif for (; i < count; ++i) { int y_fixed = (y[i] << 20) + (1<<19); // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr* float2fixed(1.40200f); g = y_fixed + cr*-float2fixed(0.71414f) + ((cb*-float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #endif // set up the kernels static void stbi__setup_jpeg(stbi__jpeg *j) { j->idct_block_kernel = stbi__idct_block; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; #ifdef STBI_SSE2 if (stbi__sse2_available()) { j->idct_block_kernel = stbi__idct_simd; #ifndef STBI_JPEG_OLD j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; #endif j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; } #endif #ifdef STBI_NEON j->idct_block_kernel = stbi__idct_simd; #ifndef STBI_JPEG_OLD j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; #endif j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; #endif } // clean up the temporary component buffers static void stbi__cleanup_jpeg(stbi__jpeg *j) { int i; for (i=0; i < j->s->img_n; ++i) { if (j->img_comp[i].raw_data) { STBI_FREE(j->img_comp[i].raw_data); j->img_comp[i].raw_data = NULL; j->img_comp[i].data = NULL; } if (j->img_comp[i].raw_coeff) { STBI_FREE(j->img_comp[i].raw_coeff); j->img_comp[i].raw_coeff = 0; j->img_comp[i].coeff = 0; } if (j->img_comp[i].linebuf) { STBI_FREE(j->img_comp[i].linebuf); j->img_comp[i].linebuf = NULL; } } } typedef struct { resample_row_func resample; stbi_uc *line0,*line1; int hs,vs; // expansion factor in each axis int w_lores; // horizontal pixels pre-expansion int ystep; // how far through vertical expansion we are int ypos; // which pre-expansion row we're on } stbi__resample; static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) { int n, decode_n; z->s->img_n = 0; // make stbi__cleanup_jpeg safe // validate req_comp if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); // load a jpeg image from whichever source, but leave in YCbCr format if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } // determine actual number of components to generate n = req_comp ? req_comp : z->s->img_n; if (z->s->img_n == 3 && n < 3) decode_n = 1; else decode_n = z->s->img_n; // resample and color-convert { int k; unsigned int i,j; stbi_uc *output; stbi_uc *coutput[4]; stbi__resample res_comp[4]; for (k=0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; // allocate line buffer big enough for upsampling off the edges // with upsample factor of 4 z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } r->hs = z->img_h_max / z->img_comp[k].h; r->vs = z->img_v_max / z->img_comp[k].v; r->ystep = r->vs >> 1; r->w_lores = (z->s->img_x + r->hs-1) / r->hs; r->ypos = 0; r->line0 = r->line1 = z->img_comp[k].data; if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; else r->resample = stbi__resample_row_generic; } // can't error after this so, this is safe output = (stbi_uc *) stbi__malloc(n * z->s->img_x * z->s->img_y + 1); if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } // now go ahead and resample for (j=0; j < z->s->img_y; ++j) { stbi_uc *out = output + n * z->s->img_x * j; for (k=0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; int y_bot = r->ystep >= (r->vs >> 1); coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, y_bot ? r->line0 : r->line1, r->w_lores, r->hs); if (++r->ystep >= r->vs) { r->ystep = 0; r->line0 = r->line1; if (++r->ypos < z->img_comp[k].y) r->line1 += z->img_comp[k].w2; } } if (n >= 3) { stbi_uc *y = coutput[0]; if (z->s->img_n == 3) { z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); } else for (i=0; i < z->s->img_x; ++i) { out[0] = out[1] = out[2] = y[i]; out[3] = 255; // not used if n==3 out += n; } } else { stbi_uc *y = coutput[0]; if (n == 1) for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; else for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255; } } stbi__cleanup_jpeg(z); *out_x = z->s->img_x; *out_y = z->s->img_y; if (comp) *comp = z->s->img_n; // report original components, not output return output; } } static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi__jpeg j; j.s = s; stbi__setup_jpeg(&j); return load_jpeg_image(&j, x,y,comp,req_comp); } static int stbi__jpeg_test(stbi__context *s) { int r; stbi__jpeg j; j.s = s; stbi__setup_jpeg(&j); r = stbi__decode_jpeg_header(&j, STBI__SCAN_type); stbi__rewind(s); return r; } static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) { if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { stbi__rewind( j->s ); return 0; } if (x) *x = j->s->img_x; if (y) *y = j->s->img_y; if (comp) *comp = j->s->img_n; return 1; } static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) { stbi__jpeg j; j.s = s; return stbi__jpeg_info_raw(&j, x, y, comp); } #endif // public domain zlib decode v0.2 Sean Barrett 2006-11-18 // simple implementation // - all input must be provided in an upfront buffer // - all output is written to a single output buffer (can malloc/realloc) // performance // - fast huffman #ifndef STBI_NO_ZLIB // fast-way is faster to check than jpeg huffman, but slow way is slower #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) // zlib-style huffman encoding // (jpegs packs from left, zlib from right, so can't share code) typedef struct { stbi__uint16 fast[1 << STBI__ZFAST_BITS]; stbi__uint16 firstcode[16]; int maxcode[17]; stbi__uint16 firstsymbol[16]; stbi_uc size[288]; stbi__uint16 value[288]; } stbi__zhuffman; stbi_inline static int stbi__bitreverse16(int n) { n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); return n; } stbi_inline static int stbi__bit_reverse(int v, int bits) { STBI_ASSERT(bits <= 16); // to bit reverse n bits, reverse 16 and shift // e.g. 11 bits, bit reverse and shift away 5 return stbi__bitreverse16(v) >> (16-bits); } static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num) { int i,k=0; int code, next_code[16], sizes[17]; // DEFLATE spec for generating codes memset(sizes, 0, sizeof(sizes)); memset(z->fast, 0, sizeof(z->fast)); for (i=0; i < num; ++i) ++sizes[sizelist[i]]; sizes[0] = 0; for (i=1; i < 16; ++i) if (sizes[i] > (1 << i)) return stbi__err("bad sizes", "Corrupt PNG"); code = 0; for (i=1; i < 16; ++i) { next_code[i] = code; z->firstcode[i] = (stbi__uint16) code; z->firstsymbol[i] = (stbi__uint16) k; code = (code + sizes[i]); if (sizes[i]) if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); z->maxcode[i] = code << (16-i); // preshift for inner loop code <<= 1; k += sizes[i]; } z->maxcode[16] = 0x10000; // sentinel for (i=0; i < num; ++i) { int s = sizelist[i]; if (s) { int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); z->size [c] = (stbi_uc ) s; z->value[c] = (stbi__uint16) i; if (s <= STBI__ZFAST_BITS) { int j = stbi__bit_reverse(next_code[s],s); while (j < (1 << STBI__ZFAST_BITS)) { z->fast[j] = fastv; j += (1 << s); } } ++next_code[s]; } } return 1; } // zlib-from-memory implementation for PNG reading // because PNG allows splitting the zlib stream arbitrarily, // and it's annoying structurally to have PNG call ZLIB call PNG, // we require PNG read all the IDATs and combine them into a single // memory buffer typedef struct { stbi_uc *zbuffer, *zbuffer_end; int num_bits; stbi__uint32 code_buffer; char *zout; char *zout_start; char *zout_end; int z_expandable; stbi__zhuffman z_length, z_distance; } stbi__zbuf; stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) { if (z->zbuffer >= z->zbuffer_end) return 0; return *z->zbuffer++; } static void stbi__fill_bits(stbi__zbuf *z) { do { STBI_ASSERT(z->code_buffer < (1U << z->num_bits)); z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; z->num_bits += 8; } while (z->num_bits <= 24); } stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) { unsigned int k; if (z->num_bits < n) stbi__fill_bits(z); k = z->code_buffer & ((1 << n) - 1); z->code_buffer >>= n; z->num_bits -= n; return k; } static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) { int b,s,k; // not resolved by fast table, so compute it the slow way // use jpeg approach, which requires MSbits at top k = stbi__bit_reverse(a->code_buffer, 16); for (s=STBI__ZFAST_BITS+1; ; ++s) if (k < z->maxcode[s]) break; if (s == 16) return -1; // invalid code! // code size is s, so: b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; STBI_ASSERT(z->size[b] == s); a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; } stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) { int b,s; if (a->num_bits < 16) stbi__fill_bits(a); b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; if (b) { s = b >> 9; a->code_buffer >>= s; a->num_bits -= s; return b & 511; } return stbi__zhuffman_decode_slowpath(a, z); } static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes { char *q; int cur, limit, old_limit; z->zout = zout; if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); cur = (int) (z->zout - z->zout_start); limit = old_limit = (int) (z->zout_end - z->zout_start); while (cur + n > limit) limit *= 2; q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); STBI_NOTUSED(old_limit); if (q == NULL) return stbi__err("outofmem", "Out of memory"); z->zout_start = q; z->zout = q + cur; z->zout_end = q + limit; return 1; } static int stbi__zlength_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static int stbi__zlength_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; static int stbi__zdist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static int stbi__parse_huffman_block(stbi__zbuf *a) { char *zout = a->zout; for(;;) { int z = stbi__zhuffman_decode(a, &a->z_length); if (z < 256) { if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes if (zout >= a->zout_end) { if (!stbi__zexpand(a, zout, 1)) return 0; zout = a->zout; } *zout++ = (char) z; } else { stbi_uc *p; int len,dist; if (z == 256) { a->zout = zout; return 1; } z -= 257; len = stbi__zlength_base[z]; if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); z = stbi__zhuffman_decode(a, &a->z_distance); if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); dist = stbi__zdist_base[z]; if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); if (zout + len > a->zout_end) { if (!stbi__zexpand(a, zout, len)) return 0; zout = a->zout; } p = (stbi_uc *) (zout - dist); if (dist == 1) { // run of one byte; common in images. stbi_uc v = *p; if (len) { do *zout++ = v; while (--len); } } else { if (len) { do *zout++ = *p++; while (--len); } } } } } static int stbi__compute_huffman_codes(stbi__zbuf *a) { static stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; stbi__zhuffman z_codelength; stbi_uc lencodes[286+32+137];//padding for maximum single op stbi_uc codelength_sizes[19]; int i,n; int hlit = stbi__zreceive(a,5) + 257; int hdist = stbi__zreceive(a,5) + 1; int hclen = stbi__zreceive(a,4) + 4; memset(codelength_sizes, 0, sizeof(codelength_sizes)); for (i=0; i < hclen; ++i) { int s = stbi__zreceive(a,3); codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; } if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; n = 0; while (n < hlit + hdist) { int c = stbi__zhuffman_decode(a, &z_codelength); if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); if (c < 16) lencodes[n++] = (stbi_uc) c; else if (c == 16) { c = stbi__zreceive(a,2)+3; memset(lencodes+n, lencodes[n-1], c); n += c; } else if (c == 17) { c = stbi__zreceive(a,3)+3; memset(lencodes+n, 0, c); n += c; } else { STBI_ASSERT(c == 18); c = stbi__zreceive(a,7)+11; memset(lencodes+n, 0, c); n += c; } } if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG"); if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; return 1; } static int stbi__parse_uncomperssed_block(stbi__zbuf *a) { stbi_uc header[4]; int len,nlen,k; if (a->num_bits & 7) stbi__zreceive(a, a->num_bits & 7); // discard // drain the bit-packed data into header k = 0; while (a->num_bits > 0) { header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check a->code_buffer >>= 8; a->num_bits -= 8; } STBI_ASSERT(a->num_bits == 0); // now fill header the normal way while (k < 4) header[k++] = stbi__zget8(a); len = header[1] * 256 + header[0]; nlen = header[3] * 256 + header[2]; if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); if (a->zout + len > a->zout_end) if (!stbi__zexpand(a, a->zout, len)) return 0; memcpy(a->zout, a->zbuffer, len); a->zbuffer += len; a->zout += len; return 1; } static int stbi__parse_zlib_header(stbi__zbuf *a) { int cmf = stbi__zget8(a); int cm = cmf & 15; /* int cinfo = cmf >> 4; */ int flg = stbi__zget8(a); if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png // window = 1 << (8 + cinfo)... but who cares, we fully buffer output return 1; } // @TODO: should statically initialize these for optimal thread safety static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32]; static void stbi__init_zdefaults(void) { int i; // use <= to match clearly with spec for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; } static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) { int final, type; if (parse_header) if (!stbi__parse_zlib_header(a)) return 0; a->num_bits = 0; a->code_buffer = 0; do { final = stbi__zreceive(a,1); type = stbi__zreceive(a,2); if (type == 0) { if (!stbi__parse_uncomperssed_block(a)) return 0; } else if (type == 3) { return 0; } else { if (type == 1) { // use fixed code lengths if (!stbi__zdefault_distance[31]) stbi__init_zdefaults(); if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; } else { if (!stbi__compute_huffman_codes(a)) return 0; } if (!stbi__parse_huffman_block(a)) return 0; } } while (!final); return 1; } static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) { a->zout_start = obuf; a->zout = obuf; a->zout_end = obuf + olen; a->z_expandable = exp; return stbi__parse_zlib(a, parse_header); } STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) { stbi__zbuf a; char *p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer + len; if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) { return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); } STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) { stbi__zbuf a; char *p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer + len; if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) return (int) (a.zout - a.zout_start); else return -1; } STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) { stbi__zbuf a; char *p = (char *) stbi__malloc(16384); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer+len; if (stbi__do_zlib(&a, p, 16384, 1, 0)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) return (int) (a.zout - a.zout_start); else return -1; } #endif // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 // simple implementation // - only 8-bit samples // - no CRC checking // - allocates lots of intermediate memory // - avoids problem of streaming data between subsystems // - avoids explicit window management // performance // - uses stb_zlib, a PD zlib implementation with fast huffman decoding #ifndef STBI_NO_PNG typedef struct { stbi__uint32 length; stbi__uint32 type; } stbi__pngchunk; static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) { stbi__pngchunk c; c.length = stbi__get32be(s); c.type = stbi__get32be(s); return c; } static int stbi__check_png_header(stbi__context *s) { static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; int i; for (i=0; i < 8; ++i) if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); return 1; } typedef struct { stbi__context *s; stbi_uc *idata, *expanded, *out; } stbi__png; enum { STBI__F_none=0, STBI__F_sub=1, STBI__F_up=2, STBI__F_avg=3, STBI__F_paeth=4, // synthetic filters used for first scanline to avoid needing a dummy row of 0s STBI__F_avg_first, STBI__F_paeth_first }; static stbi_uc first_row_filter[5] = { STBI__F_none, STBI__F_sub, STBI__F_none, STBI__F_avg_first, STBI__F_paeth_first }; static int stbi__paeth(int a, int b, int c) { int p = a + b - c; int pa = abs(p-a); int pb = abs(p-b); int pc = abs(p-c); if (pa <= pb && pa <= pc) return a; if (pb <= pc) return b; return c; } static stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; // create the png data from post-deflated data static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) { stbi__context *s = a->s; stbi__uint32 i,j,stride = x*out_n; stbi__uint32 img_len, img_width_bytes; int k; int img_n = s->img_n; // copy it into a local for later STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); a->out = (stbi_uc *) stbi__malloc(x * y * out_n); // extra bytes to write off the end into if (!a->out) return stbi__err("outofmem", "Out of memory"); img_width_bytes = (((img_n * x * depth) + 7) >> 3); img_len = (img_width_bytes + 1) * y; if (s->img_x == x && s->img_y == y) { if (raw_len != img_len) return stbi__err("not enough pixels","Corrupt PNG"); } else { // interlaced: if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); } for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *prior = cur - stride; int filter = *raw++; int filter_bytes = img_n; int width = x; if (filter > 4) return stbi__err("invalid filter","Corrupt PNG"); if (depth < 8) { STBI_ASSERT(img_width_bytes <= x); cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place filter_bytes = 1; width = img_width_bytes; } // if first row, use special filter that doesn't sample previous row if (j == 0) filter = first_row_filter[filter]; // handle first byte explicitly for (k=0; k < filter_bytes; ++k) { switch (filter) { case STBI__F_none : cur[k] = raw[k]; break; case STBI__F_sub : cur[k] = raw[k]; break; case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; case STBI__F_avg_first : cur[k] = raw[k]; break; case STBI__F_paeth_first: cur[k] = raw[k]; break; } } if (depth == 8) { if (img_n != out_n) cur[img_n] = 255; // first pixel raw += img_n; cur += out_n; prior += out_n; } else { raw += 1; cur += 1; prior += 1; } // this is a little gross, so that we don't switch per-pixel or per-component if (depth < 8 || img_n == out_n) { int nk = (width - 1)*img_n; #define CASE(f) \ case f: \ for (k=0; k < nk; ++k) switch (filter) { // "none" filter turns into a memcpy here; make that explicit. case STBI__F_none: memcpy(cur, raw, nk); break; CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); break; CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); break; CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); break; CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); break; CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); break; } #undef CASE raw += nk; } else { STBI_ASSERT(img_n+1 == out_n); #define CASE(f) \ case f: \ for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \ for (k=0; k < img_n; ++k) switch (filter) { CASE(STBI__F_none) cur[k] = raw[k]; break; CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-out_n]); break; CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-out_n])>>1)); break; CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-out_n],prior[k],prior[k-out_n])); break; CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-out_n] >> 1)); break; CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-out_n],0,0)); break; } #undef CASE } } // we make a separate pass to expand bits to pixels; for performance, // this could run two scanlines behind the above code, so it won't // intefere with filtering but will still be in the cache. if (depth < 8) { for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range // note that the final byte might overshoot and write more data than desired. // we can allocate enough data that this never writes out of memory, but it // could also overwrite the next scanline. can it overwrite non-empty data // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. // so we need to explicitly clamp the final ones if (depth == 4) { for (k=x*img_n; k >= 2; k-=2, ++in) { *cur++ = scale * ((*in >> 4) ); *cur++ = scale * ((*in ) & 0x0f); } if (k > 0) *cur++ = scale * ((*in >> 4) ); } else if (depth == 2) { for (k=x*img_n; k >= 4; k-=4, ++in) { *cur++ = scale * ((*in >> 6) ); *cur++ = scale * ((*in >> 4) & 0x03); *cur++ = scale * ((*in >> 2) & 0x03); *cur++ = scale * ((*in ) & 0x03); } if (k > 0) *cur++ = scale * ((*in >> 6) ); if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); } else if (depth == 1) { for (k=x*img_n; k >= 8; k-=8, ++in) { *cur++ = scale * ((*in >> 7) ); *cur++ = scale * ((*in >> 6) & 0x01); *cur++ = scale * ((*in >> 5) & 0x01); *cur++ = scale * ((*in >> 4) & 0x01); *cur++ = scale * ((*in >> 3) & 0x01); *cur++ = scale * ((*in >> 2) & 0x01); *cur++ = scale * ((*in >> 1) & 0x01); *cur++ = scale * ((*in ) & 0x01); } if (k > 0) *cur++ = scale * ((*in >> 7) ); if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); } if (img_n != out_n) { int q; // insert alpha = 255 cur = a->out + stride*j; if (img_n == 1) { for (q=x-1; q >= 0; --q) { cur[q*2+1] = 255; cur[q*2+0] = cur[q]; } } else { STBI_ASSERT(img_n == 3); for (q=x-1; q >= 0; --q) { cur[q*4+3] = 255; cur[q*4+2] = cur[q*3+2]; cur[q*4+1] = cur[q*3+1]; cur[q*4+0] = cur[q*3+0]; } } } } } return 1; } static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) { stbi_uc *final; int p; if (!interlaced) return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); // de-interlacing final = (stbi_uc *) stbi__malloc(a->s->img_x * a->s->img_y * out_n); for (p=0; p < 7; ++p) { int xorig[] = { 0,4,0,2,0,1,0 }; int yorig[] = { 0,0,4,0,2,0,1 }; int xspc[] = { 8,8,4,4,2,2,1 }; int yspc[] = { 8,8,8,4,4,2,2 }; int i,j,x,y; // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; if (x && y) { stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { STBI_FREE(final); return 0; } for (j=0; j < y; ++j) { for (i=0; i < x; ++i) { int out_y = j*yspc[p]+yorig[p]; int out_x = i*xspc[p]+xorig[p]; memcpy(final + out_y*a->s->img_x*out_n + out_x*out_n, a->out + (j*x+i)*out_n, out_n); } } STBI_FREE(a->out); image_data += img_len; image_data_len -= img_len; } } a->out = final; return 1; } static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; // compute color-based transparency, assuming we've // already got 255 as the alpha value in the output STBI_ASSERT(out_n == 2 || out_n == 4); if (out_n == 2) { for (i=0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 255); p += 2; } } else { for (i=0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) { stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; stbi_uc *p, *temp_out, *orig = a->out; p = (stbi_uc *) stbi__malloc(pixel_count * pal_img_n); if (p == NULL) return stbi__err("outofmem", "Out of memory"); // between here and free(out) below, exitting would leak temp_out = p; if (pal_img_n == 3) { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p += 3; } } else { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p[3] = palette[n+3]; p += 4; } } STBI_FREE(a->out); a->out = temp_out; STBI_NOTUSED(len); return 1; } static int stbi__unpremultiply_on_load = 0; static int stbi__de_iphone_flag = 0; STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) { stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; } STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) { stbi__de_iphone_flag = flag_true_if_should_convert; } static void stbi__de_iphone(stbi__png *z) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; if (s->img_out_n == 3) { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 3; } } else { STBI_ASSERT(s->img_out_n == 4); if (stbi__unpremultiply_on_load) { // convert bgr to rgb and unpremultiply for (i=0; i < pixel_count; ++i) { stbi_uc a = p[3]; stbi_uc t = p[0]; if (a) { p[0] = p[2] * 255 / a; p[1] = p[1] * 255 / a; p[2] = t * 255 / a; } else { p[0] = p[2]; p[2] = t; } p += 4; } } else { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 4; } } } } #define STBI__PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d)) static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) { stbi_uc palette[1024], pal_img_n=0; stbi_uc has_trans=0, tc[3]; stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; int first=1,k,interlace=0, color=0, depth=0, is_iphone=0; stbi__context *s = z->s; z->expanded = NULL; z->idata = NULL; z->out = NULL; if (!stbi__check_png_header(s)) return 0; if (scan == STBI__SCAN_type) return 1; for (;;) { stbi__pngchunk c = stbi__get_chunk_header(s); switch (c.type) { case STBI__PNG_TYPE('C','g','B','I'): is_iphone = 1; stbi__skip(s, c.length); break; case STBI__PNG_TYPE('I','H','D','R'): { int comp,filter; if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); first = 0; if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); depth = stbi__get8(s); if (depth != 1 && depth != 2 && depth != 4 && depth != 8) return stbi__err("1/2/4/8-bit only","PNG not supported: 1/2/4/8-bit only"); color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); if (!pal_img_n) { s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); if (scan == STBI__SCAN_header) return 1; } else { // if paletted, then pal_n is our final components, and // img_n is # components to decompress/filter. s->img_n = 1; if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); // if SCAN_header, have to scan to see if we have a tRNS } break; } case STBI__PNG_TYPE('P','L','T','E'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); pal_len = c.length / 3; if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); for (i=0; i < pal_len; ++i) { palette[i*4+0] = stbi__get8(s); palette[i*4+1] = stbi__get8(s); palette[i*4+2] = stbi__get8(s); palette[i*4+3] = 255; } break; } case STBI__PNG_TYPE('t','R','N','S'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); if (pal_img_n) { if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); pal_img_n = 4; for (i=0; i < c.length; ++i) palette[i*4+3] = stbi__get8(s); } else { if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); has_trans = 1; for (k=0; k < s->img_n; ++k) tc[k] = (stbi_uc) (stbi__get16be(s) & 255) * stbi__depth_scale_table[depth]; // non 8-bit images will be larger } break; } case STBI__PNG_TYPE('I','D','A','T'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } if ((int)(ioff + c.length) < (int)ioff) return 0; if (ioff + c.length > idata_limit) { stbi__uint32 idata_limit_old = idata_limit; stbi_uc *p; if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) idata_limit *= 2; STBI_NOTUSED(idata_limit_old); p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); z->idata = p; } if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); ioff += c.length; break; } case STBI__PNG_TYPE('I','E','N','D'): { stbi__uint32 raw_len, bpl; if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (scan != STBI__SCAN_load) return 1; if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); // initial guess for decoded data size to avoid unnecessary reallocs bpl = (s->img_x * depth + 7) / 8; // bytes per line, per component raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); if (z->expanded == NULL) return 0; // zlib should set error STBI_FREE(z->idata); z->idata = NULL; if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) s->img_out_n = s->img_n+1; else s->img_out_n = s->img_n; if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, depth, color, interlace)) return 0; if (has_trans) if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) stbi__de_iphone(z); if (pal_img_n) { // pal_img_n == 3 or 4 s->img_n = pal_img_n; // record the actual colors we had s->img_out_n = pal_img_n; if (req_comp >= 3) s->img_out_n = req_comp; if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) return 0; } STBI_FREE(z->expanded); z->expanded = NULL; return 1; } default: // if critical, fail if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if ((c.type & (1 << 29)) == 0) { #ifndef STBI_NO_FAILURE_STRINGS // not threadsafe static char invalid_chunk[] = "XXXX PNG chunk not known"; invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); #endif return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); } stbi__skip(s, c.length); break; } // end of PNG chunk, read and skip CRC stbi__get32be(s); } } static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp) { unsigned char *result=NULL; if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { result = p->out; p->out = NULL; if (req_comp && req_comp != p->s->img_out_n) { result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); p->s->img_out_n = req_comp; if (result == NULL) return result; } *x = p->s->img_x; *y = p->s->img_y; if (n) *n = p->s->img_out_n; } STBI_FREE(p->out); p->out = NULL; STBI_FREE(p->expanded); p->expanded = NULL; STBI_FREE(p->idata); p->idata = NULL; return result; } static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi__png p; p.s = s; return stbi__do_png(&p, x,y,comp,req_comp); } static int stbi__png_test(stbi__context *s) { int r; r = stbi__check_png_header(s); stbi__rewind(s); return r; } static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) { if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { stbi__rewind( p->s ); return 0; } if (x) *x = p->s->img_x; if (y) *y = p->s->img_y; if (comp) *comp = p->s->img_n; return 1; } static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) { stbi__png p; p.s = s; return stbi__png_info_raw(&p, x, y, comp); } #endif // Microsoft/Windows BMP image #ifndef STBI_NO_BMP static int stbi__bmp_test_raw(stbi__context *s) { int r; int sz; if (stbi__get8(s) != 'B') return 0; if (stbi__get8(s) != 'M') return 0; stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved stbi__get32le(s); // discard data offset sz = stbi__get32le(s); r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); return r; } static int stbi__bmp_test(stbi__context *s) { int r = stbi__bmp_test_raw(s); stbi__rewind(s); return r; } // returns 0..31 for the highest set bit static int stbi__high_bit(unsigned int z) { int n=0; if (z == 0) return -1; if (z >= 0x10000) n += 16, z >>= 16; if (z >= 0x00100) n += 8, z >>= 8; if (z >= 0x00010) n += 4, z >>= 4; if (z >= 0x00004) n += 2, z >>= 2; if (z >= 0x00002) n += 1, z >>= 1; return n; } static int stbi__bitcount(unsigned int a) { a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits a = (a + (a >> 8)); // max 16 per 8 bits a = (a + (a >> 16)); // max 32 per 8 bits return a & 0xff; } static int stbi__shiftsigned(int v, int shift, int bits) { int result; int z=0; if (shift < 0) v <<= -shift; else v >>= shift; result = v; z = bits; while (z < 8) { result += v >> z; z += bits; } return result; } typedef struct { int bpp, offset, hsz; unsigned int mr,mg,mb,ma, all_a; } stbi__bmp_data; static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) { int hsz; if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved info->offset = stbi__get32le(s); info->hsz = hsz = stbi__get32le(s); if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); if (hsz == 12) { s->img_x = stbi__get16le(s); s->img_y = stbi__get16le(s); } else { s->img_x = stbi__get32le(s); s->img_y = stbi__get32le(s); } if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); info->bpp = stbi__get16le(s); if (info->bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit"); if (hsz != 12) { int compress = stbi__get32le(s); if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); stbi__get32le(s); // discard sizeof stbi__get32le(s); // discard hres stbi__get32le(s); // discard vres stbi__get32le(s); // discard colorsused stbi__get32le(s); // discard max important if (hsz == 40 || hsz == 56) { if (hsz == 56) { stbi__get32le(s); stbi__get32le(s); stbi__get32le(s); stbi__get32le(s); } if (info->bpp == 16 || info->bpp == 32) { info->mr = info->mg = info->mb = 0; if (compress == 0) { if (info->bpp == 32) { info->mr = 0xffu << 16; info->mg = 0xffu << 8; info->mb = 0xffu << 0; info->ma = 0xffu << 24; info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 } else { info->mr = 31u << 10; info->mg = 31u << 5; info->mb = 31u << 0; } } else if (compress == 3) { info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); // not documented, but generated by photoshop and handled by mspaint if (info->mr == info->mg && info->mg == info->mb) { // ?!?!? return stbi__errpuc("bad BMP", "bad BMP"); } } else return stbi__errpuc("bad BMP", "bad BMP"); } } else { int i; if (hsz != 108 && hsz != 124) return stbi__errpuc("bad BMP", "bad BMP"); info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); info->ma = stbi__get32le(s); stbi__get32le(s); // discard color space for (i=0; i < 12; ++i) stbi__get32le(s); // discard color space parameters if (hsz == 124) { stbi__get32le(s); // discard rendering intent stbi__get32le(s); // discard offset of profile data stbi__get32le(s); // discard size of profile data stbi__get32le(s); // discard reserved } } } return (void *) 1; } static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi_uc *out; unsigned int mr=0,mg=0,mb=0,ma=0, all_a; stbi_uc pal[256][4]; int psize=0,i,j,width; int flip_vertically, pad, target; stbi__bmp_data info; info.all_a = 255; if (stbi__bmp_parse_header(s, &info) == NULL) return NULL; // error code already set flip_vertically = ((int) s->img_y) > 0; s->img_y = abs((int) s->img_y); mr = info.mr; mg = info.mg; mb = info.mb; ma = info.ma; all_a = info.all_a; if (info.hsz == 12) { if (info.bpp < 24) psize = (info.offset - 14 - 24) / 3; } else { if (info.bpp < 16) psize = (info.offset - 14 - info.hsz) >> 2; } s->img_n = ma ? 4 : 3; if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 target = req_comp; else target = s->img_n; // if they want monochrome, we'll post-convert out = (stbi_uc *) stbi__malloc(target * s->img_x * s->img_y); if (!out) return stbi__errpuc("outofmem", "Out of memory"); if (info.bpp < 16) { int z=0; if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } for (i=0; i < psize; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); if (info.hsz != 12) stbi__get8(s); pal[i][3] = 255; } stbi__skip(s, info.offset - 14 - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); if (info.bpp == 4) width = (s->img_x + 1) >> 1; else if (info.bpp == 8) width = s->img_x; else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } pad = (-width)&3; for (j=0; j < (int) s->img_y; ++j) { for (i=0; i < (int) s->img_x; i += 2) { int v=stbi__get8(s),v2=0; if (info.bpp == 4) { v2 = v & 15; v >>= 4; } out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; if (i+1 == (int) s->img_x) break; v = (info.bpp == 8) ? stbi__get8(s) : v2; out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; } stbi__skip(s, pad); } } else { int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; int z = 0; int easy=0; stbi__skip(s, info.offset - 14 - info.hsz); if (info.bpp == 24) width = 3 * s->img_x; else if (info.bpp == 16) width = 2*s->img_x; else /* bpp = 32 and pad = 0 */ width=0; pad = (-width) & 3; if (info.bpp == 24) { easy = 1; } else if (info.bpp == 32) { if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) easy = 2; } if (!easy) { if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } // right shift amt to put high bit in position #7 rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); } for (j=0; j < (int) s->img_y; ++j) { if (easy) { for (i=0; i < (int) s->img_x; ++i) { unsigned char a; out[z+2] = stbi__get8(s); out[z+1] = stbi__get8(s); out[z+0] = stbi__get8(s); z += 3; a = (easy == 2 ? stbi__get8(s) : 255); all_a |= a; if (target == 4) out[z++] = a; } } else { int bpp = info.bpp; for (i=0; i < (int) s->img_x; ++i) { stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); int a; out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); all_a |= a; if (target == 4) out[z++] = STBI__BYTECAST(a); } } stbi__skip(s, pad); } } // if alpha channel is all 0s, replace with all 255s if (target == 4 && all_a == 0) for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) out[i] = 255; if (flip_vertically) { stbi_uc t; for (j=0; j < (int) s->img_y>>1; ++j) { stbi_uc *p1 = out + j *s->img_x*target; stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; for (i=0; i < (int) s->img_x*target; ++i) { t = p1[i], p1[i] = p2[i], p2[i] = t; } } } if (req_comp && req_comp != target) { out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // stbi__convert_format frees input on failure } *x = s->img_x; *y = s->img_y; if (comp) *comp = s->img_n; return out; } #endif // Targa Truevision - TGA // by Jonathan Dummer #ifndef STBI_NO_TGA // returns STBI_rgb or whatever, 0 on error static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) { // only RGB or RGBA (incl. 16bit) or grey allowed if(is_rgb16) *is_rgb16 = 0; switch(bits_per_pixel) { case 8: return STBI_grey; case 16: if(is_grey) return STBI_grey_alpha; // else: fall-through case 15: if(is_rgb16) *is_rgb16 = 1; return STBI_rgb; case 24: // fall-through case 32: return bits_per_pixel/8; default: return 0; } } static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) { int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; int sz, tga_colormap_type; stbi__get8(s); // discard Offset tga_colormap_type = stbi__get8(s); // colormap type if( tga_colormap_type > 1 ) { stbi__rewind(s); return 0; // only RGB or indexed allowed } tga_image_type = stbi__get8(s); // image type if ( tga_colormap_type == 1 ) { // colormapped (paletted) image if (tga_image_type != 1 && tga_image_type != 9) { stbi__rewind(s); return 0; } stbi__skip(s,4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { stbi__rewind(s); return 0; } stbi__skip(s,4); // skip image x and y origin tga_colormap_bpp = sz; } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { stbi__rewind(s); return 0; // only RGB or grey allowed, +/- RLE } stbi__skip(s,9); // skip colormap specification and image x/y origin tga_colormap_bpp = 0; } tga_w = stbi__get16le(s); if( tga_w < 1 ) { stbi__rewind(s); return 0; // test width } tga_h = stbi__get16le(s); if( tga_h < 1 ) { stbi__rewind(s); return 0; // test height } tga_bits_per_pixel = stbi__get8(s); // bits per pixel stbi__get8(s); // ignore alpha bits if (tga_colormap_bpp != 0) { if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { // when using a colormap, tga_bits_per_pixel is the size of the indexes // I don't think anything but 8 or 16bit indexes makes sense stbi__rewind(s); return 0; } tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); } else { tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); } if(!tga_comp) { stbi__rewind(s); return 0; } if (x) *x = tga_w; if (y) *y = tga_h; if (comp) *comp = tga_comp; return 1; // seems to have passed everything } static int stbi__tga_test(stbi__context *s) { int res = 0; int sz, tga_color_type; stbi__get8(s); // discard Offset tga_color_type = stbi__get8(s); // color type if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed sz = stbi__get8(s); // image type if ( tga_color_type == 1 ) { // colormapped (paletted) image if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 stbi__skip(s,4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; stbi__skip(s,4); // skip image x and y origin } else { // "normal" image w/o colormap if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE stbi__skip(s,9); // skip colormap specification and image x/y origin } if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height sz = stbi__get8(s); // bits per pixel if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; res = 1; // if we got this far, everything's good and we can return 1 instead of 0 errorEnd: stbi__rewind(s); return res; } // read 16bit value and convert to 24bit RGB void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) { stbi__uint16 px = stbi__get16le(s); stbi__uint16 fiveBitMask = 31; // we have 3 channels with 5bits each int r = (px >> 10) & fiveBitMask; int g = (px >> 5) & fiveBitMask; int b = px & fiveBitMask; // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later out[0] = (r * 255)/31; out[1] = (g * 255)/31; out[2] = (b * 255)/31; // some people claim that the most significant bit might be used for alpha // (possibly if an alpha-bit is set in the "image descriptor byte") // but that only made 16bit test images completely translucent.. // so let's treat all 15 and 16bit TGAs as RGB with no alpha. } static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) { // read in the TGA header stuff int tga_offset = stbi__get8(s); int tga_indexed = stbi__get8(s); int tga_image_type = stbi__get8(s); int tga_is_RLE = 0; int tga_palette_start = stbi__get16le(s); int tga_palette_len = stbi__get16le(s); int tga_palette_bits = stbi__get8(s); int tga_x_origin = stbi__get16le(s); int tga_y_origin = stbi__get16le(s); int tga_width = stbi__get16le(s); int tga_height = stbi__get16le(s); int tga_bits_per_pixel = stbi__get8(s); int tga_comp, tga_rgb16=0; int tga_inverted = stbi__get8(s); // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) // image data unsigned char *tga_data; unsigned char *tga_palette = NULL; int i, j; unsigned char raw_data[4]; int RLE_count = 0; int RLE_repeating = 0; int read_next_pixel = 1; // do a tiny bit of precessing if ( tga_image_type >= 8 ) { tga_image_type -= 8; tga_is_RLE = 1; } tga_inverted = 1 - ((tga_inverted >> 5) & 1); // If I'm paletted, then I'll use the number of bits from the palette if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); // tga info *x = tga_width; *y = tga_height; if (comp) *comp = tga_comp; tga_data = (unsigned char*)stbi__malloc( (size_t)tga_width * tga_height * tga_comp ); if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); // skip to the data's starting position (offset usually = 0) stbi__skip(s, tga_offset ); if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { for (i=0; i < tga_height; ++i) { int row = tga_inverted ? tga_height -i - 1 : i; stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; stbi__getn(s, tga_row, tga_width * tga_comp); } } else { // do I need to load a palette? if ( tga_indexed) { // any data to skip? (offset usually = 0) stbi__skip(s, tga_palette_start ); // load the palette tga_palette = (unsigned char*)stbi__malloc( tga_palette_len * tga_comp ); if (!tga_palette) { STBI_FREE(tga_data); return stbi__errpuc("outofmem", "Out of memory"); } if (tga_rgb16) { stbi_uc *pal_entry = tga_palette; STBI_ASSERT(tga_comp == STBI_rgb); for (i=0; i < tga_palette_len; ++i) { stbi__tga_read_rgb16(s, pal_entry); pal_entry += tga_comp; } } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { STBI_FREE(tga_data); STBI_FREE(tga_palette); return stbi__errpuc("bad palette", "Corrupt TGA"); } } // load the data for (i=0; i < tga_width * tga_height; ++i) { // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? if ( tga_is_RLE ) { if ( RLE_count == 0 ) { // yep, get the next byte as a RLE command int RLE_cmd = stbi__get8(s); RLE_count = 1 + (RLE_cmd & 127); RLE_repeating = RLE_cmd >> 7; read_next_pixel = 1; } else if ( !RLE_repeating ) { read_next_pixel = 1; } } else { read_next_pixel = 1; } // OK, if I need to read a pixel, do it now if ( read_next_pixel ) { // load however much data we did have if ( tga_indexed ) { // read in index, then perform the lookup int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); if ( pal_idx >= tga_palette_len ) { // invalid index pal_idx = 0; } pal_idx *= tga_comp; for (j = 0; j < tga_comp; ++j) { raw_data[j] = tga_palette[pal_idx+j]; } } else if(tga_rgb16) { STBI_ASSERT(tga_comp == STBI_rgb); stbi__tga_read_rgb16(s, raw_data); } else { // read in the data raw for (j = 0; j < tga_comp; ++j) { raw_data[j] = stbi__get8(s); } } // clear the reading flag for the next pixel read_next_pixel = 0; } // end of reading a pixel // copy data for (j = 0; j < tga_comp; ++j) tga_data[i*tga_comp+j] = raw_data[j]; // in case we're in RLE mode, keep counting down --RLE_count; } // do I need to invert the image? if ( tga_inverted ) { for (j = 0; j*2 < tga_height; ++j) { int index1 = j * tga_width * tga_comp; int index2 = (tga_height - 1 - j) * tga_width * tga_comp; for (i = tga_width * tga_comp; i > 0; --i) { unsigned char temp = tga_data[index1]; tga_data[index1] = tga_data[index2]; tga_data[index2] = temp; ++index1; ++index2; } } } // clear my palette, if I had one if ( tga_palette != NULL ) { STBI_FREE( tga_palette ); } } // swap RGB - if the source data was RGB16, it already is in the right order if (tga_comp >= 3 && !tga_rgb16) { unsigned char* tga_pixel = tga_data; for (i=0; i < tga_width * tga_height; ++i) { unsigned char temp = tga_pixel[0]; tga_pixel[0] = tga_pixel[2]; tga_pixel[2] = temp; tga_pixel += tga_comp; } } // convert to target component count if (req_comp && req_comp != tga_comp) tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); // the things I do to get rid of an error message, and yet keep // Microsoft's C compilers happy... [8^( tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0; // OK, done return tga_data; } #endif // ************************************************************************************************* // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s) { int r = (stbi__get32be(s) == 0x38425053); stbi__rewind(s); return r; } static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) { int pixelCount; int channelCount, compression; int channel, i, count, len; int bitdepth; int w,h; stbi_uc *out; // Check identifier if (stbi__get32be(s) != 0x38425053) // "8BPS" return stbi__errpuc("not PSD", "Corrupt PSD image"); // Check file type version. if (stbi__get16be(s) != 1) return stbi__errpuc("wrong version", "Unsupported version of PSD image"); // Skip 6 reserved bytes. stbi__skip(s, 6 ); // Read the number of channels (R, G, B, A, etc). channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); // Read the rows and columns of the image. h = stbi__get32be(s); w = stbi__get32be(s); // Make sure the depth is 8 bits. bitdepth = stbi__get16be(s); if (bitdepth != 8 && bitdepth != 16) return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); // Make sure the color mode is RGB. // Valid options are: // 0: Bitmap // 1: Grayscale // 2: Indexed color // 3: RGB color // 4: CMYK color // 7: Multichannel // 8: Duotone // 9: Lab color if (stbi__get16be(s) != 3) return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) stbi__skip(s,stbi__get32be(s) ); // Skip the image resources. (resolution, pen tool paths, etc) stbi__skip(s, stbi__get32be(s) ); // Skip the reserved data. stbi__skip(s, stbi__get32be(s) ); // Find out if the data is compressed. // Known values: // 0: no compression // 1: RLE compressed compression = stbi__get16be(s); if (compression > 1) return stbi__errpuc("bad compression", "PSD has an unknown compression format"); // Create the destination image. out = (stbi_uc *) stbi__malloc(4 * w*h); if (!out) return stbi__errpuc("outofmem", "Out of memory"); pixelCount = w*h; // Initialize the data to zero. //memset( out, 0, pixelCount * 4 ); // Finally, the image data. if (compression) { // RLE as used by .PSD and .TIFF // Loop until you get the number of unpacked bytes you are expecting: // Read the next source byte into n. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. // Else if n is 128, noop. // Endloop // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data, // which we're going to just skip. stbi__skip(s, h * channelCount * 2 ); // Read the RLE data by channel. for (channel = 0; channel < 4; channel++) { stbi_uc *p; p = out+channel; if (channel >= channelCount) { // Fill this channel with default data. for (i = 0; i < pixelCount; i++, p += 4) *p = (channel == 3 ? 255 : 0); } else { // Read the RLE data. count = 0; while (count < pixelCount) { len = stbi__get8(s); if (len == 128) { // No-op. } else if (len < 128) { // Copy next len+1 bytes literally. len++; count += len; while (len) { *p = stbi__get8(s); p += 4; len--; } } else if (len > 128) { stbi_uc val; // Next -len+1 bytes in the dest are replicated from next source byte. // (Interpret len as a negative 8-bit int.) len ^= 0x0FF; len += 2; val = stbi__get8(s); count += len; while (len) { *p = val; p += 4; len--; } } } } } } else { // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) // where each channel consists of an 8-bit value for each pixel in the image. // Read the data by channel. for (channel = 0; channel < 4; channel++) { stbi_uc *p; p = out + channel; if (channel >= channelCount) { // Fill this channel with default data. stbi_uc val = channel == 3 ? 255 : 0; for (i = 0; i < pixelCount; i++, p += 4) *p = val; } else { // Read the data. if (bitdepth == 16) { for (i = 0; i < pixelCount; i++, p += 4) *p = (stbi_uc) (stbi__get16be(s) >> 8); } else { for (i = 0; i < pixelCount; i++, p += 4) *p = stbi__get8(s); } } } } if (req_comp && req_comp != 4) { out = stbi__convert_format(out, 4, req_comp, w, h); if (out == NULL) return out; // stbi__convert_format frees input on failure } if (comp) *comp = 4; *y = h; *x = w; return out; } #endif // ************************************************************************************************* // Softimage PIC loader // by Tom Seddon // // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ #ifndef STBI_NO_PIC static int stbi__pic_is4(stbi__context *s,const char *str) { int i; for (i=0; i<4; ++i) if (stbi__get8(s) != (stbi_uc)str[i]) return 0; return 1; } static int stbi__pic_test_core(stbi__context *s) { int i; if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) return 0; for(i=0;i<84;++i) stbi__get8(s); if (!stbi__pic_is4(s,"PICT")) return 0; return 1; } typedef struct { stbi_uc size,type,channel; } stbi__pic_packet; static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) { int mask=0x80, i; for (i=0; i<4; ++i, mask>>=1) { if (channel & mask) { if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); dest[i]=stbi__get8(s); } } return dest; } static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) { int mask=0x80,i; for (i=0;i<4; ++i, mask>>=1) if (channel&mask) dest[i]=src[i]; } static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) { int act_comp=0,num_packets=0,y,chained; stbi__pic_packet packets[10]; // this will (should...) cater for even some bizarre stuff like having data // for the same channel in multiple packets. do { stbi__pic_packet *packet; if (num_packets==sizeof(packets)/sizeof(packets[0])) return stbi__errpuc("bad format","too many packets"); packet = &packets[num_packets++]; chained = stbi__get8(s); packet->size = stbi__get8(s); packet->type = stbi__get8(s); packet->channel = stbi__get8(s); act_comp |= packet->channel; if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? for(y=0; y<height; ++y) { int packet_idx; for(packet_idx=0; packet_idx < num_packets; ++packet_idx) { stbi__pic_packet *packet = &packets[packet_idx]; stbi_uc *dest = result+y*width*4; switch (packet->type) { default: return stbi__errpuc("bad format","packet has bad compression type"); case 0: {//uncompressed int x; for(x=0;x<width;++x, dest+=4) if (!stbi__readval(s,packet->channel,dest)) return 0; break; } case 1://Pure RLE { int left=width, i; while (left>0) { stbi_uc count,value[4]; count=stbi__get8(s); if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); if (count > left) count = (stbi_uc) left; if (!stbi__readval(s,packet->channel,value)) return 0; for(i=0; i<count; ++i,dest+=4) stbi__copyval(packet->channel,dest,value); left -= count; } } break; case 2: {//Mixed RLE int left=width; while (left>0) { int count = stbi__get8(s), i; if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); if (count >= 128) { // Repeated stbi_uc value[4]; if (count==128) count = stbi__get16be(s); else count -= 127; if (count > left) return stbi__errpuc("bad file","scanline overrun"); if (!stbi__readval(s,packet->channel,value)) return 0; for(i=0;i<count;++i, dest += 4) stbi__copyval(packet->channel,dest,value); } else { // Raw ++count; if (count>left) return stbi__errpuc("bad file","scanline overrun"); for(i=0;i<count;++i, dest+=4) if (!stbi__readval(s,packet->channel,dest)) return 0; } left-=count; } break; } } } } return result; } static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp) { stbi_uc *result; int i, x,y; for (i=0; i<92; ++i) stbi__get8(s); x = stbi__get16be(s); y = stbi__get16be(s); if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to decode"); stbi__get32be(s); //skip `ratio' stbi__get16be(s); //skip `fields' stbi__get16be(s); //skip `pad' // intermediate buffer is RGBA result = (stbi_uc *) stbi__malloc(x*y*4); memset(result, 0xff, x*y*4); if (!stbi__pic_load_core(s,x,y,comp, result)) { STBI_FREE(result); result=0; } *px = x; *py = y; if (req_comp == 0) req_comp = *comp; result=stbi__convert_format(result,4,req_comp,x,y); return result; } static int stbi__pic_test(stbi__context *s) { int r = stbi__pic_test_core(s); stbi__rewind(s); return r; } #endif // ************************************************************************************************* // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb #ifndef STBI_NO_GIF typedef struct { stbi__int16 prefix; stbi_uc first; stbi_uc suffix; } stbi__gif_lzw; typedef struct { int w,h; stbi_uc *out, *old_out; // output buffer (always 4 components) int flags, bgindex, ratio, transparent, eflags, delay; stbi_uc pal[256][4]; stbi_uc lpal[256][4]; stbi__gif_lzw codes[4096]; stbi_uc *color_table; int parse, step; int lflags; int start_x, start_y; int max_x, max_y; int cur_x, cur_y; int line_size; } stbi__gif; static int stbi__gif_test_raw(stbi__context *s) { int sz; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; sz = stbi__get8(s); if (sz != '9' && sz != '7') return 0; if (stbi__get8(s) != 'a') return 0; return 1; } static int stbi__gif_test(stbi__context *s) { int r = stbi__gif_test_raw(s); stbi__rewind(s); return r; } static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) { int i; for (i=0; i < num_entries; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); pal[i][3] = transp == i ? 0 : 255; } } static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) { stbi_uc version; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return stbi__err("not GIF", "Corrupt GIF"); version = stbi__get8(s); if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); stbi__g_failure_reason = ""; g->w = stbi__get16le(s); g->h = stbi__get16le(s); g->flags = stbi__get8(s); g->bgindex = stbi__get8(s); g->ratio = stbi__get8(s); g->transparent = -1; if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments if (is_info) return 1; if (g->flags & 0x80) stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); return 1; } static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) { stbi__gif g; if (!stbi__gif_header(s, &g, comp, 1)) { stbi__rewind( s ); return 0; } if (x) *x = g.w; if (y) *y = g.h; return 1; } static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) { stbi_uc *p, *c; // recurse to decode the prefixes, since the linked-list is backwards, // and working backwards through an interleaved image would be nasty if (g->codes[code].prefix >= 0) stbi__out_gif_code(g, g->codes[code].prefix); if (g->cur_y >= g->max_y) return; p = &g->out[g->cur_x + g->cur_y]; c = &g->color_table[g->codes[code].suffix * 4]; if (c[3] >= 128) { p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; p[3] = c[3]; } g->cur_x += 4; if (g->cur_x >= g->max_x) { g->cur_x = g->start_x; g->cur_y += g->step; while (g->cur_y >= g->max_y && g->parse > 0) { g->step = (1 << g->parse) * g->line_size; g->cur_y = g->start_y + (g->step >> 1); --g->parse; } } } static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) { stbi_uc lzw_cs; stbi__int32 len, init_code; stbi__uint32 first; stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; stbi__gif_lzw *p; lzw_cs = stbi__get8(s); if (lzw_cs > 12) return NULL; clear = 1 << lzw_cs; first = 1; codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; bits = 0; valid_bits = 0; for (init_code = 0; init_code < clear; init_code++) { g->codes[init_code].prefix = -1; g->codes[init_code].first = (stbi_uc) init_code; g->codes[init_code].suffix = (stbi_uc) init_code; } // support no starting clear code avail = clear+2; oldcode = -1; len = 0; for(;;) { if (valid_bits < codesize) { if (len == 0) { len = stbi__get8(s); // start new block if (len == 0) return g->out; } --len; bits |= (stbi__int32) stbi__get8(s) << valid_bits; valid_bits += 8; } else { stbi__int32 code = bits & codemask; bits >>= codesize; valid_bits -= codesize; // @OPTIMIZE: is there some way we can accelerate the non-clear path? if (code == clear) { // clear code codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; first = 0; } else if (code == clear + 1) { // end of stream code stbi__skip(s, len); while ((len = stbi__get8(s)) > 0) stbi__skip(s,len); return g->out; } else if (code <= avail) { if (first) return stbi__errpuc("no clear code", "Corrupt GIF"); if (oldcode >= 0) { p = &g->codes[avail++]; if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF"); p->prefix = (stbi__int16) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; } else if (code == avail) return stbi__errpuc("illegal code in raster", "Corrupt GIF"); stbi__out_gif_code(g, (stbi__uint16) code); if ((avail & codemask) == 0 && avail <= 0x0FFF) { codesize++; codemask = (1 << codesize) - 1; } oldcode = code; } else { return stbi__errpuc("illegal code in raster", "Corrupt GIF"); } } } } static void stbi__fill_gif_background(stbi__gif *g, int x0, int y0, int x1, int y1) { int x, y; stbi_uc *c = g->pal[g->bgindex]; for (y = y0; y < y1; y += 4 * g->w) { for (x = x0; x < x1; x += 4) { stbi_uc *p = &g->out[y + x]; p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; p[3] = 0; } } } // this function is designed to support animated gifs, although stb_image doesn't support it static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp) { int i; stbi_uc *prev_out = 0; if (g->out == 0 && !stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header prev_out = g->out; g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h); if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); switch ((g->eflags & 0x1C) >> 2) { case 0: // unspecified (also always used on 1st frame) stbi__fill_gif_background(g, 0, 0, 4 * g->w, 4 * g->w * g->h); break; case 1: // do not dispose if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); g->old_out = prev_out; break; case 2: // dispose to background if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); stbi__fill_gif_background(g, g->start_x, g->start_y, g->max_x, g->max_y); break; case 3: // dispose to previous if (g->old_out) { for (i = g->start_y; i < g->max_y; i += 4 * g->w) memcpy(&g->out[i + g->start_x], &g->old_out[i + g->start_x], g->max_x - g->start_x); } break; } for (;;) { switch (stbi__get8(s)) { case 0x2C: /* Image Descriptor */ { int prev_trans = -1; stbi__int32 x, y, w, h; stbi_uc *o; x = stbi__get16le(s); y = stbi__get16le(s); w = stbi__get16le(s); h = stbi__get16le(s); if (((x + w) > (g->w)) || ((y + h) > (g->h))) return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); g->line_size = g->w * 4; g->start_x = x * 4; g->start_y = y * g->line_size; g->max_x = g->start_x + w * 4; g->max_y = g->start_y + h * g->line_size; g->cur_x = g->start_x; g->cur_y = g->start_y; g->lflags = stbi__get8(s); if (g->lflags & 0x40) { g->step = 8 * g->line_size; // first interlaced spacing g->parse = 3; } else { g->step = g->line_size; g->parse = 0; } if (g->lflags & 0x80) { stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); g->color_table = (stbi_uc *) g->lpal; } else if (g->flags & 0x80) { if (g->transparent >= 0 && (g->eflags & 0x01)) { prev_trans = g->pal[g->transparent][3]; g->pal[g->transparent][3] = 0; } g->color_table = (stbi_uc *) g->pal; } else return stbi__errpuc("missing color table", "Corrupt GIF"); o = stbi__process_gif_raster(s, g); if (o == NULL) return NULL; if (prev_trans != -1) g->pal[g->transparent][3] = (stbi_uc) prev_trans; return o; } case 0x21: // Comment Extension. { int len; if (stbi__get8(s) == 0xF9) { // Graphic Control Extension. len = stbi__get8(s); if (len == 4) { g->eflags = stbi__get8(s); g->delay = stbi__get16le(s); g->transparent = stbi__get8(s); } else { stbi__skip(s, len); break; } } while ((len = stbi__get8(s)) != 0) stbi__skip(s, len); break; } case 0x3B: // gif stream termination code return (stbi_uc *) s; // using '1' causes warning on some compilers default: return stbi__errpuc("unknown code", "Corrupt GIF"); } } STBI_NOTUSED(req_comp); } static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi_uc *u = 0; stbi__gif g; memset(&g, 0, sizeof(g)); u = stbi__gif_load_next(s, &g, comp, req_comp); if (u == (stbi_uc *) s) u = 0; // end of animated gif marker if (u) { *x = g.w; *y = g.h; if (req_comp && req_comp != 4) u = stbi__convert_format(u, 4, req_comp, g.w, g.h); } else if (g.out) STBI_FREE(g.out); return u; } static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) { return stbi__gif_info_raw(s,x,y,comp); } #endif // ************************************************************************************************* // Radiance RGBE HDR loader // originally by Nicolas Schulz #ifndef STBI_NO_HDR static int stbi__hdr_test_core(stbi__context *s) { const char *signature = "#?RADIANCE\n"; int i; for (i=0; signature[i]; ++i) if (stbi__get8(s) != signature[i]) return 0; return 1; } static int stbi__hdr_test(stbi__context* s) { int r = stbi__hdr_test_core(s); stbi__rewind(s); return r; } #define STBI__HDR_BUFLEN 1024 static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) { int len=0; char c = '\0'; c = (char) stbi__get8(z); while (!stbi__at_eof(z) && c != '\n') { buffer[len++] = c; if (len == STBI__HDR_BUFLEN-1) { // flush to end of line while (!stbi__at_eof(z) && stbi__get8(z) != '\n') ; break; } c = (char) stbi__get8(z); } buffer[len] = 0; return buffer; } static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) { if ( input[3] != 0 ) { float f1; // Exponent f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); if (req_comp <= 2) output[0] = (input[0] + input[1] + input[2]) * f1 / 3; else { output[0] = input[0] * f1; output[1] = input[1] * f1; output[2] = input[2] * f1; } if (req_comp == 2) output[1] = 1; if (req_comp == 4) output[3] = 1; } else { switch (req_comp) { case 4: output[3] = 1; /* fallthrough */ case 3: output[0] = output[1] = output[2] = 0; break; case 2: output[1] = 1; /* fallthrough */ case 1: output[0] = 0; break; } } } static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) { char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; int width, height; stbi_uc *scanline; float *hdr_data; int len; unsigned char count, value; int i, j, k, c1,c2, z; // Check identifier if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) return stbi__errpf("not HDR", "Corrupt HDR image"); // Parse header for(;;) { token = stbi__hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); // Parse width and height // can't use sscanf() if we're not using stdio! token = stbi__hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); token += 3; height = (int) strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); token += 3; width = (int) strtol(token, NULL, 10); *x = width; *y = height; if (comp) *comp = 3; if (req_comp == 0) req_comp = 3; // Read data hdr_data = (float *) stbi__malloc(height * width * req_comp * sizeof(float)); // Load image data // image data is stored as some number of sca if ( width < 8 || width >= 32768) { // Read flat data for (j=0; j < height; ++j) { for (i=0; i < width; ++i) { stbi_uc rgbe[4]; main_decode_loop: stbi__getn(s, rgbe, 4); stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); } } } else { // Read RLE-encoded data scanline = NULL; for (j = 0; j < height; ++j) { c1 = stbi__get8(s); c2 = stbi__get8(s); len = stbi__get8(s); if (c1 != 2 || c2 != 2 || (len & 0x80)) { // not run-length encoded, so we have to actually use THIS data as a decoded // pixel (note this can't be a valid pixel--one of RGB must be >= 128) stbi_uc rgbe[4]; rgbe[0] = (stbi_uc) c1; rgbe[1] = (stbi_uc) c2; rgbe[2] = (stbi_uc) len; rgbe[3] = (stbi_uc) stbi__get8(s); stbi__hdr_convert(hdr_data, rgbe, req_comp); i = 1; j = 0; STBI_FREE(scanline); goto main_decode_loop; // yes, this makes no sense } len <<= 8; len |= stbi__get8(s); if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } if (scanline == NULL) scanline = (stbi_uc *) stbi__malloc(width * 4); for (k = 0; k < 4; ++k) { i = 0; while (i < width) { count = stbi__get8(s); if (count > 128) { // Run value = stbi__get8(s); count -= 128; for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = stbi__get8(s); } } } for (i=0; i < width; ++i) stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); } STBI_FREE(scanline); } return hdr_data; } static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) { char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; if (stbi__hdr_test(s) == 0) { stbi__rewind( s ); return 0; } for(;;) { token = stbi__hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) { stbi__rewind( s ); return 0; } token = stbi__hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) { stbi__rewind( s ); return 0; } token += 3; *y = (int) strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) { stbi__rewind( s ); return 0; } token += 3; *x = (int) strtol(token, NULL, 10); *comp = 3; return 1; } #endif // STBI_NO_HDR #ifndef STBI_NO_BMP static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) { void *p; stbi__bmp_data info; info.all_a = 255; p = stbi__bmp_parse_header(s, &info); stbi__rewind( s ); if (p == NULL) return 0; *x = s->img_x; *y = s->img_y; *comp = info.ma ? 4 : 3; return 1; } #endif #ifndef STBI_NO_PSD static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) { int channelCount; if (stbi__get32be(s) != 0x38425053) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 1) { stbi__rewind( s ); return 0; } stbi__skip(s, 6); channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) { stbi__rewind( s ); return 0; } *y = stbi__get32be(s); *x = stbi__get32be(s); if (stbi__get16be(s) != 8) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 3) { stbi__rewind( s ); return 0; } *comp = 4; return 1; } #endif #ifndef STBI_NO_PIC static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) { int act_comp=0,num_packets=0,chained; stbi__pic_packet packets[10]; if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { stbi__rewind(s); return 0; } stbi__skip(s, 88); *x = stbi__get16be(s); *y = stbi__get16be(s); if (stbi__at_eof(s)) { stbi__rewind( s); return 0; } if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { stbi__rewind( s ); return 0; } stbi__skip(s, 8); do { stbi__pic_packet *packet; if (num_packets==sizeof(packets)/sizeof(packets[0])) return 0; packet = &packets[num_packets++]; chained = stbi__get8(s); packet->size = stbi__get8(s); packet->type = stbi__get8(s); packet->channel = stbi__get8(s); act_comp |= packet->channel; if (stbi__at_eof(s)) { stbi__rewind( s ); return 0; } if (packet->size != 8) { stbi__rewind( s ); return 0; } } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); return 1; } #endif // ************************************************************************************************* // Portable Gray Map and Portable Pixel Map loader // by Ken Miller // // PGM: http://netpbm.sourceforge.net/doc/pgm.html // PPM: http://netpbm.sourceforge.net/doc/ppm.html // // Known limitations: // Does not support comments in the header section // Does not support ASCII image data (formats P2 and P3) // Does not support 16-bit-per-channel #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s) { char p, t; p = (char) stbi__get8(s); t = (char) stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { stbi__rewind( s ); return 0; } return 1; } static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi_uc *out; if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) return 0; *x = s->img_x; *y = s->img_y; *comp = s->img_n; out = (stbi_uc *) stbi__malloc(s->img_n * s->img_x * s->img_y); if (!out) return stbi__errpuc("outofmem", "Out of memory"); stbi__getn(s, out, s->img_n * s->img_x * s->img_y); if (req_comp && req_comp != s->img_n) { out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // stbi__convert_format frees input on failure } return out; } static int stbi__pnm_isspace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; } static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) { for (;;) { while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) *c = (char) stbi__get8(s); if (stbi__at_eof(s) || *c != '#') break; while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) *c = (char) stbi__get8(s); } } static int stbi__pnm_isdigit(char c) { return c >= '0' && c <= '9'; } static int stbi__pnm_getinteger(stbi__context *s, char *c) { int value = 0; while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { value = value*10 + (*c - '0'); *c = (char) stbi__get8(s); } return value; } static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) { int maxv; char c, p, t; stbi__rewind( s ); // Get identifier p = (char) stbi__get8(s); t = (char) stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { stbi__rewind( s ); return 0; } *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm c = (char) stbi__get8(s); stbi__pnm_skip_whitespace(s, &c); *x = stbi__pnm_getinteger(s, &c); // read width stbi__pnm_skip_whitespace(s, &c); *y = stbi__pnm_getinteger(s, &c); // read height stbi__pnm_skip_whitespace(s, &c); maxv = stbi__pnm_getinteger(s, &c); // read max value if (maxv > 255) return stbi__err("max value > 255", "PPM image not 8-bit"); else return 1; } #endif static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) { #ifndef STBI_NO_JPEG if (stbi__jpeg_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PNG if (stbi__png_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_GIF if (stbi__gif_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_BMP if (stbi__bmp_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PSD if (stbi__psd_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PIC if (stbi__pic_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PNM if (stbi__pnm_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_HDR if (stbi__hdr_info(s, x, y, comp)) return 1; #endif // test tga last because it's a crappy test! #ifndef STBI_NO_TGA if (stbi__tga_info(s, x, y, comp)) return 1; #endif return stbi__err("unknown image type", "Image not of any known type, or corrupt"); } #ifndef STBI_NO_STDIO STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) { FILE *f = stbi__fopen(filename, "rb"); int result; if (!f) return stbi__err("can't fopen", "Unable to open file"); result = stbi_info_from_file(f, x, y, comp); fclose(f); return result; } STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) { int r; stbi__context s; long pos = ftell(f); stbi__start_file(&s, f); r = stbi__info_main(&s,x,y,comp); fseek(f,pos,SEEK_SET); return r; } #endif // !STBI_NO_STDIO STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__info_main(&s,x,y,comp); } STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi__info_main(&s,x,y,comp); } #endif // STB_IMAGE_IMPLEMENTATION /* revision history: 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED 2.09 (2016-01-16) allow comments in PNM files 16-bit-per-pixel TGA (not bit-per-component) info() for TGA could break due to .hdr handling info() for BMP to shares code instead of sloppy parse can use STBI_REALLOC_SIZED if allocator doesn't support realloc code cleanup 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA 2.07 (2015-09-13) fix compiler warnings partial animated GIF support limited 16-bpc PSD support #ifdef unused functions bug with < 92 byte PIC,PNM,HDR,TGA 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit 2.03 (2015-04-12) extra corruption checking (mmozeiko) stbi_set_flip_vertically_on_load (nguillemot) fix NEON support; fix mingw support 2.02 (2015-01-19) fix incorrect assert, fix warning 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) progressive JPEG (stb) PGM/PPM support (Ken Miller) STBI_MALLOC,STBI_REALLOC,STBI_FREE GIF bugfix -- seemingly never worked STBI_NO_*, STBI_ONLY_* 1.48 (2014-12-14) fix incorrectly-named assert() 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) optimize PNG (ryg) fix bug in interlaced PNG with user-specified channel count (stb) 1.46 (2014-08-26) fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG 1.45 (2014-08-16) fix MSVC-ARM internal compiler error by wrapping malloc 1.44 (2014-08-07) various warning fixes from Ronny Chevalier 1.43 (2014-07-15) fix MSVC-only compiler problem in code changed in 1.42 1.42 (2014-07-09) don't define _CRT_SECURE_NO_WARNINGS (affects user code) fixes to stbi__cleanup_jpeg path added STBI_ASSERT to avoid requiring assert.h 1.41 (2014-06-25) fix search&replace from 1.36 that messed up comments/error messages 1.40 (2014-06-22) fix gcc struct-initialization warning 1.39 (2014-06-15) fix to TGA optimization when req_comp != number of components in TGA; fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) add support for BMP version 5 (more ignored fields) 1.38 (2014-06-06) suppress MSVC warnings on integer casts truncating values fix accidental rename of 'skip' field of I/O 1.37 (2014-06-04) remove duplicate typedef 1.36 (2014-06-03) convert to header file single-file library if de-iphone isn't set, load iphone images color-swapped instead of returning NULL 1.35 (2014-05-27) various warnings fix broken STBI_SIMD path fix bug where stbi_load_from_file no longer left file pointer in correct place fix broken non-easy path for 32-bit BMP (possibly never used) TGA optimization by Arseny Kapoulkine 1.34 (unknown) use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case 1.33 (2011-07-14) make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements 1.32 (2011-07-13) support for "info" function for all supported filetypes (SpartanJ) 1.31 (2011-06-20) a few more leak fixes, bug in PNG handling (SpartanJ) 1.30 (2011-06-11) added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) removed deprecated format-specific test/load functions removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) fix inefficiency in decoding 32-bit BMP (David Woo) 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ) 1.27 (2010-08-01) cast-to-stbi_uc to fix warnings 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ 1.25 (2010-07-17) refix trans_data warning (Won Chun) 1.24 (2010-07-12) perf improvements reading from files on platforms with lock-heavy fgetc() minor perf improvements for jpeg deprecated type-specific functions so we'll get feedback if they're needed attempt to fix trans_data warning (Won Chun) 1.23 fixed bug in iPhone support 1.22 (2010-07-10) removed image *writing* support stbi_info support from Jetro Lauha GIF support from Jean-Marc Lienher iPhone PNG-extensions from James Brown warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) 1.21 fix use of 'stbi_uc' in header (reported by jon blow) 1.20 added support for Softimage PIC, by Tom Seddon 1.19 bug in interlaced PNG corruption check (found by ryg) 1.18 (2008-08-02) fix a threading bug (local mutable static) 1.17 support interlaced PNG 1.16 major bugfix - stbi__convert_format converted one too many pixels 1.15 initialize some fields for thread safety 1.14 fix threadsafe conversion bug header-file-only version (#define STBI_HEADER_FILE_ONLY before including) 1.13 threadsafe 1.12 const qualifiers in the API 1.11 Support installable IDCT, colorspace conversion routines 1.10 Fixes for 64-bit (don't use "unsigned long") optimized upsampling by Fabian "ryg" Giesen 1.09 Fix format-conversion for PSD code (bad global variables!) 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz 1.07 attempt to fix C++ warning/errors again 1.06 attempt to fix C++ warning/errors again 1.05 fix TGA loading to return correct *comp and use good luminance calc 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR 1.02 support for (subset of) HDR files, float interface for preferred access to them 1.01 fix bug: possible bug in handling right-side up bmps... not sure fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all 1.00 interface to zlib that skips zlib header 0.99 correct handling of alpha in palette 0.98 TGA loader by lonesock; dynamically add loaders (untested) 0.97 jpeg errors on too large a file; also catch another malloc failure 0.96 fix detection of invalid v value - particleman@mollyrocket forum 0.95 during header scan, seek to markers in case of padding 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same 0.93 handle jpegtran output; verbose errors 0.92 read 4,8,16,24,32-bit BMP files of several formats 0.91 output 24-bit Windows 3.0 BMP files 0.90 fix a few more warnings; bump version number to approach 1.0 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd 0.60 fix compiling as c++ 0.59 fix warnings: merge Dave Moore's -Wall fixes 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available 0.56 fix bug: zlib uncompressed mode len vs. nlen 0.55 fix bug: restart_interval not initialized to 0 0.54 allow NULL for 'int *comp' 0.53 fix bug in png 3->4; speedup png decoding 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments 0.51 obey req_comp requests, 1-component jpegs return as 1-component, on 'test' only check type, not whether we support this variant 0.50 (2006-11-19) first released version */
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\bgfx\fontstash.h
// // Copyright (c) 2009-2013 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #ifndef FONS_H #define FONS_H #define FONS_INVALID -1 enum FONSflags { FONS_ZERO_TOPLEFT = 1, FONS_ZERO_BOTTOMLEFT = 2, }; enum FONSalign { // Horizontal align FONS_ALIGN_LEFT = 1<<0, // Default FONS_ALIGN_CENTER = 1<<1, FONS_ALIGN_RIGHT = 1<<2, // Vertical align FONS_ALIGN_TOP = 1<<3, FONS_ALIGN_MIDDLE = 1<<4, FONS_ALIGN_BOTTOM = 1<<5, FONS_ALIGN_BASELINE = 1<<6, // Default }; enum FONSglyphBitmap { FONS_GLYPH_BITMAP_OPTIONAL = 1, FONS_GLYPH_BITMAP_REQUIRED = 2, }; enum FONSerrorCode { // Font atlas is full. FONS_ATLAS_FULL = 1, // Scratch memory used to render glyphs is full, requested size reported in 'val', you may need to bump up FONS_SCRATCH_BUF_SIZE. FONS_SCRATCH_FULL = 2, // Calls to fonsPushState has created too large stack, if you need deep state stack bump up FONS_MAX_STATES. FONS_STATES_OVERFLOW = 3, // Trying to pop too many states fonsPopState(). FONS_STATES_UNDERFLOW = 4, }; struct FONSparams { int width, height; unsigned char flags; void* userPtr; int (*renderCreate)(void* uptr, int width, int height); int (*renderResize)(void* uptr, int width, int height); void (*renderUpdate)(void* uptr, int* rect, const unsigned char* data); void (*renderDraw)(void* uptr, const float* verts, const float* tcoords, const unsigned int* colors, int nverts); void (*renderDelete)(void* uptr); }; typedef struct FONSparams FONSparams; struct FONSquad { float x0,y0,s0,t0; float x1,y1,s1,t1; }; typedef struct FONSquad FONSquad; struct FONStextIter { float x, y, nextx, nexty, scale, spacing; unsigned int codepoint; short isize, iblur; struct FONSfont* font; int prevGlyphIndex; const char* str; const char* next; const char* end; unsigned int utf8state; int bitmapOption; }; typedef struct FONStextIter FONStextIter; typedef struct FONScontext FONScontext; // Constructor and destructor. FONScontext* fonsCreateInternal(FONSparams* params); void fonsDeleteInternal(FONScontext* s); void fonsSetErrorCallback(FONScontext* s, void (*callback)(void* uptr, int error, int val), void* uptr); // Returns current atlas size. void fonsGetAtlasSize(FONScontext* s, int* width, int* height); // Expands the atlas size. int fonsExpandAtlas(FONScontext* s, int width, int height); // Resets the whole stash. int fonsResetAtlas(FONScontext* stash, int width, int height); // Add fonts int fonsAddFont(FONScontext* s, const char* name, const char* path); int fonsAddFontMem(FONScontext* s, const char* name, unsigned char* data, int ndata, int freeData); int fonsGetFontByName(FONScontext* s, const char* name); // State handling void fonsPushState(FONScontext* s); void fonsPopState(FONScontext* s); void fonsClearState(FONScontext* s); // State setting void fonsSetSize(FONScontext* s, float size); void fonsSetColor(FONScontext* s, unsigned int color); void fonsSetSpacing(FONScontext* s, float spacing); void fonsSetBlur(FONScontext* s, float blur); void fonsSetAlign(FONScontext* s, int align); void fonsSetFont(FONScontext* s, int font); // Draw text float fonsDrawText(FONScontext* s, float x, float y, const char* string, const char* end); // Measure text float fonsTextBounds(FONScontext* s, float x, float y, const char* string, const char* end, float* bounds); void fonsLineBounds(FONScontext* s, float y, float* miny, float* maxy); void fonsVertMetrics(FONScontext* s, float* ascender, float* descender, float* lineh); // Text iterator int fonsTextIterInit(FONScontext* stash, FONStextIter* iter, float x, float y, const char* str, const char* end, int bitmapOption); int fonsTextIterNext(FONScontext* stash, FONStextIter* iter, struct FONSquad* quad); // Pull texture changes const unsigned char* fonsGetTextureData(FONScontext* stash, int* width, int* height); int fonsValidateTexture(FONScontext* s, int* dirty); // Draws the stash texture for debugging void fonsDrawDebug(FONScontext* s, float x, float y); #endif // FONTSTASH_H #ifdef FONTSTASH_IMPLEMENTATION #define FONS_NOTUSED(v) BX_UNUSED(v) #ifdef FONS_USE_FREETYPE #include <ft2build.h> #include FT_FREETYPE_H #include FT_ADVANCES_H #include <math.h> struct FONSttFontImpl { FT_Face font; }; typedef struct FONSttFontImpl FONSttFontImpl; static FT_Library ftLibrary; int fons__tt_init(FONScontext *context) { FT_Error ftError; FONS_NOTUSED(context); ftError = FT_Init_FreeType(&ftLibrary); return ftError == 0; } int fons__tt_done(FONScontext *context) { FT_Error ftError; FONS_NOTUSED(context); ftError = FT_Done_FreeType(ftLibrary); return ftError == 0; } int fons__tt_loadFont(FONScontext *context, FONSttFontImpl *font, unsigned char *data, int dataSize) { FT_Error ftError; FONS_NOTUSED(context); //font->font.userdata = stash; ftError = FT_New_Memory_Face(ftLibrary, (const FT_Byte*)data, dataSize, 0, &font->font); return ftError == 0; } void fons__tt_getFontVMetrics(FONSttFontImpl *font, int *ascent, int *descent, int *lineGap) { *ascent = font->font->ascender; *descent = font->font->descender; *lineGap = font->font->height - (*ascent - *descent); } float fons__tt_getPixelHeightScale(FONSttFontImpl *font, float size) { return size / (font->font->ascender - font->font->descender); } int fons__tt_getGlyphIndex(FONSttFontImpl *font, int codepoint) { return FT_Get_Char_Index(font->font, codepoint); } int fons__tt_buildGlyphBitmap(FONSttFontImpl *font, int glyph, float size, float scale, int *advance, int *lsb, int *x0, int *y0, int *x1, int *y1) { FT_Error ftError; FT_GlyphSlot ftGlyph; FT_Fixed advFixed; FONS_NOTUSED(scale); ftError = FT_Set_Pixel_Sizes(font->font, 0, (FT_UInt)(size * (float)font->font->units_per_EM / (float)(font->font->ascender - font->font->descender))); if (ftError) return 0; ftError = FT_Load_Glyph(font->font, glyph, FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT); if (ftError) return 0; ftError = FT_Get_Advance(font->font, glyph, FT_LOAD_NO_SCALE, &advFixed); if (ftError) return 0; ftGlyph = font->font->glyph; *advance = (int)advFixed; *lsb = (int)ftGlyph->metrics.horiBearingX; *x0 = ftGlyph->bitmap_left; *x1 = *x0 + ftGlyph->bitmap.width; *y0 = -ftGlyph->bitmap_top; *y1 = *y0 + ftGlyph->bitmap.rows; return 1; } void fons__tt_renderGlyphBitmap(FONSttFontImpl *font, unsigned char *output, int outWidth, int outHeight, int outStride, float scaleX, float scaleY, int glyph) { FT_GlyphSlot ftGlyph = font->font->glyph; int ftGlyphOffset = 0; int x, y; FONS_NOTUSED(outWidth); FONS_NOTUSED(outHeight); FONS_NOTUSED(scaleX); FONS_NOTUSED(scaleY); FONS_NOTUSED(glyph); // glyph has already been loaded by fons__tt_buildGlyphBitmap for ( y = 0; y < ftGlyph->bitmap.rows; y++ ) { for ( x = 0; x < ftGlyph->bitmap.width; x++ ) { output[(y * outStride) + x] = ftGlyph->bitmap.buffer[ftGlyphOffset++]; } } } int fons__tt_getGlyphKernAdvance(FONSttFontImpl *font, int glyph1, int glyph2) { FT_Vector ftKerning; FT_Get_Kerning(font->font, glyph1, glyph2, FT_KERNING_DEFAULT, &ftKerning); return (int)((ftKerning.x + 32) >> 6); // Round up and convert to integer } #else #if 0 #define STB_TRUETYPE_IMPLEMENTATION # define STBTT_malloc(x,u) fons__tmpalloc(x,u) # define STBTT_free(x,u) fons__tmpfree(x,u) static void* fons__tmpalloc(size_t size, void* up); static void fons__tmpfree(void* ptr, void* up); #else # include <malloc.h> # include <string.h> #endif // 0 #define STBTT_DEF extern #include <stb/stb_truetype.h> struct FONSttFontImpl { stbtt_fontinfo font; }; typedef struct FONSttFontImpl FONSttFontImpl; int fons__tt_init(FONScontext *context) { FONS_NOTUSED(context); return 1; } int fons__tt_done(FONScontext *context) { FONS_NOTUSED(context); return 1; } int fons__tt_loadFont(FONScontext *context, FONSttFontImpl *font, unsigned char *data, int dataSize) { int stbError; FONS_NOTUSED(dataSize); font->font.userdata = context; stbError = stbtt_InitFont(&font->font, data, 0); return stbError; } void fons__tt_getFontVMetrics(FONSttFontImpl *font, int *ascent, int *descent, int *lineGap) { stbtt_GetFontVMetrics(&font->font, ascent, descent, lineGap); } float fons__tt_getPixelHeightScale(FONSttFontImpl *font, float size) { return stbtt_ScaleForPixelHeight(&font->font, size); } int fons__tt_getGlyphIndex(FONSttFontImpl *font, int codepoint) { return stbtt_FindGlyphIndex(&font->font, codepoint); } int fons__tt_buildGlyphBitmap(FONSttFontImpl *font, int glyph, float size, float scale, int *advance, int *lsb, int *x0, int *y0, int *x1, int *y1) { FONS_NOTUSED(size); stbtt_GetGlyphHMetrics(&font->font, glyph, advance, lsb); stbtt_GetGlyphBitmapBox(&font->font, glyph, scale, scale, x0, y0, x1, y1); return 1; } void fons__tt_renderGlyphBitmap(FONSttFontImpl *font, unsigned char *output, int outWidth, int outHeight, int outStride, float scaleX, float scaleY, int glyph) { stbtt_MakeGlyphBitmap(&font->font, output, outWidth, outHeight, outStride, scaleX, scaleY, glyph); } int fons__tt_getGlyphKernAdvance(FONSttFontImpl *font, int glyph1, int glyph2) { return stbtt_GetGlyphKernAdvance(&font->font, glyph1, glyph2); } #endif #ifndef FONS_SCRATCH_BUF_SIZE # define FONS_SCRATCH_BUF_SIZE 96000 #endif #ifndef FONS_HASH_LUT_SIZE # define FONS_HASH_LUT_SIZE 256 #endif #ifndef FONS_INIT_FONTS # define FONS_INIT_FONTS 4 #endif #ifndef FONS_INIT_GLYPHS # define FONS_INIT_GLYPHS 256 #endif #ifndef FONS_INIT_ATLAS_NODES # define FONS_INIT_ATLAS_NODES 256 #endif #ifndef FONS_VERTEX_COUNT # define FONS_VERTEX_COUNT 1024 #endif #ifndef FONS_MAX_STATES # define FONS_MAX_STATES 20 #endif #ifndef FONS_MAX_FALLBACKS # define FONS_MAX_FALLBACKS 20 #endif static unsigned int fons__hashint(unsigned int a) { a += ~(a<<15); a ^= (a>>10); a += (a<<3); a ^= (a>>6); a += ~(a<<11); a ^= (a>>16); return a; } static int fons__mini(int a, int b) { return a < b ? a : b; } static int fons__maxi(int a, int b) { return a > b ? a : b; } struct FONSglyph { unsigned int codepoint; int index; int next; short size, blur; short x0,y0,x1,y1; short xadv,xoff,yoff; }; typedef struct FONSglyph FONSglyph; struct FONSfont { FONSttFontImpl font; char name[64]; unsigned char* data; int dataSize; unsigned char freeData; float ascender; float descender; float lineh; FONSglyph* glyphs; int cglyphs; int nglyphs; int lut[FONS_HASH_LUT_SIZE]; int fallbacks[FONS_MAX_FALLBACKS]; int nfallbacks; }; typedef struct FONSfont FONSfont; struct FONSstate { int font; int align; float size; unsigned int color; float blur; float spacing; }; typedef struct FONSstate FONSstate; struct FONSatlasNode { short x, y, width; }; typedef struct FONSatlasNode FONSatlasNode; struct FONSatlas { int width, height; FONSatlasNode* nodes; int nnodes; int cnodes; }; typedef struct FONSatlas FONSatlas; struct FONScontext { FONSparams params; float itw,ith; unsigned char* texData; int dirtyRect[4]; FONSfont** fonts; FONSatlas* atlas; int cfonts; int nfonts; float verts[FONS_VERTEX_COUNT*2]; float tcoords[FONS_VERTEX_COUNT*2]; unsigned int colors[FONS_VERTEX_COUNT]; int nverts; unsigned char* scratch; int nscratch; FONSstate states[FONS_MAX_STATES]; int nstates; void (*handleError)(void* uptr, int error, int val); void* errorUptr; }; #if 0 // defined(STB_TRUETYPE_IMPLEMENTATION) static void* fons__tmpalloc(size_t size, void* up) { unsigned char* ptr; FONScontext* stash = (FONScontext*)up; // 16-byte align the returned pointer size = (size + 0xf) & ~0xf; if (stash->nscratch+(int)size > FONS_SCRATCH_BUF_SIZE) { if (stash->handleError) stash->handleError(stash->errorUptr, FONS_SCRATCH_FULL, stash->nscratch+(int)size); return NULL; } ptr = stash->scratch + stash->nscratch; stash->nscratch += (int)size; return ptr; } static void fons__tmpfree(void* ptr, void* up) { (void)ptr; (void)up; // empty } #endif // STB_TRUETYPE_IMPLEMENTATION // Copyright (c) 2008-2010 Bjoern Hoehrmann <bjoern@hoehrmann.de> // See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. #define FONS_UTF8_ACCEPT 0 #define FONS_UTF8_REJECT 12 static unsigned int fons__decutf8(unsigned int* state, unsigned int* codep, unsigned int byte) { static const unsigned char utf8d[] = { // The first part of the table maps bytes to character classes that // to reduce the size of the transition table and create bitmasks. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, // The second part is a transition table that maps a combination // of a state of the automaton and a character class to a state. 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12, 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,12,12,12,12,12, }; unsigned int type = utf8d[byte]; *codep = (*state != FONS_UTF8_ACCEPT) ? (byte & 0x3fu) | (*codep << 6) : (0xff >> type) & (byte); *state = utf8d[256 + *state + type]; return *state; } // Atlas based on Skyline Bin Packer by Jukka Jylänki static void fons__deleteAtlas(FONSatlas* atlas) { if (atlas == NULL) return; if (atlas->nodes != NULL) free(atlas->nodes); free(atlas); } static FONSatlas* fons__allocAtlas(int w, int h, int nnodes) { FONSatlas* atlas = NULL; // Allocate memory for the font stash. atlas = (FONSatlas*)malloc(sizeof(FONSatlas)); if (atlas == NULL) goto error; memset(atlas, 0, sizeof(FONSatlas)); atlas->width = w; atlas->height = h; // Allocate space for skyline nodes atlas->nodes = (FONSatlasNode*)malloc(sizeof(FONSatlasNode) * nnodes); if (atlas->nodes == NULL) goto error; memset(atlas->nodes, 0, sizeof(FONSatlasNode) * nnodes); atlas->nnodes = 0; atlas->cnodes = nnodes; // Init root node. atlas->nodes[0].x = 0; atlas->nodes[0].y = 0; atlas->nodes[0].width = (short)w; atlas->nnodes++; return atlas; error: if (atlas) fons__deleteAtlas(atlas); return NULL; } static int fons__atlasInsertNode(FONSatlas* atlas, int idx, int x, int y, int w) { int i; // Insert node if (atlas->nnodes+1 > atlas->cnodes) { atlas->cnodes = atlas->cnodes == 0 ? 8 : atlas->cnodes * 2; atlas->nodes = (FONSatlasNode*)realloc(atlas->nodes, sizeof(FONSatlasNode) * atlas->cnodes); if (atlas->nodes == NULL) return 0; } for (i = atlas->nnodes; i > idx; i--) atlas->nodes[i] = atlas->nodes[i-1]; atlas->nodes[idx].x = (short)x; atlas->nodes[idx].y = (short)y; atlas->nodes[idx].width = (short)w; atlas->nnodes++; return 1; } static void fons__atlasRemoveNode(FONSatlas* atlas, int idx) { int i; if (atlas->nnodes == 0) return; for (i = idx; i < atlas->nnodes-1; i++) atlas->nodes[i] = atlas->nodes[i+1]; atlas->nnodes--; } static void fons__atlasExpand(FONSatlas* atlas, int w, int h) { // Insert node for empty space if (w > atlas->width) fons__atlasInsertNode(atlas, atlas->nnodes, atlas->width, 0, w - atlas->width); atlas->width = w; atlas->height = h; } static void fons__atlasReset(FONSatlas* atlas, int w, int h) { atlas->width = w; atlas->height = h; atlas->nnodes = 0; // Init root node. atlas->nodes[0].x = 0; atlas->nodes[0].y = 0; atlas->nodes[0].width = (short)w; atlas->nnodes++; } static int fons__atlasAddSkylineLevel(FONSatlas* atlas, int idx, int x, int y, int w, int h) { int i; // Insert new node if (fons__atlasInsertNode(atlas, idx, x, y+h, w) == 0) return 0; // Delete skyline segments that fall under the shadow of the new segment. for (i = idx+1; i < atlas->nnodes; i++) { if (atlas->nodes[i].x < atlas->nodes[i-1].x + atlas->nodes[i-1].width) { int shrink = atlas->nodes[i-1].x + atlas->nodes[i-1].width - atlas->nodes[i].x; atlas->nodes[i].x += (short)shrink; atlas->nodes[i].width -= (short)shrink; if (atlas->nodes[i].width <= 0) { fons__atlasRemoveNode(atlas, i); i--; } else { break; } } else { break; } } // Merge same height skyline segments that are next to each other. for (i = 0; i < atlas->nnodes-1; i++) { if (atlas->nodes[i].y == atlas->nodes[i+1].y) { atlas->nodes[i].width += atlas->nodes[i+1].width; fons__atlasRemoveNode(atlas, i+1); i--; } } return 1; } static int fons__atlasRectFits(FONSatlas* atlas, int i, int w, int h) { // Checks if there is enough space at the location of skyline span 'i', // and return the max height of all skyline spans under that at that location, // (think tetris block being dropped at that position). Or -1 if no space found. int x = atlas->nodes[i].x; int y = atlas->nodes[i].y; int spaceLeft; if (x + w > atlas->width) return -1; spaceLeft = w; while (spaceLeft > 0) { if (i == atlas->nnodes) return -1; y = fons__maxi(y, atlas->nodes[i].y); if (y + h > atlas->height) return -1; spaceLeft -= atlas->nodes[i].width; ++i; } return y; } static int fons__atlasAddRect(FONSatlas* atlas, int rw, int rh, int* rx, int* ry) { int besth = atlas->height, bestw = atlas->width, besti = -1; int bestx = -1, besty = -1, i; // Bottom left fit heuristic. for (i = 0; i < atlas->nnodes; i++) { int y = fons__atlasRectFits(atlas, i, rw, rh); if (y != -1) { if (y + rh < besth || (y + rh == besth && atlas->nodes[i].width < bestw)) { besti = i; bestw = atlas->nodes[i].width; besth = y + rh; bestx = atlas->nodes[i].x; besty = y; } } } if (besti == -1) return 0; // Perform the actual packing. if (fons__atlasAddSkylineLevel(atlas, besti, bestx, besty, rw, rh) == 0) return 0; *rx = bestx; *ry = besty; return 1; } static void fons__addWhiteRect(FONScontext* stash, int w, int h) { int x, y, gx, gy; unsigned char* dst; if (fons__atlasAddRect(stash->atlas, w, h, &gx, &gy) == 0) return; // Rasterize dst = &stash->texData[gx + gy * stash->params.width]; for (y = 0; y < h; y++) { for (x = 0; x < w; x++) dst[x] = 0xff; dst += stash->params.width; } stash->dirtyRect[0] = fons__mini(stash->dirtyRect[0], gx); stash->dirtyRect[1] = fons__mini(stash->dirtyRect[1], gy); stash->dirtyRect[2] = fons__maxi(stash->dirtyRect[2], gx+w); stash->dirtyRect[3] = fons__maxi(stash->dirtyRect[3], gy+h); } FONScontext* fonsCreateInternal(FONSparams* params) { FONScontext* stash = NULL; // Allocate memory for the font stash. stash = (FONScontext*)malloc(sizeof(FONScontext)); if (stash == NULL) goto error; memset(stash, 0, sizeof(FONScontext)); stash->params = *params; // Allocate scratch buffer. stash->scratch = (unsigned char*)malloc(FONS_SCRATCH_BUF_SIZE); if (stash->scratch == NULL) goto error; // Initialize implementation library if (!fons__tt_init(stash)) goto error; if (stash->params.renderCreate != NULL) { if (stash->params.renderCreate(stash->params.userPtr, stash->params.width, stash->params.height) == 0) goto error; } stash->atlas = fons__allocAtlas(stash->params.width, stash->params.height, FONS_INIT_ATLAS_NODES); if (stash->atlas == NULL) goto error; // Allocate space for fonts. stash->fonts = (FONSfont**)malloc(sizeof(FONSfont*) * FONS_INIT_FONTS); if (stash->fonts == NULL) goto error; memset(stash->fonts, 0, sizeof(FONSfont*) * FONS_INIT_FONTS); stash->cfonts = FONS_INIT_FONTS; stash->nfonts = 0; // Create texture for the cache. stash->itw = 1.0f/stash->params.width; stash->ith = 1.0f/stash->params.height; stash->texData = (unsigned char*)malloc(stash->params.width * stash->params.height); if (stash->texData == NULL) goto error; memset(stash->texData, 0, stash->params.width * stash->params.height); stash->dirtyRect[0] = stash->params.width; stash->dirtyRect[1] = stash->params.height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; // Add white rect at 0,0 for debug drawing. fons__addWhiteRect(stash, 2,2); fonsPushState(stash); fonsClearState(stash); return stash; error: fonsDeleteInternal(stash); return NULL; } static FONSstate* fons__getState(FONScontext* stash) { return &stash->states[stash->nstates-1]; } int fonsAddFallbackFont(FONScontext* stash, int base, int fallback) { FONSfont* baseFont = stash->fonts[base]; if (baseFont->nfallbacks < FONS_MAX_FALLBACKS) { baseFont->fallbacks[baseFont->nfallbacks++] = fallback; return 1; } return 0; } void fonsSetSize(FONScontext* stash, float size) { fons__getState(stash)->size = size; } void fonsSetColor(FONScontext* stash, unsigned int color) { fons__getState(stash)->color = color; } void fonsSetSpacing(FONScontext* stash, float spacing) { fons__getState(stash)->spacing = spacing; } void fonsSetBlur(FONScontext* stash, float blur) { fons__getState(stash)->blur = blur; } void fonsSetAlign(FONScontext* stash, int align) { fons__getState(stash)->align = align; } void fonsSetFont(FONScontext* stash, int font) { fons__getState(stash)->font = font; } void fonsPushState(FONScontext* stash) { if (stash->nstates >= FONS_MAX_STATES) { if (stash->handleError) stash->handleError(stash->errorUptr, FONS_STATES_OVERFLOW, 0); return; } if (stash->nstates > 0) memcpy(&stash->states[stash->nstates], &stash->states[stash->nstates-1], sizeof(FONSstate)); stash->nstates++; } void fonsPopState(FONScontext* stash) { if (stash->nstates <= 1) { if (stash->handleError) stash->handleError(stash->errorUptr, FONS_STATES_UNDERFLOW, 0); return; } stash->nstates--; } void fonsClearState(FONScontext* stash) { FONSstate* state = fons__getState(stash); state->size = 12.0f; state->color = 0xffffffff; state->font = 0; state->blur = 0; state->spacing = 0; state->align = FONS_ALIGN_LEFT | FONS_ALIGN_BASELINE; } static void fons__freeFont(FONSfont* font) { if (font == NULL) return; if (font->glyphs) free(font->glyphs); if (font->freeData && font->data) free(font->data); free(font); } static int fons__allocFont(FONScontext* stash) { FONSfont* font = NULL; if (stash->nfonts+1 > stash->cfonts) { stash->cfonts = stash->cfonts == 0 ? 8 : stash->cfonts * 2; stash->fonts = (FONSfont**)realloc(stash->fonts, sizeof(FONSfont*) * stash->cfonts); if (stash->fonts == NULL) return -1; } font = (FONSfont*)malloc(sizeof(FONSfont)); if (font == NULL) goto error; memset(font, 0, sizeof(FONSfont)); font->glyphs = (FONSglyph*)malloc(sizeof(FONSglyph) * FONS_INIT_GLYPHS); if (font->glyphs == NULL) goto error; font->cglyphs = FONS_INIT_GLYPHS; font->nglyphs = 0; stash->fonts[stash->nfonts++] = font; return stash->nfonts-1; error: fons__freeFont(font); return FONS_INVALID; } int fonsAddFont(FONScontext* stash, const char* name, const char* path) { FILE* fp = 0; int dataSize = 0; size_t readed; unsigned char* data = NULL; // Read in the font data. fp = fopen(path, "rb"); if (fp == NULL) goto error; fseek(fp,0,SEEK_END); dataSize = (int)ftell(fp); fseek(fp,0,SEEK_SET); data = (unsigned char*)malloc(dataSize); if (data == NULL) goto error; readed = fread(data, 1, dataSize, fp); fclose(fp); fp = 0; if ((int)readed != dataSize) goto error; return fonsAddFontMem(stash, name, data, dataSize, 1); error: if (data) free(data); if (fp) fclose(fp); return FONS_INVALID; } int fonsAddFontMem(FONScontext* stash, const char* name, unsigned char* data, int dataSize, int freeData) { int i, ascent, descent, fh, lineGap; FONSfont* font; int idx = fons__allocFont(stash); if (idx == FONS_INVALID) return FONS_INVALID; font = stash->fonts[idx]; strncpy(font->name, name, sizeof(font->name)); font->name[sizeof(font->name)-1] = '\0'; // Init hash lookup. for (i = 0; i < FONS_HASH_LUT_SIZE; ++i) font->lut[i] = -1; // Read in the font data. font->dataSize = dataSize; font->data = data; font->freeData = (unsigned char)freeData; // Init font stash->nscratch = 0; if (!fons__tt_loadFont(stash, &font->font, data, dataSize)) goto error; // Store normalized line height. The real line height is got // by multiplying the lineh by font size. fons__tt_getFontVMetrics( &font->font, &ascent, &descent, &lineGap); fh = ascent - descent; font->ascender = (float)ascent / (float)fh; font->descender = (float)descent / (float)fh; font->lineh = (float)(fh + lineGap) / (float)fh; return idx; error: fons__freeFont(font); stash->nfonts--; return FONS_INVALID; } int fonsGetFontByName(FONScontext* s, const char* name) { int i; for (i = 0; i < s->nfonts; i++) { if (strcmp(s->fonts[i]->name, name) == 0) return i; } return FONS_INVALID; } static FONSglyph* fons__allocGlyph(FONSfont* font) { if (font->nglyphs+1 > font->cglyphs) { font->cglyphs = font->cglyphs == 0 ? 8 : font->cglyphs * 2; font->glyphs = (FONSglyph*)realloc(font->glyphs, sizeof(FONSglyph) * font->cglyphs); if (font->glyphs == NULL) return NULL; } font->nglyphs++; return &font->glyphs[font->nglyphs-1]; } // Based on Exponential blur, Jani Huhtanen, 2006 #define APREC 16 #define ZPREC 7 static void fons__blurCols(unsigned char* dst, int w, int h, int dstStride, int alpha) { int x, y; for (y = 0; y < h; y++) { int z = 0; // force zero border for (x = 1; x < w; x++) { z += (alpha * (((int)(dst[x]) << ZPREC) - z)) >> APREC; dst[x] = (unsigned char)(z >> ZPREC); } dst[w-1] = 0; // force zero border z = 0; for (x = w-2; x >= 0; x--) { z += (alpha * (((int)(dst[x]) << ZPREC) - z)) >> APREC; dst[x] = (unsigned char)(z >> ZPREC); } dst[0] = 0; // force zero border dst += dstStride; } } static void fons__blurRows(unsigned char* dst, int w, int h, int dstStride, int alpha) { int x, y; for (x = 0; x < w; x++) { int z = 0; // force zero border for (y = dstStride; y < h*dstStride; y += dstStride) { z += (alpha * (((int)(dst[y]) << ZPREC) - z)) >> APREC; dst[y] = (unsigned char)(z >> ZPREC); } dst[(h-1)*dstStride] = 0; // force zero border z = 0; for (y = (h-2)*dstStride; y >= 0; y -= dstStride) { z += (alpha * (((int)(dst[y]) << ZPREC) - z)) >> APREC; dst[y] = (unsigned char)(z >> ZPREC); } dst[0] = 0; // force zero border dst++; } } static void fons__blur(FONScontext* stash, unsigned char* dst, int w, int h, int dstStride, int blur) { int alpha; float sigma; (void)stash; if (blur < 1) return; // Calculate the alpha such that 90% of the kernel is within the radius. (Kernel extends to infinity) sigma = (float)blur * 0.57735f; // 1 / sqrt(3) alpha = (int)((1<<APREC) * (1.0f - expf(-2.3f / (sigma+1.0f)))); fons__blurRows(dst, w, h, dstStride, alpha); fons__blurCols(dst, w, h, dstStride, alpha); fons__blurRows(dst, w, h, dstStride, alpha); fons__blurCols(dst, w, h, dstStride, alpha); // fons__blurrows(dst, w, h, dstStride, alpha); // fons__blurcols(dst, w, h, dstStride, alpha); } static FONSglyph* fons__getGlyph(FONScontext* stash, FONSfont* font, unsigned int codepoint, short isize, short iblur, int bitmapOption) { int i, g, advance, lsb, x0, y0, x1, y1, gw, gh, gx, gy, x, y; float scale; FONSglyph* glyph = NULL; unsigned int h; float size = isize/10.0f; int pad, added; unsigned char* bdst; unsigned char* dst; FONSfont* renderFont = font; if (isize < 2) return NULL; if (iblur > 20) iblur = 20; pad = iblur+2; // Reset allocator. stash->nscratch = 0; // Find code point and size. h = fons__hashint(codepoint) & (FONS_HASH_LUT_SIZE-1); i = font->lut[h]; while (i != -1) { if (font->glyphs[i].codepoint == codepoint && font->glyphs[i].size == isize && font->glyphs[i].blur == iblur) { glyph = &font->glyphs[i]; if (bitmapOption == FONS_GLYPH_BITMAP_OPTIONAL || (glyph->x0 >= 0 && glyph->y0 >= 0)) { return glyph; } // At this point, glyph exists but the bitmap data is not yet created. break; } i = font->glyphs[i].next; } // Create a new glyph or rasterize bitmap data for a cached glyph. g = fons__tt_getGlyphIndex(&font->font, codepoint); // Try to find the glyph in fallback fonts. if (g == 0) { for (i = 0; i < font->nfallbacks; ++i) { FONSfont* fallbackFont = stash->fonts[font->fallbacks[i]]; int fallbackIndex = fons__tt_getGlyphIndex(&fallbackFont->font, codepoint); if (fallbackIndex != 0) { g = fallbackIndex; renderFont = fallbackFont; break; } } // It is possible that we did not find a fallback glyph. // In that case the glyph index 'g' is 0, and we'll proceed below and cache empty glyph. } scale = fons__tt_getPixelHeightScale(&renderFont->font, size); fons__tt_buildGlyphBitmap(&renderFont->font, g, size, scale, &advance, &lsb, &x0, &y0, &x1, &y1); gw = x1-x0 + pad*2; gh = y1-y0 + pad*2; // Determines the spot to draw glyph in the atlas. if (bitmapOption == FONS_GLYPH_BITMAP_REQUIRED) { // Find free spot for the rect in the atlas added = fons__atlasAddRect(stash->atlas, gw, gh, &gx, &gy); if (added == 0 && stash->handleError != NULL) { // Atlas is full, let the user to resize the atlas (or not), and try again. stash->handleError(stash->errorUptr, FONS_ATLAS_FULL, 0); added = fons__atlasAddRect(stash->atlas, gw, gh, &gx, &gy); } if (added == 0) return NULL; } else { // Negative coordinate indicates there is no bitmap data created. gx = -1; gy = -1; } // Init glyph. if (glyph == NULL) { glyph = fons__allocGlyph(font); glyph->codepoint = codepoint; glyph->size = isize; glyph->blur = iblur; glyph->next = 0; // Insert char to hash lookup. glyph->next = font->lut[h]; font->lut[h] = font->nglyphs-1; } glyph->index = g; glyph->x0 = (short)gx; glyph->y0 = (short)gy; glyph->x1 = (short)(glyph->x0+gw); glyph->y1 = (short)(glyph->y0+gh); glyph->xadv = (short)(scale * advance * 10.0f); glyph->xoff = (short)(x0 - pad); glyph->yoff = (short)(y0 - pad); if (bitmapOption == FONS_GLYPH_BITMAP_OPTIONAL) { return glyph; } // Rasterize dst = &stash->texData[(glyph->x0+pad) + (glyph->y0+pad) * stash->params.width]; fons__tt_renderGlyphBitmap(&renderFont->font, dst, gw-pad*2,gh-pad*2, stash->params.width, scale, scale, g); // Make sure there is one pixel empty border. dst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width]; for (y = 0; y < gh; y++) { dst[y*stash->params.width] = 0; dst[gw-1 + y*stash->params.width] = 0; } for (x = 0; x < gw; x++) { dst[x] = 0; dst[x + (gh-1)*stash->params.width] = 0; } // Debug code to color the glyph background /* unsigned char* fdst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width]; for (y = 0; y < gh; y++) { for (x = 0; x < gw; x++) { int a = (int)fdst[x+y*stash->params.width] + 20; if (a > 255) a = 255; fdst[x+y*stash->params.width] = a; } }*/ // Blur if (iblur > 0) { stash->nscratch = 0; bdst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width]; fons__blur(stash, bdst, gw, gh, stash->params.width, iblur); } stash->dirtyRect[0] = fons__mini(stash->dirtyRect[0], glyph->x0); stash->dirtyRect[1] = fons__mini(stash->dirtyRect[1], glyph->y0); stash->dirtyRect[2] = fons__maxi(stash->dirtyRect[2], glyph->x1); stash->dirtyRect[3] = fons__maxi(stash->dirtyRect[3], glyph->y1); return glyph; } static void fons__getQuad(FONScontext* stash, FONSfont* font, int prevGlyphIndex, FONSglyph* glyph, float scale, float spacing, float* x, float* y, FONSquad* q) { float rx,ry,xoff,yoff,x0,y0,x1,y1; if (prevGlyphIndex != -1) { float adv = fons__tt_getGlyphKernAdvance(&font->font, prevGlyphIndex, glyph->index) * scale; *x += (int)(adv + spacing + 0.5f); } // Each glyph has 2px border to allow good interpolation, // one pixel to prevent leaking, and one to allow good interpolation for rendering. // Inset the texture region by one pixel for correct interpolation. xoff = (short)(glyph->xoff+1); yoff = (short)(glyph->yoff+1); x0 = (float)(glyph->x0+1); y0 = (float)(glyph->y0+1); x1 = (float)(glyph->x1-1); y1 = (float)(glyph->y1-1); if (stash->params.flags & FONS_ZERO_TOPLEFT) { rx = (float)(int)(*x + xoff); ry = (float)(int)(*y + yoff); q->x0 = rx; q->y0 = ry; q->x1 = rx + x1 - x0; q->y1 = ry + y1 - y0; q->s0 = x0 * stash->itw; q->t0 = y0 * stash->ith; q->s1 = x1 * stash->itw; q->t1 = y1 * stash->ith; } else { rx = (float)(int)(*x + xoff); ry = (float)(int)(*y - yoff); q->x0 = rx; q->y0 = ry; q->x1 = rx + x1 - x0; q->y1 = ry - y1 + y0; q->s0 = x0 * stash->itw; q->t0 = y0 * stash->ith; q->s1 = x1 * stash->itw; q->t1 = y1 * stash->ith; } *x += (int)(glyph->xadv / 10.0f + 0.5f); } static void fons__flush(FONScontext* stash) { // Flush texture if (stash->dirtyRect[0] < stash->dirtyRect[2] && stash->dirtyRect[1] < stash->dirtyRect[3]) { if (stash->params.renderUpdate != NULL) stash->params.renderUpdate(stash->params.userPtr, stash->dirtyRect, stash->texData); // Reset dirty rect stash->dirtyRect[0] = stash->params.width; stash->dirtyRect[1] = stash->params.height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; } // Flush triangles if (stash->nverts > 0) { if (stash->params.renderDraw != NULL) stash->params.renderDraw(stash->params.userPtr, stash->verts, stash->tcoords, stash->colors, stash->nverts); stash->nverts = 0; } } static __inline void fons__vertex(FONScontext* stash, float x, float y, float s, float t, unsigned int c) { stash->verts[stash->nverts*2+0] = x; stash->verts[stash->nverts*2+1] = y; stash->tcoords[stash->nverts*2+0] = s; stash->tcoords[stash->nverts*2+1] = t; stash->colors[stash->nverts] = c; stash->nverts++; } static float fons__getVertAlign(FONScontext* stash, FONSfont* font, int align, short isize) { if (stash->params.flags & FONS_ZERO_TOPLEFT) { if (align & FONS_ALIGN_TOP) { return font->ascender * (float)isize/10.0f; } else if (align & FONS_ALIGN_MIDDLE) { return (font->ascender + font->descender) / 2.0f * (float)isize/10.0f; } else if (align & FONS_ALIGN_BASELINE) { return 0.0f; } else if (align & FONS_ALIGN_BOTTOM) { return font->descender * (float)isize/10.0f; } } else { if (align & FONS_ALIGN_TOP) { return -font->ascender * (float)isize/10.0f; } else if (align & FONS_ALIGN_MIDDLE) { return -(font->ascender + font->descender) / 2.0f * (float)isize/10.0f; } else if (align & FONS_ALIGN_BASELINE) { return 0.0f; } else if (align & FONS_ALIGN_BOTTOM) { return -font->descender * (float)isize/10.0f; } } return 0.0; } float fonsDrawText(FONScontext* stash, float x, float y, const char* str, const char* end) { FONSstate* state = fons__getState(stash); unsigned int codepoint; unsigned int utf8state = 0; FONSglyph* glyph = NULL; FONSquad q; int prevGlyphIndex = -1; short isize = (short)(state->size*10.0f); short iblur = (short)state->blur; float scale; FONSfont* font; float width; if (stash == NULL) return x; if (state->font < 0 || state->font >= stash->nfonts) return x; font = stash->fonts[state->font]; if (font->data == NULL) return x; scale = fons__tt_getPixelHeightScale(&font->font, (float)isize/10.0f); if (end == NULL) end = str + strlen(str); // Align horizontally if (state->align & FONS_ALIGN_LEFT) { // empty } else if (state->align & FONS_ALIGN_RIGHT) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width; } else if (state->align & FONS_ALIGN_CENTER) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width * 0.5f; } // Align vertically. y += fons__getVertAlign(stash, font, state->align, isize); for (; str != end; ++str) { if (fons__decutf8(&utf8state, &codepoint, *(const unsigned char*)str)) continue; glyph = fons__getGlyph(stash, font, codepoint, isize, iblur, FONS_GLYPH_BITMAP_REQUIRED); if (glyph != NULL) { fons__getQuad(stash, font, prevGlyphIndex, glyph, scale, state->spacing, &x, &y, &q); if (stash->nverts+6 > FONS_VERTEX_COUNT) fons__flush(stash); fons__vertex(stash, q.x0, q.y0, q.s0, q.t0, state->color); fons__vertex(stash, q.x1, q.y1, q.s1, q.t1, state->color); fons__vertex(stash, q.x1, q.y0, q.s1, q.t0, state->color); fons__vertex(stash, q.x0, q.y0, q.s0, q.t0, state->color); fons__vertex(stash, q.x0, q.y1, q.s0, q.t1, state->color); fons__vertex(stash, q.x1, q.y1, q.s1, q.t1, state->color); } prevGlyphIndex = glyph != NULL ? glyph->index : -1; } fons__flush(stash); return x; } int fonsTextIterInit(FONScontext* stash, FONStextIter* iter, float x, float y, const char* str, const char* end, int bitmapOption) { FONSstate* state = fons__getState(stash); float width; memset(iter, 0, sizeof(*iter)); if (stash == NULL) return 0; if (state->font < 0 || state->font >= stash->nfonts) return 0; iter->font = stash->fonts[state->font]; if (iter->font->data == NULL) return 0; iter->isize = (short)(state->size*10.0f); iter->iblur = (short)state->blur; iter->scale = fons__tt_getPixelHeightScale(&iter->font->font, (float)iter->isize/10.0f); // Align horizontally if (state->align & FONS_ALIGN_LEFT) { // empty } else if (state->align & FONS_ALIGN_RIGHT) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width; } else if (state->align & FONS_ALIGN_CENTER) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width * 0.5f; } // Align vertically. y += fons__getVertAlign(stash, iter->font, state->align, iter->isize); if (end == NULL) end = str + strlen(str); iter->x = iter->nextx = x; iter->y = iter->nexty = y; iter->spacing = state->spacing; iter->str = str; iter->next = str; iter->end = end; iter->codepoint = 0; iter->prevGlyphIndex = -1; iter->bitmapOption = bitmapOption; return 1; } int fonsTextIterNext(FONScontext* stash, FONStextIter* iter, FONSquad* quad) { FONSglyph* glyph = NULL; const char* str = iter->next; iter->str = iter->next; if (str == iter->end) return 0; for (; str != iter->end; str++) { if (fons__decutf8(&iter->utf8state, &iter->codepoint, *(const unsigned char*)str)) continue; str++; // Get glyph and quad iter->x = iter->nextx; iter->y = iter->nexty; glyph = fons__getGlyph(stash, iter->font, iter->codepoint, iter->isize, iter->iblur, iter->bitmapOption); // If the iterator was initialized with FONS_GLYPH_BITMAP_OPTIONAL, then the UV coordinates of the quad will be invalid. if (glyph != NULL) fons__getQuad(stash, iter->font, iter->prevGlyphIndex, glyph, iter->scale, iter->spacing, &iter->nextx, &iter->nexty, quad); iter->prevGlyphIndex = glyph != NULL ? glyph->index : -1; break; } iter->next = str; return 1; } void fonsDrawDebug(FONScontext* stash, float x, float y) { int i; int w = stash->params.width; int h = stash->params.height; float u = w == 0 ? 0 : (1.0f / w); float v = h == 0 ? 0 : (1.0f / h); if (stash->nverts+6+6 > FONS_VERTEX_COUNT) fons__flush(stash); // Draw background fons__vertex(stash, x+0, y+0, u, v, 0x0fffffff); fons__vertex(stash, x+w, y+h, u, v, 0x0fffffff); fons__vertex(stash, x+w, y+0, u, v, 0x0fffffff); fons__vertex(stash, x+0, y+0, u, v, 0x0fffffff); fons__vertex(stash, x+0, y+h, u, v, 0x0fffffff); fons__vertex(stash, x+w, y+h, u, v, 0x0fffffff); // Draw texture fons__vertex(stash, x+0, y+0, 0, 0, 0xffffffff); fons__vertex(stash, x+w, y+h, 1, 1, 0xffffffff); fons__vertex(stash, x+w, y+0, 1, 0, 0xffffffff); fons__vertex(stash, x+0, y+0, 0, 0, 0xffffffff); fons__vertex(stash, x+0, y+h, 0, 1, 0xffffffff); fons__vertex(stash, x+w, y+h, 1, 1, 0xffffffff); // Drawbug draw atlas for (i = 0; i < stash->atlas->nnodes; i++) { FONSatlasNode* n = &stash->atlas->nodes[i]; if (stash->nverts+6 > FONS_VERTEX_COUNT) fons__flush(stash); fons__vertex(stash, x+n->x+0, y+n->y+0, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+n->width, y+n->y+1, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+n->width, y+n->y+0, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+0, y+n->y+0, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+0, y+n->y+1, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+n->width, y+n->y+1, u, v, 0xc00000ff); } fons__flush(stash); } float fonsTextBounds(FONScontext* stash, float x, float y, const char* str, const char* end, float* bounds) { FONSstate* state = fons__getState(stash); unsigned int codepoint; unsigned int utf8state = 0; FONSquad q; FONSglyph* glyph = NULL; int prevGlyphIndex = -1; short isize = (short)(state->size*10.0f); short iblur = (short)state->blur; float scale; FONSfont* font; float startx, advance; float minx, miny, maxx, maxy; if (stash == NULL) return 0; if (state->font < 0 || state->font >= stash->nfonts) return 0; font = stash->fonts[state->font]; if (font->data == NULL) return 0; scale = fons__tt_getPixelHeightScale(&font->font, (float)isize/10.0f); // Align vertically. y += fons__getVertAlign(stash, font, state->align, isize); minx = maxx = x; miny = maxy = y; startx = x; if (end == NULL) end = str + strlen(str); for (; str != end; ++str) { if (fons__decutf8(&utf8state, &codepoint, *(const unsigned char*)str)) continue; glyph = fons__getGlyph(stash, font, codepoint, isize, iblur, FONS_GLYPH_BITMAP_OPTIONAL); if (glyph != NULL) { fons__getQuad(stash, font, prevGlyphIndex, glyph, scale, state->spacing, &x, &y, &q); if (q.x0 < minx) minx = q.x0; if (q.x1 > maxx) maxx = q.x1; if (stash->params.flags & FONS_ZERO_TOPLEFT) { if (q.y0 < miny) miny = q.y0; if (q.y1 > maxy) maxy = q.y1; } else { if (q.y1 < miny) miny = q.y1; if (q.y0 > maxy) maxy = q.y0; } } prevGlyphIndex = glyph != NULL ? glyph->index : -1; } advance = x - startx; // Align horizontally if (state->align & FONS_ALIGN_LEFT) { // empty } else if (state->align & FONS_ALIGN_RIGHT) { minx -= advance; maxx -= advance; } else if (state->align & FONS_ALIGN_CENTER) { minx -= advance * 0.5f; maxx -= advance * 0.5f; } if (bounds) { bounds[0] = minx; bounds[1] = miny; bounds[2] = maxx; bounds[3] = maxy; } return advance; } void fonsVertMetrics(FONScontext* stash, float* ascender, float* descender, float* lineh) { FONSfont* font; FONSstate* state = fons__getState(stash); short isize; if (stash == NULL) return; if (state->font < 0 || state->font >= stash->nfonts) return; font = stash->fonts[state->font]; isize = (short)(state->size*10.0f); if (font->data == NULL) return; if (ascender) *ascender = font->ascender*isize/10.0f; if (descender) *descender = font->descender*isize/10.0f; if (lineh) *lineh = font->lineh*isize/10.0f; } void fonsLineBounds(FONScontext* stash, float y, float* miny, float* maxy) { FONSfont* font; FONSstate* state = fons__getState(stash); short isize; if (stash == NULL) return; if (state->font < 0 || state->font >= stash->nfonts) return; font = stash->fonts[state->font]; isize = (short)(state->size*10.0f); if (font->data == NULL) return; y += fons__getVertAlign(stash, font, state->align, isize); if (stash->params.flags & FONS_ZERO_TOPLEFT) { *miny = y - font->ascender * (float)isize/10.0f; *maxy = *miny + font->lineh*isize/10.0f; } else { *maxy = y + font->descender * (float)isize/10.0f; *miny = *maxy - font->lineh*isize/10.0f; } } const unsigned char* fonsGetTextureData(FONScontext* stash, int* width, int* height) { if (width != NULL) *width = stash->params.width; if (height != NULL) *height = stash->params.height; return stash->texData; } int fonsValidateTexture(FONScontext* stash, int* dirty) { if (stash->dirtyRect[0] < stash->dirtyRect[2] && stash->dirtyRect[1] < stash->dirtyRect[3]) { dirty[0] = stash->dirtyRect[0]; dirty[1] = stash->dirtyRect[1]; dirty[2] = stash->dirtyRect[2]; dirty[3] = stash->dirtyRect[3]; // Reset dirty rect stash->dirtyRect[0] = stash->params.width; stash->dirtyRect[1] = stash->params.height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; return 1; } return 0; } void fonsDeleteInternal(FONScontext* stash) { int i; if (stash == NULL) return; if (stash->params.renderDelete) stash->params.renderDelete(stash->params.userPtr); for (i = 0; i < stash->nfonts; ++i) fons__freeFont(stash->fonts[i]); if (stash->atlas) fons__deleteAtlas(stash->atlas); if (stash->fonts) free(stash->fonts); if (stash->texData) free(stash->texData); if (stash->scratch) free(stash->scratch); free(stash); fons__tt_done(stash); } void fonsSetErrorCallback(FONScontext* stash, void (*callback)(void* uptr, int error, int val), void* uptr) { if (stash == NULL) return; stash->handleError = callback; stash->errorUptr = uptr; } void fonsGetAtlasSize(FONScontext* stash, int* width, int* height) { if (stash == NULL) return; *width = stash->params.width; *height = stash->params.height; } int fonsExpandAtlas(FONScontext* stash, int width, int height) { int i, maxy = 0; unsigned char* data = NULL; if (stash == NULL) return 0; width = fons__maxi(width, stash->params.width); height = fons__maxi(height, stash->params.height); if (width == stash->params.width && height == stash->params.height) return 1; // Flush pending glyphs. fons__flush(stash); // Create new texture if (stash->params.renderResize != NULL) { if (stash->params.renderResize(stash->params.userPtr, width, height) == 0) return 0; } // Copy old texture data over. data = (unsigned char*)malloc(width * height); if (data == NULL) return 0; for (i = 0; i < stash->params.height; i++) { unsigned char* dst = &data[i*width]; unsigned char* src = &stash->texData[i*stash->params.width]; memcpy(dst, src, stash->params.width); if (width > stash->params.width) memset(dst+stash->params.width, 0, width - stash->params.width); } if (height > stash->params.height) memset(&data[stash->params.height * width], 0, (height - stash->params.height) * width); free(stash->texData); stash->texData = data; // Increase atlas size fons__atlasExpand(stash->atlas, width, height); // Add existing data as dirty. for (i = 0; i < stash->atlas->nnodes; i++) maxy = fons__maxi(maxy, stash->atlas->nodes[i].y); stash->dirtyRect[0] = 0; stash->dirtyRect[1] = 0; stash->dirtyRect[2] = stash->params.width; stash->dirtyRect[3] = maxy; stash->params.width = width; stash->params.height = height; stash->itw = 1.0f/stash->params.width; stash->ith = 1.0f/stash->params.height; return 1; } int fonsResetAtlas(FONScontext* stash, int width, int height) { int i, j; if (stash == NULL) return 0; // Flush pending glyphs. fons__flush(stash); // Create new texture if (stash->params.renderResize != NULL) { if (stash->params.renderResize(stash->params.userPtr, width, height) == 0) return 0; } // Reset atlas fons__atlasReset(stash->atlas, width, height); // Clear texture data. stash->texData = (unsigned char*)realloc(stash->texData, width * height); if (stash->texData == NULL) return 0; memset(stash->texData, 0, width * height); // Reset dirty rect stash->dirtyRect[0] = width; stash->dirtyRect[1] = height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; // Reset cached glyphs for (i = 0; i < stash->nfonts; i++) { FONSfont* font = stash->fonts[i]; font->nglyphs = 0; for (j = 0; j < FONS_HASH_LUT_SIZE; j++) font->lut[j] = -1; } stash->params.width = width; stash->params.height = height; stash->itw = 1.0f/stash->params.width; stash->ith = 1.0f/stash->params.height; // Add white rect at 0,0 for debug drawing. fons__addWhiteRect(stash, 2,2); return 1; } #endif
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\bgfx\fs_nanovg_fill.bin.h
static const uint8_t fs_nanovg_fill_glsl[2932] = { 0x46, 0x53, 0x48, 0x06, 0xcf, 0xda, 0x1b, 0x94, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x75, // FSH............u 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x4d, 0x61, 0x74, 0x03, 0x01, 0x00, 0x00, 0x01, // _scissorMat..... 0x00, 0x0a, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x03, 0x01, 0x00, 0x00, // ..u_paintMat.... 0x01, 0x00, 0x0a, 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x02, 0x01, 0x00, // ...u_innerCol... 0x00, 0x01, 0x00, 0x0a, 0x75, 0x5f, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x02, 0x01, // ....u_outerCol.. 0x00, 0x00, 0x01, 0x00, 0x11, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x45, 0x78, // .....u_scissorEx 0x74, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x02, 0x01, 0x00, 0x00, 0x01, 0x00, 0x0e, 0x75, 0x5f, 0x65, // tScale.......u_e 0x78, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x02, 0x01, 0x00, 0x00, 0x01, // xtentRadius..... 0x00, 0x08, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x02, 0x01, 0x00, 0x00, 0x01, 0x00, // ..u_params...... 0x05, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0xd3, 0x0a, 0x00, 0x00, // .s_tex.......... 0x76, 0x61, 0x72, 0x79, 0x69, 0x6e, 0x67, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, // varying highp ve 0x63, 0x32, 0x20, 0x76, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x0a, 0x76, // c2 v_position;.v 0x61, 0x72, 0x79, 0x69, 0x6e, 0x67, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, // arying highp vec 0x32, 0x20, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x3b, 0x0a, 0x75, // 2 v_texcoord0;.u 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x6d, 0x61, 0x74, // niform highp mat 0x33, 0x20, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x4d, 0x61, 0x74, 0x3b, 0x0a, // 3 u_scissorMat;. 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x6d, 0x61, // uniform highp ma 0x74, 0x33, 0x20, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x3b, 0x0a, 0x75, // t3 u_paintMat;.u 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, // niform highp vec 0x34, 0x20, 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x3b, 0x0a, 0x75, 0x6e, // 4 u_innerCol;.un 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, // iform highp vec4 0x20, 0x75, 0x5f, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x3b, 0x0a, 0x75, 0x6e, 0x69, // u_outerCol;.uni 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, // form highp vec4 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x45, 0x78, 0x74, 0x53, 0x63, 0x61, 0x6c, // u_scissorExtScal 0x65, 0x3b, 0x0a, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, // e;.uniform highp 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x75, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x61, // vec4 u_extentRa 0x64, 0x69, 0x75, 0x73, 0x3b, 0x0a, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x68, 0x69, // dius;.uniform hi 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, // ghp vec4 u_param 0x73, 0x3b, 0x0a, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x73, 0x61, 0x6d, 0x70, 0x6c, // s;.uniform sampl 0x65, 0x72, 0x32, 0x44, 0x20, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x3b, 0x0a, 0x76, 0x6f, 0x69, 0x64, // er2D s_tex;.void 0x20, 0x6d, 0x61, 0x69, 0x6e, 0x20, 0x28, 0x29, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x6c, 0x6f, 0x77, // main ().{. low 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x31, 0x3b, // p vec4 result_1; 0x0a, 0x20, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x20, 0x74, // . highp float t 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, // mpvar_2;. highp 0x20, 0x76, 0x65, 0x63, 0x32, 0x20, 0x73, 0x63, 0x5f, 0x33, 0x3b, 0x0a, 0x20, 0x20, 0x68, 0x69, // vec2 sc_3;. hi 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x33, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, // ghp vec3 tmpvar_ 0x34, 0x3b, 0x0a, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x34, 0x2e, 0x7a, 0x20, // 4;. tmpvar_4.z 0x3d, 0x20, 0x31, 0x2e, 0x30, 0x3b, 0x0a, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, // = 1.0;. tmpvar_ 0x34, 0x2e, 0x78, 0x79, 0x20, 0x3d, 0x20, 0x76, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, // 4.xy = v_positio 0x6e, 0x3b, 0x0a, 0x20, 0x20, 0x73, 0x63, 0x5f, 0x33, 0x20, 0x3d, 0x20, 0x28, 0x76, 0x65, 0x63, // n;. sc_3 = (vec 0x32, 0x28, 0x30, 0x2e, 0x35, 0x2c, 0x20, 0x30, 0x2e, 0x35, 0x29, 0x20, 0x2d, 0x20, 0x28, 0x28, // 2(0.5, 0.5) - (( 0x0a, 0x20, 0x20, 0x20, 0x20, 0x61, 0x62, 0x73, 0x28, 0x28, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, // . abs((u_scis 0x73, 0x6f, 0x72, 0x4d, 0x61, 0x74, 0x20, 0x2a, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, // sorMat * tmpvar_ 0x34, 0x29, 0x2e, 0x78, 0x79, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x2d, 0x20, 0x75, 0x5f, 0x73, 0x63, // 4).xy). - u_sc 0x69, 0x73, 0x73, 0x6f, 0x72, 0x45, 0x78, 0x74, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x2e, 0x78, 0x79, // issorExtScale.xy 0x29, 0x20, 0x2a, 0x20, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x45, 0x78, 0x74, // ) * u_scissorExt 0x53, 0x63, 0x61, 0x6c, 0x65, 0x2e, 0x7a, 0x77, 0x29, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x74, 0x6d, // Scale.zw));. tm 0x70, 0x76, 0x61, 0x72, 0x5f, 0x32, 0x20, 0x3d, 0x20, 0x28, 0x63, 0x6c, 0x61, 0x6d, 0x70, 0x20, // pvar_2 = (clamp 0x28, 0x73, 0x63, 0x5f, 0x33, 0x2e, 0x78, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x2c, 0x20, 0x31, 0x2e, // (sc_3.x, 0.0, 1. 0x30, 0x29, 0x20, 0x2a, 0x20, 0x63, 0x6c, 0x61, 0x6d, 0x70, 0x20, 0x28, 0x73, 0x63, 0x5f, 0x33, // 0) * clamp (sc_3 0x2e, 0x79, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x3b, 0x0a, // .y, 0.0, 1.0));. 0x20, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x20, 0x74, 0x6d, // highp float tm 0x70, 0x76, 0x61, 0x72, 0x5f, 0x35, 0x3b, 0x0a, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, // pvar_5;. tmpvar 0x5f, 0x35, 0x20, 0x3d, 0x20, 0x28, 0x6d, 0x69, 0x6e, 0x20, 0x28, 0x31, 0x2e, 0x30, 0x2c, 0x20, // _5 = (min (1.0, 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x28, 0x31, 0x2e, 0x30, 0x20, 0x2d, 0x20, 0x61, 0x62, 0x73, // (. (1.0 - abs 0x28, 0x28, 0x28, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x2e, 0x78, // (((v_texcoord0.x 0x20, 0x2a, 0x20, 0x32, 0x2e, 0x30, 0x29, 0x20, 0x2d, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x29, // * 2.0) - 1.0))) 0x0a, 0x20, 0x20, 0x20, 0x2a, 0x20, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x79, // . * u_params.y 0x29, 0x29, 0x20, 0x2a, 0x20, 0x6d, 0x69, 0x6e, 0x20, 0x28, 0x31, 0x2e, 0x30, 0x2c, 0x20, 0x76, // )) * min (1.0, v 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x2e, 0x79, 0x29, 0x29, 0x3b, 0x0a, // _texcoord0.y));. 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x28, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, // if ((u_params. 0x77, 0x20, 0x3d, 0x3d, 0x20, 0x30, 0x2e, 0x30, 0x29, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, // w == 0.0)) {. 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x33, 0x20, 0x74, 0x6d, 0x70, 0x76, // highp vec3 tmpv 0x61, 0x72, 0x5f, 0x36, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, // ar_6;. tmpvar 0x5f, 0x36, 0x2e, 0x7a, 0x20, 0x3d, 0x20, 0x31, 0x2e, 0x30, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, // _6.z = 1.0;. 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x36, 0x2e, 0x78, 0x79, 0x20, 0x3d, 0x20, 0x76, 0x5f, // tmpvar_6.xy = v_ 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x68, 0x69, // position;. hi 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x32, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, // ghp vec2 tmpvar_ 0x37, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x37, 0x20, // 7;. tmpvar_7 0x3d, 0x20, 0x28, 0x61, 0x62, 0x73, 0x28, 0x28, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, // = (abs((u_paintM 0x61, 0x74, 0x20, 0x2a, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x36, 0x29, 0x2e, 0x78, // at * tmpvar_6).x 0x79, 0x29, 0x20, 0x2d, 0x20, 0x28, 0x75, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x61, // y) - (u_extentRa 0x64, 0x69, 0x75, 0x73, 0x2e, 0x78, 0x79, 0x20, 0x2d, 0x20, 0x75, 0x5f, 0x65, 0x78, 0x74, 0x65, // dius.xy - u_exte 0x6e, 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x2e, 0x7a, 0x7a, 0x29, 0x29, 0x3b, 0x0a, 0x20, // ntRadius.zz));. 0x20, 0x20, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x32, 0x20, 0x74, 0x6d, // highp vec2 tm 0x70, 0x76, 0x61, 0x72, 0x5f, 0x38, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, // pvar_8;. tmpv 0x61, 0x72, 0x5f, 0x38, 0x20, 0x3d, 0x20, 0x6d, 0x61, 0x78, 0x20, 0x28, 0x74, 0x6d, 0x70, 0x76, // ar_8 = max (tmpv 0x61, 0x72, 0x5f, 0x37, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, // ar_7, 0.0);. 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x31, 0x20, 0x3d, 0x20, 0x28, 0x6d, 0x69, 0x78, 0x20, // result_1 = (mix 0x28, 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x2c, 0x20, 0x75, 0x5f, 0x6f, // (u_innerCol, u_o 0x75, 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x2c, 0x20, 0x63, 0x6c, 0x61, 0x6d, 0x70, 0x20, 0x28, // uterCol, clamp ( 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x28, 0x28, 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, // . ((((. 0x20, 0x20, 0x20, 0x20, 0x6d, 0x69, 0x6e, 0x20, 0x28, 0x6d, 0x61, 0x78, 0x20, 0x28, 0x74, 0x6d, // min (max (tm 0x70, 0x76, 0x61, 0x72, 0x5f, 0x37, 0x2e, 0x78, 0x2c, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, // pvar_7.x, tmpvar 0x5f, 0x37, 0x2e, 0x79, 0x29, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, // _7.y), 0.0). 0x20, 0x20, 0x20, 0x2b, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x71, // + . sq 0x72, 0x74, 0x28, 0x64, 0x6f, 0x74, 0x20, 0x28, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x38, // rt(dot (tmpvar_8 0x2c, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x38, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x20, // , tmpvar_8)). 0x20, 0x20, 0x20, 0x29, 0x20, 0x2d, 0x20, 0x75, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x74, 0x52, // ) - u_extentR 0x61, 0x64, 0x69, 0x75, 0x73, 0x2e, 0x7a, 0x29, 0x20, 0x2b, 0x20, 0x28, 0x75, 0x5f, 0x70, 0x61, // adius.z) + (u_pa 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x78, 0x20, 0x2a, 0x20, 0x30, 0x2e, 0x35, 0x29, 0x29, 0x20, 0x2f, // rams.x * 0.5)) / 0x20, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x78, 0x29, 0x0a, 0x20, 0x20, 0x20, // u_params.x). 0x20, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x20, 0x2a, 0x20, // , 0.0, 1.0)) * 0x28, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x35, 0x20, 0x2a, 0x20, 0x74, 0x6d, 0x70, 0x76, // (tmpvar_5 * tmpv 0x61, 0x72, 0x5f, 0x32, 0x29, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x7d, 0x20, 0x65, 0x6c, 0x73, 0x65, // ar_2));. } else 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x28, 0x75, 0x5f, 0x70, 0x61, // {. if ((u_pa 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x77, 0x20, 0x3d, 0x3d, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x20, // rams.w == 1.0)) 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x77, 0x70, 0x20, 0x76, 0x65, 0x63, // {. lowp vec 0x34, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x39, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, // 4 color_9;. 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x33, 0x20, 0x74, 0x6d, 0x70, 0x76, // highp vec3 tmpv 0x61, 0x72, 0x5f, 0x31, 0x30, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6d, 0x70, // ar_10;. tmp 0x76, 0x61, 0x72, 0x5f, 0x31, 0x30, 0x2e, 0x7a, 0x20, 0x3d, 0x20, 0x31, 0x2e, 0x30, 0x3b, 0x0a, // var_10.z = 1.0;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x30, 0x2e, // tmpvar_10. 0x78, 0x79, 0x20, 0x3d, 0x20, 0x76, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3b, // xy = v_position; 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x77, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, // . lowp vec4 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x31, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, // tmpvar_11;. 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x31, 0x20, 0x3d, 0x20, 0x74, 0x65, // tmpvar_11 = te 0x78, 0x74, 0x75, 0x72, 0x65, 0x32, 0x44, 0x20, 0x28, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x2c, 0x20, // xture2D (s_tex, 0x28, 0x28, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x20, 0x2a, 0x20, 0x74, // ((u_paintMat * t 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x30, 0x29, 0x2e, 0x78, 0x79, 0x20, 0x2f, 0x20, 0x75, // mpvar_10).xy / u 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x2e, 0x78, 0x79, // _extentRadius.xy 0x29, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, // ));. color_ 0x39, 0x20, 0x3d, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x31, 0x3b, 0x0a, 0x20, // 9 = tmpvar_11;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x28, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, // if ((u_para 0x6d, 0x73, 0x2e, 0x7a, 0x20, 0x3d, 0x3d, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x20, 0x7b, 0x0a, // ms.z == 1.0)) {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x77, 0x70, 0x20, 0x76, 0x65, 0x63, // lowp vec 0x34, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x20, // 4 tmpvar_12;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x32, 0x2e, 0x78, // tmpvar_12.x 0x79, 0x7a, 0x20, 0x3d, 0x20, 0x28, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x31, 0x2e, // yz = (tmpvar_11. 0x78, 0x79, 0x7a, 0x20, 0x2a, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x31, 0x2e, // xyz * tmpvar_11. 0x77, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, // w);. tmpv 0x61, 0x72, 0x5f, 0x31, 0x32, 0x2e, 0x77, 0x20, 0x3d, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, // ar_12.w = tmpvar 0x5f, 0x31, 0x31, 0x2e, 0x77, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, // _11.w;. c 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x39, 0x20, 0x3d, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, // olor_9 = tmpvar_ 0x31, 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x20, // 12;. };. 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x28, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, // if ((u_params 0x2e, 0x7a, 0x20, 0x3d, 0x3d, 0x20, 0x32, 0x2e, 0x30, 0x29, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, // .z == 2.0)) {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x39, 0x20, 0x3d, 0x20, // color_9 = 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x39, 0x2e, 0x78, 0x78, 0x78, 0x78, 0x3b, 0x0a, 0x20, 0x20, // color_9.xxxx;. 0x20, 0x20, 0x20, 0x20, 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, // };. col 0x6f, 0x72, 0x5f, 0x39, 0x20, 0x3d, 0x20, 0x28, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x39, 0x20, // or_9 = (color_9 0x2a, 0x20, 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x29, 0x3b, 0x0a, 0x20, // * u_innerCol);. 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x39, 0x20, 0x3d, 0x20, 0x28, // color_9 = ( 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x39, 0x20, 0x2a, 0x20, 0x28, 0x74, 0x6d, 0x70, 0x76, 0x61, // color_9 * (tmpva 0x72, 0x5f, 0x35, 0x20, 0x2a, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x32, 0x29, 0x29, // r_5 * tmpvar_2)) 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x31, // ;. result_1 0x20, 0x3d, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x39, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, // = color_9;. 0x7d, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, // } else {. i 0x66, 0x20, 0x28, 0x28, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x77, 0x20, 0x3d, // f ((u_params.w = 0x3d, 0x20, 0x32, 0x2e, 0x30, 0x29, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // = 2.0)) {. 0x20, 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x31, 0x20, 0x3d, 0x20, 0x76, 0x65, 0x63, // result_1 = vec 0x34, 0x28, 0x31, 0x2e, 0x30, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x2c, // 4(1.0, 1.0, 1.0, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x20, 0x65, // 1.0);. } e 0x6c, 0x73, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, // lse {. if 0x20, 0x28, 0x28, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x77, 0x20, 0x3d, 0x3d, // ((u_params.w == 0x20, 0x33, 0x2e, 0x30, 0x29, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 3.0)) {. 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x77, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x63, 0x6f, 0x6c, // lowp vec4 col 0x6f, 0x72, 0x5f, 0x31, 0x33, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // or_13;. 0x20, 0x6c, 0x6f, 0x77, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, // lowp vec4 tmpva 0x72, 0x5f, 0x31, 0x34, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // r_14;. 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x34, 0x20, 0x3d, 0x20, 0x74, 0x65, 0x78, 0x74, // tmpvar_14 = text 0x75, 0x72, 0x65, 0x32, 0x44, 0x20, 0x28, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x2c, 0x20, 0x76, 0x5f, // ure2D (s_tex, v_ 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, // texcoord0);. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x31, 0x33, 0x20, 0x3d, // color_13 = 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x34, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, // tmpvar_14;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x28, 0x75, 0x5f, 0x70, 0x61, 0x72, // if ((u_par 0x61, 0x6d, 0x73, 0x2e, 0x7a, 0x20, 0x3d, 0x3d, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x20, 0x7b, // ams.z == 1.0)) { 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x77, // . low 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x35, // p vec4 tmpvar_15 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6d, // ;. tm 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x35, 0x2e, 0x78, 0x79, 0x7a, 0x20, 0x3d, 0x20, 0x28, 0x74, // pvar_15.xyz = (t 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x34, 0x2e, 0x78, 0x79, 0x7a, 0x20, 0x2a, 0x20, 0x74, // mpvar_14.xyz * t 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x34, 0x2e, 0x77, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, // mpvar_14.w);. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, // tmpvar_ 0x31, 0x35, 0x2e, 0x77, 0x20, 0x3d, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x34, // 15.w = tmpvar_14 0x2e, 0x77, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // .w;. 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x31, 0x33, 0x20, 0x3d, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, // color_13 = tmpva 0x72, 0x5f, 0x31, 0x35, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // r_15;. 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, // };. if 0x28, 0x28, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x7a, 0x20, 0x3d, 0x3d, 0x20, // ((u_params.z == 0x32, 0x2e, 0x30, 0x29, 0x29, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 2.0)) {. 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x31, 0x33, 0x20, 0x3d, 0x20, 0x63, // color_13 = c 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x31, 0x33, 0x2e, 0x78, 0x78, 0x78, 0x78, 0x3b, 0x0a, 0x20, 0x20, // olor_13.xxxx;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, // };. 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x31, 0x33, 0x20, 0x3d, 0x20, // color_13 = 0x28, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x5f, 0x31, 0x33, 0x20, 0x2a, 0x20, 0x74, 0x6d, 0x70, 0x76, // (color_13 * tmpv 0x61, 0x72, 0x5f, 0x32, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // ar_2);. 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x31, 0x20, 0x3d, 0x20, 0x28, 0x63, 0x6f, 0x6c, // result_1 = (col 0x6f, 0x72, 0x5f, 0x31, 0x33, 0x20, 0x2a, 0x20, 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, // or_13 * u_innerC 0x6f, 0x6c, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x3b, 0x0a, // ol);. };. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x3b, 0x0a, // };. };. 0x20, 0x20, 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x67, 0x6c, 0x5f, 0x46, 0x72, 0x61, 0x67, 0x43, 0x6f, // };. gl_FragCo 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x31, 0x3b, 0x0a, // lor = result_1;. 0x7d, 0x0a, 0x0a, 0x00, // }... }; static const uint8_t fs_nanovg_fill_spv[5576] = { 0x46, 0x53, 0x48, 0x06, 0xcf, 0xda, 0x1b, 0x94, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x75, // FSH............u 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x12, 0x01, 0xa0, 0x00, 0x01, 0x00, 0x0a, 0x75, 0x5f, // _params.......u_ 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x13, 0x01, 0x30, 0x00, 0x03, 0x00, 0x0e, 0x75, // paintMat..0....u 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x12, 0x01, 0x90, // _extentRadius... 0x00, 0x01, 0x00, 0x0a, 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x12, 0x01, // ....u_innerCol.. 0x60, 0x00, 0x01, 0x00, 0x0a, 0x75, 0x5f, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x12, // `....u_outerCol. 0x01, 0x70, 0x00, 0x01, 0x00, 0x0c, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x4d, // .p....u_scissorM 0x61, 0x74, 0x13, 0x01, 0x00, 0x00, 0x03, 0x00, 0x11, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, // at.......u_sciss 0x6f, 0x72, 0x45, 0x78, 0x74, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x12, 0x01, 0x80, 0x00, 0x01, 0x00, // orExtScale...... 0x30, 0x15, 0x00, 0x00, 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0x08, 0x00, // 0.....#......... 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, // ........GLSL.std 0x2e, 0x34, 0x35, 0x30, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, // .450............ 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x08, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, // ................ 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x63, 0x01, 0x00, 0x00, 0x66, 0x01, 0x00, 0x00, // main....c...f... 0x71, 0x01, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, // q............... 0x03, 0x00, 0x03, 0x00, 0x05, 0x00, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, // ................ 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x06, 0x00, // ....main........ 0x35, 0x00, 0x00, 0x00, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, // 5...s_texSampler 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x06, 0x00, 0x38, 0x00, 0x00, 0x00, 0x73, 0x5f, 0x74, 0x65, // ........8...s_te 0x78, 0x54, 0x65, 0x78, 0x74, 0x75, 0x72, 0x65, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, // xTexture........ 0x7d, 0x00, 0x00, 0x00, 0x24, 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x00, 0x06, 0x00, 0x07, 0x00, // }...$Global..... 0x7d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, // }.......u_scisso 0x72, 0x4d, 0x61, 0x74, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x7d, 0x00, 0x00, 0x00, // rMat........}... 0x01, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x00, 0x00, // ....u_paintMat.. 0x06, 0x00, 0x06, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x69, 0x6e, // ....}.......u_in 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x7d, 0x00, 0x00, 0x00, // nerCol......}... 0x03, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x00, 0x00, // ....u_outerCol.. 0x06, 0x00, 0x08, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x73, 0x63, // ....}.......u_sc 0x69, 0x73, 0x73, 0x6f, 0x72, 0x45, 0x78, 0x74, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x00, 0x00, 0x00, // issorExtScale... 0x06, 0x00, 0x07, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x65, 0x78, // ....}.......u_ex 0x74, 0x65, 0x6e, 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, // tentRadius...... 0x7d, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, // }.......u_params 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x05, 0x00, 0x05, 0x00, 0x63, 0x01, 0x00, 0x00, 0x76, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, // ....c...v_positi 0x6f, 0x6e, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x66, 0x01, 0x00, 0x00, 0x76, 0x5f, 0x74, 0x65, // on......f...v_te 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x00, 0x05, 0x00, 0x06, 0x00, 0x71, 0x01, 0x00, 0x00, // xcoord0.....q... 0x62, 0x67, 0x66, 0x78, 0x5f, 0x46, 0x72, 0x61, 0x67, 0x44, 0x61, 0x74, 0x61, 0x30, 0x00, 0x00, // bgfx_FragData0.. 0x47, 0x00, 0x04, 0x00, 0x35, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // G...5..."....... 0x47, 0x00, 0x04, 0x00, 0x35, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // G...5...!....... 0x47, 0x00, 0x04, 0x00, 0x38, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // G...8..."....... 0x47, 0x00, 0x04, 0x00, 0x38, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // G...8...!....... 0x48, 0x00, 0x04, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, // H...}........... 0x48, 0x00, 0x05, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, // H...}.......#... 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ....H...}....... 0x07, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x04, 0x00, 0x7d, 0x00, 0x00, 0x00, // ........H...}... 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x7d, 0x00, 0x00, 0x00, // ........H...}... 0x01, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, // ....#...0...H... 0x7d, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, // }............... 0x48, 0x00, 0x05, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, // H...}.......#... 0x60, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // `...H...}....... 0x23, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x7d, 0x00, 0x00, 0x00, // #...p...H...}... 0x04, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, // ....#.......H... 0x7d, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, // }.......#....... 0x48, 0x00, 0x05, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, // H...}.......#... 0xa0, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // ....G...}....... 0x47, 0x00, 0x04, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // G......."....... 0x47, 0x00, 0x04, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // G.......!....... 0x47, 0x00, 0x04, 0x00, 0x63, 0x01, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // G...c........... 0x47, 0x00, 0x04, 0x00, 0x66, 0x01, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // G...f........... 0x47, 0x00, 0x04, 0x00, 0x71, 0x01, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // G...q........... 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, // ........!....... 0x02, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x02, 0x00, 0x06, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00, // ................ 0x07, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x19, 0x00, 0x09, 0x00, 0x08, 0x00, 0x00, 0x00, // .... ........... 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, // ................ 0x0b, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, // ................ 0x0d, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, // ............ ... 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, // 4...........;... 0x34, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, // 4...5....... ... 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, // 7...........;... 0x37, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, // 7...8........... 0x3b, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, // ;... .......+... 0x3b, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, // ;...<.......+... 0x3b, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x03, 0x00, // ;...@........... 0x44, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, 0x62, 0x00, 0x00, 0x00, // D...........b... 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x62, 0x00, 0x00, 0x00, // .......+...b... 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x62, 0x00, 0x00, 0x00, // c.......+...b... 0x66, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, // f.......+....... 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, // j.......,....... 0x6d, 0x00, 0x00, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, // m...j...j...+... 0x07, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x17, 0x00, 0x04, 0x00, // ....w......?.... 0x78, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x18, 0x00, 0x04, 0x00, // x............... 0x7c, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x09, 0x00, // |...x........... 0x7d, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, // }...|...|....... 0x0d, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, // ................ 0x20, 0x00, 0x04, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, // ...~.......}... 0x3b, 0x00, 0x04, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // ;...~........... 0x20, 0x00, 0x04, 0x00, 0x80, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x00, // ...........|... 0x2b, 0x00, 0x04, 0x00, 0x3b, 0x00, 0x00, 0x00, 0x86, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, // +...;........... 0x20, 0x00, 0x04, 0x00, 0x87, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, // ............... 0x2b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, // +..............? 0x2c, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, // ,............... 0x8c, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, // ....+........... 0x00, 0x00, 0x00, 0x40, 0x2b, 0x00, 0x04, 0x00, 0x3b, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, // ...@+...;....... 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0xa5, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // .... ........... 0x07, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x62, 0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, // ....+...b....... 0x03, 0x00, 0x00, 0x00, 0x14, 0x00, 0x02, 0x00, 0xbe, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, // ............+... 0x3b, 0x00, 0x00, 0x00, 0xcc, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, // ;...........+... 0x62, 0x00, 0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, // b...........+... 0x3b, 0x00, 0x00, 0x00, 0xe1, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, // ;...........+... 0x3b, 0x00, 0x00, 0x00, 0xe2, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x07, 0x00, // ;...........,... 0x0d, 0x00, 0x00, 0x00, 0x34, 0x01, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, // ....4...w...w... 0x77, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, // w...w...+....... 0x38, 0x01, 0x00, 0x00, 0x00, 0x00, 0x40, 0x40, 0x20, 0x00, 0x04, 0x00, 0x62, 0x01, 0x00, 0x00, // 8.....@@ ...b... 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x62, 0x01, 0x00, 0x00, // ........;...b... 0x63, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x62, 0x01, 0x00, 0x00, // c.......;...b... 0x66, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x70, 0x01, 0x00, 0x00, // f....... ...p... 0x03, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x70, 0x01, 0x00, 0x00, // ........;...p... 0x71, 0x01, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x0d, 0x00, 0x00, 0x00, // q............... 0xa7, 0x02, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, // ....6........... 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, // ................ 0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, // =.......6...5... 0x3d, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x39, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, // =.......9...8... 0x3d, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x64, 0x01, 0x00, 0x00, 0x63, 0x01, 0x00, 0x00, // =.......d...c... 0x3d, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x67, 0x01, 0x00, 0x00, 0x66, 0x01, 0x00, 0x00, // =.......g...f... 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x37, 0x02, 0x00, 0x00, 0x64, 0x01, 0x00, 0x00, // Q.......7...d... 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x38, 0x02, 0x00, 0x00, // ....Q.......8... 0x64, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x50, 0x00, 0x06, 0x00, 0x78, 0x00, 0x00, 0x00, // d.......P...x... 0x39, 0x02, 0x00, 0x00, 0x37, 0x02, 0x00, 0x00, 0x38, 0x02, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, // 9...7...8...w... 0x41, 0x00, 0x05, 0x00, 0x80, 0x00, 0x00, 0x00, 0x3a, 0x02, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, // A.......:....... 0x40, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x3b, 0x02, 0x00, 0x00, // @...=...|...;... 0x3a, 0x02, 0x00, 0x00, 0x90, 0x00, 0x05, 0x00, 0x78, 0x00, 0x00, 0x00, 0x3c, 0x02, 0x00, 0x00, // :.......x...<... 0x39, 0x02, 0x00, 0x00, 0x3b, 0x02, 0x00, 0x00, 0x4f, 0x00, 0x07, 0x00, 0x0b, 0x00, 0x00, 0x00, // 9...;...O....... 0x3d, 0x02, 0x00, 0x00, 0x3c, 0x02, 0x00, 0x00, 0x3c, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // =...<...<....... 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x06, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x3e, 0x02, 0x00, 0x00, // ............>... 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x3d, 0x02, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, // ........=...A... 0x87, 0x00, 0x00, 0x00, 0x3f, 0x02, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x86, 0x00, 0x00, 0x00, // ....?........... 0x3d, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x3f, 0x02, 0x00, 0x00, // =.......@...?... 0x4f, 0x00, 0x07, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x41, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, // O.......A...@... 0x40, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x83, 0x00, 0x05, 0x00, // @............... 0x0b, 0x00, 0x00, 0x00, 0x42, 0x02, 0x00, 0x00, 0x3e, 0x02, 0x00, 0x00, 0x41, 0x02, 0x00, 0x00, // ....B...>...A... 0x41, 0x00, 0x05, 0x00, 0x87, 0x00, 0x00, 0x00, 0x44, 0x02, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, // A.......D....... 0x86, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x45, 0x02, 0x00, 0x00, // ....=.......E... 0x44, 0x02, 0x00, 0x00, 0x4f, 0x00, 0x07, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x46, 0x02, 0x00, 0x00, // D...O.......F... 0x45, 0x02, 0x00, 0x00, 0x45, 0x02, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // E...E........... 0x85, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x47, 0x02, 0x00, 0x00, 0x42, 0x02, 0x00, 0x00, // ........G...B... 0x46, 0x02, 0x00, 0x00, 0x83, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x48, 0x02, 0x00, 0x00, // F...........H... 0x8d, 0x00, 0x00, 0x00, 0x47, 0x02, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, // ....G...Q....... 0x4a, 0x02, 0x00, 0x00, 0x48, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x08, 0x00, // J...H........... 0x07, 0x00, 0x00, 0x00, 0x4b, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, // ....K.......+... 0x4a, 0x02, 0x00, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, // J...j...w...Q... 0x07, 0x00, 0x00, 0x00, 0x4d, 0x02, 0x00, 0x00, 0x48, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ....M...H....... 0x0c, 0x00, 0x08, 0x00, 0x07, 0x00, 0x00, 0x00, 0x4e, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ........N....... 0x2b, 0x00, 0x00, 0x00, 0x4d, 0x02, 0x00, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, // +...M...j...w... 0x85, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x4f, 0x02, 0x00, 0x00, 0x4b, 0x02, 0x00, 0x00, // ........O...K... 0x4e, 0x02, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x52, 0x02, 0x00, 0x00, // N...Q.......R... 0x67, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, // g............... 0x53, 0x02, 0x00, 0x00, 0x52, 0x02, 0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, 0x83, 0x00, 0x05, 0x00, // S...R........... 0x07, 0x00, 0x00, 0x00, 0x54, 0x02, 0x00, 0x00, 0x53, 0x02, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, // ....T...S...w... 0x0c, 0x00, 0x06, 0x00, 0x07, 0x00, 0x00, 0x00, 0x55, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ........U....... 0x04, 0x00, 0x00, 0x00, 0x54, 0x02, 0x00, 0x00, 0x83, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, // ....T........... 0x56, 0x02, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x55, 0x02, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, // V...w...U...A... 0xa5, 0x00, 0x00, 0x00, 0x57, 0x02, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, // ....W........... 0x66, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x58, 0x02, 0x00, 0x00, // f...=.......X... 0x57, 0x02, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x59, 0x02, 0x00, 0x00, // W...........Y... 0x56, 0x02, 0x00, 0x00, 0x58, 0x02, 0x00, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, // V...X........... 0x5a, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, // Z.......%...w... 0x59, 0x02, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x5c, 0x02, 0x00, 0x00, // Y...Q........... 0x67, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, // g............... 0x5d, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, // ].......%...w... 0x5c, 0x02, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x5e, 0x02, 0x00, 0x00, // ............^... 0x5a, 0x02, 0x00, 0x00, 0x5d, 0x02, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0xa5, 0x00, 0x00, 0x00, // Z...]...A....... 0xa1, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, // ................ 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0xa2, 0x01, 0x00, 0x00, 0xa1, 0x01, 0x00, 0x00, // =............... 0xb4, 0x00, 0x05, 0x00, 0xbe, 0x00, 0x00, 0x00, 0xa3, 0x01, 0x00, 0x00, 0xa2, 0x01, 0x00, 0x00, // ................ 0x6a, 0x00, 0x00, 0x00, 0xf7, 0x00, 0x03, 0x00, 0xa4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // j............... 0xfa, 0x00, 0x04, 0x00, 0xa3, 0x01, 0x00, 0x00, 0xa5, 0x01, 0x00, 0x00, 0xa6, 0x01, 0x00, 0x00, // ................ 0xf8, 0x00, 0x02, 0x00, 0xa5, 0x01, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, // ........Q....... 0xa8, 0x01, 0x00, 0x00, 0x64, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, // ....d.......Q... 0x07, 0x00, 0x00, 0x00, 0xa9, 0x01, 0x00, 0x00, 0x64, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ........d....... 0x50, 0x00, 0x06, 0x00, 0x78, 0x00, 0x00, 0x00, 0xaa, 0x01, 0x00, 0x00, 0xa8, 0x01, 0x00, 0x00, // P...x........... 0xa9, 0x01, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x80, 0x00, 0x00, 0x00, // ....w...A....... 0xab, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, // ........<...=... 0x7c, 0x00, 0x00, 0x00, 0xac, 0x01, 0x00, 0x00, 0xab, 0x01, 0x00, 0x00, 0x90, 0x00, 0x05, 0x00, // |............... 0x78, 0x00, 0x00, 0x00, 0xad, 0x01, 0x00, 0x00, 0xaa, 0x01, 0x00, 0x00, 0xac, 0x01, 0x00, 0x00, // x............... 0x4f, 0x00, 0x07, 0x00, 0x0b, 0x00, 0x00, 0x00, 0xae, 0x01, 0x00, 0x00, 0xad, 0x01, 0x00, 0x00, // O............... 0xad, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, // ............A... 0x87, 0x00, 0x00, 0x00, 0xb0, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xcc, 0x00, 0x00, 0x00, // ................ 0x3d, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xb1, 0x01, 0x00, 0x00, 0xb0, 0x01, 0x00, 0x00, // =............... 0x4f, 0x00, 0x07, 0x00, 0x0b, 0x00, 0x00, 0x00, 0xb2, 0x01, 0x00, 0x00, 0xb1, 0x01, 0x00, 0x00, // O............... 0xb1, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, // ............A... 0xa5, 0x00, 0x00, 0x00, 0xb3, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xcc, 0x00, 0x00, 0x00, // ................ 0xd4, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0xb4, 0x01, 0x00, 0x00, // ....=........... 0xb3, 0x01, 0x00, 0x00, 0x50, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x65, 0x02, 0x00, 0x00, // ....P.......e... 0xb4, 0x01, 0x00, 0x00, 0xb4, 0x01, 0x00, 0x00, 0x83, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, // ................ 0x66, 0x02, 0x00, 0x00, 0xb2, 0x01, 0x00, 0x00, 0x65, 0x02, 0x00, 0x00, 0x0c, 0x00, 0x06, 0x00, // f.......e....... 0x0b, 0x00, 0x00, 0x00, 0x68, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, // ....h........... 0xae, 0x01, 0x00, 0x00, 0x83, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x6a, 0x02, 0x00, 0x00, // ............j... 0x68, 0x02, 0x00, 0x00, 0x66, 0x02, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, // h...f...Q....... 0x6c, 0x02, 0x00, 0x00, 0x6a, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, // l...j.......Q... 0x07, 0x00, 0x00, 0x00, 0x6e, 0x02, 0x00, 0x00, 0x6a, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ....n...j....... 0x0c, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, 0x6f, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ........o....... 0x28, 0x00, 0x00, 0x00, 0x6c, 0x02, 0x00, 0x00, 0x6e, 0x02, 0x00, 0x00, 0x0c, 0x00, 0x07, 0x00, // (...l...n....... 0x07, 0x00, 0x00, 0x00, 0x70, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, // ....p.......%... 0x6f, 0x02, 0x00, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x0b, 0x00, 0x00, 0x00, // o...j........... 0x72, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x6a, 0x02, 0x00, 0x00, // r.......(...j... 0x6d, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x06, 0x00, 0x07, 0x00, 0x00, 0x00, 0x73, 0x02, 0x00, 0x00, // m...........s... 0x01, 0x00, 0x00, 0x00, 0x42, 0x00, 0x00, 0x00, 0x72, 0x02, 0x00, 0x00, 0x81, 0x00, 0x05, 0x00, // ....B...r....... 0x07, 0x00, 0x00, 0x00, 0x74, 0x02, 0x00, 0x00, 0x70, 0x02, 0x00, 0x00, 0x73, 0x02, 0x00, 0x00, // ....t...p...s... 0x83, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x76, 0x02, 0x00, 0x00, 0x74, 0x02, 0x00, 0x00, // ........v...t... 0xb4, 0x01, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0xa5, 0x00, 0x00, 0x00, 0xb6, 0x01, 0x00, 0x00, // ....A........... 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, // ........c...=... 0x07, 0x00, 0x00, 0x00, 0xb7, 0x01, 0x00, 0x00, 0xb6, 0x01, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, // ................ 0x07, 0x00, 0x00, 0x00, 0xb8, 0x01, 0x00, 0x00, 0xb7, 0x01, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, // ................ 0x81, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0xb9, 0x01, 0x00, 0x00, 0x76, 0x02, 0x00, 0x00, // ............v... 0xb8, 0x01, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0xa5, 0x00, 0x00, 0x00, 0xba, 0x01, 0x00, 0x00, // ....A........... 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, // ........c...=... 0x07, 0x00, 0x00, 0x00, 0xbb, 0x01, 0x00, 0x00, 0xba, 0x01, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, // ................ 0x07, 0x00, 0x00, 0x00, 0xbc, 0x01, 0x00, 0x00, 0xb9, 0x01, 0x00, 0x00, 0xbb, 0x01, 0x00, 0x00, // ................ 0x0c, 0x00, 0x08, 0x00, 0x07, 0x00, 0x00, 0x00, 0xbd, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 0x2b, 0x00, 0x00, 0x00, 0xbc, 0x01, 0x00, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, // +.......j...w... 0x50, 0x00, 0x07, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xbf, 0x01, 0x00, 0x00, 0xbd, 0x01, 0x00, 0x00, // P............... 0xbd, 0x01, 0x00, 0x00, 0xbd, 0x01, 0x00, 0x00, 0xbd, 0x01, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, // ............A... 0x87, 0x00, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xe1, 0x00, 0x00, 0x00, // ................ 0x3d, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xc1, 0x01, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, // =............... 0x41, 0x00, 0x05, 0x00, 0x87, 0x00, 0x00, 0x00, 0xc2, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, // A............... 0xe2, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xc3, 0x01, 0x00, 0x00, // ....=........... 0xc2, 0x01, 0x00, 0x00, 0x0c, 0x00, 0x08, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x7b, 0x02, 0x00, 0x00, // ............{... 0x01, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00, 0xc1, 0x01, 0x00, 0x00, 0xc3, 0x01, 0x00, 0x00, // ................ 0xbf, 0x01, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0xc7, 0x01, 0x00, 0x00, // ................ 0x5e, 0x02, 0x00, 0x00, 0x4f, 0x02, 0x00, 0x00, 0x8e, 0x00, 0x05, 0x00, 0x0d, 0x00, 0x00, 0x00, // ^...O........... 0xc9, 0x01, 0x00, 0x00, 0x7b, 0x02, 0x00, 0x00, 0xc7, 0x01, 0x00, 0x00, 0xf9, 0x00, 0x02, 0x00, // ....{........... 0xa4, 0x01, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0xa6, 0x01, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, // ............A... 0xa5, 0x00, 0x00, 0x00, 0xcb, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, // ................ 0xbb, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0xcc, 0x01, 0x00, 0x00, // ....=........... 0xcb, 0x01, 0x00, 0x00, 0xb4, 0x00, 0x05, 0x00, 0xbe, 0x00, 0x00, 0x00, 0xcd, 0x01, 0x00, 0x00, // ................ 0xcc, 0x01, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0xf7, 0x00, 0x03, 0x00, 0xce, 0x01, 0x00, 0x00, // ....w........... 0x00, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x04, 0x00, 0xcd, 0x01, 0x00, 0x00, 0xcf, 0x01, 0x00, 0x00, // ................ 0xd0, 0x01, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0xcf, 0x01, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, // ............Q... 0x07, 0x00, 0x00, 0x00, 0xd2, 0x01, 0x00, 0x00, 0x64, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........d....... 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0xd3, 0x01, 0x00, 0x00, 0x64, 0x01, 0x00, 0x00, // Q...........d... 0x01, 0x00, 0x00, 0x00, 0x50, 0x00, 0x06, 0x00, 0x78, 0x00, 0x00, 0x00, 0xd4, 0x01, 0x00, 0x00, // ....P...x....... 0xd2, 0x01, 0x00, 0x00, 0xd3, 0x01, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, // ........w...A... 0x80, 0x00, 0x00, 0x00, 0xd5, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, // ............<... 0x3d, 0x00, 0x04, 0x00, 0x7c, 0x00, 0x00, 0x00, 0xd6, 0x01, 0x00, 0x00, 0xd5, 0x01, 0x00, 0x00, // =...|........... 0x90, 0x00, 0x05, 0x00, 0x78, 0x00, 0x00, 0x00, 0xd7, 0x01, 0x00, 0x00, 0xd4, 0x01, 0x00, 0x00, // ....x........... 0xd6, 0x01, 0x00, 0x00, 0x4f, 0x00, 0x07, 0x00, 0x0b, 0x00, 0x00, 0x00, 0xd8, 0x01, 0x00, 0x00, // ....O........... 0xd7, 0x01, 0x00, 0x00, 0xd7, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 0x41, 0x00, 0x05, 0x00, 0x87, 0x00, 0x00, 0x00, 0xd9, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, // A............... 0xcc, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xda, 0x01, 0x00, 0x00, // ....=........... 0xd9, 0x01, 0x00, 0x00, 0x4f, 0x00, 0x07, 0x00, 0x0b, 0x00, 0x00, 0x00, 0xdb, 0x01, 0x00, 0x00, // ....O........... 0xda, 0x01, 0x00, 0x00, 0xda, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 0x88, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, 0xdc, 0x01, 0x00, 0x00, 0xd8, 0x01, 0x00, 0x00, // ................ 0xdb, 0x01, 0x00, 0x00, 0x56, 0x00, 0x05, 0x00, 0x44, 0x00, 0x00, 0x00, 0x81, 0x02, 0x00, 0x00, // ....V...D....... 0x39, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x57, 0x00, 0x05, 0x00, 0x0d, 0x00, 0x00, 0x00, // 9...6...W....... 0x83, 0x02, 0x00, 0x00, 0x81, 0x02, 0x00, 0x00, 0xdc, 0x01, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, // ............A... 0xa5, 0x00, 0x00, 0x00, 0xe0, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, // ................ 0xd4, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0xe1, 0x01, 0x00, 0x00, // ....=........... 0xe0, 0x01, 0x00, 0x00, 0xb4, 0x00, 0x05, 0x00, 0xbe, 0x00, 0x00, 0x00, 0xe2, 0x01, 0x00, 0x00, // ................ 0xe1, 0x01, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0xf7, 0x00, 0x03, 0x00, 0xe3, 0x01, 0x00, 0x00, // ....w........... 0x00, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x04, 0x00, 0xe2, 0x01, 0x00, 0x00, 0xe4, 0x01, 0x00, 0x00, // ................ 0xe3, 0x01, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0xe4, 0x01, 0x00, 0x00, 0x4f, 0x00, 0x08, 0x00, // ............O... 0x78, 0x00, 0x00, 0x00, 0xe6, 0x01, 0x00, 0x00, 0x83, 0x02, 0x00, 0x00, 0x83, 0x02, 0x00, 0x00, // x............... 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, // ............Q... 0x07, 0x00, 0x00, 0x00, 0xe8, 0x01, 0x00, 0x00, 0x83, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // ................ 0x8e, 0x00, 0x05, 0x00, 0x78, 0x00, 0x00, 0x00, 0xe9, 0x01, 0x00, 0x00, 0xe6, 0x01, 0x00, 0x00, // ....x........... 0xe8, 0x01, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0xeb, 0x01, 0x00, 0x00, // ....Q........... 0x83, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, // ........Q....... 0xec, 0x01, 0x00, 0x00, 0xe9, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, // ............Q... 0x07, 0x00, 0x00, 0x00, 0xed, 0x01, 0x00, 0x00, 0xe9, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0xee, 0x01, 0x00, 0x00, 0xe9, 0x01, 0x00, 0x00, // Q............... 0x02, 0x00, 0x00, 0x00, 0x50, 0x00, 0x07, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xef, 0x01, 0x00, 0x00, // ....P........... 0xec, 0x01, 0x00, 0x00, 0xed, 0x01, 0x00, 0x00, 0xee, 0x01, 0x00, 0x00, 0xeb, 0x01, 0x00, 0x00, // ................ 0xf9, 0x00, 0x02, 0x00, 0xe3, 0x01, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0xe3, 0x01, 0x00, 0x00, // ................ 0xf5, 0x00, 0x07, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xa1, 0x02, 0x00, 0x00, 0x83, 0x02, 0x00, 0x00, // ................ 0xcf, 0x01, 0x00, 0x00, 0xef, 0x01, 0x00, 0x00, 0xe4, 0x01, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, // ............A... 0xa5, 0x00, 0x00, 0x00, 0xf0, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, // ................ 0xd4, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0xf1, 0x01, 0x00, 0x00, // ....=........... 0xf0, 0x01, 0x00, 0x00, 0xb4, 0x00, 0x05, 0x00, 0xbe, 0x00, 0x00, 0x00, 0xf2, 0x01, 0x00, 0x00, // ................ 0xf1, 0x01, 0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, 0xf7, 0x00, 0x03, 0x00, 0xf3, 0x01, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x04, 0x00, 0xf2, 0x01, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, // ................ 0xf3, 0x01, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x4f, 0x00, 0x09, 0x00, // ............O... 0x0d, 0x00, 0x00, 0x00, 0xf6, 0x01, 0x00, 0x00, 0xa1, 0x02, 0x00, 0x00, 0xa1, 0x02, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0xf9, 0x00, 0x02, 0x00, 0xf3, 0x01, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0xf3, 0x01, 0x00, 0x00, // ................ 0xf5, 0x00, 0x07, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xa2, 0x02, 0x00, 0x00, 0xa1, 0x02, 0x00, 0x00, // ................ 0xe3, 0x01, 0x00, 0x00, 0xf6, 0x01, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, // ............A... 0x87, 0x00, 0x00, 0x00, 0xf7, 0x01, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xe1, 0x00, 0x00, 0x00, // ................ 0x3d, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xf8, 0x01, 0x00, 0x00, 0xf7, 0x01, 0x00, 0x00, // =............... 0x85, 0x00, 0x05, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xfa, 0x01, 0x00, 0x00, 0xa2, 0x02, 0x00, 0x00, // ................ 0xf8, 0x01, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0xfd, 0x01, 0x00, 0x00, // ................ 0x5e, 0x02, 0x00, 0x00, 0x4f, 0x02, 0x00, 0x00, 0x8e, 0x00, 0x05, 0x00, 0x0d, 0x00, 0x00, 0x00, // ^...O........... 0xff, 0x01, 0x00, 0x00, 0xfa, 0x01, 0x00, 0x00, 0xfd, 0x01, 0x00, 0x00, 0xf9, 0x00, 0x02, 0x00, // ................ 0xce, 0x01, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0xd0, 0x01, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, // ............A... 0xa5, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, // ................ 0xbb, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, // ....=........... 0x01, 0x02, 0x00, 0x00, 0xb4, 0x00, 0x05, 0x00, 0xbe, 0x00, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, // ................ 0x02, 0x02, 0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, 0xf7, 0x00, 0x03, 0x00, 0x04, 0x02, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x04, 0x00, 0x03, 0x02, 0x00, 0x00, 0x05, 0x02, 0x00, 0x00, // ................ 0x06, 0x02, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x02, 0x00, 0x00, 0xf9, 0x00, 0x02, 0x00, // ................ 0x04, 0x02, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x06, 0x02, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, // ............A... 0xa5, 0x00, 0x00, 0x00, 0x07, 0x02, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, // ................ 0xbb, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, 0x02, 0x00, 0x00, // ....=........... 0x07, 0x02, 0x00, 0x00, 0xb4, 0x00, 0x05, 0x00, 0xbe, 0x00, 0x00, 0x00, 0x09, 0x02, 0x00, 0x00, // ................ 0x08, 0x02, 0x00, 0x00, 0x38, 0x01, 0x00, 0x00, 0xf7, 0x00, 0x03, 0x00, 0x0a, 0x02, 0x00, 0x00, // ....8........... 0x00, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x04, 0x00, 0x09, 0x02, 0x00, 0x00, 0x0b, 0x02, 0x00, 0x00, // ................ 0x0a, 0x02, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x0b, 0x02, 0x00, 0x00, 0x56, 0x00, 0x05, 0x00, // ............V... 0x44, 0x00, 0x00, 0x00, 0x89, 0x02, 0x00, 0x00, 0x39, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, // D.......9...6... 0x57, 0x00, 0x05, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x8b, 0x02, 0x00, 0x00, 0x89, 0x02, 0x00, 0x00, // W............... 0x67, 0x01, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0xa5, 0x00, 0x00, 0x00, 0x0f, 0x02, 0x00, 0x00, // g...A........... 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, // ............=... 0x07, 0x00, 0x00, 0x00, 0x10, 0x02, 0x00, 0x00, 0x0f, 0x02, 0x00, 0x00, 0xb4, 0x00, 0x05, 0x00, // ................ 0xbe, 0x00, 0x00, 0x00, 0x11, 0x02, 0x00, 0x00, 0x10, 0x02, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, // ............w... 0xf7, 0x00, 0x03, 0x00, 0x12, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x04, 0x00, // ................ 0x11, 0x02, 0x00, 0x00, 0x13, 0x02, 0x00, 0x00, 0x12, 0x02, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, // ................ 0x13, 0x02, 0x00, 0x00, 0x4f, 0x00, 0x08, 0x00, 0x78, 0x00, 0x00, 0x00, 0x15, 0x02, 0x00, 0x00, // ....O...x....... 0x8b, 0x02, 0x00, 0x00, 0x8b, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 0x02, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x17, 0x02, 0x00, 0x00, // ....Q........... 0x8b, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x8e, 0x00, 0x05, 0x00, 0x78, 0x00, 0x00, 0x00, // ............x... 0x18, 0x02, 0x00, 0x00, 0x15, 0x02, 0x00, 0x00, 0x17, 0x02, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, // ............Q... 0x07, 0x00, 0x00, 0x00, 0x1a, 0x02, 0x00, 0x00, 0x8b, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // ................ 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x1b, 0x02, 0x00, 0x00, 0x18, 0x02, 0x00, 0x00, // Q............... 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x1c, 0x02, 0x00, 0x00, // ....Q........... 0x18, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, // ........Q....... 0x1d, 0x02, 0x00, 0x00, 0x18, 0x02, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x50, 0x00, 0x07, 0x00, // ............P... 0x0d, 0x00, 0x00, 0x00, 0x1e, 0x02, 0x00, 0x00, 0x1b, 0x02, 0x00, 0x00, 0x1c, 0x02, 0x00, 0x00, // ................ 0x1d, 0x02, 0x00, 0x00, 0x1a, 0x02, 0x00, 0x00, 0xf9, 0x00, 0x02, 0x00, 0x12, 0x02, 0x00, 0x00, // ................ 0xf8, 0x00, 0x02, 0x00, 0x12, 0x02, 0x00, 0x00, 0xf5, 0x00, 0x07, 0x00, 0x0d, 0x00, 0x00, 0x00, // ................ 0x9f, 0x02, 0x00, 0x00, 0x8b, 0x02, 0x00, 0x00, 0x0b, 0x02, 0x00, 0x00, 0x1e, 0x02, 0x00, 0x00, // ................ 0x13, 0x02, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0xa5, 0x00, 0x00, 0x00, 0x1f, 0x02, 0x00, 0x00, // ....A........... 0x7f, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, // ............=... 0x07, 0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00, 0x1f, 0x02, 0x00, 0x00, 0xb4, 0x00, 0x05, 0x00, // .... ........... 0xbe, 0x00, 0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, // ....!... ....... 0xf7, 0x00, 0x03, 0x00, 0x22, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x04, 0x00, // ...."........... 0x21, 0x02, 0x00, 0x00, 0x23, 0x02, 0x00, 0x00, 0x22, 0x02, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, // !...#..."....... 0x23, 0x02, 0x00, 0x00, 0x4f, 0x00, 0x09, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x25, 0x02, 0x00, 0x00, // #...O.......%... 0x9f, 0x02, 0x00, 0x00, 0x9f, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf9, 0x00, 0x02, 0x00, 0x22, 0x02, 0x00, 0x00, // ............"... 0xf8, 0x00, 0x02, 0x00, 0x22, 0x02, 0x00, 0x00, 0xf5, 0x00, 0x07, 0x00, 0x0d, 0x00, 0x00, 0x00, // ...."........... 0xa0, 0x02, 0x00, 0x00, 0x9f, 0x02, 0x00, 0x00, 0x12, 0x02, 0x00, 0x00, 0x25, 0x02, 0x00, 0x00, // ............%... 0x23, 0x02, 0x00, 0x00, 0x8e, 0x00, 0x05, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x28, 0x02, 0x00, 0x00, // #...........(... 0xa0, 0x02, 0x00, 0x00, 0x4f, 0x02, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x87, 0x00, 0x00, 0x00, // ....O...A....... 0x2a, 0x02, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xe1, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, // *...........=... 0x0d, 0x00, 0x00, 0x00, 0x2b, 0x02, 0x00, 0x00, 0x2a, 0x02, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, // ....+...*....... 0x0d, 0x00, 0x00, 0x00, 0x2c, 0x02, 0x00, 0x00, 0x28, 0x02, 0x00, 0x00, 0x2b, 0x02, 0x00, 0x00, // ....,...(...+... 0xf9, 0x00, 0x02, 0x00, 0x0a, 0x02, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x0a, 0x02, 0x00, 0x00, // ................ 0xf5, 0x00, 0x07, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xa6, 0x02, 0x00, 0x00, 0xa7, 0x02, 0x00, 0x00, // ................ 0x06, 0x02, 0x00, 0x00, 0x2c, 0x02, 0x00, 0x00, 0x22, 0x02, 0x00, 0x00, 0xf9, 0x00, 0x02, 0x00, // ....,..."....... 0x04, 0x02, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x04, 0x02, 0x00, 0x00, 0xf5, 0x00, 0x07, 0x00, // ................ 0x0d, 0x00, 0x00, 0x00, 0xa5, 0x02, 0x00, 0x00, 0x34, 0x01, 0x00, 0x00, 0x05, 0x02, 0x00, 0x00, // ........4....... 0xa6, 0x02, 0x00, 0x00, 0x0a, 0x02, 0x00, 0x00, 0xf9, 0x00, 0x02, 0x00, 0xce, 0x01, 0x00, 0x00, // ................ 0xf8, 0x00, 0x02, 0x00, 0xce, 0x01, 0x00, 0x00, 0xf5, 0x00, 0x07, 0x00, 0x0d, 0x00, 0x00, 0x00, // ................ 0xa4, 0x02, 0x00, 0x00, 0xff, 0x01, 0x00, 0x00, 0xf3, 0x01, 0x00, 0x00, 0xa5, 0x02, 0x00, 0x00, // ................ 0x04, 0x02, 0x00, 0x00, 0xf9, 0x00, 0x02, 0x00, 0xa4, 0x01, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, // ................ 0xa4, 0x01, 0x00, 0x00, 0xf5, 0x00, 0x07, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xa3, 0x02, 0x00, 0x00, // ................ 0xc9, 0x01, 0x00, 0x00, 0xa5, 0x01, 0x00, 0x00, 0xa4, 0x02, 0x00, 0x00, 0xce, 0x01, 0x00, 0x00, // ................ 0x3e, 0x00, 0x03, 0x00, 0x71, 0x01, 0x00, 0x00, 0xa3, 0x02, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00, // >...q........... 0x38, 0x00, 0x01, 0x00, 0x00, 0x00, 0xb0, 0x00, // 8....... }; static const uint8_t fs_nanovg_fill_dx9[1589] = { 0x46, 0x53, 0x48, 0x06, 0xcf, 0xda, 0x1b, 0x94, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x05, 0x73, // FSH............s 0x5f, 0x74, 0x65, 0x78, 0x30, 0x01, 0x00, 0x00, 0x01, 0x00, 0x0e, 0x75, 0x5f, 0x65, 0x78, 0x74, // _tex0......u_ext 0x65, 0x6e, 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x12, 0x01, 0x09, 0x00, 0x01, 0x00, 0x0a, // entRadius....... 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x12, 0x01, 0x06, 0x00, 0x01, 0x00, // u_innerCol...... 0x0a, 0x75, 0x5f, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x12, 0x01, 0x07, 0x00, 0x01, // .u_outerCol..... 0x00, 0x0a, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x13, 0x01, 0x03, 0x00, // ..u_paintMat.... 0x03, 0x00, 0x08, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x12, 0x01, 0x0a, 0x00, 0x01, // ...u_params..... 0x00, 0x11, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x45, 0x78, 0x74, 0x53, 0x63, // ..u_scissorExtSc 0x61, 0x6c, 0x65, 0x12, 0x01, 0x08, 0x00, 0x01, 0x00, 0x0c, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, // ale.......u_scis 0x73, 0x6f, 0x72, 0x4d, 0x61, 0x74, 0x13, 0x01, 0x00, 0x00, 0x03, 0x00, 0x94, 0x05, 0x00, 0x00, // sorMat.......... 0x00, 0x03, 0xff, 0xff, 0xfe, 0xff, 0x61, 0x00, 0x43, 0x54, 0x41, 0x42, 0x1c, 0x00, 0x00, 0x00, // ......a.CTAB.... 0x57, 0x01, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0x08, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, // W............... 0x00, 0x91, 0x00, 0x00, 0x50, 0x01, 0x00, 0x00, 0xbc, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // ....P........... 0x01, 0x00, 0x02, 0x00, 0xc4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, // ................ 0x02, 0x00, 0x09, 0x00, 0x01, 0x00, 0x00, 0x00, 0xe4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0xf4, 0x00, 0x00, 0x00, 0x02, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0xe4, 0x00, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x02, 0x00, 0x07, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 0xe4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x02, 0x00, 0x03, 0x00, // ................ 0x03, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x01, 0x00, 0x00, // ............(... 0x02, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x00, 0x00, 0xe4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x31, 0x01, 0x00, 0x00, 0x02, 0x00, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0xe4, 0x00, 0x00, 0x00, // 1............... 0x00, 0x00, 0x00, 0x00, 0x43, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // ....C........... 0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x00, 0xab, 0xab, // ........s_tex... 0x04, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x75, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x00, 0xab, // u_extentRadius.. 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x00, 0x75, 0x5f, 0x6f, 0x75, 0x74, // u_innerCol.u_out 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x00, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, // erCol.u_paintMat 0x00, 0xab, 0xab, 0xab, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x00, 0x75, 0x5f, 0x73, // ....u_params.u_s 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x45, 0x78, 0x74, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x00, 0x75, // cissorExtScale.u 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x4d, 0x61, 0x74, 0x00, 0x70, 0x73, 0x5f, 0x33, // _scissorMat.ps_3 0x5f, 0x30, 0x00, 0x4d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f, 0x66, 0x74, 0x20, 0x28, 0x52, 0x29, // _0.Microsoft (R) 0x20, 0x48, 0x4c, 0x53, 0x4c, 0x20, 0x53, 0x68, 0x61, 0x64, 0x65, 0x72, 0x20, 0x43, 0x6f, 0x6d, // HLSL Shader Com 0x70, 0x69, 0x6c, 0x65, 0x72, 0x20, 0x31, 0x30, 0x2e, 0x31, 0x00, 0xab, 0x51, 0x00, 0x00, 0x05, // piler 10.1..Q... 0x0b, 0x00, 0x0f, 0xa0, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x80, 0xbf, // .......?...@.... 0x00, 0x00, 0x80, 0x3f, 0x51, 0x00, 0x00, 0x05, 0x0c, 0x00, 0x0f, 0xa0, 0x00, 0x00, 0x00, 0x00, // ...?Q........... 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x02, // ..@@............ 0x05, 0x00, 0x00, 0x80, 0x00, 0x00, 0x03, 0x90, 0x1f, 0x00, 0x00, 0x02, 0x05, 0x00, 0x01, 0x80, // ................ 0x01, 0x00, 0x03, 0x90, 0x1f, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x90, 0x00, 0x08, 0x0f, 0xa0, // ................ 0x05, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x80, 0x01, 0x00, 0xe4, 0xa0, 0x00, 0x00, 0x55, 0x90, // ..............U. 0x04, 0x00, 0x00, 0x04, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 0xe4, 0xa0, 0x00, 0x00, 0x00, 0x90, // ................ 0x00, 0x00, 0xe4, 0x80, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 0xe4, 0x80, // ................ 0x02, 0x00, 0xe4, 0xa0, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 0xe4, 0x8b, // ................ 0x08, 0x00, 0xe4, 0xa1, 0x01, 0x00, 0x00, 0x02, 0x01, 0x00, 0x0b, 0x80, 0x0b, 0x00, 0xe4, 0xa0, // ................ 0x04, 0x00, 0x00, 0x04, 0x00, 0x00, 0x13, 0x80, 0x00, 0x00, 0xe4, 0x80, 0x08, 0x00, 0xee, 0xa1, // ................ 0x01, 0x00, 0x00, 0x80, 0x05, 0x00, 0x00, 0x03, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x55, 0x80, // ..............U. 0x00, 0x00, 0x00, 0x80, 0x04, 0x00, 0x00, 0x04, 0x00, 0x00, 0x02, 0x80, 0x01, 0x00, 0x00, 0x90, // ................ 0x0b, 0x00, 0x55, 0xa0, 0x0b, 0x00, 0xaa, 0xa0, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x02, 0x80, // ..U............. 0x00, 0x00, 0x55, 0x8c, 0x0b, 0x00, 0xff, 0xa0, 0x05, 0x00, 0x00, 0x03, 0x00, 0x00, 0x02, 0x80, // ..U............. 0x00, 0x00, 0x55, 0x80, 0x0a, 0x00, 0x55, 0xa0, 0x0a, 0x00, 0x00, 0x03, 0x01, 0x00, 0x04, 0x80, // ..U...U......... 0x00, 0x00, 0x55, 0x80, 0x0b, 0x00, 0xff, 0xa0, 0x0a, 0x00, 0x00, 0x03, 0x00, 0x00, 0x02, 0x80, // ..U............. 0x01, 0x00, 0x55, 0x90, 0x0b, 0x00, 0xff, 0xa0, 0x05, 0x00, 0x00, 0x03, 0x00, 0x00, 0x02, 0x80, // ..U............. 0x00, 0x00, 0x55, 0x80, 0x01, 0x00, 0xaa, 0x80, 0x23, 0x00, 0x00, 0x02, 0x00, 0x00, 0x04, 0x80, // ..U.....#....... 0x0a, 0x00, 0xff, 0xa0, 0x05, 0x00, 0x00, 0x03, 0x02, 0x00, 0x03, 0x80, 0x04, 0x00, 0xe4, 0xa0, // ................ 0x00, 0x00, 0x55, 0x90, 0x04, 0x00, 0x00, 0x04, 0x02, 0x00, 0x03, 0x80, 0x03, 0x00, 0xe4, 0xa0, // ..U............. 0x00, 0x00, 0x00, 0x90, 0x02, 0x00, 0xe4, 0x80, 0x02, 0x00, 0x00, 0x03, 0x02, 0x00, 0x03, 0x80, // ................ 0x02, 0x00, 0xe4, 0x80, 0x05, 0x00, 0xe4, 0xa0, 0x02, 0x00, 0x00, 0x03, 0x02, 0x00, 0x0c, 0x80, // ................ 0x09, 0x00, 0xaa, 0xa1, 0x09, 0x00, 0x44, 0xa0, 0x02, 0x00, 0x00, 0x03, 0x02, 0x00, 0x0c, 0x80, // ......D......... 0x02, 0x00, 0xe4, 0x81, 0x02, 0x00, 0x44, 0x8b, 0x0b, 0x00, 0x00, 0x03, 0x03, 0x00, 0x03, 0x80, // ......D......... 0x02, 0x00, 0xee, 0x80, 0x0c, 0x00, 0x00, 0xa0, 0x5a, 0x00, 0x00, 0x04, 0x00, 0x00, 0x08, 0x80, // ........Z....... 0x03, 0x00, 0xe4, 0x80, 0x03, 0x00, 0xe4, 0x80, 0x0c, 0x00, 0x00, 0xa0, 0x07, 0x00, 0x00, 0x02, // ................ 0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0xff, 0x80, 0x06, 0x00, 0x00, 0x02, 0x00, 0x00, 0x08, 0x80, // ................ 0x00, 0x00, 0xff, 0x80, 0x0b, 0x00, 0x00, 0x03, 0x01, 0x00, 0x04, 0x80, 0x02, 0x00, 0xaa, 0x80, // ................ 0x02, 0x00, 0xff, 0x80, 0x0a, 0x00, 0x00, 0x03, 0x02, 0x00, 0x04, 0x80, 0x01, 0x00, 0xaa, 0x80, // ................ 0x0c, 0x00, 0x00, 0xa0, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0xff, 0x80, // ................ 0x02, 0x00, 0xaa, 0x80, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0xff, 0x80, // ................ 0x09, 0x00, 0xaa, 0xa1, 0x04, 0x00, 0x00, 0x04, 0x00, 0x00, 0x08, 0x80, 0x0a, 0x00, 0x00, 0xa0, // ................ 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xff, 0x80, 0x06, 0x00, 0x00, 0x02, 0x01, 0x00, 0x01, 0x80, // ................ 0x0a, 0x00, 0x00, 0xa0, 0x05, 0x00, 0x00, 0x03, 0x00, 0x00, 0x18, 0x80, 0x00, 0x00, 0xff, 0x80, // ................ 0x01, 0x00, 0x00, 0x80, 0x05, 0x00, 0x00, 0x03, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x00, 0x80, // ................ 0x00, 0x00, 0x55, 0x80, 0x06, 0x00, 0x00, 0x02, 0x03, 0x00, 0x01, 0x80, 0x09, 0x00, 0x00, 0xa0, // ..U............. 0x06, 0x00, 0x00, 0x02, 0x03, 0x00, 0x02, 0x80, 0x09, 0x00, 0x55, 0xa0, 0x05, 0x00, 0x00, 0x03, // ..........U..... 0x01, 0x00, 0x05, 0x80, 0x02, 0x00, 0xd4, 0x80, 0x03, 0x00, 0xd4, 0x80, 0x42, 0x00, 0x00, 0x03, // ............B... 0x02, 0x00, 0x0f, 0x80, 0x01, 0x00, 0xe8, 0x80, 0x00, 0x08, 0xe4, 0xa0, 0x02, 0x00, 0x00, 0x03, // ................ 0x01, 0x00, 0x0d, 0x80, 0x01, 0x00, 0x77, 0x81, 0x0a, 0x00, 0xa7, 0xa0, 0x05, 0x00, 0x00, 0x03, // ......w......... 0x03, 0x00, 0x07, 0x80, 0x02, 0x00, 0xff, 0x80, 0x02, 0x00, 0xe4, 0x80, 0x58, 0x00, 0x00, 0x04, // ............X... 0x02, 0x00, 0x07, 0x80, 0x01, 0x00, 0xaa, 0x8c, 0x03, 0x00, 0xe4, 0x80, 0x02, 0x00, 0xe4, 0x80, // ................ 0x58, 0x00, 0x00, 0x04, 0x02, 0x00, 0x0e, 0x80, 0x01, 0x00, 0xff, 0x8c, 0x02, 0x00, 0x00, 0x80, // X............... 0x02, 0x00, 0xe4, 0x80, 0x05, 0x00, 0x00, 0x03, 0x02, 0x00, 0x0f, 0x80, 0x02, 0x00, 0xe4, 0x80, // ................ 0x06, 0x00, 0xe4, 0xa0, 0x05, 0x00, 0x00, 0x03, 0x02, 0x00, 0x0f, 0x80, 0x00, 0x00, 0x55, 0x80, // ..............U. 0x02, 0x00, 0xe4, 0x80, 0x29, 0x00, 0x02, 0x02, 0x0a, 0x00, 0xff, 0xa0, 0x01, 0x00, 0x55, 0x80, // ....).........U. 0x01, 0x00, 0x00, 0x02, 0x03, 0x00, 0x0f, 0x80, 0x0b, 0x00, 0xff, 0xa0, 0x2a, 0x00, 0x00, 0x00, // ............*... 0x01, 0x00, 0x00, 0x02, 0x01, 0x00, 0x02, 0x80, 0x0c, 0x00, 0x55, 0xa0, 0x29, 0x00, 0x02, 0x02, // ..........U.)... 0x0a, 0x00, 0xff, 0xa0, 0x01, 0x00, 0x55, 0x80, 0x42, 0x00, 0x00, 0x03, 0x04, 0x00, 0x0f, 0x80, // ......U.B....... 0x01, 0x00, 0xe4, 0x90, 0x00, 0x08, 0xe4, 0xa0, 0x05, 0x00, 0x00, 0x03, 0x05, 0x00, 0x07, 0x80, // ................ 0x04, 0x00, 0xff, 0x80, 0x04, 0x00, 0xe4, 0x80, 0x58, 0x00, 0x00, 0x04, 0x04, 0x00, 0x07, 0x80, // ........X....... 0x01, 0x00, 0xaa, 0x8c, 0x05, 0x00, 0xe4, 0x80, 0x04, 0x00, 0xe4, 0x80, 0x58, 0x00, 0x00, 0x04, // ............X... 0x04, 0x00, 0x0e, 0x80, 0x01, 0x00, 0xff, 0x8c, 0x04, 0x00, 0x00, 0x80, 0x04, 0x00, 0xe4, 0x80, // ................ 0x05, 0x00, 0x00, 0x03, 0x04, 0x00, 0x0f, 0x80, 0x00, 0x00, 0x00, 0x80, 0x04, 0x00, 0xe4, 0x80, // ................ 0x05, 0x00, 0x00, 0x03, 0x03, 0x00, 0x0f, 0x80, 0x04, 0x00, 0xe4, 0x80, 0x06, 0x00, 0xe4, 0xa0, // ................ 0x2a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x03, 0x00, 0x0f, 0x80, 0x0c, 0x00, 0x00, 0xa0, // *............... 0x2b, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x58, 0x00, 0x00, 0x04, 0x01, 0x00, 0x0f, 0x80, // +...+...X....... 0x01, 0x00, 0x00, 0x8c, 0x02, 0x00, 0xe4, 0x80, 0x03, 0x00, 0xe4, 0x80, 0x01, 0x00, 0x00, 0x02, // ................ 0x02, 0x00, 0x0f, 0x80, 0x06, 0x00, 0xe4, 0xa0, 0x02, 0x00, 0x00, 0x03, 0x02, 0x00, 0x0f, 0x80, // ................ 0x02, 0x00, 0xe4, 0x81, 0x07, 0x00, 0xe4, 0xa0, 0x04, 0x00, 0x00, 0x04, 0x02, 0x00, 0x0f, 0x80, // ................ 0x00, 0x00, 0xff, 0x80, 0x02, 0x00, 0xe4, 0x80, 0x06, 0x00, 0xe4, 0xa0, 0x05, 0x00, 0x00, 0x03, // ................ 0x02, 0x00, 0x0f, 0x80, 0x00, 0x00, 0x55, 0x80, 0x02, 0x00, 0xe4, 0x80, 0x58, 0x00, 0x00, 0x04, // ......U.....X... 0x00, 0x08, 0x0f, 0x80, 0x00, 0x00, 0xaa, 0x81, 0x02, 0x00, 0xe4, 0x80, 0x01, 0x00, 0xe4, 0x80, // ................ 0xff, 0xff, 0x00, 0x00, 0x00, // ..... }; static const uint8_t fs_nanovg_fill_dx11[2368] = { 0x46, 0x53, 0x48, 0x06, 0xcf, 0xda, 0x1b, 0x94, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x75, // FSH............u 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x4d, 0x61, 0x74, 0x13, 0x00, 0x00, 0x00, 0x03, // _scissorMat..... 0x00, 0x0a, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x13, 0x00, 0x30, 0x00, // ..u_paintMat..0. 0x03, 0x00, 0x0a, 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x12, 0x00, 0x60, // ...u_innerCol..` 0x00, 0x01, 0x00, 0x0a, 0x75, 0x5f, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x12, 0x00, // ....u_outerCol.. 0x70, 0x00, 0x01, 0x00, 0x11, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x45, 0x78, // p....u_scissorEx 0x74, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x12, 0x00, 0x80, 0x00, 0x01, 0x00, 0x0e, 0x75, 0x5f, 0x65, // tScale.......u_e 0x78, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x12, 0x00, 0x90, 0x00, 0x01, // xtentRadius..... 0x00, 0x08, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x12, 0x00, 0xa0, 0x00, 0x01, 0x00, // ..u_params...... 0x05, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x30, 0x01, 0x00, 0x00, 0x01, 0x00, 0x9c, 0x08, 0x00, 0x00, // .s_tex0......... 0x44, 0x58, 0x42, 0x43, 0x21, 0x36, 0x2a, 0x19, 0x73, 0x28, 0xce, 0xe0, 0xff, 0xcd, 0x27, 0x27, // DXBC!6*.s(....'' 0x8e, 0x5c, 0x18, 0x73, 0x01, 0x00, 0x00, 0x00, 0x9c, 0x08, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // ...s............ 0x2c, 0x00, 0x00, 0x00, 0x9c, 0x00, 0x00, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x49, 0x53, 0x47, 0x4e, // ,...........ISGN 0x68, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, // h...........P... 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x0f, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, // ................ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 0x0c, 0x0c, 0x00, 0x00, 0x53, 0x56, 0x5f, 0x50, 0x4f, 0x53, 0x49, 0x54, 0x49, 0x4f, 0x4e, 0x00, // ....SV_POSITION. 0x54, 0x45, 0x58, 0x43, 0x4f, 0x4f, 0x52, 0x44, 0x00, 0xab, 0xab, 0xab, 0x4f, 0x53, 0x47, 0x4e, // TEXCOORD....OSGN 0x2c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, // ,........... ... 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x0f, 0x00, 0x00, 0x00, 0x53, 0x56, 0x5f, 0x54, 0x41, 0x52, 0x47, 0x45, 0x54, 0x00, 0xab, 0xab, // ....SV_TARGET... 0x53, 0x48, 0x44, 0x52, 0xc4, 0x07, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0xf1, 0x01, 0x00, 0x00, // SHDR....@....... 0x59, 0x00, 0x00, 0x04, 0x46, 0x8e, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, // Y...F. ......... 0x5a, 0x00, 0x00, 0x03, 0x00, 0x60, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x18, 0x00, 0x04, // Z....`......X... 0x00, 0x70, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x55, 0x00, 0x00, 0x62, 0x10, 0x00, 0x03, // .p......UU..b... 0x32, 0x10, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x62, 0x10, 0x00, 0x03, 0xc2, 0x10, 0x10, 0x00, // 2.......b....... 0x01, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x03, 0xf2, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ....e.... ...... 0x68, 0x00, 0x00, 0x02, 0x03, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x08, 0x32, 0x00, 0x10, 0x00, // h.......8...2... 0x00, 0x00, 0x00, 0x00, 0x56, 0x15, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x46, 0x80, 0x20, 0x00, // ....V.......F. . 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x0a, 0x32, 0x00, 0x10, 0x00, // ........2...2... 0x00, 0x00, 0x00, 0x00, 0x46, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ....F. ......... 0x06, 0x10, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x46, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ........F....... 0x00, 0x00, 0x00, 0x08, 0x32, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x10, 0x00, // ....2.......F... 0x00, 0x00, 0x00, 0x00, 0x46, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // ....F. ......... 0x00, 0x00, 0x00, 0x0a, 0x32, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x10, 0x80, // ....2.......F... 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x80, 0x20, 0x80, 0x41, 0x00, 0x00, 0x00, // ........F. .A... 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x32, 0x20, 0x00, 0x0e, 0x32, 0x00, 0x10, 0x00, // ........2 ..2... 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x10, 0x80, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ....F...A....... 0xe6, 0x8a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, // .. ..........@.. 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...?...?........ 0x38, 0x00, 0x00, 0x07, 0x12, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x10, 0x00, // 8............... 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x09, // ............2... 0x22, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, 0x10, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, // ".......*....... 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x80, 0xbf, // .@.....@.@...... 0x00, 0x00, 0x00, 0x08, 0x22, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x10, 0x80, // ...."........... 0xc1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, // .........@.....? 0x38, 0x00, 0x00, 0x08, 0x22, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x10, 0x00, // 8..."........... 0x00, 0x00, 0x00, 0x00, 0x1a, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, // ...... ......... 0x33, 0x00, 0x00, 0x07, 0x22, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x10, 0x00, // 3..."........... 0x00, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x33, 0x00, 0x00, 0x07, // .....@.....?3... 0x42, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x10, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, // B.......:....... 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x38, 0x00, 0x00, 0x07, 0x22, 0x00, 0x10, 0x00, // .@.....?8..."... 0x00, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x10, 0x00, // ....*........... 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x08, 0x42, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ........B....... 0x3a, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, // :. ..........@.. 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x04, 0x03, 0x2a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ........*....... 0x38, 0x00, 0x00, 0x08, 0xc2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x15, 0x10, 0x00, // 8...........V... 0x01, 0x00, 0x00, 0x00, 0x06, 0x84, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, // ...... ......... 0x32, 0x00, 0x00, 0x0a, 0xc2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x84, 0x20, 0x00, // 2............. . 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x06, 0x10, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, // ................ 0xa6, 0x0e, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0xc2, 0x00, 0x10, 0x00, // ................ 0x00, 0x00, 0x00, 0x00, 0xa6, 0x0e, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x84, 0x20, 0x00, // .............. . 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x32, 0x00, 0x10, 0x00, // ............2... 0x01, 0x00, 0x00, 0x00, 0xa6, 0x8a, 0x20, 0x80, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...... .A....... 0x09, 0x00, 0x00, 0x00, 0x46, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, // ....F. ......... 0x00, 0x00, 0x00, 0x09, 0xc2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa6, 0x0e, 0x10, 0x80, // ................ 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x04, 0x10, 0x80, 0x41, 0x00, 0x00, 0x00, // ............A... 0x01, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x07, 0x12, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, // ....4........... 0x3a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // :.......*....... 0x33, 0x00, 0x00, 0x07, 0x12, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, // 3............... 0x01, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x0a, // .....@......4... 0xc2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa6, 0x0e, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x02, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // .@.............. 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x07, 0x42, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ........B....... 0xe6, 0x0a, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe6, 0x0a, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x4b, 0x00, 0x00, 0x05, 0x42, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x10, 0x00, // K...B.......*... 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x42, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ........B....... 0x2a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, // *............... 0x00, 0x00, 0x00, 0x09, 0x42, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x10, 0x00, // ....B.......*... 0x00, 0x00, 0x00, 0x00, 0x2a, 0x80, 0x20, 0x80, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ....*. .A....... 0x09, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x0a, 0x42, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ....2...B....... 0x0a, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, // .. ..........@.. 0x00, 0x00, 0x00, 0x3f, 0x2a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x20, 0x00, 0x08, // ...?*........ .. 0x42, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // B.......*....... 0x0a, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, // .. ............. 0xf2, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x46, 0x8e, 0x20, 0x80, 0x41, 0x00, 0x00, 0x00, // ........F. .A... 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x46, 0x8e, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, // ........F. ..... 0x07, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x0a, 0xf2, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, // ....2........... 0xa6, 0x0a, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x0e, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, // ........F....... 0x46, 0x8e, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x07, // F. .........8... 0x42, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // B............... 0x1a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x07, 0xf2, 0x20, 0x10, 0x00, // ........8.... .. 0x00, 0x00, 0x00, 0x00, 0xa6, 0x0a, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x0e, 0x10, 0x00, // ............F... 0x01, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x01, 0x18, 0x00, 0x00, 0x08, 0x42, 0x00, 0x10, 0x00, // ............B... 0x00, 0x00, 0x00, 0x00, 0x3a, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, // ....:. ......... 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x1f, 0x00, 0x04, 0x03, 0x2a, 0x00, 0x10, 0x00, // .@.....?....*... 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x08, 0xc2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ....8........... 0x56, 0x15, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x84, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, // V......... ..... 0x04, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x0a, 0xc2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ....2........... 0x06, 0x84, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x06, 0x10, 0x10, 0x00, // .. ............. 0x01, 0x00, 0x00, 0x00, 0xa6, 0x0e, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, // ................ 0xc2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa6, 0x0e, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x06, 0x84, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x08, // .. ............. 0xc2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa6, 0x0e, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x06, 0x84, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x09, // .. .........E... 0xf2, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0xe6, 0x0a, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x46, 0x7e, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // F~.......`...... 0x18, 0x00, 0x00, 0x0b, 0xc2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa6, 0x8a, 0x20, 0x00, // .............. . 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // .........@...... 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x38, 0x00, 0x00, 0x07, // .......?...@8... 0x72, 0x00, 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0xf6, 0x0f, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, // r............... 0x46, 0x02, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x09, 0x72, 0x00, 0x10, 0x00, // F.......7...r... 0x01, 0x00, 0x00, 0x00, 0xa6, 0x0a, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x02, 0x10, 0x00, // ............F... 0x02, 0x00, 0x00, 0x00, 0x46, 0x02, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x09, // ....F.......7... 0xe2, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0xf6, 0x0f, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x06, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x56, 0x0e, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, // ........V....... 0x38, 0x00, 0x00, 0x08, 0xf2, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x46, 0x0e, 0x10, 0x00, // 8...........F... 0x01, 0x00, 0x00, 0x00, 0x46, 0x8e, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, // ....F. ......... 0x38, 0x00, 0x00, 0x07, 0x22, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, // 8..."........... 0x00, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x07, // ............8... 0xf2, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x05, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // . ......V....... 0x46, 0x0e, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x01, 0x18, 0x00, 0x00, 0x08, // F............... 0x22, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, // ".......:. ..... 0x0a, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x1f, 0x00, 0x04, 0x03, // .....@.....@.... 0x1a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x08, 0xf2, 0x20, 0x10, 0x00, // ........6.... .. 0x00, 0x00, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x80, 0x3f, // .....@.....?...? 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x80, 0x3f, 0x12, 0x00, 0x00, 0x01, 0x18, 0x00, 0x00, 0x08, // ...?...?........ 0x22, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, // ".......:. ..... 0x0a, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x40, 0x40, 0x1f, 0x00, 0x04, 0x03, // .....@....@@.... 0x1a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x09, 0xf2, 0x00, 0x10, 0x00, // ........E....... 0x01, 0x00, 0x00, 0x00, 0xe6, 0x1a, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x46, 0x7e, 0x10, 0x00, // ............F~.. 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x0b, // .....`.......... 0x62, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa6, 0x8a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, // b......... ..... 0x0a, 0x00, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, // .....@.........? 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x07, 0x72, 0x00, 0x10, 0x00, // ...@....8...r... 0x02, 0x00, 0x00, 0x00, 0xf6, 0x0f, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x46, 0x02, 0x10, 0x00, // ............F... 0x01, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x09, 0x72, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, // ....7...r....... 0x56, 0x05, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x02, 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, // V.......F....... 0x46, 0x02, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x09, 0xe2, 0x00, 0x10, 0x00, // F.......7....... 0x01, 0x00, 0x00, 0x00, 0xa6, 0x0a, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x10, 0x00, // ................ 0x01, 0x00, 0x00, 0x00, 0x56, 0x0e, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x07, // ....V.......8... 0xf2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x46, 0x0e, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x08, 0xf2, 0x20, 0x10, 0x00, // F.......8.... .. 0x00, 0x00, 0x00, 0x00, 0x46, 0x0e, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x8e, 0x20, 0x00, // ....F.......F. . 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x01, 0x15, 0x00, 0x00, 0x01, // ................ 0x15, 0x00, 0x00, 0x01, 0x15, 0x00, 0x00, 0x01, 0x3e, 0x00, 0x00, 0x01, 0x00, 0x00, 0xb0, 0x00, // ........>....... }; static const uint8_t fs_nanovg_fill_mtl[3662] = { 0x46, 0x53, 0x48, 0x06, 0xcf, 0xda, 0x1b, 0x94, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x08, 0x75, // FSH............u 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x12, 0x01, 0xa0, 0x00, 0x01, 0x00, 0x0a, 0x75, 0x5f, // _params.......u_ 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x13, 0x01, 0x30, 0x00, 0x03, 0x00, 0x0e, 0x75, // paintMat..0....u 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x12, 0x01, 0x90, // _extentRadius... 0x00, 0x01, 0x00, 0x0a, 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x12, 0x01, // ....u_innerCol.. 0x60, 0x00, 0x01, 0x00, 0x0a, 0x75, 0x5f, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x12, // `....u_outerCol. 0x01, 0x70, 0x00, 0x01, 0x00, 0x0c, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x4d, // .p....u_scissorM 0x61, 0x74, 0x13, 0x01, 0x00, 0x00, 0x03, 0x00, 0x11, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, // at.......u_sciss 0x6f, 0x72, 0x45, 0x78, 0x74, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x12, 0x01, 0x80, 0x00, 0x01, 0x00, // orExtScale...... 0xb6, 0x0d, 0x00, 0x00, 0x23, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x20, 0x3c, 0x6d, 0x65, // ....#include <me 0x74, 0x61, 0x6c, 0x5f, 0x73, 0x74, 0x64, 0x6c, 0x69, 0x62, 0x3e, 0x0a, 0x23, 0x69, 0x6e, 0x63, // tal_stdlib>.#inc 0x6c, 0x75, 0x64, 0x65, 0x20, 0x3c, 0x73, 0x69, 0x6d, 0x64, 0x2f, 0x73, 0x69, 0x6d, 0x64, 0x2e, // lude <simd/simd. 0x68, 0x3e, 0x0a, 0x0a, 0x75, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, // h>..using namesp 0x61, 0x63, 0x65, 0x20, 0x6d, 0x65, 0x74, 0x61, 0x6c, 0x3b, 0x0a, 0x0a, 0x73, 0x74, 0x72, 0x75, // ace metal;..stru 0x63, 0x74, 0x20, 0x5f, 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x20, // ct _Global.{. 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x33, 0x78, 0x33, 0x20, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, // float3x3 u_scis 0x73, 0x6f, 0x72, 0x4d, 0x61, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, // sorMat;. floa 0x74, 0x33, 0x78, 0x33, 0x20, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x3b, // t3x3 u_paintMat; 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x75, 0x5f, 0x69, 0x6e, // . float4 u_in 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, // nerCol;. floa 0x74, 0x34, 0x20, 0x75, 0x5f, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x3b, 0x0a, 0x20, // t4 u_outerCol;. 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, // float4 u_scis 0x73, 0x6f, 0x72, 0x45, 0x78, 0x74, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20, // sorExtScale;. 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x75, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x74, // float4 u_extent 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, // Radius;. floa 0x74, 0x34, 0x20, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x3b, 0x0a, 0x7d, 0x3b, 0x0a, // t4 u_params;.};. 0x0a, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x74, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, // .constant float4 0x20, 0x5f, 0x36, 0x37, 0x39, 0x20, 0x3d, 0x20, 0x7b, 0x7d, 0x3b, 0x0a, 0x0a, 0x73, 0x74, 0x72, // _679 = {};..str 0x75, 0x63, 0x74, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, 0x6e, 0x5f, // uct xlatMtlMain_ 0x6f, 0x75, 0x74, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, // out.{. float4 0x20, 0x62, 0x67, 0x66, 0x78, 0x5f, 0x46, 0x72, 0x61, 0x67, 0x44, 0x61, 0x74, 0x61, 0x30, 0x20, // bgfx_FragData0 0x5b, 0x5b, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x28, 0x30, 0x29, 0x5d, 0x5d, 0x3b, 0x0a, 0x7d, 0x3b, // [[color(0)]];.}; 0x0a, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, // ..struct xlatMtl 0x4d, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x6e, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, // Main_in.{. fl 0x6f, 0x61, 0x74, 0x32, 0x20, 0x76, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x20, // oat2 v_position 0x5b, 0x5b, 0x75, 0x73, 0x65, 0x72, 0x28, 0x6c, 0x6f, 0x63, 0x6e, 0x30, 0x29, 0x5d, 0x5d, 0x3b, // [[user(locn0)]]; 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x32, 0x20, 0x76, 0x5f, 0x74, 0x65, // . float2 v_te 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x20, 0x5b, 0x5b, 0x75, 0x73, 0x65, 0x72, 0x28, 0x6c, // xcoord0 [[user(l 0x6f, 0x63, 0x6e, 0x31, 0x29, 0x5d, 0x5d, 0x3b, 0x0a, 0x7d, 0x3b, 0x0a, 0x0a, 0x66, 0x72, 0x61, // ocn1)]];.};..fra 0x67, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, // gment xlatMtlMai 0x6e, 0x5f, 0x6f, 0x75, 0x74, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, // n_out xlatMtlMai 0x6e, 0x28, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x6e, // n(xlatMtlMain_in 0x20, 0x69, 0x6e, 0x20, 0x5b, 0x5b, 0x73, 0x74, 0x61, 0x67, 0x65, 0x5f, 0x69, 0x6e, 0x5d, 0x5d, // in [[stage_in]] 0x2c, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x74, 0x20, 0x5f, 0x47, 0x6c, 0x6f, 0x62, // , constant _Glob 0x61, 0x6c, 0x26, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x20, 0x5b, 0x5b, 0x62, 0x75, 0x66, // al& _mtl_u [[buf 0x66, 0x65, 0x72, 0x28, 0x30, 0x29, 0x5d, 0x5d, 0x2c, 0x20, 0x74, 0x65, 0x78, 0x74, 0x75, 0x72, // fer(0)]], textur 0x65, 0x32, 0x64, 0x3c, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x3e, 0x20, 0x73, 0x5f, 0x74, 0x65, 0x78, // e2d<float> s_tex 0x20, 0x5b, 0x5b, 0x74, 0x65, 0x78, 0x74, 0x75, 0x72, 0x65, 0x28, 0x30, 0x29, 0x5d, 0x5d, 0x2c, // [[texture(0)]], 0x20, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x20, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x53, 0x61, // sampler s_texSa 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x20, 0x5b, 0x5b, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x28, // mpler [[sampler( 0x30, 0x29, 0x5d, 0x5d, 0x29, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6c, 0x61, 0x74, // 0)]]).{. xlat 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, 0x6e, 0x5f, 0x6f, 0x75, 0x74, 0x20, 0x6f, 0x75, 0x74, 0x20, // MtlMain_out out 0x3d, 0x20, 0x7b, 0x7d, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x32, // = {};. float2 0x20, 0x5f, 0x35, 0x38, 0x34, 0x20, 0x3d, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x32, 0x28, 0x30, // _584 = float2(0 0x2e, 0x35, 0x29, 0x20, 0x2d, 0x20, 0x28, 0x28, 0x61, 0x62, 0x73, 0x28, 0x28, 0x5f, 0x6d, 0x74, // .5) - ((abs((_mt 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x73, 0x63, 0x69, 0x73, 0x73, 0x6f, 0x72, 0x4d, 0x61, 0x74, // l_u.u_scissorMat 0x20, 0x2a, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x33, 0x28, 0x69, 0x6e, 0x2e, 0x76, 0x5f, 0x70, // * float3(in.v_p 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x2e, 0x78, // osition, 1.0)).x 0x79, 0x29, 0x20, 0x2d, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x73, 0x63, // y) - _mtl_u.u_sc 0x69, 0x73, 0x73, 0x6f, 0x72, 0x45, 0x78, 0x74, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x2e, 0x78, 0x79, // issorExtScale.xy 0x29, 0x20, 0x2a, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x73, 0x63, 0x69, // ) * _mtl_u.u_sci 0x73, 0x73, 0x6f, 0x72, 0x45, 0x78, 0x74, 0x53, 0x63, 0x61, 0x6c, 0x65, 0x2e, 0x7a, 0x77, 0x29, // ssorExtScale.zw) 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x20, 0x5f, 0x35, 0x39, 0x31, // ;. float _591 0x20, 0x3d, 0x20, 0x66, 0x61, 0x73, 0x74, 0x3a, 0x3a, 0x63, 0x6c, 0x61, 0x6d, 0x70, 0x28, 0x5f, // = fast::clamp(_ 0x35, 0x38, 0x34, 0x2e, 0x78, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x29, // 584.x, 0.0, 1.0) 0x20, 0x2a, 0x20, 0x66, 0x61, 0x73, 0x74, 0x3a, 0x3a, 0x63, 0x6c, 0x61, 0x6d, 0x70, 0x28, 0x5f, // * fast::clamp(_ 0x35, 0x38, 0x34, 0x2e, 0x79, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x29, // 584.y, 0.0, 1.0) 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x20, 0x5f, 0x36, 0x30, 0x36, // ;. float _606 0x20, 0x3d, 0x20, 0x66, 0x61, 0x73, 0x74, 0x3a, 0x3a, 0x6d, 0x69, 0x6e, 0x28, 0x31, 0x2e, 0x30, // = fast::min(1.0 0x2c, 0x20, 0x28, 0x31, 0x2e, 0x30, 0x20, 0x2d, 0x20, 0x61, 0x62, 0x73, 0x28, 0x28, 0x69, 0x6e, // , (1.0 - abs((in 0x2e, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x2e, 0x78, 0x20, 0x2a, // .v_texcoord0.x * 0x20, 0x32, 0x2e, 0x30, 0x29, 0x20, 0x2d, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x20, 0x2a, 0x20, // 2.0) - 1.0)) * 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, // _mtl_u.u_params. 0x79, 0x29, 0x20, 0x2a, 0x20, 0x66, 0x61, 0x73, 0x74, 0x3a, 0x3a, 0x6d, 0x69, 0x6e, 0x28, 0x31, // y) * fast::min(1 0x2e, 0x30, 0x2c, 0x20, 0x69, 0x6e, 0x2e, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, // .0, in.v_texcoor 0x64, 0x30, 0x2e, 0x79, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, // d0.y);. float 0x34, 0x20, 0x5f, 0x36, 0x37, 0x35, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, // 4 _675;. if ( 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, // _mtl_u.u_params. 0x77, 0x20, 0x3d, 0x3d, 0x20, 0x30, 0x2e, 0x30, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, // w == 0.0). {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x32, 0x20, 0x5f, // float2 _ 0x36, 0x31, 0x38, 0x20, 0x3d, 0x20, 0x61, 0x62, 0x73, 0x28, 0x28, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, // 618 = abs((_mtl_ 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x20, 0x2a, 0x20, 0x66, // u.u_paintMat * f 0x6c, 0x6f, 0x61, 0x74, 0x33, 0x28, 0x69, 0x6e, 0x2e, 0x76, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, // loat3(in.v_posit 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x2e, 0x78, 0x79, 0x29, 0x20, 0x2d, // ion, 1.0)).xy) - 0x20, 0x28, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, // (_mtl_u.u_exten 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x2e, 0x78, 0x79, 0x20, 0x2d, 0x20, 0x66, 0x6c, 0x6f, // tRadius.xy - flo 0x61, 0x74, 0x32, 0x28, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x65, 0x78, 0x74, // at2(_mtl_u.u_ext 0x65, 0x6e, 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x2e, 0x7a, 0x29, 0x29, 0x3b, 0x0a, 0x20, // entRadius.z));. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, 0x36, 0x37, 0x35, 0x20, 0x3d, 0x20, 0x6d, 0x69, // _675 = mi 0x78, 0x28, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, // x(_mtl_u.u_inner 0x43, 0x6f, 0x6c, 0x2c, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x6f, 0x75, // Col, _mtl_u.u_ou 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x2c, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x28, 0x66, // terCol, float4(f 0x61, 0x73, 0x74, 0x3a, 0x3a, 0x63, 0x6c, 0x61, 0x6d, 0x70, 0x28, 0x28, 0x28, 0x28, 0x66, 0x61, // ast::clamp((((fa 0x73, 0x74, 0x3a, 0x3a, 0x6d, 0x69, 0x6e, 0x28, 0x66, 0x61, 0x73, 0x74, 0x3a, 0x3a, 0x6d, 0x61, // st::min(fast::ma 0x78, 0x28, 0x5f, 0x36, 0x31, 0x38, 0x2e, 0x78, 0x2c, 0x20, 0x5f, 0x36, 0x31, 0x38, 0x2e, 0x79, // x(_618.x, _618.y 0x29, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x29, 0x20, 0x2b, 0x20, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, // ), 0.0) + length 0x28, 0x66, 0x61, 0x73, 0x74, 0x3a, 0x3a, 0x6d, 0x61, 0x78, 0x28, 0x5f, 0x36, 0x31, 0x38, 0x2c, // (fast::max(_618, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x32, 0x28, 0x30, 0x2e, 0x30, 0x29, 0x29, 0x29, 0x29, 0x20, // float2(0.0)))) 0x2d, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, // - _mtl_u.u_exten 0x74, 0x52, 0x61, 0x64, 0x69, 0x75, 0x73, 0x2e, 0x7a, 0x29, 0x20, 0x2b, 0x20, 0x28, 0x5f, 0x6d, // tRadius.z) + (_m 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x78, 0x20, // tl_u.u_params.x 0x2a, 0x20, 0x30, 0x2e, 0x35, 0x29, 0x29, 0x20, 0x2f, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, // * 0.5)) / _mtl_u 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x78, 0x2c, 0x20, 0x30, 0x2e, 0x30, // .u_params.x, 0.0 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x29, 0x20, 0x2a, 0x20, 0x28, 0x5f, 0x36, 0x30, 0x36, // , 1.0))) * (_606 0x20, 0x2a, 0x20, 0x5f, 0x35, 0x39, 0x31, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, // * _591);. }. 0x20, 0x20, 0x20, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, // else. {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x5f, 0x36, // float4 _6 0x37, 0x36, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, // 76;. if ( 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, // _mtl_u.u_params. 0x77, 0x20, 0x3d, 0x3d, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // w == 1.0). 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // {. 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x5f, 0x36, 0x34, 0x33, 0x20, 0x3d, 0x20, 0x73, 0x5f, // float4 _643 = s_ 0x74, 0x65, 0x78, 0x2e, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x28, 0x73, 0x5f, 0x74, 0x65, 0x78, // tex.sample(s_tex 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x28, 0x28, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, // Sampler, ((_mtl_ 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x4d, 0x61, 0x74, 0x20, 0x2a, 0x20, 0x66, // u.u_paintMat * f 0x6c, 0x6f, 0x61, 0x74, 0x33, 0x28, 0x69, 0x6e, 0x2e, 0x76, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, // loat3(in.v_posit 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x29, 0x2e, 0x78, 0x79, 0x20, 0x2f, 0x20, // ion, 1.0)).xy / 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x74, 0x52, // _mtl_u.u_extentR 0x61, 0x64, 0x69, 0x75, 0x73, 0x2e, 0x78, 0x79, 0x29, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, // adius.xy));. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x5f, // float4 _ 0x36, 0x37, 0x33, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 673;. 0x20, 0x69, 0x66, 0x20, 0x28, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, // if (_mtl_u.u_pa 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x7a, 0x20, 0x3d, 0x3d, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x0a, 0x20, // rams.z == 1.0). 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, // {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, 0x36, 0x37, // _67 0x33, 0x20, 0x3d, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x28, 0x5f, 0x36, 0x34, 0x33, 0x2e, // 3 = float4(_643. 0x78, 0x79, 0x7a, 0x20, 0x2a, 0x20, 0x5f, 0x36, 0x34, 0x33, 0x2e, 0x77, 0x2c, 0x20, 0x5f, 0x36, // xyz * _643.w, _6 0x34, 0x33, 0x2e, 0x77, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 43.w);. 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // }. 0x20, 0x65, 0x6c, 0x73, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // else. 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // {. 0x20, 0x20, 0x20, 0x20, 0x5f, 0x36, 0x37, 0x33, 0x20, 0x3d, 0x20, 0x5f, 0x36, 0x34, 0x33, 0x3b, // _673 = _643; 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, // . }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, // float 0x34, 0x20, 0x5f, 0x36, 0x37, 0x34, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 4 _674;. 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, // if (_mtl_u.u 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x7a, 0x20, 0x3d, 0x3d, 0x20, 0x32, 0x2e, 0x30, // _params.z == 2.0 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, // ). {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 0x5f, 0x36, 0x37, 0x34, 0x20, 0x3d, 0x20, 0x5f, 0x36, 0x37, 0x33, 0x2e, 0x78, 0x78, 0x78, 0x78, // _674 = _673.xxxx 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, // ;. }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x6c, 0x73, 0x65, // else 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, // . {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, // _ 0x36, 0x37, 0x34, 0x20, 0x3d, 0x20, 0x5f, 0x36, 0x37, 0x33, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, // 674 = _673;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, 0x36, 0x37, 0x36, 0x20, 0x3d, 0x20, 0x28, 0x5f, 0x36, // _676 = (_6 0x37, 0x34, 0x20, 0x2a, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x69, 0x6e, // 74 * _mtl_u.u_in 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6c, 0x29, 0x20, 0x2a, 0x20, 0x28, 0x5f, 0x36, 0x30, 0x36, 0x20, // nerCol) * (_606 0x2a, 0x20, 0x5f, 0x35, 0x39, 0x31, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // * _591);. 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x0a, // }. else. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x5f, 0x36, 0x37, // float4 _67 0x37, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, // 7;. i 0x66, 0x20, 0x28, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, // f (_mtl_u.u_para 0x6d, 0x73, 0x2e, 0x77, 0x20, 0x3d, 0x3d, 0x20, 0x32, 0x2e, 0x30, 0x29, 0x0a, 0x20, 0x20, 0x20, // ms.w == 2.0). 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, // {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, 0x36, 0x37, 0x37, 0x20, // _677 0x3d, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x28, 0x31, 0x2e, 0x30, 0x29, 0x3b, 0x0a, 0x20, // = float4(1.0);. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, // }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x0a, 0x20, 0x20, // else. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, // {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, // floa 0x74, 0x34, 0x20, 0x5f, 0x36, 0x37, 0x38, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // t4 _678;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x5f, 0x6d, 0x74, // if (_mt 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x77, 0x20, 0x3d, // l_u.u_params.w = 0x3d, 0x20, 0x33, 0x2e, 0x30, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // = 3.0). 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, // flo 0x61, 0x74, 0x34, 0x20, 0x5f, 0x36, 0x35, 0x31, 0x20, 0x3d, 0x20, 0x73, 0x5f, 0x74, 0x65, 0x78, // at4 _651 = s_tex 0x2e, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x28, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x53, 0x61, 0x6d, // .sample(s_texSam 0x70, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x69, 0x6e, 0x2e, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, // pler, in.v_texco 0x6f, 0x72, 0x64, 0x30, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // ord0);. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, // float 0x34, 0x20, 0x5f, 0x36, 0x37, 0x31, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 4 _671;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, // if ( 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, // _mtl_u.u_params. 0x7a, 0x20, 0x3d, 0x3d, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // z == 1.0). 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, // {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, 0x36, 0x37, 0x31, 0x20, 0x3d, 0x20, 0x66, // _671 = f 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x28, 0x5f, 0x36, 0x35, 0x31, 0x2e, 0x78, 0x79, 0x7a, 0x20, 0x2a, // loat4(_651.xyz * 0x20, 0x5f, 0x36, 0x35, 0x31, 0x2e, 0x77, 0x2c, 0x20, 0x5f, 0x36, 0x35, 0x31, 0x2e, 0x77, 0x29, // _651.w, _651.w) 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // ;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x6c, 0x73, 0x65, // else 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // . 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, // _ 0x36, 0x37, 0x31, 0x20, 0x3d, 0x20, 0x5f, 0x36, 0x35, 0x31, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, // 671 = _651;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x5f, 0x36, 0x37, // float4 _67 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 2;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, // if (_mtl_ 0x75, 0x2e, 0x75, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x7a, 0x20, 0x3d, 0x3d, 0x20, // u.u_params.z == 0x32, 0x2e, 0x30, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 2.0). 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, // {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 0x20, 0x20, 0x20, 0x5f, 0x36, 0x37, 0x32, 0x20, 0x3d, 0x20, 0x5f, 0x36, 0x37, 0x31, 0x2e, 0x78, // _672 = _671.x 0x78, 0x78, 0x78, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // xxx;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, // }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, // e 0x6c, 0x73, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // lse. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 0x20, 0x20, 0x5f, 0x36, 0x37, 0x32, 0x20, 0x3d, 0x20, 0x5f, 0x36, 0x37, 0x31, 0x3b, 0x0a, 0x20, // _672 = _671;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, 0x36, 0x37, 0x38, 0x20, 0x3d, 0x20, // _678 = 0x28, 0x5f, 0x36, 0x37, 0x32, 0x20, 0x2a, 0x20, 0x5f, 0x35, 0x39, 0x31, 0x29, 0x20, 0x2a, 0x20, // (_672 * _591) * 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, // _mtl_u.u_innerCo 0x6c, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // l;. 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // else. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, // {. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 0x5f, 0x36, 0x37, 0x38, 0x20, 0x3d, 0x20, 0x5f, 0x36, 0x37, 0x39, 0x3b, 0x0a, 0x20, 0x20, 0x20, // _678 = _679;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, // }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, // _ 0x36, 0x37, 0x37, 0x20, 0x3d, 0x20, 0x5f, 0x36, 0x37, 0x38, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, // 677 = _678;. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, 0x36, 0x37, 0x36, 0x20, 0x3d, 0x20, 0x5f, 0x36, 0x37, // _676 = _67 0x37, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, // 7;. }. 0x20, 0x20, 0x20, 0x20, 0x20, 0x5f, 0x36, 0x37, 0x35, 0x20, 0x3d, 0x20, 0x5f, 0x36, 0x37, 0x36, // _675 = _676 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x75, 0x74, 0x2e, // ;. }. out. 0x62, 0x67, 0x66, 0x78, 0x5f, 0x46, 0x72, 0x61, 0x67, 0x44, 0x61, 0x74, 0x61, 0x30, 0x20, 0x3d, // bgfx_FragData0 = 0x20, 0x5f, 0x36, 0x37, 0x35, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, // _675;. retur 0x6e, 0x20, 0x6f, 0x75, 0x74, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, 0x00, 0x00, 0xb0, 0x00, // n out;.}...... }; extern const uint8_t* fs_nanovg_fill_pssl; extern const uint32_t fs_nanovg_fill_pssl_size;
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\bgfx\nanovg_bgfx.h
/* * Copyright 2011-2019 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #ifndef NANOVG_BGFX_H_HEADER_GUARD #define NANOVG_BGFX_H_HEADER_GUARD #include <bgfx/bgfx.h> namespace bx { struct AllocatorI; } struct NVGcontext; struct NVGLUframebuffer { NVGcontext* ctx; bgfx::FrameBufferHandle handle; int image; bgfx::ViewId viewId; }; /// NVGcontext* nvgCreate(int32_t _edgeaa, bgfx::ViewId _viewId, bx::AllocatorI* _allocator); /// NVGcontext* nvgCreate(int32_t _edgeaa, bgfx::ViewId _viewId); /// void nvgDelete(NVGcontext* _ctx); /// void nvgSetViewId(NVGcontext* _ctx, bgfx::ViewId _viewId); /// uint16_t nvgGetViewId(struct NVGcontext* _ctx); // Helper functions to create bgfx framebuffer to render to. // Example: // float scale = 2; // NVGLUframebuffer* fb = nvgluCreateFramebuffer(ctx, 100 * scale, 100 * scale, 0); // nvgluSetViewFramebuffer(VIEW_ID, fb); // nvgluBindFramebuffer(fb); // nvgBeginFrame(ctx, 100, 100, scale); // // renders anything offscreen // nvgEndFrame(ctx); // nvgluBindFramebuffer(NULL); // // // Pastes the framebuffer rendering. // nvgBeginFrame(ctx, 1024, 768, scale); // NVGpaint paint = nvgImagePattern(ctx, 0, 0, 100, 100, 0, fb->image, 1); // nvgBeginPath(ctx); // nvgRect(ctx, 0, 0, 100, 100); // nvgFillPaint(ctx, paint); // nvgFill(ctx); // nvgEndFrame(ctx); /// NVGLUframebuffer* nvgluCreateFramebuffer(NVGcontext* _ctx, int32_t _width, int32_t _height, int32_t _imageFlags, bgfx::ViewId _viewId); /// NVGLUframebuffer* nvgluCreateFramebuffer(NVGcontext* _ctx, int32_t _width, int32_t _height, int32_t _imageFlags); /// void nvgluBindFramebuffer(NVGLUframebuffer* _framebuffer); /// void nvgluDeleteFramebuffer(NVGLUframebuffer* _framebuffer); /// void nvgluSetViewFramebuffer(bgfx::ViewId _viewId, NVGLUframebuffer* _framebuffer); #endif // NANOVG_BGFX_H_HEADER_GUARD
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\bgfx\nanovg_bgfxEx.h
#ifndef NANOVG_BGFXEX_H_HEADER_GUARD #define NANOVG_BGFXEX_H_HEADER_GUARD #include <bgfx/bgfx.h> namespace bx { struct AllocatorI; } /// NVGcontext* nvgCreate(int32_t _edgeaa, bgfx::ViewId _viewId, bx::AllocatorI* _allocator); /// void nvgSetViewId(NVGcontext* _ctx, bgfx::ViewId _viewId); /// uint16_t nvgGetViewId(struct NVGcontext* _ctx); #endif
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\bgfx\nanovg_bgfx_ex.h
#ifndef NANOVG_BGFX_EX_H_ #define NANOVG_BGFX_EX_H_ #include <math.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include "nanovg.h" #include <SDL.h> #ifndef M_PI #define M_PI 3.1415926f #endif /*M_PI*/ struct NVGLUframebuffer; #ifdef __cplusplus extern "C" { #endif ///sdl entry NVGcontext* nvgCreateBGFX(int32_t _edgeaa, uint16_t _viewId,uint32_t _width, uint32_t _height, SDL_Window* _window); void nvgDeleteBGFX(NVGcontext* _ctx); uint32_t renderBGFXFrame(int32_t _msecs); void setBGFXViewRect(uint16_t _viewId, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height); void touchBGFX(uint16_t _viewId); uint32_t frameBGFX(bool _capture); void resetBGFX(uint32_t _width, uint32_t _height, uint32_t _flags); void* nvgluCreateFramebufferByViewId(NVGcontext* _ctx, int32_t _width, int32_t _height, int32_t _imageFlags, uint16_t _viewId); /// void nvgluBindFramebufferEx(struct NVGLUframebuffer* _framebuffer); /// void nvgluDeleteFramebufferEx(struct NVGLUframebuffer* _framebuffer); uint32_t getBgfxFboViewId(struct NVGLUframebuffer* _framebuffer); uint32_t getBgfxFboImage(struct NVGLUframebuffer* _framebuffer); #ifdef __cplusplus } #endif #endif
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\bgfx\vs_nanovg_fill.bin.h
static const uint8_t vs_nanovg_fill_glsl[545] = { 0x56, 0x53, 0x48, 0x06, 0x00, 0x00, 0x00, 0x00, 0xcf, 0xda, 0x1b, 0x94, 0x02, 0x00, 0x0a, 0x75, // VSH............u 0x5f, 0x76, 0x69, 0x65, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x02, 0x01, 0x00, 0x00, 0x01, 0x00, 0x0b, // _viewSize....... 0x75, 0x5f, 0x68, 0x61, 0x6c, 0x66, 0x54, 0x65, 0x78, 0x65, 0x6c, 0x02, 0x01, 0x00, 0x00, 0x01, // u_halfTexel..... 0x00, 0xeb, 0x01, 0x00, 0x00, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x20, 0x68, // .....attribute h 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x32, 0x20, 0x61, 0x5f, 0x70, 0x6f, 0x73, 0x69, // ighp vec2 a_posi 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x20, // tion;.attribute 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x32, 0x20, 0x61, 0x5f, 0x74, 0x65, 0x78, // highp vec2 a_tex 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x3b, 0x0a, 0x76, 0x61, 0x72, 0x79, 0x69, 0x6e, 0x67, 0x20, // coord0;.varying 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x32, 0x20, 0x76, 0x5f, 0x70, 0x6f, 0x73, // highp vec2 v_pos 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x0a, 0x76, 0x61, 0x72, 0x79, 0x69, 0x6e, 0x67, 0x20, 0x68, // ition;.varying h 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x32, 0x20, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, // ighp vec2 v_texc 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x3b, 0x0a, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x68, // oord0;.uniform h 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x75, 0x5f, 0x76, 0x69, 0x65, 0x77, // ighp vec4 u_view 0x53, 0x69, 0x7a, 0x65, 0x3b, 0x0a, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x68, 0x69, // Size;.uniform hi 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x75, 0x5f, 0x68, 0x61, 0x6c, 0x66, 0x54, // ghp vec4 u_halfT 0x65, 0x78, 0x65, 0x6c, 0x3b, 0x0a, 0x76, 0x6f, 0x69, 0x64, 0x20, 0x6d, 0x61, 0x69, 0x6e, 0x20, // exel;.void main 0x28, 0x29, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x76, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, // ().{. v_positio 0x6e, 0x20, 0x3d, 0x20, 0x61, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x0a, // n = a_position;. 0x20, 0x20, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x20, 0x3d, 0x20, // v_texcoord0 = 0x28, 0x61, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x20, 0x2b, 0x20, 0x75, // (a_texcoord0 + u 0x5f, 0x68, 0x61, 0x6c, 0x66, 0x54, 0x65, 0x78, 0x65, 0x6c, 0x2e, 0x78, 0x79, 0x29, 0x3b, 0x0a, // _halfTexel.xy);. 0x20, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x74, 0x6d, 0x70, // highp vec4 tmp 0x76, 0x61, 0x72, 0x5f, 0x31, 0x3b, 0x0a, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, // var_1;. tmpvar_ 0x31, 0x2e, 0x7a, 0x77, 0x20, 0x3d, 0x20, 0x76, 0x65, 0x63, 0x32, 0x28, 0x30, 0x2e, 0x30, 0x2c, // 1.zw = vec2(0.0, 0x20, 0x31, 0x2e, 0x30, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, // 1.0);. tmpvar_ 0x31, 0x2e, 0x78, 0x20, 0x3d, 0x20, 0x28, 0x28, 0x28, 0x32, 0x2e, 0x30, 0x20, 0x2a, 0x20, 0x61, // 1.x = (((2.0 * a 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x78, 0x29, 0x20, 0x2f, 0x20, 0x75, // _position.x) / u 0x5f, 0x76, 0x69, 0x65, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x2e, 0x78, 0x29, 0x20, 0x2d, 0x20, 0x31, // _viewSize.x) - 1 0x2e, 0x30, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x2e, // .0);. tmpvar_1. 0x79, 0x20, 0x3d, 0x20, 0x28, 0x31, 0x2e, 0x30, 0x20, 0x2d, 0x20, 0x28, 0x28, 0x32, 0x2e, 0x30, // y = (1.0 - ((2.0 0x20, 0x2a, 0x20, 0x61, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x79, 0x29, // * a_position.y) 0x20, 0x2f, 0x20, 0x75, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x2e, 0x79, 0x29, // / u_viewSize.y) 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, // );. gl_Position 0x20, 0x3d, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, // = tmpvar_1;.}.. 0x00, // . }; static const uint8_t vs_nanovg_fill_spv[1501] = { 0x56, 0x53, 0x48, 0x06, 0x00, 0x00, 0x00, 0x00, 0xcf, 0xda, 0x1b, 0x94, 0x02, 0x00, 0x0b, 0x75, // VSH............u 0x5f, 0x68, 0x61, 0x6c, 0x66, 0x54, 0x65, 0x78, 0x65, 0x6c, 0x02, 0x01, 0x10, 0x00, 0x01, 0x00, // _halfTexel...... 0x0a, 0x75, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x02, 0x01, 0x00, 0x00, 0x01, // .u_viewSize..... 0x00, 0xa0, 0x05, 0x00, 0x00, 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0x08, // .......#........ 0x00, 0xb1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, // ................ 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, // .........GLSL.st 0x64, 0x2e, 0x34, 0x35, 0x30, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, // d.450........... 0x00, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, // ................ 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, // .main....G...J.. 0x00, 0x53, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, // .S...W...Z...... 0x00, 0x05, 0x00, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, // ................ 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x1c, 0x00, 0x00, // .main........... 0x00, 0x24, 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x00, 0x06, 0x00, 0x06, 0x00, 0x1c, 0x00, 0x00, // .$Global........ 0x00, 0x00, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x00, // .....u_viewSize. 0x00, 0x06, 0x00, 0x06, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x68, // .............u_h 0x61, 0x6c, 0x66, 0x54, 0x65, 0x78, 0x65, 0x6c, 0x00, 0x05, 0x00, 0x03, 0x00, 0x1e, 0x00, 0x00, // alfTexel........ 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x47, 0x00, 0x00, 0x00, 0x61, 0x5f, 0x70, // .........G...a_p 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x4a, 0x00, 0x00, // osition......J.. 0x00, 0x61, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x00, 0x05, 0x00, 0x0a, // .a_texcoord0.... 0x00, 0x53, 0x00, 0x00, 0x00, 0x40, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x69, 0x6e, 0x74, // .S...@entryPoint 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2e, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x73, 0x69, 0x74, 0x69, // Output.gl_Positi 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x57, 0x00, 0x00, 0x00, 0x40, 0x65, 0x6e, // on.......W...@en 0x74, 0x72, 0x79, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2e, 0x76, // tryPointOutput.v 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, // _position....... 0x00, 0x5a, 0x00, 0x00, 0x00, 0x40, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x69, 0x6e, 0x74, // .Z...@entryPoint 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2e, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, // Output.v_texcoor 0x64, 0x30, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // d0...H.......... 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x1c, 0x00, 0x00, // .#.......H...... 0x00, 0x01, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, // .....#.......G.. 0x00, 0x1c, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x1e, 0x00, 0x00, // .........G...... 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x1e, 0x00, 0x00, // .".......G...... 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x47, 0x00, 0x00, // .!.......G...G.. 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x4a, 0x00, 0x00, // .........G...J.. 0x00, 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x53, 0x00, 0x00, // .........G...S.. 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x57, 0x00, 0x00, // .........G...W.. 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x5a, 0x00, 0x00, // .........G...Z.. 0x00, 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, // ................ 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, // .!.............. 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, // ..... .......... 0x00, 0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, // ................ 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, // ................ 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, // . .......+...... 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, // .........+...... 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x04, 0x00, 0x1c, 0x00, 0x00, // ................ 0x00, 0x09, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x1d, 0x00, 0x00, // ......... ...... 0x00, 0x02, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x1d, 0x00, 0x00, // .........;...... 0x00, 0x1e, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x1f, 0x00, 0x00, // ......... ...... 0x00, 0x02, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, // .........+...... 0x00, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, // .%.......+...... 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x15, 0x00, 0x04, 0x00, 0x27, 0x00, 0x00, // .&......@....'.. 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x27, 0x00, 0x00, // . .......+...'.. 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x2d, 0x00, 0x00, // .(....... ...-.. 0x00, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, // .........+...... 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x2b, 0x00, 0x04, 0x00, 0x27, 0x00, 0x00, // .1......?+...'.. 0x00, 0x33, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x46, 0x00, 0x00, // .3....... ...F.. 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x46, 0x00, 0x00, // .........;...F.. 0x00, 0x47, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x46, 0x00, 0x00, // .G.......;...F.. 0x00, 0x4a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x52, 0x00, 0x00, // .J....... ...R.. 0x00, 0x03, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x52, 0x00, 0x00, // .........;...R.. 0x00, 0x53, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x56, 0x00, 0x00, // .S....... ...V.. 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x56, 0x00, 0x00, // .........;...V.. 0x00, 0x57, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x56, 0x00, 0x00, // .W.......;...V.. 0x00, 0x5a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, // .Z.............. 0x00, 0xb0, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, // .....6.......... 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, // ................ 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x47, 0x00, 0x00, // .=.......H...G.. 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x4b, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, // .=.......K...J.. 0x00, 0x41, 0x00, 0x05, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, // .A.......v...... 0x00, 0x13, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, // .....=.......w.. 0x00, 0x76, 0x00, 0x00, 0x00, 0x4f, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, // .v...O.......x.. 0x00, 0x77, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, // .w...w.......... 0x00, 0x81, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x79, 0x00, 0x00, 0x00, 0x4b, 0x00, 0x00, // .........y...K.. 0x00, 0x78, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, // .x...Q.......|.. 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, // .H.............. 0x00, 0x7d, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, // .}...&...|...A.. 0x00, 0x2d, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, // .-...~.......%.. 0x00, 0x28, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, // .(...=.......... 0x00, 0x7e, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, // .~.............. 0x00, 0x7d, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x83, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, // .}.............. 0x00, 0x81, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, // .........1...Q.. 0x00, 0x06, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, // .........H...... 0x00, 0x85, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, // .............&.. 0x00, 0x83, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x2d, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00, // .....A...-...... 0x00, 0x1e, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, // .....%...3...=.. 0x00, 0x06, 0x00, 0x00, 0x00, 0x86, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, // ................ 0x00, 0x06, 0x00, 0x00, 0x00, 0x87, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x86, 0x00, 0x00, // ................ 0x00, 0x50, 0x00, 0x07, 0x00, 0x09, 0x00, 0x00, 0x00, 0x89, 0x00, 0x00, 0x00, 0x81, 0x00, 0x00, // .P.............. 0x00, 0xb0, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x83, 0x00, 0x05, // .........1...... 0x00, 0x06, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x87, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, // .............1.. 0x00, 0x52, 0x00, 0x06, 0x00, 0x09, 0x00, 0x00, 0x00, 0xaf, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, // .R.............. 0x00, 0x89, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x53, 0x00, 0x00, // .........>...S.. 0x00, 0xaf, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x57, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, // .....>...W...H.. 0x00, 0x3e, 0x00, 0x03, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x79, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, // .>...Z...y...... 0x00, 0x38, 0x00, 0x01, 0x00, 0x00, 0x02, 0x01, 0x00, 0x10, 0x00, 0x20, 0x00, // .8......... . }; static const uint8_t vs_nanovg_fill_dx9[430] = { 0x56, 0x53, 0x48, 0x06, 0x00, 0x00, 0x00, 0x00, 0xcf, 0xda, 0x1b, 0x94, 0x02, 0x00, 0x0b, 0x75, // VSH............u 0x5f, 0x68, 0x61, 0x6c, 0x66, 0x54, 0x65, 0x78, 0x65, 0x6c, 0x02, 0x01, 0x01, 0x00, 0x01, 0x00, // _halfTexel...... 0x0a, 0x75, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x02, 0x01, 0x00, 0x00, 0x01, // .u_viewSize..... 0x00, 0x78, 0x01, 0x00, 0x00, 0x00, 0x03, 0xfe, 0xff, 0xfe, 0xff, 0x28, 0x00, 0x43, 0x54, 0x41, // .x.........(.CTA 0x42, 0x1c, 0x00, 0x00, 0x00, 0x72, 0x00, 0x00, 0x00, 0x00, 0x03, 0xfe, 0xff, 0x02, 0x00, 0x00, // B....r.......... 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x91, 0x00, 0x00, 0x6b, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, // .........k...D.. 0x00, 0x02, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // .........P...... 0x00, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, // .`...........P.. 0x00, 0x00, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x68, 0x61, 0x6c, 0x66, 0x54, 0x65, 0x78, 0x65, 0x6c, // .....u_halfTexel 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x00, 0x75, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x00, 0x76, 0x73, 0x5f, 0x33, // .u_viewSize.vs_3 0x5f, 0x30, 0x00, 0x4d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f, 0x66, 0x74, 0x20, 0x28, 0x52, 0x29, // _0.Microsoft (R) 0x20, 0x48, 0x4c, 0x53, 0x4c, 0x20, 0x53, 0x68, 0x61, 0x64, 0x65, 0x72, 0x20, 0x43, 0x6f, 0x6d, // HLSL Shader Com 0x70, 0x69, 0x6c, 0x65, 0x72, 0x20, 0x31, 0x30, 0x2e, 0x31, 0x00, 0xab, 0xab, 0x51, 0x00, 0x00, // piler 10.1...Q.. 0x05, 0x02, 0x00, 0x0f, 0xa0, 0x00, 0x00, 0x80, 0xbf, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, // ............?... 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x0f, // ................ 0x90, 0x1f, 0x00, 0x00, 0x02, 0x05, 0x00, 0x00, 0x80, 0x01, 0x00, 0x0f, 0x90, 0x1f, 0x00, 0x00, // ................ 0x02, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x0f, 0xe0, 0x1f, 0x00, 0x00, 0x02, 0x05, 0x00, 0x00, // ................ 0x80, 0x01, 0x00, 0x03, 0xe0, 0x1f, 0x00, 0x00, 0x02, 0x05, 0x00, 0x01, 0x80, 0x02, 0x00, 0x03, // ................ 0xe0, 0x02, 0x00, 0x00, 0x03, 0x02, 0x00, 0x03, 0xe0, 0x01, 0x00, 0xe4, 0xa0, 0x01, 0x00, 0xe4, // ................ 0x90, 0x06, 0x00, 0x00, 0x02, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, 0xa0, 0x02, 0x00, 0x00, // ................ 0x03, 0x00, 0x00, 0x06, 0x80, 0x00, 0x00, 0xd0, 0x90, 0x00, 0x00, 0xd0, 0x90, 0x04, 0x00, 0x00, // ................ 0x04, 0x00, 0x00, 0x01, 0xe0, 0x00, 0x00, 0x55, 0x80, 0x00, 0x00, 0x00, 0x80, 0x02, 0x00, 0x00, // .......U........ 0xa0, 0x06, 0x00, 0x00, 0x02, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x55, 0xa0, 0x04, 0x00, 0x00, // ...........U.... 0x04, 0x00, 0x00, 0x02, 0xe0, 0x00, 0x00, 0xaa, 0x80, 0x00, 0x00, 0x00, 0x81, 0x02, 0x00, 0x55, // ...............U 0xa0, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x0c, 0xe0, 0x02, 0x00, 0x64, 0xa0, 0x01, 0x00, 0x00, // ...........d.... 0x02, 0x01, 0x00, 0x03, 0xe0, 0x00, 0x00, 0xe4, 0x90, 0xff, 0xff, 0x00, 0x00, 0x00, // .............. }; static const uint8_t vs_nanovg_fill_dx11[583] = { 0x56, 0x53, 0x48, 0x06, 0x00, 0x00, 0x00, 0x00, 0xcf, 0xda, 0x1b, 0x94, 0x01, 0x00, 0x0a, 0x75, // VSH............u 0x5f, 0x76, 0x69, 0x65, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x1c, // _viewSize....... 0x02, 0x00, 0x00, 0x44, 0x58, 0x42, 0x43, 0x99, 0x64, 0x1c, 0x9f, 0xec, 0x38, 0xd9, 0xd2, 0x91, // ...DXBC.d...8... 0x86, 0xde, 0x66, 0x7d, 0x52, 0x06, 0xfe, 0x01, 0x00, 0x00, 0x00, 0x1c, 0x02, 0x00, 0x00, 0x03, // ..f}R........... 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x49, // ...,...........I 0x53, 0x47, 0x4e, 0x4c, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x38, // SGNL...........8 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // .......A........ 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x50, // ...............P 0x4f, 0x53, 0x49, 0x54, 0x49, 0x4f, 0x4e, 0x00, 0x54, 0x45, 0x58, 0x43, 0x4f, 0x4f, 0x52, 0x44, // OSITION.TEXCOORD 0x00, 0xab, 0xab, 0x4f, 0x53, 0x47, 0x4e, 0x68, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, // ...OSGNh........ 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, // ...P............ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, // ................ 0x0c, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // ................ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x03, 0x00, 0x00, 0x53, 0x56, 0x5f, 0x50, 0x4f, // ...........SV_PO 0x53, 0x49, 0x54, 0x49, 0x4f, 0x4e, 0x00, 0x54, 0x45, 0x58, 0x43, 0x4f, 0x4f, 0x52, 0x44, 0x00, // SITION.TEXCOORD. 0xab, 0xab, 0xab, 0x53, 0x48, 0x44, 0x52, 0x24, 0x01, 0x00, 0x00, 0x40, 0x00, 0x01, 0x00, 0x49, // ...SHDR$...@...I 0x00, 0x00, 0x00, 0x59, 0x00, 0x00, 0x04, 0x46, 0x8e, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // ...Y...F. ...... 0x00, 0x00, 0x00, 0x5f, 0x00, 0x00, 0x03, 0x32, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5f, // ..._...2......._ 0x00, 0x00, 0x03, 0x32, 0x10, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x67, 0x00, 0x00, 0x04, 0xf2, // ...2.......g.... 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x03, 0x32, // ..........e...2 0x20, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x03, 0xc2, 0x20, 0x10, 0x00, 0x01, // ......e.... ... 0x00, 0x00, 0x00, 0x68, 0x00, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x32, // ...h...........2 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, // .......F.......F 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x08, 0x32, 0x00, 0x10, 0x00, 0x00, // ...........2.... 0x00, 0x00, 0x00, 0x46, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x80, 0x20, 0x00, 0x00, // ...F.......F. .. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x12, 0x20, 0x10, 0x00, 0x00, // ............ ... 0x00, 0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, // ............@... 0x00, 0x80, 0xbf, 0x00, 0x00, 0x00, 0x08, 0x22, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, // ......." ....... 0x00, 0x10, 0x80, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, // ...A........@... 0x00, 0x80, 0x3f, 0x36, 0x00, 0x00, 0x08, 0xc2, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // ..?6.... ....... 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // @............... 0x00, 0x80, 0x3f, 0x36, 0x00, 0x00, 0x05, 0x32, 0x20, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x46, // ..?6...2 ......F 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x05, 0xc2, 0x20, 0x10, 0x00, 0x01, // .......6.... ... 0x00, 0x00, 0x00, 0x06, 0x14, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x01, 0x00, // ...........>.... 0x02, 0x01, 0x00, 0x10, 0x00, 0x10, 0x00, // ....... }; static const uint8_t vs_nanovg_fill_mtl[933] = { 0x56, 0x53, 0x48, 0x06, 0x00, 0x00, 0x00, 0x00, 0xcf, 0xda, 0x1b, 0x94, 0x02, 0x00, 0x0b, 0x75, // VSH............u 0x5f, 0x68, 0x61, 0x6c, 0x66, 0x54, 0x65, 0x78, 0x65, 0x6c, 0x02, 0x01, 0x10, 0x00, 0x01, 0x00, // _halfTexel...... 0x0a, 0x75, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x02, 0x01, 0x00, 0x00, 0x01, // .u_viewSize..... 0x00, 0x68, 0x03, 0x00, 0x00, 0x23, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x20, 0x3c, 0x6d, // .h...#include <m 0x65, 0x74, 0x61, 0x6c, 0x5f, 0x73, 0x74, 0x64, 0x6c, 0x69, 0x62, 0x3e, 0x0a, 0x23, 0x69, 0x6e, // etal_stdlib>.#in 0x63, 0x6c, 0x75, 0x64, 0x65, 0x20, 0x3c, 0x73, 0x69, 0x6d, 0x64, 0x2f, 0x73, 0x69, 0x6d, 0x64, // clude <simd/simd 0x2e, 0x68, 0x3e, 0x0a, 0x0a, 0x75, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, // .h>..using names 0x70, 0x61, 0x63, 0x65, 0x20, 0x6d, 0x65, 0x74, 0x61, 0x6c, 0x3b, 0x0a, 0x0a, 0x73, 0x74, 0x72, // pace metal;..str 0x75, 0x63, 0x74, 0x20, 0x5f, 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x0a, 0x7b, 0x0a, 0x20, 0x20, // uct _Global.{. 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x75, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x53, // float4 u_viewS 0x69, 0x7a, 0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, // ize;. float4 0x75, 0x5f, 0x68, 0x61, 0x6c, 0x66, 0x54, 0x65, 0x78, 0x65, 0x6c, 0x3b, 0x0a, 0x7d, 0x3b, 0x0a, // u_halfTexel;.};. 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, // .struct xlatMtlM 0x61, 0x69, 0x6e, 0x5f, 0x6f, 0x75, 0x74, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, // ain_out.{. fl 0x6f, 0x61, 0x74, 0x32, 0x20, 0x5f, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x69, 0x6e, 0x74, // oat2 _entryPoint 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x76, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, // Output_v_positio 0x6e, 0x20, 0x5b, 0x5b, 0x75, 0x73, 0x65, 0x72, 0x28, 0x6c, 0x6f, 0x63, 0x6e, 0x30, 0x29, 0x5d, // n [[user(locn0)] 0x5d, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x32, 0x20, 0x5f, 0x65, // ];. float2 _e 0x6e, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, // ntryPointOutput_ 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x20, 0x5b, 0x5b, 0x75, 0x73, // v_texcoord0 [[us 0x65, 0x72, 0x28, 0x6c, 0x6f, 0x63, 0x6e, 0x31, 0x29, 0x5d, 0x5d, 0x3b, 0x0a, 0x20, 0x20, 0x20, // er(locn1)]];. 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x73, 0x69, 0x74, // float4 gl_Posit 0x69, 0x6f, 0x6e, 0x20, 0x5b, 0x5b, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x5d, 0x5d, // ion [[position]] 0x3b, 0x0a, 0x7d, 0x3b, 0x0a, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x20, 0x78, 0x6c, 0x61, // ;.};..struct xla 0x74, 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x6e, 0x0a, 0x7b, 0x0a, 0x20, 0x20, // tMtlMain_in.{. 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x32, 0x20, 0x61, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, // float2 a_posit 0x69, 0x6f, 0x6e, 0x20, 0x5b, 0x5b, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x28, // ion [[attribute( 0x30, 0x29, 0x5d, 0x5d, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x32, // 0)]];. float2 0x20, 0x61, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x20, 0x5b, 0x5b, 0x61, // a_texcoord0 [[a 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x28, 0x31, 0x29, 0x5d, 0x5d, 0x3b, 0x0a, 0x7d, // ttribute(1)]];.} 0x3b, 0x0a, 0x0a, 0x76, 0x65, 0x72, 0x74, 0x65, 0x78, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, // ;..vertex xlatMt 0x6c, 0x4d, 0x61, 0x69, 0x6e, 0x5f, 0x6f, 0x75, 0x74, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, // lMain_out xlatMt 0x6c, 0x4d, 0x61, 0x69, 0x6e, 0x28, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, // lMain(xlatMtlMai 0x6e, 0x5f, 0x69, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x5b, 0x5b, 0x73, 0x74, 0x61, 0x67, 0x65, 0x5f, // n_in in [[stage_ 0x69, 0x6e, 0x5d, 0x5d, 0x2c, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x74, 0x20, 0x5f, // in]], constant _ 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x26, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x20, 0x5b, // Global& _mtl_u [ 0x5b, 0x62, 0x75, 0x66, 0x66, 0x65, 0x72, 0x28, 0x30, 0x29, 0x5d, 0x5d, 0x29, 0x0a, 0x7b, 0x0a, // [buffer(0)]]).{. 0x20, 0x20, 0x20, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, 0x6e, 0x5f, // xlatMtlMain_ 0x6f, 0x75, 0x74, 0x20, 0x6f, 0x75, 0x74, 0x20, 0x3d, 0x20, 0x7b, 0x7d, 0x3b, 0x0a, 0x20, 0x20, // out out = {};. 0x20, 0x20, 0x6f, 0x75, 0x74, 0x2e, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, // out.gl_Positio 0x6e, 0x20, 0x3d, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x28, 0x28, 0x28, 0x32, 0x2e, 0x30, // n = float4(((2.0 0x20, 0x2a, 0x20, 0x69, 0x6e, 0x2e, 0x61, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, // * in.a_position 0x2e, 0x78, 0x29, 0x20, 0x2f, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x76, // .x) / _mtl_u.u_v 0x69, 0x65, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x2e, 0x78, 0x29, 0x20, 0x2d, 0x20, 0x31, 0x2e, 0x30, // iewSize.x) - 1.0 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x20, 0x2d, 0x20, 0x28, 0x28, 0x32, 0x2e, 0x30, 0x20, 0x2a, 0x20, // , 1.0 - ((2.0 * 0x69, 0x6e, 0x2e, 0x61, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x79, 0x29, // in.a_position.y) 0x20, 0x2f, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x76, 0x69, 0x65, 0x77, // / _mtl_u.u_view 0x53, 0x69, 0x7a, 0x65, 0x2e, 0x79, 0x29, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x2c, 0x20, 0x31, 0x2e, // Size.y), 0.0, 1. 0x30, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x75, 0x74, 0x2e, 0x5f, 0x65, 0x6e, 0x74, // 0);. out._ent 0x72, 0x79, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x76, 0x5f, // ryPointOutput_v_ 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x2e, 0x61, 0x5f, // position = in.a_ 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x75, // position;. ou 0x74, 0x2e, 0x5f, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x4f, 0x75, 0x74, // t._entryPointOut 0x70, 0x75, 0x74, 0x5f, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x20, // put_v_texcoord0 0x3d, 0x20, 0x69, 0x6e, 0x2e, 0x61, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, // = in.a_texcoord0 0x20, 0x2b, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x68, 0x61, 0x6c, 0x66, // + _mtl_u.u_half 0x54, 0x65, 0x78, 0x65, 0x6c, 0x2e, 0x78, 0x79, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, // Texel.xy;. re 0x74, 0x75, 0x72, 0x6e, 0x20, 0x6f, 0x75, 0x74, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, 0x00, 0x02, 0x01, // turn out;.}..... 0x00, 0x10, 0x00, 0x20, 0x00, // ... . }; extern const uint8_t* vs_nanovg_fill_pssl; extern const uint32_t vs_nanovg_fill_pssl_size;
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\demos\agge_draw_image.c
#include <string.h> #include <stdlib.h> #include "agge/nanovg_agge.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../stb/stb_image_write.h" #define STB_IMAGE_IMPLEMENTATION #include "../stb/stb_image.h" #include "draw_image.inc" static void run_test(int32_t w, int32_t h, int32_t BPP, const char* filename) { int32_t size = w * h * BPP; uint8_t* data = (uint8_t*)malloc(size); NVGcontext* vg = nvgCreateAGGE(w, h, w * BPP, BPP == 2 ? NVG_TEXTURE_BGR565 : NVG_TEXTURE_BGRA, data); memset(data, 0xff, size); do_draw(vg, w, h); nvgDeleteAGGE(vg); if(filename != NULL) { stbi_write_png(filename, w, h, BPP, data, 0); } free(data); } int main() { run_test(400, 400, 4, "result32.png"); run_test(400, 400, 2, "result16.png"); return 0; }
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\demos\agge_fill.c
#include <string.h> #include <stdlib.h> #include "agge/nanovg_agge.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../stb/stb_image_write.h" #define STB_IMAGE_IMPLEMENTATION #include "../stb/stb_image.h" #include "fill.inc" static void run_test(int32_t w, int32_t h, int32_t BPP, const char* filename) { int32_t size = w * h * BPP; uint8_t* data = (uint8_t*)malloc(size); NVGcontext* vg = nvgCreateAGGE(w, h, w*BPP, BPP == 2 ? NVG_TEXTURE_BGR565 : NVG_TEXTURE_BGRA, data); memset(data, 0xff, size); do_fill(vg, w, h); nvgDeleteAGGE(vg); if(filename != NULL) { stbi_write_png(filename, w, h, BPP, data, 0); } free(data); } int main() { run_test(400, 400, 4, "result32.png"); run_test(400, 400, 2, "result16.png"); return 0; }
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\demos\agge_stroke.c
#include <math.h> #include <stdlib.h> #include <string.h> #include "agge/nanovg_agge.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../stb/stb_image_write.h" #define STB_IMAGE_IMPLEMENTATION #include "../stb/stb_image.h" #include "stroke.inc" static void run_test(int32_t w, int32_t h, int32_t BPP, const char* filename) { int32_t size = w * h * BPP; uint8_t* data = (uint8_t*)malloc(size); NVGcontext* vg = nvgCreateAGGE(w, h, w*BPP, BPP == 2 ? NVG_TEXTURE_BGR565 : NVG_TEXTURE_BGRA, data); memset(data, 0xff, size); do_stroke(vg, w, h); nvgDeleteAGGE(vg); if(filename != NULL) { stbi_write_png(filename, w, h, BPP, data, 0); } free(data); } int main() { run_test(400, 400, 4, "result32.png"); run_test(400, 400, 2, "result16.png"); return 0; }
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\demos\agg_draw_image.c
#include <string.h> #include <stdlib.h> #include "agg/nanovg_agg.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../stb/stb_image_write.h" #define STB_IMAGE_IMPLEMENTATION #include "../stb/stb_image.h" #include "draw_image.inc" static void run_test(int32_t w, int32_t h, int32_t BPP, const char* filename) { int32_t size = w * h * BPP; uint8_t* data = (uint8_t*)malloc(size); NVGcontext* vg = nvgCreateAGG(w, h, w*BPP, BPP == 2 ? NVG_TEXTURE_BGR565 : NVG_TEXTURE_RGBA, data); memset(data, 0xff, size); do_draw(vg, w, h); nvgDeleteAGG(vg); if(filename != NULL) { stbi_write_png(filename, w, h, BPP, data, 0); } free(data); } int main() { run_test(400, 400, 4, "result32.png"); run_test(400, 400, 2, "result16.png"); return 0; }
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\demos\agg_fill.c
#include <string.h> #include <stdlib.h> #include "agg/nanovg_agg.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../stb/stb_image_write.h" #define STB_IMAGE_IMPLEMENTATION #include "../stb/stb_image.h" #include "fill.inc" static void run_test(int32_t w, int32_t h, int32_t BPP, const char* filename) { int32_t size = w * h * BPP; uint8_t* data = (uint8_t*)malloc(size); NVGcontext* vg = nvgCreateAGG(w, h, w*BPP, BPP == 2 ? NVG_TEXTURE_BGR565 : NVG_TEXTURE_RGBA, data); memset(data, 0xff, size); do_fill(vg, w, h); nvgDeleteAGG(vg); if(filename != NULL) { stbi_write_png(filename, w, h, BPP, data, 0); } free(data); } int main() { run_test(400, 400, 4, "result32.png"); run_test(400, 400, 2, "result16.png"); return 0; }
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\demos\agg_stroke.c
#include <math.h> #include <stdlib.h> #include <string.h> #include "agg/nanovg_agg.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../stb/stb_image_write.h" #define STB_IMAGE_IMPLEMENTATION #include "../stb/stb_image.h" #include "stroke.inc" static void run_test(int32_t w, int32_t h, int32_t BPP, const char* filename) { int32_t size = w * h * BPP; uint8_t* data = (uint8_t*)malloc(size); NVGcontext* vg = nvgCreateAGG(w, h, w*BPP, BPP == 2 ? NVG_TEXTURE_BGR565 : NVG_TEXTURE_RGBA, data); memset(data, 0xff, size); do_stroke(vg, w, h); nvgDeleteAGG(vg); if(filename != NULL) { stbi_write_png(filename, w, h, BPP, data, 0); } free(data); } int main() { run_test(400, 400, 4, "result32.png"); run_test(400, 400, 2, "result16.png"); return 0; }
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\gl\nanovg_gl.h
// // Copyright (c) 2009-2013 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #ifndef NANOVG_GL_H #define NANOVG_GL_H #ifdef __cplusplus extern "C" { #endif // Create flags enum NVGcreateFlags { // Flag indicating if geometry based anti-aliasing is used (may not be needed when using MSAA). NVG_ANTIALIAS = 1 << 0, // Flag indicating if strokes should be drawn using stencil buffer. The rendering will be a little // slower, but path overlaps (i.e. self-intersecting or sharp turns) will be drawn just once. NVG_STENCIL_STROKES = 1 << 1, // Flag indicating that additional debug checks are done. NVG_DEBUG = 1 << 2, }; #if defined NANOVG_GL2_IMPLEMENTATION #define NANOVG_GL2 1 #define NANOVG_GL_IMPLEMENTATION 1 #elif defined NANOVG_GL3_IMPLEMENTATION #define NANOVG_GL3 1 #define NANOVG_GL_IMPLEMENTATION 1 #define NANOVG_GL_USE_UNIFORMBUFFER 1 #elif defined NANOVG_GLES2_IMPLEMENTATION #define NANOVG_GLES2 1 #define NANOVG_GL_IMPLEMENTATION 1 #elif defined NANOVG_GLES3_IMPLEMENTATION #define NANOVG_GLES3 1 #define NANOVG_GL_IMPLEMENTATION 1 #endif #define NANOVG_GL_USE_STATE_FILTER (1) // Creates NanoVG contexts for different OpenGL (ES) versions. // Flags should be combination of the create flags above. #if defined NANOVG_GL2 NVGcontext* nvgCreateGL2(int flags); void nvgDeleteGL2(NVGcontext* ctx); int nvglCreateImageFromHandleGL2(NVGcontext* ctx, GLuint textureId, int w, int h, int flags); GLuint nvglImageHandleGL2(NVGcontext* ctx, int image); #endif #if defined NANOVG_GL3 NVGcontext* nvgCreateGL3(int flags); void nvgDeleteGL3(NVGcontext* ctx); int nvglCreateImageFromHandleGL3(NVGcontext* ctx, GLuint textureId, int w, int h, int flags); GLuint nvglImageHandleGL3(NVGcontext* ctx, int image); #endif #if defined NANOVG_GLES2 NVGcontext* nvgCreateGLES2(int flags); void nvgDeleteGLES2(NVGcontext* ctx); int nvglCreateImageFromHandleGLES2(NVGcontext* ctx, GLuint textureId, int w, int h, int flags); GLuint nvglImageHandleGLES2(NVGcontext* ctx, int image); #endif #if defined NANOVG_GLES3 NVGcontext* nvgCreateGLES3(int flags); void nvgDeleteGLES3(NVGcontext* ctx); int nvglCreateImageFromHandleGLES3(NVGcontext* ctx, GLuint textureId, int w, int h, int flags); GLuint nvglImageHandleGLES3(NVGcontext* ctx, int image); #endif // These are additional flags on top of NVGimageFlags. enum NVGimageFlagsGL { NVG_IMAGE_NODELETE = 1 << 16, // Do not delete GL texture handle. }; #ifdef __cplusplus } #endif #endif /* NANOVG_GL_H */ #ifdef NANOVG_GL_IMPLEMENTATION #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "nanovg.h" enum GLNVGuniformLoc { GLNVG_LOC_VIEWSIZE, GLNVG_LOC_TEX, GLNVG_LOC_FRAG, GLNVG_MAX_LOCS }; enum GLNVGshaderType { NSVG_SHADER_FILLGRAD, NSVG_SHADER_FILLIMG, NSVG_SHADER_SIMPLE, NSVG_SHADER_IMG, NSVG_SHADER_FAST_FILLCOLOR = 5, NSVG_SHADER_FAST_FILLIMG, NSVG_SHADER_FILLCOLOR, NSVG_SHADER_FAST_FILLGLYPH, }; #if NANOVG_GL_USE_UNIFORMBUFFER enum GLNVGuniformBindings { GLNVG_FRAG_BINDING = 0, }; #endif struct GLNVGshader { GLuint prog; GLuint frag; GLuint vert; GLint loc[GLNVG_MAX_LOCS]; }; typedef struct GLNVGshader GLNVGshader; struct GLNVGtexture { int id; GLuint tex; int width, height; int type; int flags; }; typedef struct GLNVGtexture GLNVGtexture; struct GLNVGblend { GLenum srcRGB; GLenum dstRGB; GLenum srcAlpha; GLenum dstAlpha; }; typedef struct GLNVGblend GLNVGblend; enum GLNVGcallType { GLNVG_NONE = 0, GLNVG_FILL, GLNVG_CONVEXFILL, GLNVG_STROKE, GLNVG_TRIANGLES, }; struct GLNVGcall { int type; int image; int pathOffset; int pathCount; int triangleOffset; int triangleCount; int uniformOffset; GLNVGblend blendFunc; }; typedef struct GLNVGcall GLNVGcall; struct GLNVGpath { int fillOffset; int fillCount; int strokeOffset; int strokeCount; }; typedef struct GLNVGpath GLNVGpath; struct GLNVGfragUniforms { #if NANOVG_GL_USE_UNIFORMBUFFER float scissorMat[12]; // matrices are actually 3 vec4s float paintMat[12]; struct NVGcolor innerCol; struct NVGcolor outerCol; float scissorExt[2]; float scissorScale[2]; float extent[2]; float radius; float feather; float strokeMult; float strokeThr; int texType; int type; #else // note: after modifying layout or size of uniform array, // don't forget to also update the fragment shader source! #define NANOVG_GL_UNIFORMARRAY_SIZE 11 union { struct { float scissorMat[12]; // matrices are actually 3 vec4s float paintMat[12]; struct NVGcolor innerCol; struct NVGcolor outerCol; float scissorExt[2]; float scissorScale[2]; float extent[2]; float radius; float feather; float strokeMult; float strokeThr; float texType; float type; }; float uniformArray[NANOVG_GL_UNIFORMARRAY_SIZE][4]; }; #endif }; typedef struct GLNVGfragUniforms GLNVGfragUniforms; struct GLNVGcontext { GLNVGshader shader; GLNVGtexture* textures; float view[2]; int ntextures; int ctextures; int textureId; GLuint vertBuf; float devicePixelRatio; #if defined NANOVG_GL3 GLuint vertArr; #endif #if NANOVG_GL_USE_UNIFORMBUFFER GLuint fragBuf; #endif int fragSize; int flags; float g_xform[6]; // Per frame buffers GLNVGcall* calls; int ccalls; int ncalls; GLNVGpath* paths; int cpaths; int npaths; struct NVGvertex* verts; int cverts; int nverts; unsigned char* uniforms; int cuniforms; int nuniforms; // cached state #if NANOVG_GL_USE_STATE_FILTER GLuint boundTexture; GLuint stencilMask; GLenum stencilFunc; GLint stencilFuncRef; GLuint stencilFuncMask; GLNVGblend blendFunc; #endif }; typedef struct GLNVGcontext GLNVGcontext; static int glnvg__maxi(int a, int b) { return a > b ? a : b; } #ifdef NANOVG_GLES2 static unsigned int glnvg__nearestPow2(unsigned int num) { unsigned n = num > 0 ? num - 1 : 0; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n; } #endif static void glnvg__bindTexture(GLNVGcontext* gl, GLuint tex) { #if NANOVG_GL_USE_STATE_FILTER if (gl->boundTexture != tex) { gl->boundTexture = tex; glBindTexture(GL_TEXTURE_2D, tex); } #else glBindTexture(GL_TEXTURE_2D, tex); #endif } static void glnvg__stencilMask(GLNVGcontext* gl, GLuint mask) { #if NANOVG_GL_USE_STATE_FILTER if (gl->stencilMask != mask) { gl->stencilMask = mask; glStencilMask(mask); } #else glStencilMask(mask); #endif } static void glnvg__stencilFunc(GLNVGcontext* gl, GLenum func, GLint ref, GLuint mask) { #if NANOVG_GL_USE_STATE_FILTER if ((gl->stencilFunc != func) || (gl->stencilFuncRef != ref) || (gl->stencilFuncMask != mask)) { gl->stencilFunc = func; gl->stencilFuncRef = ref; gl->stencilFuncMask = mask; glStencilFunc(func, ref, mask); } #else glStencilFunc(func, ref, mask); #endif } static void glnvg__blendFuncSeparate(GLNVGcontext* gl, const GLNVGblend* blend) { #if NANOVG_GL_USE_STATE_FILTER if ((gl->blendFunc.srcRGB != blend->srcRGB) || (gl->blendFunc.dstRGB != blend->dstRGB) || (gl->blendFunc.srcAlpha != blend->srcAlpha) || (gl->blendFunc.dstAlpha != blend->dstAlpha)) { gl->blendFunc = *blend; glBlendFuncSeparate(blend->srcRGB, blend->dstRGB, blend->srcAlpha, blend->dstAlpha); } #else glBlendFuncSeparate(blend->srcRGB, blend->dstRGB, blend->srcAlpha, blend->dstAlpha); #endif } static GLNVGtexture* glnvg__allocTexture(GLNVGcontext* gl) { GLNVGtexture* tex = NULL; int i; for (i = 0; i < gl->ntextures; i++) { if (gl->textures[i].id == 0) { tex = &gl->textures[i]; break; } } if (tex == NULL) { if (gl->ntextures + 1 > gl->ctextures) { GLNVGtexture* textures; int ctextures = glnvg__maxi(gl->ntextures + 1, 4) + gl->ctextures / 2; // 1.5x Overallocate textures = (GLNVGtexture*)realloc(gl->textures, sizeof(GLNVGtexture) * ctextures); if (textures == NULL) return NULL; gl->textures = textures; gl->ctextures = ctextures; } tex = &gl->textures[gl->ntextures++]; } memset(tex, 0, sizeof(*tex)); tex->id = ++gl->textureId; return tex; } static GLNVGtexture* glnvg__findTexture(GLNVGcontext* gl, int id) { int i; for (i = 0; i < gl->ntextures; i++) if (gl->textures[i].id == id) return &gl->textures[i]; return NULL; } static int glnvg__deleteTexture(GLNVGcontext* gl, int id) { int i; for (i = 0; i < gl->ntextures; i++) { if (gl->textures[i].id == id) { if (gl->textures[i].tex != 0 && (gl->textures[i].flags & NVG_IMAGE_NODELETE) == 0) glDeleteTextures(1, &gl->textures[i].tex); memset(&gl->textures[i], 0, sizeof(gl->textures[i])); return 1; } } return 0; } static void glnvg__dumpShaderError(GLuint shader, const char* name, const char* type) { GLchar str[512 + 1]; GLsizei len = 0; glGetShaderInfoLog(shader, 512, &len, str); if (len > 512) len = 512; str[len] = '\0'; printf("Shader %s/%s error:\n%s\n", name, type, str); } static void glnvg__dumpProgramError(GLuint prog, const char* name) { GLchar str[512 + 1]; GLsizei len = 0; glGetProgramInfoLog(prog, 512, &len, str); if (len > 512) len = 512; str[len] = '\0'; printf("Program %s error:\n%s\n", name, str); } static void glnvg__checkError(GLNVGcontext* gl, const char* str) { GLenum err; if ((gl->flags & NVG_DEBUG) == 0) return; err = glGetError(); if (err != GL_NO_ERROR) { printf("Error %08x after %s\n", err, str); return; } } static int glnvg__createShader(GLNVGshader* shader, const char* name, const char* header, const char* opts, const char* vshader, const char* fshader) { GLint status; GLuint prog, vert, frag; const char* str[3]; str[0] = header; str[1] = opts != NULL ? opts : ""; memset(shader, 0, sizeof(*shader)); prog = glCreateProgram(); vert = glCreateShader(GL_VERTEX_SHADER); frag = glCreateShader(GL_FRAGMENT_SHADER); str[2] = vshader; glShaderSource(vert, 3, str, 0); str[2] = fshader; glShaderSource(frag, 3, str, 0); glCompileShader(vert); glGetShaderiv(vert, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { glnvg__dumpShaderError(vert, name, "vert"); return 0; } glCompileShader(frag); glGetShaderiv(frag, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { glnvg__dumpShaderError(frag, name, "frag"); return 0; } glAttachShader(prog, vert); glAttachShader(prog, frag); glBindAttribLocation(prog, 0, "vertex"); glBindAttribLocation(prog, 1, "tcoord"); glLinkProgram(prog); glGetProgramiv(prog, GL_LINK_STATUS, &status); if (status != GL_TRUE) { glnvg__dumpProgramError(prog, name); return 0; } shader->prog = prog; shader->vert = vert; shader->frag = frag; return 1; } static void glnvg__deleteShader(GLNVGshader* shader) { if (shader->prog != 0) glDeleteProgram(shader->prog); if (shader->vert != 0) glDeleteShader(shader->vert); if (shader->frag != 0) glDeleteShader(shader->frag); } static void glnvg__getUniforms(GLNVGshader* shader) { shader->loc[GLNVG_LOC_VIEWSIZE] = glGetUniformLocation(shader->prog, "viewSize"); shader->loc[GLNVG_LOC_TEX] = glGetUniformLocation(shader->prog, "tex"); #if NANOVG_GL_USE_UNIFORMBUFFER shader->loc[GLNVG_LOC_FRAG] = glGetUniformBlockIndex(shader->prog, "frag"); #else shader->loc[GLNVG_LOC_FRAG] = glGetUniformLocation(shader->prog, "frag"); #endif } static int glnvg__renderCreate(void* uptr) { GLNVGcontext* gl = (GLNVGcontext*)uptr; int align = 4; // TODO: mediump float may not be enough for GLES2 in iOS. // see the following discussion: https://github.com/memononen/nanovg/issues/46 static const char* shaderHeader = #if defined NANOVG_GL2 "#define NANOVG_GL2 1\n" #elif defined NANOVG_GL3 "#version 150 core\n" "#define NANOVG_GL3 1\n" #elif defined NANOVG_GLES2 "#version 100\n" "#define NANOVG_GL2 1\n" #elif defined NANOVG_GLES3 "#version 300 es\n" "#define NANOVG_GL3 1\n" #endif #if NANOVG_GL_USE_UNIFORMBUFFER "#define USE_UNIFORMBUFFER 1\n" #else "#define UNIFORMARRAY_SIZE 11\n" #endif "\n"; static const char* fillVertShader = "#ifdef NANOVG_GL3\n" " uniform vec2 viewSize;\n" " in vec2 vertex;\n" " in vec2 tcoord;\n" " out vec2 ftcoord;\n" " out vec2 fpos;\n" "#else\n" " uniform vec2 viewSize;\n" " attribute vec2 vertex;\n" " attribute vec2 tcoord;\n" " varying vec2 ftcoord;\n" " varying vec2 fpos;\n" "#endif\n" "void main(void) {\n" " ftcoord = tcoord;\n" " fpos = vertex;\n" " gl_Position = vec4(2.0*vertex.x/viewSize.x - 1.0, 1.0 - 2.0*vertex.y/viewSize.y, 0, 1);\n" "}\n"; static const char* fillFragShader = "#ifdef GL_ES\n" "#if defined(GL_FRAGMENT_PRECISION_HIGH) || defined(NANOVG_GL3)\n" " precision highp float;\n" "#else\n" " precision mediump float;\n" "#endif\n" "#endif\n" "#ifdef NANOVG_GL3\n" "#ifdef USE_UNIFORMBUFFER\n" " layout(std140) uniform frag {\n" " mat3 scissorMat;\n" " mat3 paintMat;\n" " vec4 innerCol;\n" " vec4 outerCol;\n" " vec2 scissorExt;\n" " vec2 scissorScale;\n" " vec2 extent;\n" " float radius;\n" " float feather;\n" " float strokeMult;\n" " float strokeThr;\n" " int texType;\n" " int type;\n" " };\n" "#else\n" // NANOVG_GL3 && !USE_UNIFORMBUFFER " uniform vec4 frag[UNIFORMARRAY_SIZE];\n" "#endif\n" " uniform sampler2D tex;\n" " in vec2 ftcoord;\n" " in vec2 fpos;\n" " out vec4 outColor;\n" "#else\n" // !NANOVG_GL3 " uniform vec4 frag[UNIFORMARRAY_SIZE];\n" " uniform sampler2D tex;\n" " varying vec2 ftcoord;\n" " varying vec2 fpos;\n" "#endif\n" "#ifndef USE_UNIFORMBUFFER\n" " #define scissorMat mat3(frag[0].xyz, frag[1].xyz, frag[2].xyz)\n" " #define paintMat mat3(frag[3].xyz, frag[4].xyz, frag[5].xyz)\n" " #define innerCol frag[6]\n" " #define outerCol frag[7]\n" " #define scissorExt frag[8].xy\n" " #define scissorScale frag[8].zw\n" " #define extent frag[9].xy\n" " #define radius frag[9].z\n" " #define feather frag[9].w\n" " #define strokeMult frag[10].x\n" " #define strokeThr frag[10].y\n" " #define texType int(frag[10].z)\n" " #define type int(frag[10].w)\n" "#endif\n" "\n" "float sdroundrect(vec2 pt, vec2 ext, float rad) {\n" " vec2 ext2 = ext - vec2(rad,rad);\n" " vec2 d = abs(pt) - ext2;\n" " return min(max(d.x,d.y),0.0) + length(max(d,0.0)) - rad;\n" "}\n" "\n" "// Scissoring\n" "float scissorMask(vec2 p) {\n" " vec2 sc = (abs((scissorMat * vec3(p,1.0)).xy) - scissorExt);\n" " sc = vec2(0.5,0.5) - sc * scissorScale;\n" " return clamp(sc.x,0.0,1.0) * clamp(sc.y,0.0,1.0);\n" "}\n" "// Stroke - from [0..1] to clipped pyramid, where the slope is 1px.\n" "float strokeMask() {\n" " return min(1.0, (1.0-abs(ftcoord.x*2.0-1.0))*strokeMult) * min(1.0, ftcoord.y);\n" "}\n" "\n" "void main(void) {\n" " vec4 result;\n" " float strokeAlpha;\n" " if (type == 5) { //fast fill color\n" " result = innerCol;\n" " } else if (type == 6) { //fast fill image\n" " vec2 pt = (paintMat * vec3(fpos,1.0)).xy / extent;\n" "#ifdef NANOVG_GL3\n" " vec4 color = texture(tex, pt);\n" "#else\n" " vec4 color = texture2D(tex, pt);\n" "#endif\n" " strokeAlpha = strokeMask();\n" " if (strokeAlpha < strokeThr) discard;\n" " if (texType == 1) color = vec4(color.xyz*color.w,color.w);" " result = innerCol * color * strokeAlpha;\n" " } else if(type == 7) { // fill color\n" " strokeAlpha = strokeMask();\n" " if (strokeAlpha < strokeThr) discard;\n" " float scissor = scissorMask(fpos);\n" " vec4 color = innerCol;\n" " color *= strokeAlpha * scissor;\n" " result = color;\n" " } else if (type == 8) { // fast fill glyph\n" "#ifdef NANOVG_GL3\n" " vec4 color = texture(tex, ftcoord);\n" "#else\n" " vec4 color = texture2D(tex, ftcoord);\n" "#endif\n" " if(color.x < 0.02) discard;\n" " result = innerCol * color.x;\n" " } else if (type == 0) { // gradient\n" " strokeAlpha = strokeMask();\n" " if (strokeAlpha < strokeThr) discard;\n" " // Calculate gradient color using box gradient\n" " vec2 pt = (paintMat * vec3(fpos,1.0)).xy;\n" " float d = clamp((sdroundrect(pt, extent, radius) + feather*0.5) / feather, 0.0, 1.0);\n" " vec4 color = mix(innerCol,outerCol,d);\n" " // Combine alpha\n" " float scissor = scissorMask(fpos);\n" " color *= strokeAlpha * scissor;\n" " result = color;\n" " } else if (type == 1) { // Image\n" " strokeAlpha = strokeMask();\n" " if (strokeAlpha < strokeThr) discard;\n" " // Calculate color fron texture\n" " vec2 pt = (paintMat * vec3(fpos,1.0)).xy / extent;\n" "#ifdef NANOVG_GL3\n" " vec4 color = texture(tex, pt);\n" "#else\n" " vec4 color = texture2D(tex, pt);\n" "#endif\n" " if (texType == 1) color = vec4(color.xyz*color.w,color.w);" " if (texType == 2) color = vec4(color.x);" " // Apply color tint and alpha.\n" " color *= innerCol;\n" " // Combine alpha\n" " float scissor = scissorMask(fpos);\n" " color *= strokeAlpha * scissor;\n" " result = color;\n" " } else if (type == 2) { // Stencil fill\n" " result = vec4(1,1,1,1);\n" " } else if (type == 3) { // Textured tris\n" "#ifdef NANOVG_GL3\n" " vec4 color = texture(tex, ftcoord);\n" "#else\n" " vec4 color = texture2D(tex, ftcoord);\n" "#endif\n" " if(color.x < 0.02) discard;\n" " strokeAlpha = strokeMask();\n" " if (strokeAlpha < strokeThr) discard;\n" " float scissor = scissorMask(fpos);\n" " color = vec4(color.x);" " color *= scissor;\n" " result = color * innerCol;\n" " }\n" "#ifdef NANOVG_GL3\n" " outColor = result;\n" "#else\n" " gl_FragColor = result;\n" "#endif\n" "}\n"; glnvg__checkError(gl, "init"); if (gl->flags & NVG_ANTIALIAS) { if (glnvg__createShader(&gl->shader, "shader", shaderHeader, "#define EDGE_AA 1\n", fillVertShader, fillFragShader) == 0) return 0; } else { if (glnvg__createShader(&gl->shader, "shader", shaderHeader, NULL, fillVertShader, fillFragShader) == 0) return 0; } glnvg__checkError(gl, "uniform locations"); glnvg__getUniforms(&gl->shader); // Create dynamic vertex array #if defined NANOVG_GL3 glGenVertexArrays(1, &gl->vertArr); #endif glGenBuffers(1, &gl->vertBuf); #if NANOVG_GL_USE_UNIFORMBUFFER // Create UBOs glUniformBlockBinding(gl->shader.prog, gl->shader.loc[GLNVG_LOC_FRAG], GLNVG_FRAG_BINDING); glGenBuffers(1, &gl->fragBuf); glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &align); #endif gl->fragSize = sizeof(GLNVGfragUniforms) + align - sizeof(GLNVGfragUniforms) % align; glnvg__checkError(gl, "create done"); glFinish(); return 1; } static int glnvg__renderCreateTexture(void* uptr, int type, int w, int h, int stride, int imageFlags, enum NVGorientation orientation, const unsigned char* data) { GLNVGcontext* gl = (GLNVGcontext*)uptr; GLNVGtexture* tex = glnvg__allocTexture(gl); if (tex == NULL) return 0; #ifdef NANOVG_GLES2 // Check for non-power of 2. if (glnvg__nearestPow2(w) != (unsigned int)w || glnvg__nearestPow2(h) != (unsigned int)h) { // No repeat if ((imageFlags & NVG_IMAGE_REPEATX) != 0 || (imageFlags & NVG_IMAGE_REPEATY) != 0) { printf("Repeat X/Y is not supported for non power-of-two textures (%d x %d)\n", w, h); imageFlags &= ~(NVG_IMAGE_REPEATX | NVG_IMAGE_REPEATY); } // No mips. if (imageFlags & NVG_IMAGE_GENERATE_MIPMAPS) { printf("Mip-maps is not support for non power-of-two textures (%d x %d)\n", w, h); imageFlags &= ~NVG_IMAGE_GENERATE_MIPMAPS; } } #endif glGenTextures(1, &tex->tex); tex->width = w; tex->height = h; tex->type = type; tex->flags = imageFlags; glnvg__bindTexture(gl, tex->tex); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); #ifndef NANOVG_GLES2 glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->width); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); #endif #if defined(NANOVG_GL2) // GL 1.4 and later has support for generating mipmaps using a tex parameter. if (imageFlags & NVG_IMAGE_GENERATE_MIPMAPS) { glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); } #endif if (type == NVG_TEXTURE_RGBA) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); else #if defined(NANOVG_GLES2) || defined(NANOVG_GL2) glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, data); #elif defined(NANOVG_GLES3) glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, data); #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, data); #endif if (imageFlags & NVG_IMAGE_GENERATE_MIPMAPS) { if (imageFlags & NVG_IMAGE_NEAREST) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } } else { if (imageFlags & NVG_IMAGE_NEAREST) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } } if (imageFlags & NVG_IMAGE_NEAREST) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } if (imageFlags & NVG_IMAGE_REPEATX) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); if (imageFlags & NVG_IMAGE_REPEATY) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); #ifndef NANOVG_GLES2 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); #endif // The new way to build mipmaps on GLES and GL3 #if !defined(NANOVG_GL2) if (imageFlags & NVG_IMAGE_GENERATE_MIPMAPS) { glGenerateMipmap(GL_TEXTURE_2D); } #endif glnvg__checkError(gl, "create tex"); glnvg__bindTexture(gl, 0); return tex->id; } static int glnvg__renderDeleteTexture(void* uptr, int image) { GLNVGcontext* gl = (GLNVGcontext*)uptr; return glnvg__deleteTexture(gl, image); } static int glnvg__renderUpdateTexture(void* uptr, int image, int x, int y, int w, int h, const unsigned char* data) { GLNVGcontext* gl = (GLNVGcontext*)uptr; GLNVGtexture* tex = glnvg__findTexture(gl, image); if (tex == NULL) return 0; glnvg__bindTexture(gl, tex->tex); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); #ifndef NANOVG_GLES2 glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->width); glPixelStorei(GL_UNPACK_SKIP_PIXELS, x); glPixelStorei(GL_UNPACK_SKIP_ROWS, y); #else // No support for all of skip, need to update a whole row at a time. if (tex->type == NVG_TEXTURE_RGBA) data += y * tex->width * 4; else data += y * tex->width; x = 0; w = tex->width; #endif if (tex->type == NVG_TEXTURE_RGBA) glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, data); else #if defined(NANOVG_GLES2) || defined(NANOVG_GL2) glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_LUMINANCE, GL_UNSIGNED_BYTE, data); #else glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RED, GL_UNSIGNED_BYTE, data); #endif glPixelStorei(GL_UNPACK_ALIGNMENT, 4); #ifndef NANOVG_GLES2 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); #endif glnvg__bindTexture(gl, 0); return 1; } static int glnvg__renderGetTextureSize(void* uptr, int image, int* w, int* h) { GLNVGcontext* gl = (GLNVGcontext*)uptr; GLNVGtexture* tex = glnvg__findTexture(gl, image); if (tex == NULL) return 0; *w = tex->width; *h = tex->height; return 1; } static void glnvg__xformToMat3x4(float* m3, float* t) { m3[0] = t[0]; m3[1] = t[1]; m3[2] = 0.0f; m3[3] = 0.0f; m3[4] = t[2]; m3[5] = t[3]; m3[6] = 0.0f; m3[7] = 0.0f; m3[8] = t[4]; m3[9] = t[5]; m3[10] = 1.0f; m3[11] = 0.0f; } static NVGcolor glnvg__premulColor(NVGcolor c) { c.r *= c.a; c.g *= c.a; c.b *= c.a; return c; } static int glnvg__convertPaint(GLNVGcontext* gl, GLNVGfragUniforms* frag, NVGpaint* paint, NVGscissor* scissor, float width, float fringe, float strokeThr) { GLNVGtexture* tex = NULL; float invxform[6]; memset(frag, 0, sizeof(*frag)); frag->innerCol = glnvg__premulColor(paint->innerColor); frag->outerCol = glnvg__premulColor(paint->outerColor); if (scissor->extent[0] < -0.5f || scissor->extent[1] < -0.5f) { memset(frag->scissorMat, 0, sizeof(frag->scissorMat)); frag->scissorExt[0] = 1.0f; frag->scissorExt[1] = 1.0f; frag->scissorScale[0] = 1.0f; frag->scissorScale[1] = 1.0f; } else { nvgTransformInverse(invxform, scissor->xform); glnvg__xformToMat3x4(frag->scissorMat, invxform); frag->scissorExt[0] = scissor->extent[0]; frag->scissorExt[1] = scissor->extent[1]; frag->scissorScale[0] = sqrtf(scissor->xform[0] * scissor->xform[0] + scissor->xform[2] * scissor->xform[2]) / fringe; frag->scissorScale[1] = sqrtf(scissor->xform[1] * scissor->xform[1] + scissor->xform[3] * scissor->xform[3]) / fringe; } memcpy(frag->extent, paint->extent, sizeof(frag->extent)); frag->strokeMult = (width * 0.5f + fringe * 0.5f) / fringe; frag->strokeThr = strokeThr; if (paint->image != 0) { tex = glnvg__findTexture(gl, paint->image); if (tex == NULL) return 0; if ((tex->flags & NVG_IMAGE_FLIPY) != 0) { float m1[6], m2[6]; nvgTransformTranslate(m1, 0.0f, frag->extent[1] * 0.5f); nvgTransformMultiply(m1, paint->xform); nvgTransformScale(m2, 1.0f, -1.0f); nvgTransformMultiply(m2, m1); nvgTransformTranslate(m1, 0.0f, -frag->extent[1] * 0.5f); nvgTransformMultiply(m1, m2); nvgTransformInverse(invxform, m1); } else { nvgTransformInverse(invxform, paint->xform); } frag->type = NSVG_SHADER_FILLIMG; #if NANOVG_GL_USE_UNIFORMBUFFER if (tex->type == NVG_TEXTURE_RGBA) frag->texType = (tex->flags & NVG_IMAGE_PREMULTIPLIED) ? 0 : 1; else frag->texType = 2; #else if (tex->type == NVG_TEXTURE_RGBA) frag->texType = (tex->flags & NVG_IMAGE_PREMULTIPLIED) ? 0.0f : 1.0f; else frag->texType = 2.0f; #endif // printf("frag->texType = %d\n", frag->texType); } else { frag->type = NSVG_SHADER_FILLGRAD; frag->radius = paint->radius; frag->feather = paint->feather; nvgTransformInverse(invxform, paint->xform); } glnvg__xformToMat3x4(frag->paintMat, invxform); return 1; } static GLNVGfragUniforms* nvg__fragUniformPtr(GLNVGcontext* gl, int i); static void glnvg__setUniforms(GLNVGcontext* gl, int uniformOffset, int image) { #if NANOVG_GL_USE_UNIFORMBUFFER glBindBufferRange(GL_UNIFORM_BUFFER, GLNVG_FRAG_BINDING, gl->fragBuf, uniformOffset, sizeof(GLNVGfragUniforms)); #else GLNVGfragUniforms* frag = nvg__fragUniformPtr(gl, uniformOffset); glUniform4fv(gl->shader.loc[GLNVG_LOC_FRAG], NANOVG_GL_UNIFORMARRAY_SIZE, &(frag->uniformArray[0][0])); #endif if (image != 0) { GLNVGtexture* tex = glnvg__findTexture(gl, image); glnvg__bindTexture(gl, tex != NULL ? tex->tex : 0); glnvg__checkError(gl, "tex paint tex"); } else { glnvg__bindTexture(gl, 0); } } static void glnvg__renderViewport(void* uptr, float width, float height, float devicePixelRatio) { //NVG_NOTUSED(devicePixelRatio); GLNVGcontext* gl = (GLNVGcontext*)uptr; gl->view[0] = width; gl->view[1] = height; gl->devicePixelRatio = devicePixelRatio; } static void glnvg__fill(GLNVGcontext* gl, GLNVGcall* call) { GLNVGpath* paths = &gl->paths[call->pathOffset]; int i, npaths = call->pathCount; // Draw shapes glEnable(GL_STENCIL_TEST); glnvg__stencilMask(gl, 0xff); glnvg__stencilFunc(gl, GL_ALWAYS, 0, 0xff); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // set bindpoint for solid loc glnvg__setUniforms(gl, call->uniformOffset, 0); glnvg__checkError(gl, "fill simple"); glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_INCR_WRAP); glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_DECR_WRAP); glDisable(GL_CULL_FACE); for (i = 0; i < npaths; i++) glDrawArrays(GL_TRIANGLE_FAN, paths[i].fillOffset, paths[i].fillCount); glEnable(GL_CULL_FACE); // Draw anti-aliased pixels glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glnvg__setUniforms(gl, call->uniformOffset + gl->fragSize, call->image); glnvg__checkError(gl, "fill fill"); if (gl->flags & NVG_ANTIALIAS) { glnvg__stencilFunc(gl, GL_EQUAL, 0x00, 0xff); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // Draw fringes for (i = 0; i < npaths; i++) glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount); } // Draw fill glnvg__stencilFunc(gl, GL_NOTEQUAL, 0x0, 0xff); glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO); glDrawArrays(GL_TRIANGLE_STRIP, call->triangleOffset, call->triangleCount); glDisable(GL_STENCIL_TEST); } static void glnvg__convexFill(GLNVGcontext* gl, GLNVGcall* call) { GLNVGpath* paths = &gl->paths[call->pathOffset]; int i, npaths = call->pathCount; glnvg__setUniforms(gl, call->uniformOffset, call->image); glnvg__checkError(gl, "convex fill"); for (i = 0; i < npaths; i++) { glDrawArrays(GL_TRIANGLE_FAN, paths[i].fillOffset, paths[i].fillCount); // Draw fringes if (paths[i].strokeCount > 0) { glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount); } } } static void glnvg__stroke(GLNVGcontext* gl, GLNVGcall* call) { GLNVGpath* paths = &gl->paths[call->pathOffset]; int npaths = call->pathCount, i; if (gl->flags & NVG_STENCIL_STROKES) { glEnable(GL_STENCIL_TEST); glnvg__stencilMask(gl, 0xff); // Fill the stroke base without overlap glnvg__stencilFunc(gl, GL_EQUAL, 0x0, 0xff); glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); glnvg__setUniforms(gl, call->uniformOffset + gl->fragSize, call->image); glnvg__checkError(gl, "stroke fill 0"); for (i = 0; i < npaths; i++) glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount); // Draw anti-aliased pixels. glnvg__setUniforms(gl, call->uniformOffset, call->image); glnvg__stencilFunc(gl, GL_EQUAL, 0x00, 0xff); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); for (i = 0; i < npaths; i++) glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount); // Clear stencil buffer. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glnvg__stencilFunc(gl, GL_ALWAYS, 0x0, 0xff); glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO); glnvg__checkError(gl, "stroke fill 1"); for (i = 0; i < npaths; i++) glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDisable(GL_STENCIL_TEST); // glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset + gl->fragSize), // paint, scissor, strokeWidth, fringe, 1.0f - 0.5f/255.0f); } else { glnvg__setUniforms(gl, call->uniformOffset, call->image); glnvg__checkError(gl, "stroke fill"); // Draw Strokes for (i = 0; i < npaths; i++) glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount); } } static void glnvg__triangles(GLNVGcontext* gl, GLNVGcall* call) { glnvg__setUniforms(gl, call->uniformOffset, call->image); glnvg__checkError(gl, "triangles fill"); glDrawArrays(GL_TRIANGLES, call->triangleOffset, call->triangleCount); } static void glnvg__renderCancel(void* uptr) { GLNVGcontext* gl = (GLNVGcontext*)uptr; gl->nverts = 0; gl->npaths = 0; gl->ncalls = 0; gl->nuniforms = 0; } static GLenum glnvg_convertBlendFuncFactor(int factor) { if (factor == NVG_ZERO) return GL_ZERO; if (factor == NVG_ONE) return GL_ONE; if (factor == NVG_SRC_COLOR) return GL_SRC_COLOR; if (factor == NVG_ONE_MINUS_SRC_COLOR) return GL_ONE_MINUS_SRC_COLOR; if (factor == NVG_DST_COLOR) return GL_DST_COLOR; if (factor == NVG_ONE_MINUS_DST_COLOR) return GL_ONE_MINUS_DST_COLOR; if (factor == NVG_SRC_ALPHA) return GL_SRC_ALPHA; if (factor == NVG_ONE_MINUS_SRC_ALPHA) return GL_ONE_MINUS_SRC_ALPHA; if (factor == NVG_DST_ALPHA) return GL_DST_ALPHA; if (factor == NVG_ONE_MINUS_DST_ALPHA) return GL_ONE_MINUS_DST_ALPHA; if (factor == NVG_SRC_ALPHA_SATURATE) return GL_SRC_ALPHA_SATURATE; return GL_INVALID_ENUM; } static GLNVGblend glnvg__blendCompositeOperation(NVGcompositeOperationState op) { GLNVGblend blend; blend.srcRGB = glnvg_convertBlendFuncFactor(op.srcRGB); blend.dstRGB = glnvg_convertBlendFuncFactor(op.dstRGB); blend.srcAlpha = glnvg_convertBlendFuncFactor(op.srcAlpha); blend.dstAlpha = glnvg_convertBlendFuncFactor(op.dstAlpha); if (blend.srcRGB == GL_INVALID_ENUM || blend.dstRGB == GL_INVALID_ENUM || blend.srcAlpha == GL_INVALID_ENUM || blend.dstAlpha == GL_INVALID_ENUM) { blend.srcRGB = GL_ONE; blend.dstRGB = GL_ONE_MINUS_SRC_ALPHA; blend.srcAlpha = GL_ONE; blend.dstAlpha = GL_ONE_MINUS_SRC_ALPHA; } return blend; } static void glnvg__renderFlush(void* uptr) { GLNVGcontext* gl = (GLNVGcontext*)uptr; int i; if (gl->ncalls > 0) { // Setup require GL state. glUseProgram(gl->shader.prog); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CCW); glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glStencilMask(0xffffffff); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glStencilFunc(GL_ALWAYS, 0, 0xffffffff); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); #if NANOVG_GL_USE_STATE_FILTER gl->boundTexture = 0; gl->stencilMask = 0xffffffff; gl->stencilFunc = GL_ALWAYS; gl->stencilFuncRef = 0; gl->stencilFuncMask = 0xffffffff; gl->blendFunc.srcRGB = GL_INVALID_ENUM; gl->blendFunc.srcAlpha = GL_INVALID_ENUM; gl->blendFunc.dstRGB = GL_INVALID_ENUM; gl->blendFunc.dstAlpha = GL_INVALID_ENUM; #endif #if NANOVG_GL_USE_UNIFORMBUFFER // Upload ubo for frag shaders glBindBuffer(GL_UNIFORM_BUFFER, gl->fragBuf); glBufferData(GL_UNIFORM_BUFFER, gl->nuniforms * gl->fragSize, gl->uniforms, GL_STREAM_DRAW); #endif // Upload vertex data #if defined NANOVG_GL3 glBindVertexArray(gl->vertArr); #endif glBindBuffer(GL_ARRAY_BUFFER, gl->vertBuf); glBufferData(GL_ARRAY_BUFFER, gl->nverts * sizeof(NVGvertex), gl->verts, GL_STREAM_DRAW); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(NVGvertex), (const GLvoid*)(size_t)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(NVGvertex), (const GLvoid*)(0 + 2 * sizeof(float))); // Set view and texture just once per frame. glUniform1i(gl->shader.loc[GLNVG_LOC_TEX], 0); glUniform2fv(gl->shader.loc[GLNVG_LOC_VIEWSIZE], 1, gl->view); #if NANOVG_GL_USE_UNIFORMBUFFER glBindBuffer(GL_UNIFORM_BUFFER, gl->fragBuf); #endif for (i = 0; i < gl->ncalls; i++) { GLNVGcall* call = &gl->calls[i]; glnvg__blendFuncSeparate(gl, &call->blendFunc); if (call->type == GLNVG_FILL) glnvg__fill(gl, call); else if (call->type == GLNVG_CONVEXFILL) glnvg__convexFill(gl, call); else if (call->type == GLNVG_STROKE) glnvg__stroke(gl, call); else if (call->type == GLNVG_TRIANGLES) glnvg__triangles(gl, call); } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); #if defined NANOVG_GL3 glBindVertexArray(0); #endif glDisable(GL_CULL_FACE); glBindBuffer(GL_ARRAY_BUFFER, 0); glUseProgram(0); glnvg__bindTexture(gl, 0); } // Reset calls gl->nverts = 0; gl->npaths = 0; gl->ncalls = 0; gl->nuniforms = 0; } static int glnvg__maxVertCount(const NVGpath* paths, int npaths) { int i, count = 0; for (i = 0; i < npaths; i++) { count += paths[i].nfill; count += paths[i].nstroke; } return count; } static GLNVGcall* glnvg__allocCall(GLNVGcontext* gl) { GLNVGcall* ret = NULL; if (gl->ncalls + 1 > gl->ccalls) { GLNVGcall* calls; int ccalls = glnvg__maxi(gl->ncalls + 1, 128) + gl->ccalls / 2; // 1.5x Overallocate calls = (GLNVGcall*)realloc(gl->calls, sizeof(GLNVGcall) * ccalls); if (calls == NULL) return NULL; gl->calls = calls; gl->ccalls = ccalls; } ret = &gl->calls[gl->ncalls++]; memset(ret, 0, sizeof(GLNVGcall)); return ret; } static int glnvg__allocPaths(GLNVGcontext* gl, int n) { int ret = 0; if (gl->npaths + n > gl->cpaths) { GLNVGpath* paths; int cpaths = glnvg__maxi(gl->npaths + n, 128) + gl->cpaths / 2; // 1.5x Overallocate paths = (GLNVGpath*)realloc(gl->paths, sizeof(GLNVGpath) * cpaths); if (paths == NULL) return -1; gl->paths = paths; gl->cpaths = cpaths; } ret = gl->npaths; gl->npaths += n; return ret; } static int glnvg__allocVerts(GLNVGcontext* gl, int n) { int ret = 0; if (gl->nverts + n > gl->cverts) { NVGvertex* verts; int cverts = glnvg__maxi(gl->nverts + n, 4096) + gl->cverts / 2; // 1.5x Overallocate verts = (NVGvertex*)realloc(gl->verts, sizeof(NVGvertex) * cverts); if (verts == NULL) return -1; gl->verts = verts; gl->cverts = cverts; } ret = gl->nverts; gl->nverts += n; return ret; } static int glnvg__allocFragUniforms(GLNVGcontext* gl, int n) { int ret = 0, structSize = gl->fragSize; if (gl->nuniforms + n > gl->cuniforms) { unsigned char* uniforms; int cuniforms = glnvg__maxi(gl->nuniforms + n, 128) + gl->cuniforms / 2; // 1.5x Overallocate uniforms = (unsigned char*)realloc(gl->uniforms, structSize * cuniforms); if (uniforms == NULL) return -1; gl->uniforms = uniforms; gl->cuniforms = cuniforms; } ret = gl->nuniforms * structSize; gl->nuniforms += n; return ret; } static GLNVGfragUniforms* nvg__fragUniformPtr(GLNVGcontext* gl, int i) { return (GLNVGfragUniforms*)&gl->uniforms[i]; } static void glnvg__vset(NVGvertex* vtx, float x, float y, float u, float v) { vtx->x = x; vtx->y = y; vtx->u = u; vtx->v = v; } static int glnvg__pathIsRect(const NVGpath* path) { const NVGvertex* verts = path->fill; if (path->nfill == 4) { int ret1 = (verts[0].y == verts[1].y && verts[1].x == verts[2].x && verts[2].y == verts[3].y && verts[3].x == verts[0].x); int ret2 = (verts[0].x == verts[1].x && verts[1].y == verts[2].y && verts[2].x == verts[3].x && verts[3].y == verts[0].y); if (ret1 || ret2) { return 1; } } return 0; } static int glnvg_getSupportFastDraw(GLNVGcontext* gl, NVGscissor* scissor) { /* 根据 nanovg 的坐标系,判断坐标系是否已经旋转或者缩放了,如果是就返回不支持快速绘画的方法 */ if(gl->g_xform[0] == 1.0f && gl->g_xform[1] == 0.0f && gl->g_xform[2] == 0.0f && gl->g_xform[3] == 1.0f && scissor->xform[0] == 1.0f && scissor->xform[1] == 0.0f && scissor->xform[2] == 0.0f && scissor->xform[3] == 1.0f) { return 1; } else { return 0; } } static int glnvg__VertsInScissor(const NVGvertex* verts, int nr, NVGscissor* scissor) { int32_t i = 0; float cx = scissor->xform[4]; float cy = scissor->xform[5]; float hw = scissor->extent[0]; float hh = scissor->extent[1]; float l = cx - hw; float t = cy - hh; float r = l + 2 * hw; float b = t + 2 * hh; for (i = 0; i < nr; i++) { const NVGvertex* iter = verts + i; int x = iter->x; int y = iter->y; if (x < l || x > r || y < t || y > b) { return 0; } } return 1; } static int glnvg__pathInScissor(const NVGpath* path, NVGscissor* scissor) { return glnvg__VertsInScissor(path->fill, path->nfill, scissor); } static void glnvg__renderFill(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, float fringe, const float* bounds, const NVGpath* paths, int npaths) { int support_fast_draw = 0; int is_gradient = memcmp(&(paint->innerColor), &(paint->outerColor), sizeof(paint->outerColor)); GLNVGcontext* gl = (GLNVGcontext*)uptr; GLNVGcall* call = glnvg__allocCall(gl); NVGvertex* quad; GLNVGfragUniforms* frag = NULL; int i, maxverts, offset; if (call == NULL) return; call->type = GLNVG_FILL; call->triangleCount = 4; call->pathOffset = glnvg__allocPaths(gl, npaths); if (call->pathOffset == -1) goto error; call->pathCount = npaths; call->image = paint->image; call->blendFunc = glnvg__blendCompositeOperation(compositeOperation); if (npaths == 1 && paths[0].convex) { call->type = GLNVG_CONVEXFILL; call->triangleCount = 0; // Bounding box fill quad not needed for convex fill } // Allocate vertices for all the paths. maxverts = glnvg__maxVertCount(paths, npaths) + call->triangleCount; offset = glnvg__allocVerts(gl, maxverts); if (offset == -1) goto error; for (i = 0; i < npaths; i++) { GLNVGpath* copy = &gl->paths[call->pathOffset + i]; const NVGpath* path = &paths[i]; memset(copy, 0, sizeof(GLNVGpath)); if (path->nfill > 0) { copy->fillOffset = offset; copy->fillCount = path->nfill; memcpy(&gl->verts[offset], path->fill, sizeof(NVGvertex) * path->nfill); offset += path->nfill; if (npaths == 1) { support_fast_draw = glnvg__pathIsRect(path) && glnvg__pathInScissor(path, scissor) && glnvg_getSupportFastDraw(gl, scissor); } } if (path->nstroke > 0) { copy->strokeOffset = offset; copy->strokeCount = path->nstroke; memcpy(&gl->verts[offset], path->stroke, sizeof(NVGvertex) * path->nstroke); offset += path->nstroke; } } // Setup uniforms for draw calls if (call->type == GLNVG_FILL) { // Quad call->triangleOffset = offset; quad = &gl->verts[call->triangleOffset]; glnvg__vset(&quad[0], bounds[2], bounds[3], 0.5f, 1.0f); glnvg__vset(&quad[1], bounds[2], bounds[1], 0.5f, 1.0f); glnvg__vset(&quad[2], bounds[0], bounds[3], 0.5f, 1.0f); glnvg__vset(&quad[3], bounds[0], bounds[1], 0.5f, 1.0f); call->uniformOffset = glnvg__allocFragUniforms(gl, 2); if (call->uniformOffset == -1) goto error; // Simple shader for stencil frag = nvg__fragUniformPtr(gl, call->uniformOffset); memset(frag, 0, sizeof(*frag)); frag->strokeThr = -1.0f; frag->type = NSVG_SHADER_SIMPLE; // Fill shader glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset + gl->fragSize), paint, scissor, fringe, fringe, -1.0f); } else { call->uniformOffset = glnvg__allocFragUniforms(gl, 1); if (call->uniformOffset == -1) goto error; // Fill shader frag = nvg__fragUniformPtr(gl, call->uniformOffset); glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset), paint, scissor, fringe, fringe, -1.0f); } if (support_fast_draw) { if (paint->image != 0) { frag->type = NSVG_SHADER_FAST_FILLIMG; } else if (!is_gradient) { frag->type = NSVG_SHADER_FAST_FILLCOLOR; } } else { if (paint->image == 0 && !is_gradient) { frag->type = NSVG_SHADER_FILLCOLOR; } } return; error: // We get here if call alloc was ok, but something else is not. // Roll back the last call to prevent drawing it. if (gl->ncalls > 0) gl->ncalls--; } static void glnvg__renderStroke(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, float fringe, float strokeWidth, const NVGpath* paths, int npaths) { GLNVGcontext* gl = (GLNVGcontext*)uptr; GLNVGcall* call = glnvg__allocCall(gl); int i, maxverts, offset; if (call == NULL) return; call->type = GLNVG_STROKE; call->pathOffset = glnvg__allocPaths(gl, npaths); if (call->pathOffset == -1) goto error; call->pathCount = npaths; call->image = paint->image; call->blendFunc = glnvg__blendCompositeOperation(compositeOperation); // Allocate vertices for all the paths. maxverts = glnvg__maxVertCount(paths, npaths); offset = glnvg__allocVerts(gl, maxverts); if (offset == -1) goto error; for (i = 0; i < npaths; i++) { GLNVGpath* copy = &gl->paths[call->pathOffset + i]; const NVGpath* path = &paths[i]; memset(copy, 0, sizeof(GLNVGpath)); if (path->nstroke) { copy->strokeOffset = offset; copy->strokeCount = path->nstroke; memcpy(&gl->verts[offset], path->stroke, sizeof(NVGvertex) * path->nstroke); offset += path->nstroke; } } if (gl->flags & NVG_STENCIL_STROKES) { // Fill shader call->uniformOffset = glnvg__allocFragUniforms(gl, 2); if (call->uniformOffset == -1) goto error; glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset), paint, scissor, strokeWidth, fringe, -1.0f); glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset + gl->fragSize), paint, scissor, strokeWidth, fringe, 1.0f - 0.5f / 255.0f); } else { // Fill shader call->uniformOffset = glnvg__allocFragUniforms(gl, 1); if (call->uniformOffset == -1) goto error; glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset), paint, scissor, strokeWidth, fringe, -1.0f); } return; error: // We get here if call alloc was ok, but something else is not. // Roll back the last call to prevent drawing it. if (gl->ncalls > 0) gl->ncalls--; } static void glnvg__renderTriangles(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, const NVGvertex* verts, int nverts) { GLNVGcontext* gl = (GLNVGcontext*)uptr; GLNVGcall* call = glnvg__allocCall(gl); GLNVGfragUniforms* frag; float fringe = 1.0f / gl->devicePixelRatio; if (call == NULL) return; call->type = GLNVG_TRIANGLES; call->image = paint->image; call->blendFunc = glnvg__blendCompositeOperation(compositeOperation); // Allocate vertices for all the paths. call->triangleOffset = glnvg__allocVerts(gl, nverts); if (call->triangleOffset == -1) goto error; call->triangleCount = nverts; memcpy(&gl->verts[call->triangleOffset], verts, sizeof(NVGvertex) * nverts); // Fill shader call->uniformOffset = glnvg__allocFragUniforms(gl, 1); if (call->uniformOffset == -1) goto error; frag = nvg__fragUniformPtr(gl, call->uniformOffset); glnvg__convertPaint(gl, frag, paint, scissor, 1.0f, fringe, -1.0f); if(glnvg__VertsInScissor(verts, nverts, scissor) && glnvg_getSupportFastDraw(gl, scissor)) { frag->type = NSVG_SHADER_FAST_FILLGLYPH; } else { frag->type = NSVG_SHADER_IMG; } return; error: // We get here if call alloc was ok, but something else is not. // Roll back the last call to prevent drawing it. if (gl->ncalls > 0) gl->ncalls--; } static void glnvg__setStateXfrom(void* uptr, float* xform) { GLNVGcontext* gl = (GLNVGcontext*)uptr; if(xform != NULL) { memcpy(gl->g_xform, xform, sizeof(gl->g_xform)); } } static void glnvg__renderDelete(void* uptr) { GLNVGcontext* gl = (GLNVGcontext*)uptr; int i; if (gl == NULL) return; glnvg__deleteShader(&gl->shader); #if NANOVG_GL3 #if NANOVG_GL_USE_UNIFORMBUFFER if (gl->fragBuf != 0) glDeleteBuffers(1, &gl->fragBuf); #endif if (gl->vertArr != 0) glDeleteVertexArrays(1, &gl->vertArr); #endif if (gl->vertBuf != 0) glDeleteBuffers(1, &gl->vertBuf); for (i = 0; i < gl->ntextures; i++) { if (gl->textures[i].tex != 0 && (gl->textures[i].flags & NVG_IMAGE_NODELETE) == 0) glDeleteTextures(1, &gl->textures[i].tex); } free(gl->textures); free(gl->paths); free(gl->verts); free(gl->uniforms); free(gl->calls); free(gl); } #if defined NANOVG_GL2 NVGcontext* nvgCreateGL2(int flags) #elif defined NANOVG_GL3 NVGcontext* nvgCreateGL3(int flags) #elif defined NANOVG_GLES2 NVGcontext* nvgCreateGLES2(int flags) #elif defined NANOVG_GLES3 NVGcontext* nvgCreateGLES3(int flags) #endif { NVGparams params; NVGcontext* ctx = NULL; GLNVGcontext* gl = (GLNVGcontext*)malloc(sizeof(GLNVGcontext)); if (gl == NULL) goto error; memset(gl, 0, sizeof(GLNVGcontext)); memset(&params, 0, sizeof(params)); params.renderCreate = glnvg__renderCreate; params.renderCreateTexture = glnvg__renderCreateTexture; params.renderDeleteTexture = glnvg__renderDeleteTexture; params.renderUpdateTexture = glnvg__renderUpdateTexture; params.renderGetTextureSize = glnvg__renderGetTextureSize; params.renderViewport = glnvg__renderViewport; params.renderCancel = glnvg__renderCancel; params.renderFlush = glnvg__renderFlush; params.renderFill = glnvg__renderFill; params.renderStroke = glnvg__renderStroke; params.renderTriangles = glnvg__renderTriangles; params.renderDelete = glnvg__renderDelete; params.setStateXfrom = glnvg__setStateXfrom; params.userPtr = gl; params.edgeAntiAlias = flags & NVG_ANTIALIAS ? 1 : 0; gl->flags = flags; ctx = nvgCreateInternal(&params); if (ctx == NULL) goto error; return ctx; error: // 'gl' is freed by nvgDeleteInternal. if (ctx != NULL) nvgDeleteInternal(ctx); return NULL; } #if defined NANOVG_GL2 void nvgDeleteGL2(NVGcontext* ctx) #elif defined NANOVG_GL3 void nvgDeleteGL3(NVGcontext* ctx) #elif defined NANOVG_GLES2 void nvgDeleteGLES2(NVGcontext* ctx) #elif defined NANOVG_GLES3 void nvgDeleteGLES3(NVGcontext* ctx) #endif { nvgDeleteInternal(ctx); } #if defined NANOVG_GL2 int nvglCreateImageFromHandleGL2(NVGcontext* ctx, GLuint textureId, int w, int h, int imageFlags) #elif defined NANOVG_GL3 int nvglCreateImageFromHandleGL3(NVGcontext* ctx, GLuint textureId, int w, int h, int imageFlags) #elif defined NANOVG_GLES2 int nvglCreateImageFromHandleGLES2(NVGcontext* ctx, GLuint textureId, int w, int h, int imageFlags) #elif defined NANOVG_GLES3 int nvglCreateImageFromHandleGLES3(NVGcontext* ctx, GLuint textureId, int w, int h, int imageFlags) #endif { GLNVGcontext* gl = (GLNVGcontext*)nvgInternalParams(ctx)->userPtr; GLNVGtexture* tex = glnvg__allocTexture(gl); if (tex == NULL) return 0; tex->type = NVG_TEXTURE_RGBA; tex->tex = textureId; tex->flags = imageFlags; tex->width = w; tex->height = h; return tex->id; } #if defined NANOVG_GL2 GLuint nvglImageHandleGL2(NVGcontext* ctx, int image) #elif defined NANOVG_GL3 GLuint nvglImageHandleGL3(NVGcontext* ctx, int image) #elif defined NANOVG_GLES2 GLuint nvglImageHandleGLES2(NVGcontext* ctx, int image) #elif defined NANOVG_GLES3 GLuint nvglImageHandleGLES3(NVGcontext* ctx, int image) #endif { GLNVGcontext* gl = (GLNVGcontext*)nvgInternalParams(ctx)->userPtr; GLNVGtexture* tex = glnvg__findTexture(gl, image); return tex->tex; } #endif /* NANOVG_GL_IMPLEMENTATION */
0
D://workCode//uploadProject\awtk\3rd\nanovg
D://workCode//uploadProject\awtk\3rd\nanovg\gl\nanovg_gl_utils.h
// // Copyright (c) 2009-2013 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #ifndef NANOVG_GL_UTILS_H #define NANOVG_GL_UTILS_H struct NVGLUframebuffer { NVGcontext* ctx; GLuint fbo; GLuint rbo; GLuint texture; int image; }; typedef struct NVGLUframebuffer NVGLUframebuffer; // Helper function to create GL frame buffer to render to. void nvgluBindFramebuffer(NVGLUframebuffer* fb); NVGLUframebuffer* nvgluCreateFramebuffer(NVGcontext* ctx, int w, int h, int imageFlags); void nvgluDeleteFramebuffer(NVGLUframebuffer* fb); #endif // NANOVG_GL_UTILS_H #ifdef NANOVG_GL_IMPLEMENTATION #if defined(NANOVG_GL3) || defined(NANOVG_GLES2) || defined(NANOVG_GLES3) // FBO is core in OpenGL 3>. # define NANOVG_FBO_VALID 1 #elif defined(NANOVG_GL2) // On OS X including glext defines FBO on GL2 too. # ifdef __APPLE__ # include <OpenGL/glext.h> # define NANOVG_FBO_VALID 1 # endif #endif static GLint defaultFBO = -1; int nvgluGetCurrFramebuffer() { #ifdef NANOVG_FBO_VALID GLint defaultFBO; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); return defaultFBO; #else return -1; #endif } NVGLUframebuffer* nvgluCreateFramebuffer(NVGcontext* ctx, int w, int h, int imageFlags) { #ifdef NANOVG_FBO_VALID GLint defaultFBO; GLint defaultRBO; NVGLUframebuffer* fb = NULL; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); glGetIntegerv(GL_RENDERBUFFER_BINDING, &defaultRBO); fb = (NVGLUframebuffer*)malloc(sizeof(NVGLUframebuffer)); if (fb == NULL) goto error; memset(fb, 0, sizeof(NVGLUframebuffer)); fb->image = nvgCreateImageRGBA(ctx, w, h, imageFlags | NVG_IMAGE_FLIPY | NVG_IMAGE_PREMULTIPLIED, NULL); #if defined NANOVG_GL2 fb->texture = nvglImageHandleGL2(ctx, fb->image); #elif defined NANOVG_GL3 fb->texture = nvglImageHandleGL3(ctx, fb->image); #elif defined NANOVG_GLES2 fb->texture = nvglImageHandleGLES2(ctx, fb->image); #elif defined NANOVG_GLES3 fb->texture = nvglImageHandleGLES3(ctx, fb->image); #endif fb->ctx = ctx; // frame buffer object glGenFramebuffers(1, &fb->fbo); glBindFramebuffer(GL_FRAMEBUFFER, fb->fbo); // render buffer object glGenRenderbuffers(1, &fb->rbo); glBindRenderbuffer(GL_RENDERBUFFER, fb->rbo); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, w, h); // combine all glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb->texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb->rbo); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { #ifdef GL_DEPTH24_STENCIL8 // If GL_STENCIL_INDEX8 is not supported, try GL_DEPTH24_STENCIL8 as a fallback. // Some graphics cards require a depth buffer along with a stencil. glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w, h); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb->texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb->rbo); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) #endif // GL_DEPTH24_STENCIL8 goto error; } glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); glBindRenderbuffer(GL_RENDERBUFFER, defaultRBO); return fb; error: glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); glBindRenderbuffer(GL_RENDERBUFFER, defaultRBO); nvgluDeleteFramebuffer(fb); return NULL; #else NVG_NOTUSED(ctx); NVG_NOTUSED(w); NVG_NOTUSED(h); NVG_NOTUSED(imageFlags); return NULL; #endif } void nvgluBindFramebuffer(NVGLUframebuffer* fb) { #ifdef NANOVG_FBO_VALID if (defaultFBO == -1) glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); glBindFramebuffer(GL_FRAMEBUFFER, fb != NULL ? fb->fbo : defaultFBO); #else NVG_NOTUSED(fb); #endif } void nvgluReadCurrentFramebufferData(unsigned int x, unsigned int y, unsigned int w, unsigned int h, unsigned int width, unsigned int height, void* pixels) { if(x + w <= width && y + h <= height && pixels != NULL) { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); } } void nvgluDeleteFramebuffer(NVGLUframebuffer* fb) { #ifdef NANOVG_FBO_VALID if (fb == NULL) return; if (fb->fbo != 0) glDeleteFramebuffers(1, &fb->fbo); if (fb->rbo != 0) glDeleteRenderbuffers(1, &fb->rbo); if (fb->image >= 0) nvgDeleteImage(fb->ctx, fb->image); fb->ctx = NULL; fb->fbo = 0; fb->rbo = 0; fb->texture = 0; fb->image = -1; free(fb); #else NVG_NOTUSED(fb); #endif } #endif // NANOVG_GL_IMPLEMENTATION
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\base\fontstash.h
// // Copyright (c) 2009-2013 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #ifndef FONS_H #define FONS_H #define FONS_INVALID -1 enum FONSflags { FONS_ZERO_TOPLEFT = 1, FONS_ZERO_BOTTOMLEFT = 2, }; enum FONSalign { // Horizontal align FONS_ALIGN_LEFT = 1<<0, // Default FONS_ALIGN_CENTER = 1<<1, FONS_ALIGN_RIGHT = 1<<2, // Vertical align FONS_ALIGN_TOP = 1<<3, FONS_ALIGN_MIDDLE = 1<<4, FONS_ALIGN_BOTTOM = 1<<5, FONS_ALIGN_BASELINE = 1<<6, // Default }; enum FONSglyphBitmap { FONS_GLYPH_BITMAP_OPTIONAL = 1, FONS_GLYPH_BITMAP_REQUIRED = 2, }; enum FONSerrorCode { // Font atlas is full. FONS_ATLAS_FULL = 1, // Scratch memory used to render glyphs is full, requested size reported in 'val', you may need to bump up FONS_SCRATCH_BUF_SIZE. FONS_SCRATCH_FULL = 2, // Calls to fonsPushState has created too large stack, if you need deep state stack bump up FONS_MAX_STATES. FONS_STATES_OVERFLOW = 3, // Trying to pop too many states fonsPopState(). FONS_STATES_UNDERFLOW = 4, }; struct FONSparams { int width, height; unsigned char flags; void* userPtr; int (*renderCreate)(void* uptr, int width, int height); int (*renderResize)(void* uptr, int width, int height); void (*renderUpdate)(void* uptr, int* rect, const unsigned char* data); void (*renderDraw)(void* uptr, const float* verts, const float* tcoords, const unsigned int* colors, int nverts); void (*renderDelete)(void* uptr); }; typedef struct FONSparams FONSparams; struct FONSquad { float x0,y0,s0,t0; float x1,y1,s1,t1; }; typedef struct FONSquad FONSquad; struct FONStextIter { float x, y, nextx, nexty, scale, spacing; unsigned int codepoint; short isize, iblur; struct FONSfont* font; int prevGlyphIndex; const char* str; const char* next; const char* end; unsigned int utf8state; int bitmapOption; }; typedef struct FONStextIter FONStextIter; typedef struct FONScontext FONScontext; // Constructor and destructor. FONScontext* fonsCreateInternal(FONSparams* params); void fonsDeleteInternal(FONScontext* s); void fontsDeleteFontByName(FONScontext* stash, const char* name); void fonsSetErrorCallback(FONScontext* s, void (*callback)(void* uptr, int error, int val), void* uptr); // Returns current atlas size. void fonsGetAtlasSize(FONScontext* s, int* width, int* height); // Expands the atlas size. int fonsExpandAtlas(FONScontext* s, int width, int height); // Resets the whole stash. int fonsResetAtlas(FONScontext* stash, int width, int height); // Add fonts int fonsAddFont(FONScontext* s, const char* name, const char* path); int fonsAddFontMem(FONScontext* s, const char* name, unsigned char* data, int ndata, int freeData); int fonsGetFontByName(FONScontext* s, const char* name); // State handling void fonsPushState(FONScontext* s); void fonsPopState(FONScontext* s); void fonsClearState(FONScontext* s); // State setting void fonsSetSize(FONScontext* s, float size); void fonsSetColor(FONScontext* s, unsigned int color); void fonsSetSpacing(FONScontext* s, float spacing); void fonsSetBlur(FONScontext* s, float blur); void fonsSetAlign(FONScontext* s, int align); void fonsSetFont(FONScontext* s, int font); // Draw text float fonsDrawText(FONScontext* s, float x, float y, const char* string, const char* end); // Measure text float fonsTextBounds(FONScontext* s, float x, float y, const char* string, const char* end, float* bounds); void fonsLineBounds(FONScontext* s, float y, float* miny, float* maxy); void fonsVertMetrics(FONScontext* s, float* ascender, float* descender, float* lineh); // Text iterator int fonsTextIterInit(FONScontext* stash, FONStextIter* iter, float x, float y, const char* str, const char* end, int bitmapOption); int fonsTextIterNext(FONScontext* stash, FONStextIter* iter, struct FONSquad* quad); // Pull texture changes const unsigned char* fonsGetTextureData(FONScontext* stash, int* width, int* height); int fonsValidateTexture(FONScontext* s, int* dirty); // Draws the stash texture for debugging void fonsDrawDebug(FONScontext* s, float x, float y); #endif // FONTSTASH_H #ifdef FONTSTASH_IMPLEMENTATION #define FONS_NOTUSED(v) (void)sizeof(v) #ifdef FONS_USE_FREETYPE #include <ft2build.h> #include FT_FREETYPE_H #include FT_ADVANCES_H #include <math.h> struct FONSttFontImpl { FT_Face font; }; typedef struct FONSttFontImpl FONSttFontImpl; static FT_Library ftLibrary; int fons__tt_init(FONScontext *context) { FT_Error ftError; FONS_NOTUSED(context); ftError = FT_Init_FreeType(&ftLibrary); return ftError == 0; } int fons__tt_done(FONScontext *context) { FT_Error ftError; FONS_NOTUSED(context); ftError = FT_Done_FreeType(ftLibrary); return ftError == 0; } int fons__tt_loadFont(FONScontext *context, FONSttFontImpl *font, unsigned char *data, int dataSize) { FT_Error ftError; FONS_NOTUSED(context); //font->font.userdata = stash; ftError = FT_New_Memory_Face(ftLibrary, (const FT_Byte*)data, dataSize, 0, &font->font); return ftError == 0; } void fons__tt_getFontVMetrics(FONSttFontImpl *font, int *ascent, int *descent, int *lineGap) { *ascent = font->font->ascender; *descent = font->font->descender; *lineGap = font->font->height - (*ascent - *descent); } float fons__tt_getPixelHeightScale(FONSttFontImpl *font, float size) { return size / (font->font->ascender - font->font->descender); } int fons__tt_getGlyphIndex(FONSttFontImpl *font, int codepoint) { return FT_Get_Char_Index(font->font, codepoint); } int fons__tt_buildGlyphBitmap(FONSttFontImpl *font, int glyph, float size, float scale, int *advance, int *lsb, int *x0, int *y0, int *x1, int *y1) { FT_Error ftError; FT_GlyphSlot ftGlyph; FT_Fixed advFixed; FONS_NOTUSED(scale); ftError = FT_Set_Pixel_Sizes(font->font, 0, (FT_UInt)(size * (float)font->font->units_per_EM / (float)(font->font->ascender - font->font->descender))); if (ftError) return 0; ftError = FT_Load_Glyph(font->font, glyph, FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT); if (ftError) return 0; ftError = FT_Get_Advance(font->font, glyph, FT_LOAD_NO_SCALE, &advFixed); if (ftError) return 0; ftGlyph = font->font->glyph; *advance = (int)advFixed; *lsb = (int)ftGlyph->metrics.horiBearingX; *x0 = ftGlyph->bitmap_left; *x1 = *x0 + ftGlyph->bitmap.width; *y0 = -ftGlyph->bitmap_top; *y1 = *y0 + ftGlyph->bitmap.rows; return 1; } void fons__tt_renderGlyphBitmap(FONSttFontImpl *font, unsigned char *output, int outWidth, int outHeight, int outStride, float scaleX, float scaleY, int glyph) { FT_GlyphSlot ftGlyph = font->font->glyph; int ftGlyphOffset = 0; int x, y; FONS_NOTUSED(outWidth); FONS_NOTUSED(outHeight); FONS_NOTUSED(scaleX); FONS_NOTUSED(scaleY); FONS_NOTUSED(glyph); // glyph has already been loaded by fons__tt_buildGlyphBitmap for ( y = 0; y < ftGlyph->bitmap.rows; y++ ) { for ( x = 0; x < ftGlyph->bitmap.width; x++ ) { output[(y * outStride) + x] = ftGlyph->bitmap.buffer[ftGlyphOffset++]; } } } int fons__tt_getGlyphKernAdvance(FONSttFontImpl *font, int glyph1, int glyph2) { FT_Vector ftKerning; FT_Get_Kerning(font->font, glyph1, glyph2, FT_KERNING_DEFAULT, &ftKerning); return (int)((ftKerning.x + 32) >> 6); // Round up and convert to integer } #else #define STB_TRUETYPE_IMPLEMENTATION // static void* fons__tmpalloc(size_t size, void* up); // static void fons__tmpfree(void* ptr, void* up); // #define STBTT_malloc(x,u) fons__tmpalloc(x,u) // #define STBTT_free(x,u) fons__tmpfree(x,u) #include "stb/stb_truetype.h" struct FONSttFontImpl { stbtt_fontinfo font; }; typedef struct FONSttFontImpl FONSttFontImpl; int fons__tt_init(FONScontext *context) { FONS_NOTUSED(context); return 1; } int fons__tt_done(FONScontext *context) { FONS_NOTUSED(context); return 1; } int fons__tt_loadFont(FONScontext *context, FONSttFontImpl *font, unsigned char *data, int dataSize) { int stbError; FONS_NOTUSED(dataSize); font->font.userdata = context; stbError = stbtt_InitFont(&font->font, data, 0); return stbError; } void fons__tt_getFontVMetrics(FONSttFontImpl *font, int *ascent, int *descent, int *lineGap) { stbtt_GetFontVMetrics(&font->font, ascent, descent, lineGap); } float fons__tt_getPixelHeightScale(FONSttFontImpl *font, float size) { return stbtt_ScaleForPixelHeight(&font->font, size); } int fons__tt_getGlyphIndex(FONSttFontImpl *font, int codepoint) { return stbtt_FindGlyphIndex(&font->font, codepoint); } int fons__tt_buildGlyphBitmap(FONSttFontImpl *font, int glyph, float size, float scale, int *advance, int *lsb, int *x0, int *y0, int *x1, int *y1) { FONS_NOTUSED(size); stbtt_GetGlyphHMetrics(&font->font, glyph, advance, lsb); stbtt_GetGlyphBitmapBox(&font->font, glyph, scale, scale, x0, y0, x1, y1); return 1; } void fons__tt_renderGlyphBitmap(FONSttFontImpl *font, unsigned char *output, int outWidth, int outHeight, int outStride, float scaleX, float scaleY, int glyph) { stbtt_MakeGlyphBitmap(&font->font, output, outWidth, outHeight, outStride, scaleX, scaleY, glyph); } int fons__tt_getGlyphKernAdvance(FONSttFontImpl *font, int glyph1, int glyph2) { return stbtt_GetGlyphKernAdvance(&font->font, glyph1, glyph2); } #endif #ifndef FONS_SCRATCH_BUF_SIZE # define FONS_SCRATCH_BUF_SIZE 1 #endif #ifndef FONS_HASH_LUT_SIZE # define FONS_HASH_LUT_SIZE 256 #endif #ifndef FONS_INIT_FONTS # define FONS_INIT_FONTS 4 #endif #ifndef FONS_INIT_GLYPHS # define FONS_INIT_GLYPHS 256 #endif #ifndef FONS_INIT_ATLAS_NODES # define FONS_INIT_ATLAS_NODES 256 #endif #ifndef FONS_VERTEX_COUNT # define FONS_VERTEX_COUNT 1024 #endif #ifndef FONS_MAX_STATES # define FONS_MAX_STATES 20 #endif #ifndef FONS_MAX_FALLBACKS # define FONS_MAX_FALLBACKS 20 #endif static unsigned int fons__hashint(unsigned int a) { a += ~(a<<15); a ^= (a>>10); a += (a<<3); a ^= (a>>6); a += ~(a<<11); a ^= (a>>16); return a; } static int fons__mini(int a, int b) { return a < b ? a : b; } static int fons__maxi(int a, int b) { return a > b ? a : b; } struct FONSglyph { unsigned int codepoint; int index; int next; short size, blur; short x0,y0,x1,y1; short xadv,xoff,yoff; }; typedef struct FONSglyph FONSglyph; struct FONSfont { FONSttFontImpl font; char name[64]; unsigned char* data; int dataSize; unsigned char freeData; float ascender; float descender; float lineh; FONSglyph* glyphs; int cglyphs; int nglyphs; int lut[FONS_HASH_LUT_SIZE]; int fallbacks[FONS_MAX_FALLBACKS]; int nfallbacks; }; typedef struct FONSfont FONSfont; struct FONSstate { int font; int align; float size; unsigned int color; float blur; float spacing; }; typedef struct FONSstate FONSstate; struct FONSatlasNode { short x, y, width; }; typedef struct FONSatlasNode FONSatlasNode; struct FONSatlas { int width, height; FONSatlasNode* nodes; int nnodes; int cnodes; }; typedef struct FONSatlas FONSatlas; struct FONScontext { FONSparams params; float itw,ith; unsigned char* texData; int dirtyRect[4]; FONSfont** fonts; FONSatlas* atlas; int cfonts; int nfonts; float verts[FONS_VERTEX_COUNT*2]; float tcoords[FONS_VERTEX_COUNT*2]; unsigned int colors[FONS_VERTEX_COUNT]; int nverts; unsigned char* scratch; int nscratch; FONSstate states[FONS_MAX_STATES]; int nstates; void (*handleError)(void* uptr, int error, int val); void* errorUptr; }; #ifdef STB_TRUETYPE_IMPLEMENTATION static void* fons__tmpalloc(size_t size, void* up) { unsigned char* ptr; FONScontext* stash = (FONScontext*)up; // 16-byte align the returned pointer size = (size + 0xf) & ~0xf; if (stash->nscratch+(int)size > FONS_SCRATCH_BUF_SIZE) { if (stash->handleError) stash->handleError(stash->errorUptr, FONS_SCRATCH_FULL, stash->nscratch+(int)size); return NULL; } ptr = stash->scratch + stash->nscratch; stash->nscratch += (int)size; return ptr; } static void fons__tmpfree(void* ptr, void* up) { (void)ptr; (void)up; // empty } #endif // STB_TRUETYPE_IMPLEMENTATION // Copyright (c) 2008-2010 Bjoern Hoehrmann <bjoern@hoehrmann.de> // See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. #define FONS_UTF8_ACCEPT 0 #define FONS_UTF8_REJECT 12 static unsigned int fons__decutf8(unsigned int* state, unsigned int* codep, unsigned int byte) { static const unsigned char utf8d[] = { // The first part of the table maps bytes to character classes that // to reduce the size of the transition table and create bitmasks. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, // The second part is a transition table that maps a combination // of a state of the automaton and a character class to a state. 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12, 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,12,12,12,12,12, }; unsigned int type = utf8d[byte]; *codep = (*state != FONS_UTF8_ACCEPT) ? (byte & 0x3fu) | (*codep << 6) : (0xff >> type) & (byte); *state = utf8d[256 + *state + type]; return *state; } // Atlas based on Skyline Bin Packer by Jukka Jylänki static void fons__deleteAtlas(FONSatlas* atlas) { if (atlas == NULL) return; if (atlas->nodes != NULL) free(atlas->nodes); free(atlas); } static FONSatlas* fons__allocAtlas(int w, int h, int nnodes) { FONSatlas* atlas = NULL; // Allocate memory for the font stash. atlas = (FONSatlas*)malloc(sizeof(FONSatlas)); if (atlas == NULL) goto error; memset(atlas, 0, sizeof(FONSatlas)); atlas->width = w; atlas->height = h; // Allocate space for skyline nodes atlas->nodes = (FONSatlasNode*)malloc(sizeof(FONSatlasNode) * nnodes); if (atlas->nodes == NULL) goto error; memset(atlas->nodes, 0, sizeof(FONSatlasNode) * nnodes); atlas->nnodes = 0; atlas->cnodes = nnodes; // Init root node. atlas->nodes[0].x = 0; atlas->nodes[0].y = 0; atlas->nodes[0].width = (short)w; atlas->nnodes++; return atlas; error: if (atlas) fons__deleteAtlas(atlas); return NULL; } static int fons__atlasInsertNode(FONSatlas* atlas, int idx, int x, int y, int w) { int i; // Insert node if (atlas->nnodes+1 > atlas->cnodes) { atlas->cnodes = atlas->cnodes == 0 ? 8 : atlas->cnodes * 2; atlas->nodes = (FONSatlasNode*)realloc(atlas->nodes, sizeof(FONSatlasNode) * atlas->cnodes); if (atlas->nodes == NULL) return 0; } for (i = atlas->nnodes; i > idx; i--) atlas->nodes[i] = atlas->nodes[i-1]; atlas->nodes[idx].x = (short)x; atlas->nodes[idx].y = (short)y; atlas->nodes[idx].width = (short)w; atlas->nnodes++; return 1; } static void fons__atlasRemoveNode(FONSatlas* atlas, int idx) { int i; if (atlas->nnodes == 0) return; for (i = idx; i < atlas->nnodes-1; i++) atlas->nodes[i] = atlas->nodes[i+1]; atlas->nnodes--; } static void fons__atlasExpand(FONSatlas* atlas, int w, int h) { // Insert node for empty space if (w > atlas->width) fons__atlasInsertNode(atlas, atlas->nnodes, atlas->width, 0, w - atlas->width); atlas->width = w; atlas->height = h; } static void fons__atlasReset(FONSatlas* atlas, int w, int h) { atlas->width = w; atlas->height = h; atlas->nnodes = 0; // Init root node. atlas->nodes[0].x = 0; atlas->nodes[0].y = 0; atlas->nodes[0].width = (short)w; atlas->nnodes++; } static int fons__atlasAddSkylineLevel(FONSatlas* atlas, int idx, int x, int y, int w, int h) { int i; // Insert new node if (fons__atlasInsertNode(atlas, idx, x, y+h, w) == 0) return 0; // Delete skyline segments that fall under the shadow of the new segment. for (i = idx+1; i < atlas->nnodes; i++) { if (atlas->nodes[i].x < atlas->nodes[i-1].x + atlas->nodes[i-1].width) { int shrink = atlas->nodes[i-1].x + atlas->nodes[i-1].width - atlas->nodes[i].x; atlas->nodes[i].x += (short)shrink; atlas->nodes[i].width -= (short)shrink; if (atlas->nodes[i].width <= 0) { fons__atlasRemoveNode(atlas, i); i--; } else { break; } } else { break; } } // Merge same height skyline segments that are next to each other. for (i = 0; i < atlas->nnodes-1; i++) { if (atlas->nodes[i].y == atlas->nodes[i+1].y) { atlas->nodes[i].width += atlas->nodes[i+1].width; fons__atlasRemoveNode(atlas, i+1); i--; } } return 1; } static int fons__atlasRectFits(FONSatlas* atlas, int i, int w, int h) { // Checks if there is enough space at the location of skyline span 'i', // and return the max height of all skyline spans under that at that location, // (think tetris block being dropped at that position). Or -1 if no space found. int x = atlas->nodes[i].x; int y = atlas->nodes[i].y; int spaceLeft; if (x + w > atlas->width) return -1; spaceLeft = w; while (spaceLeft > 0) { if (i == atlas->nnodes) return -1; y = fons__maxi(y, atlas->nodes[i].y); if (y + h > atlas->height) return -1; spaceLeft -= atlas->nodes[i].width; ++i; } return y; } static int fons__atlasAddRect(FONSatlas* atlas, int rw, int rh, int* rx, int* ry) { int besth = atlas->height, bestw = atlas->width, besti = -1; int bestx = -1, besty = -1, i; // Bottom left fit heuristic. for (i = 0; i < atlas->nnodes; i++) { int y = fons__atlasRectFits(atlas, i, rw, rh); if (y != -1) { if (y + rh < besth || (y + rh == besth && atlas->nodes[i].width < bestw)) { besti = i; bestw = atlas->nodes[i].width; besth = y + rh; bestx = atlas->nodes[i].x; besty = y; } } } if (besti == -1) return 0; // Perform the actual packing. if (fons__atlasAddSkylineLevel(atlas, besti, bestx, besty, rw, rh) == 0) return 0; *rx = bestx; *ry = besty; return 1; } static void fons__addWhiteRect(FONScontext* stash, int w, int h) { int x, y, gx, gy; unsigned char* dst; if (fons__atlasAddRect(stash->atlas, w, h, &gx, &gy) == 0) return; // Rasterize dst = &stash->texData[gx + gy * stash->params.width]; for (y = 0; y < h; y++) { for (x = 0; x < w; x++) dst[x] = 0xff; dst += stash->params.width; } stash->dirtyRect[0] = fons__mini(stash->dirtyRect[0], gx); stash->dirtyRect[1] = fons__mini(stash->dirtyRect[1], gy); stash->dirtyRect[2] = fons__maxi(stash->dirtyRect[2], gx+w); stash->dirtyRect[3] = fons__maxi(stash->dirtyRect[3], gy+h); } FONScontext* fonsCreateInternal(FONSparams* params) { FONScontext* stash = NULL; // Allocate memory for the font stash. stash = (FONScontext*)malloc(sizeof(FONScontext)); if (stash == NULL) goto error; memset(stash, 0, sizeof(FONScontext)); stash->params = *params; // Allocate scratch buffer. stash->scratch = (unsigned char*)malloc(FONS_SCRATCH_BUF_SIZE); if (stash->scratch == NULL) goto error; // Initialize implementation library if (!fons__tt_init(stash)) goto error; if (stash->params.renderCreate != NULL) { if (stash->params.renderCreate(stash->params.userPtr, stash->params.width, stash->params.height) == 0) goto error; } stash->atlas = fons__allocAtlas(stash->params.width, stash->params.height, FONS_INIT_ATLAS_NODES); if (stash->atlas == NULL) goto error; // Allocate space for fonts. stash->fonts = (FONSfont**)malloc(sizeof(FONSfont*) * FONS_INIT_FONTS); if (stash->fonts == NULL) goto error; memset(stash->fonts, 0, sizeof(FONSfont*) * FONS_INIT_FONTS); stash->cfonts = FONS_INIT_FONTS; stash->nfonts = 0; // Create texture for the cache. stash->itw = 1.0f/stash->params.width; stash->ith = 1.0f/stash->params.height; stash->texData = (unsigned char*)malloc(stash->params.width * stash->params.height); if (stash->texData == NULL) goto error; memset(stash->texData, 0, stash->params.width * stash->params.height); stash->dirtyRect[0] = stash->params.width; stash->dirtyRect[1] = stash->params.height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; // Add white rect at 0,0 for debug drawing. fons__addWhiteRect(stash, 2,2); fonsPushState(stash); fonsClearState(stash); return stash; error: fonsDeleteInternal(stash); return NULL; } static FONSstate* fons__getState(FONScontext* stash) { return &stash->states[stash->nstates-1]; } int fonsAddFallbackFont(FONScontext* stash, int base, int fallback) { FONSfont* baseFont = stash->fonts[base]; if (baseFont->nfallbacks < FONS_MAX_FALLBACKS) { baseFont->fallbacks[baseFont->nfallbacks++] = fallback; return 1; } return 0; } void fonsSetSize(FONScontext* stash, float size) { fons__getState(stash)->size = size; } void fonsSetColor(FONScontext* stash, unsigned int color) { fons__getState(stash)->color = color; } void fonsSetSpacing(FONScontext* stash, float spacing) { fons__getState(stash)->spacing = spacing; } void fonsSetBlur(FONScontext* stash, float blur) { fons__getState(stash)->blur = blur; } void fonsSetAlign(FONScontext* stash, int align) { fons__getState(stash)->align = align; } void fonsSetFont(FONScontext* stash, int font) { fons__getState(stash)->font = font; } void fonsPushState(FONScontext* stash) { if (stash->nstates >= FONS_MAX_STATES) { if (stash->handleError) stash->handleError(stash->errorUptr, FONS_STATES_OVERFLOW, 0); return; } if (stash->nstates > 0) memcpy(&stash->states[stash->nstates], &stash->states[stash->nstates-1], sizeof(FONSstate)); stash->nstates++; } void fonsPopState(FONScontext* stash) { if (stash->nstates <= 1) { if (stash->handleError) stash->handleError(stash->errorUptr, FONS_STATES_UNDERFLOW, 0); return; } stash->nstates--; } void fonsClearState(FONScontext* stash) { FONSstate* state = fons__getState(stash); state->size = 12.0f; state->color = 0xffffffff; state->font = 0; state->blur = 0; state->spacing = 0; state->align = FONS_ALIGN_LEFT | FONS_ALIGN_BASELINE; } static void fons__freeFont(FONSfont* font) { if (font == NULL) return; if (font->glyphs) free(font->glyphs); if (font->freeData && font->data) free(font->data); free(font); } static int fons__allocFont(FONScontext* stash) { FONSfont* font = NULL; if (stash->nfonts+1 > stash->cfonts) { stash->cfonts = stash->cfonts == 0 ? 8 : stash->cfonts * 2; stash->fonts = (FONSfont**)realloc(stash->fonts, sizeof(FONSfont*) * stash->cfonts); if (stash->fonts == NULL) return -1; } font = (FONSfont*)malloc(sizeof(FONSfont)); if (font == NULL) goto error; memset(font, 0, sizeof(FONSfont)); font->glyphs = (FONSglyph*)malloc(sizeof(FONSglyph) * FONS_INIT_GLYPHS); if (font->glyphs == NULL) goto error; font->cglyphs = FONS_INIT_GLYPHS; font->nglyphs = 0; stash->fonts[stash->nfonts++] = font; return stash->nfonts-1; error: fons__freeFont(font); return FONS_INVALID; } int fonsAddFont(FONScontext* stash, const char* name, const char* path) { FILE* fp = 0; int dataSize = 0; size_t readed; unsigned char* data = NULL; // Read in the font data. fp = fopen(path, "rb"); if (fp == NULL) goto error; fseek(fp,0,SEEK_END); dataSize = (int)ftell(fp); fseek(fp,0,SEEK_SET); data = (unsigned char*)malloc(dataSize); if (data == NULL) goto error; readed = fread(data, 1, dataSize, fp); fclose(fp); fp = 0; if (readed != dataSize) goto error; return fonsAddFontMem(stash, name, data, dataSize, 1); error: if (data) free(data); if (fp) fclose(fp); return FONS_INVALID; } int fonsAddFontMem(FONScontext* stash, const char* name, unsigned char* data, int dataSize, int freeData) { int i, ascent, descent, fh, lineGap; FONSfont* font; int idx = fons__allocFont(stash); if (idx == FONS_INVALID) return FONS_INVALID; font = stash->fonts[idx]; strncpy(font->name, name, sizeof(font->name)); font->name[sizeof(font->name)-1] = '\0'; // Init hash lookup. for (i = 0; i < FONS_HASH_LUT_SIZE; ++i) font->lut[i] = -1; // Read in the font data. font->dataSize = dataSize; font->data = data; font->freeData = (unsigned char)freeData; // Init font stash->nscratch = 0; if (!fons__tt_loadFont(stash, &font->font, data, dataSize)) goto error; // Store normalized line height. The real line height is got // by multiplying the lineh by font size. fons__tt_getFontVMetrics( &font->font, &ascent, &descent, &lineGap); fh = ascent - descent; font->ascender = (float)ascent / (float)fh; font->descender = (float)descent / (float)fh; font->lineh = (float)(fh + lineGap) / (float)fh; return idx; error: fons__freeFont(font); stash->nfonts--; return FONS_INVALID; } int fonsGetFontByName(FONScontext* s, const char* name) { int i; for (i = 0; i < s->nfonts; i++) { if (strcmp(s->fonts[i]->name, name) == 0) return i; } return FONS_INVALID; } static FONSglyph* fons__allocGlyph(FONSfont* font) { if (font->nglyphs+1 > font->cglyphs) { font->cglyphs = font->cglyphs == 0 ? 8 : font->cglyphs * 2; font->glyphs = (FONSglyph*)realloc(font->glyphs, sizeof(FONSglyph) * font->cglyphs); if (font->glyphs == NULL) return NULL; } font->nglyphs++; return &font->glyphs[font->nglyphs-1]; } // Based on Exponential blur, Jani Huhtanen, 2006 #define APREC 16 #define ZPREC 7 static void fons__blurCols(unsigned char* dst, int w, int h, int dstStride, int alpha) { int x, y; for (y = 0; y < h; y++) { int z = 0; // force zero border for (x = 1; x < w; x++) { z += (alpha * (((int)(dst[x]) << ZPREC) - z)) >> APREC; dst[x] = (unsigned char)(z >> ZPREC); } dst[w-1] = 0; // force zero border z = 0; for (x = w-2; x >= 0; x--) { z += (alpha * (((int)(dst[x]) << ZPREC) - z)) >> APREC; dst[x] = (unsigned char)(z >> ZPREC); } dst[0] = 0; // force zero border dst += dstStride; } } static void fons__blurRows(unsigned char* dst, int w, int h, int dstStride, int alpha) { int x, y; for (x = 0; x < w; x++) { int z = 0; // force zero border for (y = dstStride; y < h*dstStride; y += dstStride) { z += (alpha * (((int)(dst[y]) << ZPREC) - z)) >> APREC; dst[y] = (unsigned char)(z >> ZPREC); } dst[(h-1)*dstStride] = 0; // force zero border z = 0; for (y = (h-2)*dstStride; y >= 0; y -= dstStride) { z += (alpha * (((int)(dst[y]) << ZPREC) - z)) >> APREC; dst[y] = (unsigned char)(z >> ZPREC); } dst[0] = 0; // force zero border dst++; } } static void fons__blur(FONScontext* stash, unsigned char* dst, int w, int h, int dstStride, int blur) { int alpha; float sigma; (void)stash; if (blur < 1) return; // Calculate the alpha such that 90% of the kernel is within the radius. (Kernel extends to infinity) sigma = (float)blur * 0.57735f; // 1 / sqrt(3) alpha = (int)((1<<APREC) * (1.0f - expf(-2.3f / (sigma+1.0f)))); fons__blurRows(dst, w, h, dstStride, alpha); fons__blurCols(dst, w, h, dstStride, alpha); fons__blurRows(dst, w, h, dstStride, alpha); fons__blurCols(dst, w, h, dstStride, alpha); // fons__blurrows(dst, w, h, dstStride, alpha); // fons__blurcols(dst, w, h, dstStride, alpha); } static FONSglyph* fons__getGlyph(FONScontext* stash, FONSfont* font, unsigned int codepoint, short isize, short iblur, int bitmapOption) { int i, g, advance, lsb, x0, y0, x1, y1, gw, gh, gx, gy, x, y; float scale; FONSglyph* glyph = NULL; unsigned int h; float size = isize/10.0f; int pad, added; unsigned char* bdst; unsigned char* dst; FONSfont* renderFont = font; if (isize < 2) return NULL; if (iblur > 20) iblur = 20; pad = iblur+2; // Reset allocator. stash->nscratch = 0; // Find code point and size. h = fons__hashint(codepoint) & (FONS_HASH_LUT_SIZE-1); i = font->lut[h]; while (i != -1) { if (font->glyphs[i].codepoint == codepoint && font->glyphs[i].size == isize && font->glyphs[i].blur == iblur) { glyph = &font->glyphs[i]; if (bitmapOption == FONS_GLYPH_BITMAP_OPTIONAL || (glyph->x0 >= 0 && glyph->y0 >= 0)) { return glyph; } // At this point, glyph exists but the bitmap data is not yet created. break; } i = font->glyphs[i].next; } // Create a new glyph or rasterize bitmap data for a cached glyph. g = fons__tt_getGlyphIndex(&font->font, codepoint); // Try to find the glyph in fallback fonts. if (g == 0) { for (i = 0; i < font->nfallbacks; ++i) { FONSfont* fallbackFont = stash->fonts[font->fallbacks[i]]; int fallbackIndex = fons__tt_getGlyphIndex(&fallbackFont->font, codepoint); if (fallbackIndex != 0) { g = fallbackIndex; renderFont = fallbackFont; break; } } // It is possible that we did not find a fallback glyph. // In that case the glyph index 'g' is 0, and we'll proceed below and cache empty glyph. } scale = fons__tt_getPixelHeightScale(&renderFont->font, size); fons__tt_buildGlyphBitmap(&renderFont->font, g, size, scale, &advance, &lsb, &x0, &y0, &x1, &y1); gw = x1-x0 + pad*2; gh = y1-y0 + pad*2; // Determines the spot to draw glyph in the atlas. if (bitmapOption == FONS_GLYPH_BITMAP_REQUIRED) { // Find free spot for the rect in the atlas added = fons__atlasAddRect(stash->atlas, gw, gh, &gx, &gy); if (added == 0 && stash->handleError != NULL) { // Atlas is full, let the user to resize the atlas (or not), and try again. stash->handleError(stash->errorUptr, FONS_ATLAS_FULL, 0); added = fons__atlasAddRect(stash->atlas, gw, gh, &gx, &gy); } if (added == 0) return NULL; } else { // Negative coordinate indicates there is no bitmap data created. gx = -1; gy = -1; } // Init glyph. if (glyph == NULL) { glyph = fons__allocGlyph(font); glyph->codepoint = codepoint; glyph->size = isize; glyph->blur = iblur; glyph->next = 0; // Insert char to hash lookup. glyph->next = font->lut[h]; font->lut[h] = font->nglyphs-1; } glyph->index = g; glyph->x0 = (short)gx; glyph->y0 = (short)gy; glyph->x1 = (short)(glyph->x0+gw); glyph->y1 = (short)(glyph->y0+gh); glyph->xadv = (short)(scale * advance * 10.0f); glyph->xoff = (short)(x0 - pad); glyph->yoff = (short)(y0 - pad); if (bitmapOption == FONS_GLYPH_BITMAP_OPTIONAL) { return glyph; } // Rasterize dst = &stash->texData[(glyph->x0+pad) + (glyph->y0+pad) * stash->params.width]; fons__tt_renderGlyphBitmap(&renderFont->font, dst, gw-pad*2,gh-pad*2, stash->params.width, scale, scale, g); // Make sure there is one pixel empty border. dst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width]; for (y = 0; y < gh; y++) { dst[y*stash->params.width] = 0; dst[gw-1 + y*stash->params.width] = 0; } for (x = 0; x < gw; x++) { dst[x] = 0; dst[x + (gh-1)*stash->params.width] = 0; } // Debug code to color the glyph background /* unsigned char* fdst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width]; for (y = 0; y < gh; y++) { for (x = 0; x < gw; x++) { int a = (int)fdst[x+y*stash->params.width] + 20; if (a > 255) a = 255; fdst[x+y*stash->params.width] = a; } }*/ // Blur if (iblur > 0) { stash->nscratch = 0; bdst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width]; fons__blur(stash, bdst, gw, gh, stash->params.width, iblur); } stash->dirtyRect[0] = fons__mini(stash->dirtyRect[0], glyph->x0); stash->dirtyRect[1] = fons__mini(stash->dirtyRect[1], glyph->y0); stash->dirtyRect[2] = fons__maxi(stash->dirtyRect[2], glyph->x1); stash->dirtyRect[3] = fons__maxi(stash->dirtyRect[3], glyph->y1); return glyph; } static void fons__getQuad(FONScontext* stash, FONSfont* font, int prevGlyphIndex, FONSglyph* glyph, float scale, float spacing, float* x, float* y, FONSquad* q) { float rx,ry,xoff,yoff,x0,y0,x1,y1; if (prevGlyphIndex != -1) { float adv = fons__tt_getGlyphKernAdvance(&font->font, prevGlyphIndex, glyph->index) * scale; *x += (int)(adv + spacing + 0.5f); } // Each glyph has 2px border to allow good interpolation, // one pixel to prevent leaking, and one to allow good interpolation for rendering. // Inset the texture region by one pixel for correct interpolation. xoff = (short)(glyph->xoff+1); yoff = (short)(glyph->yoff+1); x0 = (float)(glyph->x0+1); y0 = (float)(glyph->y0+1); x1 = (float)(glyph->x1-1); y1 = (float)(glyph->y1-1); if (stash->params.flags & FONS_ZERO_TOPLEFT) { rx = (float)(int)(*x + xoff); ry = (float)(int)(*y + yoff); q->x0 = rx; q->y0 = ry; q->x1 = rx + x1 - x0; q->y1 = ry + y1 - y0; q->s0 = x0 * stash->itw; q->t0 = y0 * stash->ith; q->s1 = x1 * stash->itw; q->t1 = y1 * stash->ith; } else { rx = (float)(int)(*x + xoff); ry = (float)(int)(*y - yoff); q->x0 = rx; q->y0 = ry; q->x1 = rx + x1 - x0; q->y1 = ry - y1 + y0; q->s0 = x0 * stash->itw; q->t0 = y0 * stash->ith; q->s1 = x1 * stash->itw; q->t1 = y1 * stash->ith; } *x += (int)(glyph->xadv / 10.0f + 0.5f); } static void fons__flush(FONScontext* stash) { // Flush texture if (stash->dirtyRect[0] < stash->dirtyRect[2] && stash->dirtyRect[1] < stash->dirtyRect[3]) { if (stash->params.renderUpdate != NULL) stash->params.renderUpdate(stash->params.userPtr, stash->dirtyRect, stash->texData); // Reset dirty rect stash->dirtyRect[0] = stash->params.width; stash->dirtyRect[1] = stash->params.height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; } // Flush triangles if (stash->nverts > 0) { if (stash->params.renderDraw != NULL) stash->params.renderDraw(stash->params.userPtr, stash->verts, stash->tcoords, stash->colors, stash->nverts); stash->nverts = 0; } } static __inline void fons__vertex(FONScontext* stash, float x, float y, float s, float t, unsigned int c) { stash->verts[stash->nverts*2+0] = x; stash->verts[stash->nverts*2+1] = y; stash->tcoords[stash->nverts*2+0] = s; stash->tcoords[stash->nverts*2+1] = t; stash->colors[stash->nverts] = c; stash->nverts++; } static float fons__getVertAlign(FONScontext* stash, FONSfont* font, int align, short isize) { if (stash->params.flags & FONS_ZERO_TOPLEFT) { if (align & FONS_ALIGN_TOP) { return font->ascender * (float)isize/10.0f; } else if (align & FONS_ALIGN_MIDDLE) { return (font->ascender + font->descender) / 2.0f * (float)isize/10.0f; } else if (align & FONS_ALIGN_BASELINE) { return 0.0f; } else if (align & FONS_ALIGN_BOTTOM) { return font->descender * (float)isize/10.0f; } } else { if (align & FONS_ALIGN_TOP) { return -font->ascender * (float)isize/10.0f; } else if (align & FONS_ALIGN_MIDDLE) { return -(font->ascender + font->descender) / 2.0f * (float)isize/10.0f; } else if (align & FONS_ALIGN_BASELINE) { return 0.0f; } else if (align & FONS_ALIGN_BOTTOM) { return -font->descender * (float)isize/10.0f; } } return 0.0; } float fonsDrawText(FONScontext* stash, float x, float y, const char* str, const char* end) { FONSstate* state = fons__getState(stash); unsigned int codepoint; unsigned int utf8state = 0; FONSglyph* glyph = NULL; FONSquad q; int prevGlyphIndex = -1; short isize = (short)(state->size*10.0f); short iblur = (short)state->blur; float scale; FONSfont* font; float width; if (stash == NULL) return x; if (state->font < 0 || state->font >= stash->nfonts) return x; font = stash->fonts[state->font]; if (font->data == NULL) return x; scale = fons__tt_getPixelHeightScale(&font->font, (float)isize/10.0f); if (end == NULL) end = str + strlen(str); // Align horizontally if (state->align & FONS_ALIGN_LEFT) { // empty } else if (state->align & FONS_ALIGN_RIGHT) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width; } else if (state->align & FONS_ALIGN_CENTER) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width * 0.5f; } // Align vertically. y += fons__getVertAlign(stash, font, state->align, isize); for (; str != end; ++str) { if (fons__decutf8(&utf8state, &codepoint, *(const unsigned char*)str)) continue; glyph = fons__getGlyph(stash, font, codepoint, isize, iblur, FONS_GLYPH_BITMAP_REQUIRED); if (glyph != NULL) { fons__getQuad(stash, font, prevGlyphIndex, glyph, scale, state->spacing, &x, &y, &q); if (stash->nverts+6 > FONS_VERTEX_COUNT) fons__flush(stash); fons__vertex(stash, q.x0, q.y0, q.s0, q.t0, state->color); fons__vertex(stash, q.x1, q.y1, q.s1, q.t1, state->color); fons__vertex(stash, q.x1, q.y0, q.s1, q.t0, state->color); fons__vertex(stash, q.x0, q.y0, q.s0, q.t0, state->color); fons__vertex(stash, q.x0, q.y1, q.s0, q.t1, state->color); fons__vertex(stash, q.x1, q.y1, q.s1, q.t1, state->color); } prevGlyphIndex = glyph != NULL ? glyph->index : -1; } fons__flush(stash); return x; } int fonsTextIterInit(FONScontext* stash, FONStextIter* iter, float x, float y, const char* str, const char* end, int bitmapOption) { FONSstate* state = fons__getState(stash); float width; memset(iter, 0, sizeof(*iter)); if (stash == NULL) return 0; if (state->font < 0 || state->font >= stash->nfonts) return 0; iter->font = stash->fonts[state->font]; if (iter->font->data == NULL) return 0; iter->isize = (short)(state->size*10.0f); iter->iblur = (short)state->blur; iter->scale = fons__tt_getPixelHeightScale(&iter->font->font, (float)iter->isize/10.0f); // Align horizontally if (state->align & FONS_ALIGN_LEFT) { // empty } else if (state->align & FONS_ALIGN_RIGHT) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width; } else if (state->align & FONS_ALIGN_CENTER) { width = fonsTextBounds(stash, x,y, str, end, NULL); x -= width * 0.5f; } // Align vertically. y += fons__getVertAlign(stash, iter->font, state->align, iter->isize); if (end == NULL) end = str + strlen(str); iter->x = iter->nextx = x; iter->y = iter->nexty = y; iter->spacing = state->spacing; iter->str = str; iter->next = str; iter->end = end; iter->codepoint = 0; iter->prevGlyphIndex = -1; iter->bitmapOption = bitmapOption; return 1; } int fonsTextIterNext(FONScontext* stash, FONStextIter* iter, FONSquad* quad) { FONSglyph* glyph = NULL; const char* str = iter->next; iter->str = iter->next; if (str == iter->end) return 0; for (; str != iter->end; str++) { if (fons__decutf8(&iter->utf8state, &iter->codepoint, *(const unsigned char*)str)) continue; str++; // Get glyph and quad iter->x = iter->nextx; iter->y = iter->nexty; glyph = fons__getGlyph(stash, iter->font, iter->codepoint, iter->isize, iter->iblur, iter->bitmapOption); // If the iterator was initialized with FONS_GLYPH_BITMAP_OPTIONAL, then the UV coordinates of the quad will be invalid. if (glyph != NULL) fons__getQuad(stash, iter->font, iter->prevGlyphIndex, glyph, iter->scale, iter->spacing, &iter->nextx, &iter->nexty, quad); iter->prevGlyphIndex = glyph != NULL ? glyph->index : -1; break; } iter->next = str; return 1; } void fonsDrawDebug(FONScontext* stash, float x, float y) { int i; int w = stash->params.width; int h = stash->params.height; float u = w == 0 ? 0 : (1.0f / w); float v = h == 0 ? 0 : (1.0f / h); if (stash->nverts+6+6 > FONS_VERTEX_COUNT) fons__flush(stash); // Draw background fons__vertex(stash, x+0, y+0, u, v, 0x0fffffff); fons__vertex(stash, x+w, y+h, u, v, 0x0fffffff); fons__vertex(stash, x+w, y+0, u, v, 0x0fffffff); fons__vertex(stash, x+0, y+0, u, v, 0x0fffffff); fons__vertex(stash, x+0, y+h, u, v, 0x0fffffff); fons__vertex(stash, x+w, y+h, u, v, 0x0fffffff); // Draw texture fons__vertex(stash, x+0, y+0, 0, 0, 0xffffffff); fons__vertex(stash, x+w, y+h, 1, 1, 0xffffffff); fons__vertex(stash, x+w, y+0, 1, 0, 0xffffffff); fons__vertex(stash, x+0, y+0, 0, 0, 0xffffffff); fons__vertex(stash, x+0, y+h, 0, 1, 0xffffffff); fons__vertex(stash, x+w, y+h, 1, 1, 0xffffffff); // Drawbug draw atlas for (i = 0; i < stash->atlas->nnodes; i++) { FONSatlasNode* n = &stash->atlas->nodes[i]; if (stash->nverts+6 > FONS_VERTEX_COUNT) fons__flush(stash); fons__vertex(stash, x+n->x+0, y+n->y+0, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+n->width, y+n->y+1, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+n->width, y+n->y+0, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+0, y+n->y+0, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+0, y+n->y+1, u, v, 0xc00000ff); fons__vertex(stash, x+n->x+n->width, y+n->y+1, u, v, 0xc00000ff); } fons__flush(stash); } float fonsTextBounds(FONScontext* stash, float x, float y, const char* str, const char* end, float* bounds) { FONSstate* state = fons__getState(stash); unsigned int codepoint; unsigned int utf8state = 0; FONSquad q; FONSglyph* glyph = NULL; int prevGlyphIndex = -1; short isize = (short)(state->size*10.0f); short iblur = (short)state->blur; float scale; FONSfont* font; float startx, advance; float minx, miny, maxx, maxy; if (stash == NULL) return 0; if (state->font < 0 || state->font >= stash->nfonts) return 0; font = stash->fonts[state->font]; if (font->data == NULL) return 0; scale = fons__tt_getPixelHeightScale(&font->font, (float)isize/10.0f); // Align vertically. y += fons__getVertAlign(stash, font, state->align, isize); minx = maxx = x; miny = maxy = y; startx = x; if (end == NULL) end = str + strlen(str); for (; str != end; ++str) { if (fons__decutf8(&utf8state, &codepoint, *(const unsigned char*)str)) continue; glyph = fons__getGlyph(stash, font, codepoint, isize, iblur, FONS_GLYPH_BITMAP_OPTIONAL); if (glyph != NULL) { fons__getQuad(stash, font, prevGlyphIndex, glyph, scale, state->spacing, &x, &y, &q); if (q.x0 < minx) minx = q.x0; if (q.x1 > maxx) maxx = q.x1; if (stash->params.flags & FONS_ZERO_TOPLEFT) { if (q.y0 < miny) miny = q.y0; if (q.y1 > maxy) maxy = q.y1; } else { if (q.y1 < miny) miny = q.y1; if (q.y0 > maxy) maxy = q.y0; } } prevGlyphIndex = glyph != NULL ? glyph->index : -1; } advance = x - startx; // Align horizontally if (state->align & FONS_ALIGN_LEFT) { // empty } else if (state->align & FONS_ALIGN_RIGHT) { minx -= advance; maxx -= advance; } else if (state->align & FONS_ALIGN_CENTER) { minx -= advance * 0.5f; maxx -= advance * 0.5f; } if (bounds) { bounds[0] = minx; bounds[1] = miny; bounds[2] = maxx; bounds[3] = maxy; } return advance; } void fonsVertMetrics(FONScontext* stash, float* ascender, float* descender, float* lineh) { FONSfont* font; FONSstate* state = fons__getState(stash); short isize; if (stash == NULL) return; if (state->font < 0 || state->font >= stash->nfonts) return; font = stash->fonts[state->font]; isize = (short)(state->size*10.0f); if (font->data == NULL) return; if (ascender) *ascender = font->ascender*isize/10.0f; if (descender) *descender = font->descender*isize/10.0f; if (lineh) *lineh = font->lineh*isize/10.0f; } void fonsLineBounds(FONScontext* stash, float y, float* miny, float* maxy) { FONSfont* font; FONSstate* state = fons__getState(stash); short isize; if (stash == NULL) return; if (state->font < 0 || state->font >= stash->nfonts) return; font = stash->fonts[state->font]; isize = (short)(state->size*10.0f); if (font->data == NULL) return; y += fons__getVertAlign(stash, font, state->align, isize); if (stash->params.flags & FONS_ZERO_TOPLEFT) { *miny = y - font->ascender * (float)isize/10.0f; *maxy = *miny + font->lineh*isize/10.0f; } else { *maxy = y + font->descender * (float)isize/10.0f; *miny = *maxy - font->lineh*isize/10.0f; } } const unsigned char* fonsGetTextureData(FONScontext* stash, int* width, int* height) { if (width != NULL) *width = stash->params.width; if (height != NULL) *height = stash->params.height; return stash->texData; } int fonsValidateTexture(FONScontext* stash, int* dirty) { if (stash->dirtyRect[0] < stash->dirtyRect[2] && stash->dirtyRect[1] < stash->dirtyRect[3]) { dirty[0] = stash->dirtyRect[0]; dirty[1] = stash->dirtyRect[1]; dirty[2] = stash->dirtyRect[2]; dirty[3] = stash->dirtyRect[3]; // Reset dirty rect stash->dirtyRect[0] = stash->params.width; stash->dirtyRect[1] = stash->params.height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; return 1; } return 0; } void fontsDeleteFontByName(FONScontext* stash, const char* name) { int id = 0; if (stash == NULL) return; if(name == NULL) { for (id = 0; id < stash->nfonts; ++id) { fons__freeFont(stash->fonts[id]); } stash->nfonts = 0; } else { id = fonsGetFontByName(stash, name); if(id >= 0) { fons__freeFont(stash->fonts[id]); for(; id < stash->nfonts; id++) { if(id + 1 < stash->nfonts) { stash->fonts[id] = stash->fonts[id + 1]; } else { stash->fonts[id] = NULL; break; } } stash->nfonts--; } } } void fonsDeleteInternal(FONScontext* stash) { int i; if (stash == NULL) return; if (stash->params.renderDelete) stash->params.renderDelete(stash->params.userPtr); for (i = 0; i < stash->nfonts; ++i) fons__freeFont(stash->fonts[i]); if (stash->atlas) fons__deleteAtlas(stash->atlas); if (stash->fonts) free(stash->fonts); if (stash->texData) free(stash->texData); if (stash->scratch) free(stash->scratch); free(stash); fons__tt_done(stash); } void fonsSetErrorCallback(FONScontext* stash, void (*callback)(void* uptr, int error, int val), void* uptr) { if (stash == NULL) return; stash->handleError = callback; stash->errorUptr = uptr; } void fonsGetAtlasSize(FONScontext* stash, int* width, int* height) { if (stash == NULL) return; *width = stash->params.width; *height = stash->params.height; } int fonsExpandAtlas(FONScontext* stash, int width, int height) { int i, maxy = 0; unsigned char* data = NULL; if (stash == NULL) return 0; width = fons__maxi(width, stash->params.width); height = fons__maxi(height, stash->params.height); if (width == stash->params.width && height == stash->params.height) return 1; // Flush pending glyphs. fons__flush(stash); // Create new texture if (stash->params.renderResize != NULL) { if (stash->params.renderResize(stash->params.userPtr, width, height) == 0) return 0; } // Copy old texture data over. data = (unsigned char*)malloc(width * height); if (data == NULL) return 0; for (i = 0; i < stash->params.height; i++) { unsigned char* dst = &data[i*width]; unsigned char* src = &stash->texData[i*stash->params.width]; memcpy(dst, src, stash->params.width); if (width > stash->params.width) memset(dst+stash->params.width, 0, width - stash->params.width); } if (height > stash->params.height) memset(&data[stash->params.height * width], 0, (height - stash->params.height) * width); free(stash->texData); stash->texData = data; // Increase atlas size fons__atlasExpand(stash->atlas, width, height); // Add existing data as dirty. for (i = 0; i < stash->atlas->nnodes; i++) maxy = fons__maxi(maxy, stash->atlas->nodes[i].y); stash->dirtyRect[0] = 0; stash->dirtyRect[1] = 0; stash->dirtyRect[2] = stash->params.width; stash->dirtyRect[3] = maxy; stash->params.width = width; stash->params.height = height; stash->itw = 1.0f/stash->params.width; stash->ith = 1.0f/stash->params.height; return 1; } int fonsResetAtlas(FONScontext* stash, int width, int height) { int i, j; if (stash == NULL) return 0; // Flush pending glyphs. fons__flush(stash); // Create new texture if (stash->params.renderResize != NULL) { if (stash->params.renderResize(stash->params.userPtr, width, height) == 0) return 0; } // Reset atlas fons__atlasReset(stash->atlas, width, height); // Clear texture data. stash->texData = (unsigned char*)realloc(stash->texData, width * height); if (stash->texData == NULL) return 0; memset(stash->texData, 0, width * height); // Reset dirty rect stash->dirtyRect[0] = width; stash->dirtyRect[1] = height; stash->dirtyRect[2] = 0; stash->dirtyRect[3] = 0; // Reset cached glyphs for (i = 0; i < stash->nfonts; i++) { FONSfont* font = stash->fonts[i]; font->nglyphs = 0; for (j = 0; j < FONS_HASH_LUT_SIZE; j++) font->lut[j] = -1; } stash->params.width = width; stash->params.height = height; stash->itw = 1.0f/stash->params.width; stash->ith = 1.0f/stash->params.height; // Add white rect at 0,0 for debug drawing. fons__addWhiteRect(stash, 2,2); return 1; } #endif
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\base\nanovg_plus.c
/** * File: nanovg_plus.c * Author: AWTK Develop Team * Brief: refactoring nanovg. * * Copyright (c) 2018 - 2021 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-10-27 Luo Zhiming <luozhiming@zlg.cn> created * */ #include <stdarg.h> #include "nanovg_plus.h" #include <stdio.h> #include <memory.h> #define FONTSTASH_IMPLEMENTATION 1 #include <fontstash.h> #ifdef WITH_NANOVG_PLUS_GPU #include "../gl/nanovg_plus_gl.h" #endif #ifdef _WIN64 typedef double floatptr_t; #else typedef float floatptr_t; #endif #define NVGP_INIT_FONTIMAGE_SIZE 512 #define NVGP_MAX_FONTIMAGE_SIZE 2048 #define NVGP_MAX_FONTIMAGES 4 typedef enum _nvgp_winding_t { NVGP_CCW = 1, // Winding for solid shapes NVGP_CW = 2, // Winding for holes } nvgp_winding_t; typedef enum _nvgp_command_t { NVGP_MOVETO = 0, NVGP_LINETO = 1, NVGP_BEZIERTO = 2, NVGP_CLOSE = 3, NVGP_WINDING = 4, } nvgp_command_t; typedef struct _nvgp_point_t { float x,y; float dx, dy; float len; float dmx, dmy; uint32_t flags; } nvgp_point_t; typedef struct _nvgp_path_cache_t { float bounds[4]; uint32_t nverts; uint32_t cverts; nvgp_vertex_t* verts; nvgp_darray_t paths; nvgp_darray_t points; } nvgp_path_cache_t; typedef struct _nvgp_state_t { uint8_t alpha; uint8_t line_join; uint8_t line_cap; uint8_t shape_anti_alias; float miter_limit; nvgp_paint_t fill; nvgp_paint_t stroke; float stroke_width; uint32_t font_id; int32_t text_align; float font_size; float font_blur; float line_height; float letter_spacing; nvgp_matrix_t matrix; nvgp_scissor_t scissor; float text_scale; float text_width; const char* text_end; const char* text_string; } nvgp_state_t; typedef struct _nvgp_context_t { float ratio; float tess_tol; float dist_tol; float fringe_width; float width; float height; float context_width; float context_height; nvgp_mode_t nvgp_mode; float command_x; float command_y; nvgp_darray_t states; nvgp_darray_t commands; nvgp_path_cache_t cache; struct FONScontext* fs; int fontImages[NVGP_MAX_FONTIMAGES]; int fontImageIdx; int drawCallCount; int fillTriCount; int strokeTriCount; int textTriCount; void* vt_ctx; const nvgp_vtable_t* vt; } nvgp_context_t; #define CHECK_OBJECT_IS_NULL(ctx) assert(ctx != NULL) static nvgp_matrix_t* nvgp_matrix_init(nvgp_matrix_t* mat); static nvgp_vertex_t* nvgp_alloc_temp_verts(nvgp_context_t* ctx, int nverts); static void nvgp_vset(nvgp_vertex_t* vtx, float x, float y, float u, float v); static nvgp_error_t nvgp_set_line_cap_by_statue(nvgp_context_t* ctx, nvgp_state_t* state, nvgp_line_cap_t cap); static nvgp_error_t nvgp_set_line_join_by_statue(nvgp_context_t* ctx, nvgp_state_t* state, nvgp_line_join_t join); static void nvgp_set_paint_color(nvgp_paint_t* p, nvgp_color_t color){ NVGP_MEMSET(p, 0, sizeof(nvgp_paint_t)); nvgp_matrix_init(&p->mat); p->radius = 0.0f; p->feather = 1.0f; p->inner_color = color; p->outer_color = color; } static nvgp_state_t* nvgp_get_state(nvgp_context_t* ctx) { return nvgp_darray_get_ptr(&ctx->states, ctx->states.size - 1, nvgp_state_t); } static nvgp_state_t* nvgp_get_empty_state_by_tail(nvgp_context_t* ctx) { return nvgp_darray_get_empty_by_tail(&ctx->states, nvgp_state_t); } void nvgp_reset_curr_state(nvgp_context_t* ctx) { nvgp_state_t* state = nvgp_get_state(ctx); NVGP_MEMSET(state, 0, sizeof(*state)); nvgp_set_paint_color(&state->fill, nvgp_color_init(0xff, 0xff, 0xff,0xff)); nvgp_set_paint_color(&state->stroke, nvgp_color_init(0, 0, 0, 0xff)); state->shape_anti_alias = 1; state->stroke_width = 1.0f; state->miter_limit = 10.0f; nvgp_set_line_cap_by_statue(ctx, state, NVGP_BUTT); nvgp_set_line_join_by_statue(ctx, state, NVGP_MITER); state->alpha = 0xff; nvgp_matrix_init(&state->matrix); state->scissor.extent[0] = -1.0f; state->scissor.extent[1] = -1.0f; nvgp_matrix_init(&state->scissor.matrix); state->font_size = 16.0f; state->letter_spacing = 0.0f; state->line_height = 1.0f; state->font_blur = 0.0f; state->text_align = NVGP_ALIGN_LEFT | NVGP_ALIGN_BASELINE; state->font_id = 0; } static int nvgp_init(nvgp_context_t* context, nvgp_mode_t nvgp_mode, uint32_t w, uint32_t h) { context->nvgp_mode = nvgp_mode; context->context_width = w; context->context_height = h; nvgp_darray_init(&context->commands, NVGP_INIT_COMMANDS_SIZE, 0); nvgp_darray_init(&context->states, NVGP_INIT_STATES, sizeof(nvgp_state_t)); context->cache.verts = NVGP_ZALLOCN(nvgp_vertex_t, NVGP_INIT_CACHE_VERTS_SIZE); if (context->cache.verts == NULL) { return 0; } context->cache.nverts = 0; context->cache.cverts = NVGP_INIT_CACHE_VERTS_SIZE; nvgp_darray_init(&context->cache.paths, NVGP_INIT_CACHE_PATHS_SIZE, sizeof(nvgp_path_t)); nvgp_darray_init(&context->cache.points, NVGP_INIT_CACHE_POINTS_SIZE, sizeof(nvgp_point_t)); nvgp_save(context); nvgp_reset_curr_state(context); nvgp_scissor(context, 0, 0, context->context_width, context->context_height); return 1; } nvgp_context_t* nvgp_create_by_vt(uint32_t w, uint32_t h, const nvgp_vtable_t* vt, void* ctx) { nvgp_context_t* context = NVGP_ZALLOC(nvgp_context_t); if (context != NULL) { context->vt = vt; context->vt_ctx = ctx; if (!nvgp_init(context, NVGP_MODE_SPECIAL, w, h)) { goto error; } } return context; error: nvgp_destroy(context); return NULL; } nvgp_context_t* nvgp_create(nvgp_mode_t nvgp_mode, uint32_t w, uint32_t h) { nvgp_context_t* context = NVGP_ZALLOC(nvgp_context_t); if (context != NULL) { #ifdef WITH_NANOVG_PLUS_GPU if (nvgp_mode == NVGP_MODE_GPU) { FONSparams fontParams; context->vt = nvgp_gl_vtable(); context->vt_ctx = nvgp_gl_create(NVGP_GL_FLAG_ANTIALIAS | NVGP_GL_FLAG_STENCIL_STROKES); NVGP_MEMSET(&fontParams, 0, sizeof(fontParams)); fontParams.width = NVGP_INIT_FONTIMAGE_SIZE; fontParams.height = NVGP_INIT_FONTIMAGE_SIZE; fontParams.flags = FONS_ZERO_TOPLEFT; fontParams.renderCreate = NULL; fontParams.renderUpdate = NULL; fontParams.renderDraw = NULL; fontParams.renderDelete = NULL; fontParams.userPtr = NULL; context->fs = fonsCreateInternal(&fontParams); if (context->fs == NULL) { goto error; } // Create font texture context->fontImages[0] = context->vt->create_texture(context->vt_ctx, NVGP_TEXTURE_ALPHA, fontParams.width, fontParams.height, 0, 0, NULL); if (context->fontImages[0] == 0) goto error; context->fontImageIdx = 0; } else #endif if (nvgp_mode == NVGP_MODE_CPU) { } if (!nvgp_init(context, nvgp_mode, w, h)) { goto error; } } return context; error: nvgp_destroy(context); return NULL; } void nvgp_destroy(nvgp_context_t* ctx) { if (ctx != NULL) { #ifdef WITH_NANOVG_PLUS_GPU uint32_t i = 0; if (ctx->fs) { fonsDeleteInternal(ctx->fs); } for (i = 0; i < NVGP_MAX_FONTIMAGES; i++) { if (ctx->fontImages[i] != 0) { nvgp_delete_image(ctx, ctx->fontImages[i]); ctx->fontImages[i] = 0; } } #endif if (ctx->vt != NULL && ctx->vt->destroy != NULL) { ctx->vt->destroy(ctx->vt_ctx); } nvgp_darray_deinit(&ctx->states); nvgp_darray_deinit(&ctx->commands); NVGP_FREE(ctx->cache.verts); nvgp_darray_deinit(&ctx->cache.paths); nvgp_darray_deinit(&ctx->cache.points); NVGP_FREE(ctx); } } static nvgp_clear_path_cache(nvgp_path_cache_t* cache) { cache->nverts = 0; NVGP_MEMSET(cache->bounds, 0x0, sizeof(cache->bounds)); nvgp_darray_clear(&cache->paths); nvgp_darray_clear(&cache->points); } void nvgp_begin_frame_ex(nvgp_context_t *ctx, float width, float height, float pixel_ratio, nvgp_bool_t reset) { CHECK_OBJECT_IS_NULL(ctx); ctx->width = width; ctx->height = height; ctx->ratio = pixel_ratio; ctx->tess_tol = 0.25f / pixel_ratio; ctx->dist_tol = 0.01f / pixel_ratio; ctx->fringe_width = 1.0f / pixel_ratio; if (reset) { nvgp_darray_clear(&ctx->states); nvgp_darray_clear(&ctx->commands); nvgp_clear_path_cache(&ctx->cache); nvgp_save(ctx); nvgp_reset_curr_state(ctx); } ctx->vt->begin_frame(ctx->vt_ctx, width, height, pixel_ratio); ctx->drawCallCount = 0; ctx->fillTriCount = 0; ctx->strokeTriCount = 0; ctx->textTriCount = 0; } void nvgp_begin_frame(nvgp_context_t *ctx, float width, float height, float pixel_ratio) { nvgp_begin_frame_ex(ctx, width, height, pixel_ratio, 1); } void nvgp_end_frame(nvgp_context_t *ctx) { CHECK_OBJECT_IS_NULL(ctx); ctx->vt->end_frame(ctx->vt_ctx); } void nvgp_save(nvgp_context_t *ctx) { nvgp_state_t* state = NULL; nvgp_state_t* state_next = NULL; CHECK_OBJECT_IS_NULL(ctx); if (ctx->states.size > 0) { state = nvgp_get_state(ctx); state_next = nvgp_get_empty_state_by_tail(ctx); CHECK_OBJECT_IS_NULL(state); CHECK_OBJECT_IS_NULL(state_next); NVGP_MEMCPY(state_next, state, sizeof(nvgp_state_t)); } else { nvgp_get_empty_state_by_tail(ctx); } } void nvgp_restore(nvgp_context_t *ctx) { CHECK_OBJECT_IS_NULL(ctx); nvgp_darray_pop(&ctx->states); } int32_t nvgp_create_image_rgba(nvgp_context_t* ctx, int w, int h, int image_flags, const unsigned char* rgba_data) { CHECK_OBJECT_IS_NULL(ctx); return ctx->vt->create_texture(ctx->vt_ctx, NVGP_TEXTURE_RGBA, w, h, w * 4, image_flags, rgba_data); } void nvgp_get_image_size(nvgp_context_t* ctx, int image, int* w, int* h) { CHECK_OBJECT_IS_NULL(ctx); ctx->vt->get_texture_size(ctx->vt_ctx, image, w, h); } void nvgp_update_image_rgba(nvgp_context_t* ctx, int image, const unsigned char* rgba_data) { int32_t w, h; CHECK_OBJECT_IS_NULL(ctx); nvgp_get_image_size(ctx, image, &w, &h); ctx->vt->update_texture(ctx->vt_ctx, image, 0, 0, w, h, rgba_data); } int nvgp_create_font_mem(nvgp_context_t* ctx, const char* name, unsigned char* data, int ndata, nvgp_bool_t freeData) { CHECK_OBJECT_IS_NULL(ctx); return fonsAddFontMem(ctx->fs, name, data, ndata, freeData ? 1 : 0); } int nvgp_find_font(nvgp_context_t* ctx, const char* name) { CHECK_OBJECT_IS_NULL(ctx); if (name == NULL) return -1; return fonsGetFontByName(ctx->fs, name); } void nvgp_delete_font_by_name(nvgp_context_t* ctx, const char* name) { #ifdef WITH_NANOVG_PLUS_GPU if (ctx->fs) { fontsDeleteFontByName(ctx->fs, name); } #endif } void nvgp_delete_image(nvgp_context_t* ctx, int image) { ctx->vt->delete_texture(ctx->vt_ctx, image); } nvgp_bool_t nvgp_clear_cache(nvgp_context_t* ctx) { if(ctx->vt->clear_cache != NULL) { ctx->vt->clear_cache(ctx->vt_ctx); } return FALSE; } void* nvgp_get_vt_ctx(nvgp_context_t* ctx) { CHECK_OBJECT_IS_NULL(ctx); return ctx->vt_ctx; } /*********************************************************************************************** * 数学公式函数 * ***********************************************************************************************/ static int nvgp_pt_equals(float x1, float y1, float x2, float y2, float tol) { float dx = x2 - x1; float dy = y2 - y1; return dx * dx + dy * dy < tol * tol; } static float nvgp_dist_pt_seg(float x, float y, float px, float py, float qx, float qy) { float pqx, pqy, dx, dy, d, t; pqx = qx - px; pqy = qy - py; dx = x - px; dy = y - py; d = pqx * pqx + pqy * pqy; t = pqx * dx + pqy * dy; if (d > 0) t /= d; if (t < 0) t = 0; else if (t > 1) t = 1; dx = px + t * pqx - x; dy = py + t * pqy - y; return dx * dx + dy * dy; } static float nvgp_normalize(float *x, float* y) { float d = nvgp_sqrtf((*x)*(*x) + (*y)*(*y)); if (d > 1e-6f) { float id = 1.0f / d; *x *= id; *y *= id; } return d; } static float nvgp_get_average_scale(nvgp_matrix_t* t) { float sx = nvgp_sqrtf(t->mat.scale_x * t->mat.scale_x + t->mat.skew_x * t->mat.skew_x); float sy = nvgp_sqrtf(t->mat.skew_y * t->mat.skew_y + t->mat.scale_y * t->mat.scale_y); return (sx + sy) * 0.5f; } static int32_t nvgp_curve_divs(float r, float arc, float tol) { float da = nvgp_acosf(r / (r + tol)) * 2.0f; return nvgp_max(2, (int32_t)ceilf(arc / da)); } static float nvgp_quantize(float a, float d) { return ((int32_t)(a / d + 0.5f)) * d; } /***********************************************************************************************/ /*********************************************************************************************** * 路径函数 * ***********************************************************************************************/ static void nvgp_transform_point(floatptr_t* dx, floatptr_t* dy, nvgp_matrix_t* matrix, floatptr_t sx, floatptr_t sy) { // *dx = sx*xform[0] + sy*xform[2] + xform[4]; // *dy = sx*xform[1] + sy*xform[3] + xform[5]; *dx = sx * (matrix->mat.scale_x) + sy * (matrix->mat.skew_x) + (matrix->mat.trans_x); *dy = sx * (matrix->mat.skew_y) + sy * (matrix->mat.scale_y) + (matrix->mat.trans_y); } static void nvgp_append_commands(nvgp_context_t* ctx, floatptr_t* vals, int nvals) { uint32_t i; nvgp_state_t* state = nvgp_get_state(ctx); CHECK_OBJECT_IS_NULL(state); if ((int)vals[0] != NVGP_CLOSE && (int)vals[0] != NVGP_WINDING) { ctx->command_x = vals[nvals-2]; ctx->command_y = vals[nvals-1]; } // transform commands i = 0; while (i < nvals) { int cmd = (int)vals[i]; switch (cmd) { case NVGP_MOVETO: nvgp_transform_point(&vals[i+1],&vals[i+2], &(state->matrix), vals[i+1],vals[i+2]); i += 3; break; case NVGP_LINETO: nvgp_transform_point(&vals[i+1],&vals[i+2], &(state->matrix), vals[i+1],vals[i+2]); i += 3; break; case NVGP_BEZIERTO: nvgp_transform_point(&vals[i+1],&vals[i+2], &(state->matrix), vals[i+1],vals[i+2]); nvgp_transform_point(&vals[i+3],&vals[i+4], &(state->matrix), vals[i+3],vals[i+4]); nvgp_transform_point(&vals[i+5],&vals[i+6], &(state->matrix), vals[i+5],vals[i+6]); i += 7; break; case NVGP_CLOSE: i++; break; case NVGP_WINDING: i += 2; break; default: i++; } } nvgp_darray_memcpy(&ctx->commands, floatptr_t, vals, nvals); } static void nvgp_add_path(nvgp_context_t* ctx) { nvgp_path_t* path; path = nvgp_darray_get_empty_by_tail(&ctx->cache.paths, nvgp_path_t); NVGP_MEMSET(path, 0, sizeof(nvgp_path_t)); path->first = ctx->cache.points.size; path->winding = NVGP_CCW; } static nvgp_path_t* nvgp_last_path(nvgp_context_t* ctx) { return nvgp_darray_get_ptr(&ctx->cache.paths, ctx->cache.paths.size - 1, nvgp_path_t); } static nvgp_point_t* nvgp_last_point(nvgp_context_t* ctx) { return nvgp_darray_get_ptr(&ctx->cache.points, ctx->cache.points.size - 1, nvgp_point_t); } static void nvgp_add_point(nvgp_context_t* ctx, float x, float y, int flags) { nvgp_path_t* path = nvgp_last_path(ctx); nvgp_point_t* pt; if (path == NULL) return; if (path->count > 0 && ctx->cache.points.size > 0) { pt = nvgp_last_point(ctx); if (nvgp_pt_equals(pt->x,pt->y, x,y, ctx->dist_tol)) { pt->flags |= flags; return; } } pt = nvgp_darray_get_empty_by_tail(&ctx->cache.points, nvgp_point_t); NVGP_MEMSET(pt, 0, sizeof(nvgp_point_t)); pt->x = x; pt->y = y; pt->flags = (unsigned char)flags; path->count++; } static void nvgp_tesselate_bezier(nvgp_context_t* ctx, floatptr_t x1, floatptr_t y1, floatptr_t x2, floatptr_t y2, floatptr_t x3, floatptr_t y3, floatptr_t x4, floatptr_t y4, int32_t level, int32_t type) { floatptr_t x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234; floatptr_t dx,dy,d2,d3; if (level > 10) return; x12 = (x1+x2)*0.5f; y12 = (y1+y2)*0.5f; x23 = (x2+x3)*0.5f; y23 = (y2+y3)*0.5f; x34 = (x3+x4)*0.5f; y34 = (y3+y4)*0.5f; x123 = (x12+x23)*0.5f; y123 = (y12+y23)*0.5f; dx = x4 - x1; dy = y4 - y1; d2 = nvgp_abs(((x2 - x4) * dy - (y2 - y4) * dx)); d3 = nvgp_abs(((x3 - x4) * dy - (y3 - y4) * dx)); if ((d2 + d3)*(d2 + d3) < ctx->tess_tol * (dx*dx + dy*dy)) { nvgp_add_point(ctx, x4, y4, type); return; } x234 = (x23+x34)*0.5f; y234 = (y23+y34)*0.5f; x1234 = (x123+x234)*0.5f; y1234 = (y123+y234)*0.5f; nvgp_tesselate_bezier(ctx, x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0); nvgp_tesselate_bezier(ctx, x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type); } static void nvgp_close_last_path(nvgp_context_t* ctx) { nvgp_path_t* path = nvgp_last_path(ctx); if (path == NULL) { return; } path->closed = 1; } static void nvgp_path_winding(nvgp_context_t* ctx, int32_t winding) { nvgp_path_t* path = nvgp_last_path(ctx); if (path == NULL) return; path->winding = winding; } void nvgp_begin_path(nvgp_context_t *ctx) { CHECK_OBJECT_IS_NULL(ctx); nvgp_darray_clear(&ctx->commands); nvgp_darray_clear(&ctx->cache.paths); nvgp_darray_clear(&ctx->cache.points); } void nvgp_close_path(nvgp_context_t *ctx) { floatptr_t vals[] = { NVGP_CLOSE }; nvgp_append_commands(ctx, vals, nvgp_get_arrary_size(vals)); } void nvgp_move_to(nvgp_context_t *ctx, float x, float y) { floatptr_t vals[] = { NVGP_MOVETO, x, y }; CHECK_OBJECT_IS_NULL(ctx); nvgp_append_commands(ctx, vals, nvgp_get_arrary_size(vals)); } void nvgp_line_to(nvgp_context_t *ctx, float x, float y) { floatptr_t vals[] = { NVGP_LINETO, x, y }; CHECK_OBJECT_IS_NULL(ctx); nvgp_append_commands(ctx, vals, nvgp_get_arrary_size(vals)); } void nvgp_bezier_to(nvgp_context_t *ctx, float c1x, float c1y, float c2x, float c2y, float x, float y) { floatptr_t vals[] = { NVGP_BEZIERTO, c1x, c1y, c2x, c2y, x, y }; CHECK_OBJECT_IS_NULL(ctx); nvgp_append_commands(ctx, vals, nvgp_get_arrary_size(vals)); } void nvgp_quad_to(nvgp_context_t *ctx, float cx, float cy, float x, float y) { floatptr_t x0 = ctx->command_x; floatptr_t y0 = ctx->command_y; floatptr_t vals[] = { NVGP_BEZIERTO, x0 + 2.0f/3.0f*(cx - x0), y0 + 2.0f/3.0f*(cy - y0), x + 2.0f/3.0f*(cx - x), y + 2.0f/3.0f*(cy - y), x, y }; CHECK_OBJECT_IS_NULL(ctx); nvgp_append_commands(ctx, vals, nvgp_get_arrary_size(vals)); } void nvgp_arc(nvgp_context_t *ctx, float cx, float cy, float r, float a0, float a1, nvgp_bool_t ccw) { floatptr_t vals[3 + 5 * 7 + 100]; floatptr_t a = 0, da = 0, hda = 0, kappa = 0; floatptr_t px = 0, py = 0, ptanx = 0, ptany = 0; floatptr_t dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0; int32_t i, ndivs, nvals; int32_t move = ctx->commands.size > 0 ? NVGP_LINETO : NVGP_MOVETO; CHECK_OBJECT_IS_NULL(ctx); // Clamp angles da = a1 - a0; if (!ccw) { if (nvgp_abs(da) >= NVGP_PI * 2.0f) { da = NVGP_PI * 2.0f; } else { while (da < 0.0f) da += NVGP_PI * 2.0f; } } else { if (nvgp_abs(da) >= NVGP_PI * 2.0f) { da = -NVGP_PI * 2.0f; } else { while (da > 0.0f) da -= NVGP_PI * 2.0f; } } // Split arc into max 90 degree segments. ndivs = nvgp_max(1, nvgp_min((int)(nvgp_abs(da) / (NVGP_PI * 0.5f) + 0.5f), 5)); hda = (da / (floatptr_t)ndivs) / 2.0f; kappa = nvgp_abs(4.0f / 3.0f * (1.0f - nvgp_cosf(hda)) / nvgp_sinf(hda)); if (ccw) kappa = -kappa; nvals = 0; for (i = 0; i <= ndivs; i++) { a = a0 + da * (i / (floatptr_t)ndivs); dx = nvgp_cosf(a); dy = nvgp_sinf(a); x = cx + dx * r; y = cy + dy * r; tanx = -dy * r * kappa; tany = dx * r * kappa; if (i == 0) { vals[nvals++] = (float)move; vals[nvals++] = x; vals[nvals++] = y; } else { vals[nvals++] = NVGP_BEZIERTO; vals[nvals++] = px+ptanx; vals[nvals++] = py+ptany; vals[nvals++] = x-tanx; vals[nvals++] = y-tany; vals[nvals++] = x; vals[nvals++] = y; } px = x; py = y; ptanx = tanx; ptany = tany; } nvgp_append_commands(ctx, vals, nvals); } void nvgp_arc_to(nvgp_context_t *ctx, float x1, float y1, float x2, float y2, float radius) { int32_t dir; float x0 = ctx->command_x; float y0 = ctx->command_y; float dx0, dy0, dx1, dy1, a, d, cx, cy, a0, a1; CHECK_OBJECT_IS_NULL(ctx); if (ctx->commands.size == 0) { return; } // Handle degenerate cases. if (nvgp_pt_equals(x0,y0, x1,y1, ctx->dist_tol) || nvgp_pt_equals(x1,y1, x2,y2, ctx->dist_tol) || nvgp_dist_pt_seg(x1,y1, x0,y0, x2,y2) < ctx->dist_tol*ctx->dist_tol || radius < ctx->dist_tol) { nvgp_line_to(ctx, x1, y1); return; } // Calculate tangential circle to lines (x0,y0)-(x1,y1) and (x1,y1)-(x2,y2). dx0 = x0 - x1; dy0 = y0 - y1; dx1 = x2 - x1; dy1 = y2 - y1; nvgp_normalize(&dx0, &dy0); nvgp_normalize(&dx1, &dy1); a = nvgp_acosf(dx0 * dx1 + dy0 * dy1); d = radius / nvgp_tanf(a/2.0f); // printf("a=%f° d=%f\n", a/NVG_PI*180.0f, d); if (d > 10000.0f) { nvgp_line_to(ctx, x1,y1); return; } if (nvgp_cross(dx0,dy0, dx1,dy1) > 0.0f) { cx = x1 + dx0*d + dy0*radius; cy = y1 + dy0*d + -dx0*radius; a0 = nvgp_atan2f(dx0, -dy0); a1 = nvgp_atan2f(-dx1, dy1); dir = 0; // printf("CW c=(%f, %f) a0=%f° a1=%f°\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f); } else { cx = x1 + dx0 * d + -dy0 * radius; cy = y1 + dy0 * d + dx0 * radius; a0 = nvgp_atan2f(-dx0, dy0); a1 = nvgp_atan2f(dx1, -dy1); dir = 1; // printf("CCW c=(%f, %f) a0=%f° a1=%f°\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f); } nvgp_arc(ctx, cx, cy, radius, a0, a1, dir); } void nvgp_rect(nvgp_context_t *ctx, float x, float y, float w, float h) { floatptr_t vals[] = { NVGP_MOVETO, x, y, NVGP_LINETO, x, y + h, NVGP_LINETO, x + w, y + h, NVGP_LINETO, x + w, y, NVGP_CLOSE }; CHECK_OBJECT_IS_NULL(ctx); nvgp_append_commands(ctx, vals, nvgp_get_arrary_size(vals)); } void nvgp_rounded_rect_varying(nvgp_context_t *ctx, float x, float y, float w, float h, float rad_top_left, float rad_top_right, float rad_bottom_right, float rad_bottom_left) { CHECK_OBJECT_IS_NULL(ctx); if(rad_top_left < 0.1f && rad_top_right < 0.1f && rad_bottom_right < 0.1f && rad_bottom_left < 0.1f) { nvgp_rect(ctx, x, y, w, h); return; } else { floatptr_t halfw = nvgp_abs(w) * 0.5f; floatptr_t halfh = nvgp_abs(h) * 0.5f; floatptr_t rxBL = nvgp_min(rad_bottom_left, halfw) * nvgp_signf(w), ryBL = nvgp_min(rad_bottom_left, halfh) * nvgp_signf(h); floatptr_t rxBR = nvgp_min(rad_bottom_right, halfw) * nvgp_signf(w), ryBR = nvgp_min(rad_bottom_right, halfh) * nvgp_signf(h); floatptr_t rxTR = nvgp_min(rad_top_right, halfw) * nvgp_signf(w), ryTR = nvgp_min(rad_top_right, halfh) * nvgp_signf(h); floatptr_t rxTL = nvgp_min(rad_top_left, halfw) * nvgp_signf(w), ryTL = nvgp_min(rad_top_left, halfh) * nvgp_signf(h); floatptr_t vals[] = { NVGP_MOVETO, x, y + ryTL, NVGP_LINETO, x, y + h - ryBL, NVGP_BEZIERTO, x, y + h - ryBL*(1 - NVGP_KAPPA90), x + rxBL*(1 - NVGP_KAPPA90), y + h, x + rxBL, y + h, NVGP_LINETO, x + w - rxBR, y + h, NVGP_BEZIERTO, x + w - rxBR*(1 - NVGP_KAPPA90), y + h, x + w, y + h - ryBR*(1 - NVGP_KAPPA90), x + w, y + h - ryBR, NVGP_LINETO, x + w, y + ryTR, NVGP_BEZIERTO, x + w, y + ryTR*(1 - NVGP_KAPPA90), x + w - rxTR*(1 - NVGP_KAPPA90), y, x + w - rxTR, y, NVGP_LINETO, x + rxTL, y, NVGP_BEZIERTO, x + rxTL*(1 - NVGP_KAPPA90), y, x, y + ryTL*(1 - NVGP_KAPPA90), x, y + ryTL, NVGP_CLOSE }; nvgp_append_commands(ctx, vals, nvgp_get_arrary_size(vals)); } } void nvgp_rounded_rect(nvgp_context_t *ctx, float x, float y, float w, float h, float r) { nvgp_rounded_rect_varying(ctx, x, y, w, h, r, r, r, r); } void nvgp_ellipse(nvgp_context_t *ctx, float cx, float cy, float rx, float ry) { floatptr_t vals[] = { NVGP_MOVETO, cx - rx, cy, NVGP_BEZIERTO, cx - rx, cy + ry * NVGP_KAPPA90, cx - rx * NVGP_KAPPA90, cy + ry, cx, cy + ry, NVGP_BEZIERTO, cx + rx * NVGP_KAPPA90, cy + ry, cx + rx, cy + ry * NVGP_KAPPA90, cx + rx, cy, NVGP_BEZIERTO, cx + rx, cy - ry * NVGP_KAPPA90, cx + rx * NVGP_KAPPA90, cy - ry, cx, cy - ry, NVGP_BEZIERTO, cx - rx * NVGP_KAPPA90, cy - ry, cx - rx, cy - ry * NVGP_KAPPA90, cx - rx, cy, NVGP_CLOSE }; CHECK_OBJECT_IS_NULL(ctx); nvgp_append_commands(ctx, vals, nvgp_get_arrary_size(vals)); } void nvgp_circle(nvgp_context_t *ctx, float cx, float cy, float r) { nvgp_ellipse(ctx, cx, cy, r, r); } /***********************************************************************************************/ /*********************************************************************************************** * 矩形相关函数 * ***********************************************************************************************/ static nvgp_matrix_t* nvgp_matrix_init(nvgp_matrix_t* mat) { if (mat != NULL) { NVGP_MEMSET(mat, 0x0, sizeof(nvgp_matrix_t)); mat->mat.pers2 = 1.0f; mat->mat.scale_x = 1.0f; mat->mat.scale_y = 1.0f; } return mat; } static nvgp_matrix_t* nvgp_transform_multiply(nvgp_matrix_t* t, nvgp_matrix_t* s) { // float t0 = t[0] * s[0] + t[1] * s[2]; // float t2 = t[2] * s[0] + t[3] * s[2]; // float t4 = t[4] * s[0] + t[5] * s[2] + s[4]; // t[1] = t[0] * s[1] + t[1] * s[3]; // t[3] = t[2] * s[1] + t[3] * s[3]; // t[5] = t[4] * s[1] + t[5] * s[3] + s[5]; // t[0] = t0; // t[2] = t2; // t[4] = t4; float t0 = t->mat.scale_x * s->mat.scale_x + t->mat.skew_y * s->mat.skew_x; float t2 = t->mat.skew_x * s->mat.scale_x + t->mat.scale_y * s->mat.skew_x; float t4 = t->mat.trans_x * s->mat.scale_x + t->mat.trans_y * s->mat.skew_x + s->mat.trans_x; float skew_y = t->mat.scale_x * s->mat.skew_y + t->mat.skew_y * s->mat.scale_y; float scale_y = t->mat.skew_x * s->mat.skew_y + t->mat.scale_y * s->mat.scale_y; float trans_y = t->mat.trans_x * s->mat.skew_y + t->mat.trans_y * s->mat.scale_y + s->mat.trans_y; float skew_x = t2; float scale_x = t0; float trans_x = t4; s->mat.skew_x = skew_x; s->mat.skew_y = skew_y; s->mat.scale_x = scale_x; s->mat.scale_y = scale_y; s->mat.trans_x = trans_x; s->mat.trans_y = trans_y; return s; } nvgp_matrix_t* nvgp_transform_multiply_to_t(nvgp_matrix_t* t, nvgp_matrix_t* s) { // float t0 = t[0] * s[0] + t[1] * s[2]; // float t2 = t[2] * s[0] + t[3] * s[2]; // float t4 = t[4] * s[0] + t[5] * s[2] + s[4]; // t[1] = t[0] * s[1] + t[1] * s[3]; // t[3] = t[2] * s[1] + t[3] * s[3]; // t[5] = t[4] * s[1] + t[5] * s[3] + s[5]; // t[0] = t0; // t[2] = t2; // t[4] = t4; float t0 = t->mat.scale_x * s->mat.scale_x + t->mat.skew_y * s->mat.skew_x; float t2 = t->mat.skew_x * s->mat.scale_x + t->mat.scale_y * s->mat.skew_x; float t4 = t->mat.trans_x * s->mat.scale_x + t->mat.trans_y * s->mat.skew_x + s->mat.trans_x; float skew_y = t->mat.scale_x * s->mat.skew_y + t->mat.skew_y * s->mat.scale_y; float scale_y = t->mat.skew_x * s->mat.skew_y + t->mat.scale_y * s->mat.scale_y; float trans_y = t->mat.trans_x * s->mat.skew_y + t->mat.trans_y * s->mat.scale_y + s->mat.trans_y; float skew_x = t2; float scale_x = t0; float trans_x = t4; t->mat.skew_x = skew_x; t->mat.skew_y = skew_y; t->mat.scale_x = scale_x; t->mat.scale_y = scale_y; t->mat.trans_x = trans_x; t->mat.trans_y = trans_y; return t; } static void nvgp_transform_rotate(nvgp_matrix_t* mat, float a) { float cs = nvgp_cosf(a), sn = nvgp_sinf(a); mat->mat.scale_x = cs; mat->mat.scale_y = cs; mat->mat.skew_x = -sn; mat->mat.skew_y = sn; mat->mat.trans_x = 0.0f; mat->mat.trans_y = 0.0f; } nvgp_bool_t nvgp_transform_inverse(nvgp_matrix_t* inv, const nvgp_matrix_t* t) { // double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1]; // if (det > -1e-6 && det < 1e-6) { // nvgTransformIdentity(inv); // return 0; // } // invdet = 1.0 / det; // inv[0] = (float)(t[3] * invdet); // inv[2] = (float)(-t[2] * invdet); // inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet); // inv[1] = (float)(-t[1] * invdet); // inv[3] = (float)(t[0] * invdet); // inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet); double invdet, det = (double)t->mat.scale_x * t->mat.scale_y - (double)t->mat.skew_x * t->mat.skew_y; if (det > -1e-6 && det < 1e-6) { nvgp_matrix_init(inv); return FALSE; } invdet = 1.0 / det; inv->mat.scale_x = (float)(t->mat.scale_y * invdet); inv->mat.skew_x = (float)(-t->mat.skew_x * invdet); inv->mat.trans_x = (float)(((double)t->mat.skew_x * t->mat.trans_y - (double)t->mat.scale_y * t->mat.trans_x) * invdet); inv->mat.skew_y = (float)(-t->mat.skew_y * invdet); inv->mat.scale_y = (float)(t->mat.scale_x * invdet); inv->mat.trans_y = (float)(((double)t->mat.skew_y * t->mat.trans_x - (double)t->mat.scale_x * t->mat.trans_y) * invdet); return TRUE; } void nvgp_transform_translate(nvgp_matrix_t* mat, float tx, float ty) { nvgp_matrix_init(mat); mat->mat.trans_x = tx; mat->mat.trans_y = ty; } nvgp_error_t nvgp_translate(nvgp_context_t *ctx, float x, float y) { nvgp_matrix_t mat; nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { nvgp_transform_translate(&mat, x, y); nvgp_transform_multiply(&mat, &state->matrix); return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_rotate(nvgp_context_t *ctx, float angle) { nvgp_matrix_t mat; nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { nvgp_matrix_init(&mat); nvgp_transform_rotate(&mat, angle); nvgp_transform_multiply(&mat, &state->matrix); return NVGP_OK; } return NVGP_FAIL; } void nvgp_transform_scale(nvgp_matrix_t* mat, float sx, float sy) { nvgp_matrix_init(mat); mat->mat.scale_x = sx; mat->mat.scale_y = sy; } nvgp_error_t nvgp_scale(nvgp_context_t *ctx, float x, float y) { nvgp_matrix_t mat; nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { nvgp_transform_scale(&mat, x, y); nvgp_transform_multiply(&mat, &state->matrix); return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_reset_transform(nvgp_context_t *ctx) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { nvgp_matrix_init(&state->matrix); return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_transform(nvgp_context_t *ctx, float a, float b, float c, float d, float e, float f) { nvgp_matrix_t mat; nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { nvgp_matrix_init(&mat); mat.mat.skew_x = c; mat.mat.skew_y = b; mat.mat.scale_x = a; mat.mat.scale_y = d; mat.mat.trans_x = e; mat.mat.trans_y = f; nvgp_transform_multiply(&mat, &state->matrix); return NVGP_OK; } return NVGP_FAIL; } /***********************************************************************************************/ /*********************************************************************************************** * 裁剪相关函数 * ***********************************************************************************************/ static void nvgp_isect_rects(float* dst, float ax, float ay, float aw, float ah, float bx, float by, float bw, float bh) { float minx = nvgp_max(ax, bx); float miny = nvgp_max(ay, by); float maxx = nvgp_min(ax+aw, bx+bw); float maxy = nvgp_min(ay+ah, by+bh); dst[0] = minx; dst[1] = miny; dst[2] = nvgp_max(0.0f, maxx - minx); dst[3] = nvgp_max(0.0f, maxy - miny); } nvgp_error_t nvgp_scissor(nvgp_context_t* ctx, float x, float y, float w, float h) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { w = nvgp_max(0.0f, w); h = nvgp_max(0.0f, h); /* 消除着色器精度不够引起的漏出颜色的问题 */ if (w == 0.0f || h == 0.0f) { w = 0.0f; h = 0.0f; } nvgp_matrix_init(&state->scissor.matrix); state->scissor.matrix.mat.trans_x = x + w * 0.5f; state->scissor.matrix.mat.trans_y = y + h * 0.5f; nvgp_transform_multiply_to_t(&state->scissor.matrix, &state->matrix); state->scissor.extent[0] = w * 0.5f; state->scissor.extent[1] = h * 0.5f; return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_get_curr_clip_rect(nvgp_context_t* ctx, float* x, float* y, float* w, float* h) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { float rect[4]; float ex, ey, tex, tey; nvgp_matrix_t pxform, invxorm; NVGP_MEMCPY(&pxform, &state->scissor.matrix, sizeof(nvgp_matrix_t)); ex = state->scissor.extent[0]; ey = state->scissor.extent[1]; nvgp_transform_inverse(&invxorm, &state->matrix); nvgp_transform_multiply_to_t(&pxform, &invxorm); tex = ex * nvgp_abs(pxform.mat.scale_x) + ey * nvgp_abs(pxform.mat.skew_x); tey = ex * nvgp_abs(pxform.mat.skew_y) + ey * nvgp_abs(pxform.mat.scale_y); *x = pxform.mat.trans_x - tex; *y = pxform.mat.trans_y - tey; *w = tex * 2; *h = tey * 2; return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_intersect_scissor(nvgp_context_t* ctx, float* x, float* y, float* w, float* h) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { float rect[4]; float ex, ey, tex, tey; nvgp_matrix_t pxform, invxorm; // If no previous scissor has been set, set the scissor as current scissor. if (state->scissor.extent[0] < 0) { nvgp_scissor(ctx, *x, *y, *w, *h); return NVGP_OK; } // Transform the current scissor rect into current transform space. // If there is difference in rotation, this will be approximation. NVGP_MEMCPY(&pxform, &state->scissor.matrix, sizeof(nvgp_matrix_t)); ex = state->scissor.extent[0]; ey = state->scissor.extent[1]; nvgp_transform_inverse(&invxorm, &state->matrix); nvgp_transform_multiply_to_t(&pxform, &invxorm); tex = ex * nvgp_abs(pxform.mat.scale_x) + ey * nvgp_abs(pxform.mat.skew_x); tey = ex * nvgp_abs(pxform.mat.skew_y) + ey * nvgp_abs(pxform.mat.scale_y); // Intersect rects. nvgp_isect_rects(rect, pxform.mat.trans_x - tex, pxform.mat.trans_y - tey, tex * 2, tey * 2, *x, *y, *w, *h); *x = rect[0]; *y = rect[1]; *w = rect[2]; *h = rect[3]; nvgp_scissor(ctx, rect[0], rect[1], rect[2], rect[3]); return NVGP_OK; } return NVGP_FAIL; } /***********************************************************************************************/ /*********************************************************************************************** * 全局配置函数 * ***********************************************************************************************/ nvgp_error_t nvgp_set_stroke_color(nvgp_context_t *ctx, nvgp_color_t color) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { nvgp_set_paint_color(&state->stroke, color); return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_set_fill_color(nvgp_context_t *ctx, nvgp_color_t color) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { nvgp_set_paint_color(&state->fill, color); return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_set_shape_anti_alias(nvgp_context_t* ctx, nvgp_bool_t enabled) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { state->shape_anti_alias = enabled; return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_set_miter_limit(nvgp_context_t *ctx, float limit) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { state->miter_limit = limit; return NVGP_OK; } return NVGP_FAIL; } static nvgp_error_t nvgp_set_line_cap_by_statue(nvgp_context_t* ctx, nvgp_state_t* state, nvgp_line_cap_t cap) { if (state != NULL) { state->line_cap = cap; if (ctx->vt != NULL && ctx->vt->set_line_cap != NULL) { ctx->vt->set_line_cap(ctx->vt_ctx, cap); } return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_set_line_cap(nvgp_context_t* ctx, nvgp_line_cap_t cap) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); return nvgp_set_line_cap_by_statue(ctx, state, cap); } static nvgp_error_t nvgp_set_line_join_by_statue(nvgp_context_t* ctx, nvgp_state_t* state, nvgp_line_join_t join) { if (state != NULL) { state->line_join = join; if (ctx->vt != NULL && ctx->vt->set_line_join != NULL) { ctx->vt->set_line_join(ctx->vt_ctx, join); } return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_set_line_join(nvgp_context_t* ctx, nvgp_line_join_t join) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); return nvgp_set_line_join_by_statue(ctx, state, join); } nvgp_error_t nvgp_set_stroke_width(nvgp_context_t *ctx, float stroke_width) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { state->stroke_width = stroke_width; return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_set_global_alpha(nvgp_context_t *ctx, uint8_t alpha) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { state->alpha = alpha; return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_text_align(nvgp_context_t* ctx, int32_t align) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { state->text_align = align; return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_font_face_id(nvgp_context_t* ctx, int32_t font_id) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { state->font_id = font_id; return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_set_font_size(nvgp_context_t *ctx, float font_size) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { state->font_size = font_size; return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_set_fill_paint(nvgp_context_t* ctx, nvgp_paint_t paint) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { state->fill = paint; nvgp_transform_multiply_to_t(&state->fill.mat, &state->matrix); return NVGP_OK; } return NVGP_FAIL; } nvgp_error_t nvgp_set_stroke_paint(nvgp_context_t* ctx, nvgp_paint_t paint) { nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); if (state != NULL) { state->stroke = paint; nvgp_transform_multiply_to_t(&state->stroke.mat, &state->matrix); return NVGP_OK; } return NVGP_FAIL; } /***********************************************************************************************/ /*********************************************************************************************** * 画笔函数 * ***********************************************************************************************/ nvgp_paint_t nvgp_linear_gradient(nvgp_context_t* ctx, float sx, float sy, float ex, float ey, nvgp_color_t icol, nvgp_color_t ocol) { nvgp_paint_t p; float dx, dy, d; const float large = 1e5; (void)ctx; NVGP_MEMSET(&p, 0, sizeof(p)); // Calculate transform aligned to the line dx = ex - sx; dy = ey - sy; d = sqrtf(dx*dx + dy*dy); if (d > 0.0001f) { dx /= d; dy /= d; } else { dx = 0; dy = 1; } p.mat.mat.skew_x = dx; p.mat.mat.skew_y = -dx; p.mat.mat.scale_x = dy; p.mat.mat.scale_y = dy; p.mat.mat.trans_x = sx - dx * large; p.mat.mat.trans_y = sy - dy * large; p.extent[0] = large; p.extent[1] = large + d * 0.5f; p.radius = 0.0f; p.feather = nvgp_max(1.0f, d); p.inner_color = icol; p.outer_color = ocol; return p; } nvgp_paint_t nvgp_radial_gradient(nvgp_context_t* ctx, float cx, float cy, float inr, float outr, nvgp_color_t icol, nvgp_color_t ocol) { nvgp_paint_t p; float r = (inr + outr) * 0.5f; float f = (outr - inr); (void)ctx; NVGP_MEMSET(&p, 0, sizeof(p)); nvgp_matrix_init(&p.mat); p.mat.mat.trans_x = cx; p.mat.mat.trans_y = cy; p.extent[0] = r; p.extent[1] = r; p.radius = r; p.feather = nvgp_max(1.0f, f); p.inner_color = icol; p.outer_color = ocol; return p; } nvgp_paint_t nvgp_image_pattern(nvgp_context_t* ctx, float cx, float cy, float w, float h, float angle, int image, uint8_t alpha) { nvgp_paint_t p; (void)ctx; NVGP_MEMSET(&p, 0, sizeof(p)); nvgp_transform_rotate(&p.mat, angle); p.mat.mat.trans_x = cx; p.mat.mat.trans_y = cy; p.extent[0] = w; p.extent[1] = h; p.image = image; p.draw_type = NVGP_IMAGE_DRAW_DEFAULT; p.inner_color.color = p.outer_color.color = 0xffffffff; p.inner_color.rgba.a = alpha; p.outer_color.rgba.a = alpha; return p; } nvgp_paint_t nvgp_image_pattern_repeat(nvgp_context_t* ctx, float sx, float sy, float sw, float sh, float dw, float dh, float image_w, float image_h, float angle, int image, uint8_t alpha) { nvgp_paint_t p; float scale_x = dw / sw; float scale_y = dh / sh; (void)ctx; NVGP_MEMSET(&p, 0, sizeof(p)); nvgp_transform_rotate(&p.mat, angle); p.extent[0] = image_w; p.extent[1] = image_h; p.draw_info[0] = scale_x; p.draw_info[1] = scale_y; p.draw_image_rect[0] = sx; p.draw_image_rect[1] = sy; p.draw_image_rect[2] = sw; p.draw_image_rect[3] = sh; p.image = image; p.draw_type = NVGP_IMAGE_DRAW_REPEAT; p.inner_color.color = 0xffffffff; p.inner_color.rgba.a = alpha; return p; } /***********************************************************************************************/ /*********************************************************************************************** * 文字相关函数 * ***********************************************************************************************/ static float nvgp_get_font_scale(nvgp_state_t* state) { return nvgp_min(nvgp_quantize(nvgp_get_average_scale(&state->matrix), 0.01f), 4.0f); } static void nvgp_render_text(nvgp_context_t* ctx, nvgp_vertex_t* verts, uint32_t nverts) { nvgp_state_t* state = nvgp_get_state(ctx); nvgp_paint_t paint = state->fill; // Render triangles. paint.image = ctx->fontImages[ctx->fontImageIdx]; // Apply global alpha paint.inner_color.rgba.a = paint.outer_color.rgba.a * state->alpha / 255; paint.outer_color.rgba.a = paint.outer_color.rgba.a * state->alpha / 255; ctx->vt->render_draw_text(ctx->vt_ctx, &paint, &state->scissor, verts, nverts); ctx->drawCallCount++; ctx->textTriCount += nverts / 3; } static void nvgp_flush_text_texture(nvgp_context_t* ctx) { int32_t dirty[4]; if (fonsValidateTexture(ctx->fs, dirty)) { int fontImage = ctx->fontImages[ctx->fontImageIdx]; // Update texture if (fontImage != 0) { int iw, ih; const unsigned char* data = fonsGetTextureData(ctx->fs, &iw, &ih); int x = dirty[0]; int y = dirty[1]; int w = dirty[2] - dirty[0]; int h = dirty[3] - dirty[1]; ctx->vt->update_texture(ctx->vt_ctx, fontImage, x, y, w, h, data); } } } static int nvgp_alloc_text_atlas(nvgp_context_t* ctx) { int iw, ih; nvgp_flush_text_texture(ctx); if (ctx->fontImageIdx >= NVGP_MAX_FONTIMAGES-1) return 0; // if next fontImage already have a texture if (ctx->fontImages[ctx->fontImageIdx+1] != 0) { nvgp_get_image_size(ctx, ctx->fontImages[ctx->fontImageIdx + 1], &iw, &ih); } else { // calculate the new font image size and create it. nvgp_get_image_size(ctx, ctx->fontImages[ctx->fontImageIdx], &iw, &ih); if (iw > ih) { ih *= 2; } else { iw *= 2; } if (iw > NVGP_MAX_FONTIMAGE_SIZE || ih > NVGP_MAX_FONTIMAGE_SIZE) { iw = ih = NVGP_MAX_FONTIMAGE_SIZE; } ctx->fontImages[ctx->fontImageIdx+1] = ctx->vt->create_texture(ctx->vt_ctx, NVGP_TEXTURE_ALPHA, iw, ih, 0, 0, NULL); } ++ctx->fontImageIdx; fonsResetAtlas(ctx->fs, iw, ih); return 1; } void nvgp_text_metrics(nvgp_context_t* ctx, float* ascender, float* descender, float* lineh) { nvgp_state_t* state = NULL; float scale, invscale, width; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); scale = nvgp_get_font_scale(state) * ctx->ratio; invscale = 1.0f / scale; if (state->font_id == FONS_INVALID) { return; } fonsSetSize(ctx->fs, state->font_size * scale); fonsSetSpacing(ctx->fs, state->letter_spacing * scale); fonsSetBlur(ctx->fs, state->font_blur * scale); fonsSetAlign(ctx->fs, state->text_align); fonsSetFont(ctx->fs, state->font_id); fonsVertMetrics(ctx->fs, ascender, descender, lineh); if (ascender != NULL) *ascender *= invscale; if (descender != NULL) *descender *= invscale; if (lineh != NULL) *lineh *= invscale; } float nvgp_text_bounds(nvgp_context_t* ctx, float x, float y, const char* string, const char* end, float* bounds) { nvgp_state_t* state = NULL; float scale, invscale, width; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); scale = nvgp_get_font_scale(state) * ctx->ratio; invscale = 1.0f / scale; if (state->font_id == FONS_INVALID) { return 0; } fonsSetSize(ctx->fs, state->font_size*scale); fonsSetSpacing(ctx->fs, state->letter_spacing*scale); fonsSetBlur(ctx->fs, state->font_blur*scale); fonsSetAlign(ctx->fs, state->text_align); fonsSetFont(ctx->fs, state->font_id); width = fonsTextBounds(ctx->fs, x*scale, y*scale, string, end, bounds); if (bounds != NULL) { // Use line bounds for height. fonsLineBounds(ctx->fs, y*scale, &bounds[1], &bounds[3]); bounds[0] *= invscale; bounds[1] *= invscale; bounds[2] *= invscale; bounds[3] *= invscale; } state->text_end = end; state->text_scale = scale; state->text_string = string; state->text_width = width * invscale; return state->text_width; } float nvgp_text(nvgp_context_t* ctx, float x, float y, const char* string, const char* end) { FONSquad q; uint32_t nverts = 0; uint32_t cverts = 0; nvgp_vertex_t* verts; nvgp_state_t* state = NULL; FONStextIter iter, prevIter; float scale, invscale; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); scale = nvgp_get_font_scale(state) * ctx->ratio; invscale = 1.0f / scale; if (state->font_id == FONS_INVALID) { return x; } if (end == NULL) { end = string + strlen(string); } fonsSetSize(ctx->fs, state->font_size*scale); fonsSetSpacing(ctx->fs, state->letter_spacing*scale); fonsSetBlur(ctx->fs, state->font_blur*scale); fonsSetAlign(ctx->fs, state->text_align); fonsSetFont(ctx->fs, state->font_id); cverts = nvgp_max(2, (int32_t)(end - string)) * 6; // conservative estimate. verts = nvgp_alloc_temp_verts(ctx, cverts); if (verts == NULL) return x; fonsTextIterInit(ctx->fs, &iter, x * scale, y * scale, string, end, FONS_GLYPH_BITMAP_REQUIRED); prevIter = iter; while (fonsTextIterNext(ctx->fs, &iter, &q)) { floatptr_t c[4 * 2]; if (iter.prevGlyphIndex == -1) { // can not retrieve glyph? if (nverts != 0) { nvgp_render_text(ctx, verts, nverts); nverts = 0; } if (!nvgp_alloc_text_atlas(ctx)) { break; // no memory :( } iter = prevIter; fonsTextIterNext(ctx->fs, &iter, &q); // try again if (iter.prevGlyphIndex == -1) { // still can not find glyph? break; } } prevIter = iter; // Transform corners. nvgp_transform_point(&c[0],&c[1], &state->matrix, q.x0*invscale, q.y0*invscale); nvgp_transform_point(&c[2],&c[3], &state->matrix, q.x1*invscale, q.y0*invscale); nvgp_transform_point(&c[4],&c[5], &state->matrix, q.x1*invscale, q.y1*invscale); nvgp_transform_point(&c[6],&c[7], &state->matrix, q.x0*invscale, q.y1*invscale); // Create triangles if (nverts+6 <= cverts) { nvgp_vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++; nvgp_vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++; nvgp_vset(&verts[nverts], c[2], c[3], q.s1, q.t0); nverts++; nvgp_vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++; nvgp_vset(&verts[nverts], c[6], c[7], q.s0, q.t1); nverts++; nvgp_vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++; } } // TODO: add back-end bit to do this just once per frame. nvgp_flush_text_texture(ctx); nvgp_render_text(ctx, verts, nverts); return iter.nextx / scale; } /***********************************************************************************************/ /*********************************************************************************************** * 绘图函数 * ***********************************************************************************************/ static floatptr_t nvgp_triarea2(float ax, float ay, float bx, float by, float cx, float cy) { floatptr_t abx = bx - ax; floatptr_t aby = by - ay; floatptr_t acx = cx - ax; floatptr_t acy = cy - ay; return acx*aby - abx*acy; } static floatptr_t nvgp_poly_area(nvgp_darray_t* points, int32_t first, int32_t npts) { int32_t i; float area = 0; for (i = 2; i < npts; i++) { nvgp_point_t* a = nvgp_darray_get_ptr(points, first, nvgp_point_t); nvgp_point_t* b = nvgp_darray_get_ptr(points, first + i - 1, nvgp_point_t); nvgp_point_t* c = nvgp_darray_get_ptr(points, first + i, nvgp_point_t); area += nvgp_triarea2(a->x, a->y, b->x, b->y, c->x, c->y); } return area * 0.5f; } static void nvgp_poly_reverse(nvgp_darray_t* points, int32_t first, int npts) { void* tmp = NULL; int32_t i = first, j = first + npts - 1; assert(points->data_type_size != 0); tmp = NVGP_MALLOC( points->data_type_size); while (i < j) { NVGP_MEMCPY(tmp, points->elms[i], points->data_type_size); NVGP_MEMCPY(points->elms[i], points->elms[j], points->data_type_size); NVGP_MEMCPY(points->elms[j], tmp, points->data_type_size); i++; j--; } NVGP_FREE(tmp); } static void nvgp_flatten_paths(nvgp_context_t* ctx) { int32_t i, j; floatptr_t p_0; floatptr_t p_1; floatptr_t area; nvgp_path_t* path; nvgp_point_t* p0; nvgp_point_t* p1; nvgp_point_t* pts; nvgp_point_t* last; nvgp_path_cache_t* cache = &ctx->cache; nvgp_darray_t* commands = &ctx->commands; // Flatten i = 0; while (i < commands->size) { int32_t cmd = (int32_t)nvgp_darray_get(commands, i, floatptr_t); switch (cmd) { case NVGP_MOVETO:{ nvgp_add_path(ctx); p_0 = nvgp_darray_get(commands, i + 1, floatptr_t); p_1 = nvgp_darray_get(commands, i + 2, floatptr_t); nvgp_add_point(ctx, p_0, p_1, NVGP_PT_CORNER); i += 3; break; } case NVGP_LINETO: { p_0 = nvgp_darray_get(commands, i + 1, floatptr_t); p_1 = nvgp_darray_get(commands, i + 2, floatptr_t); nvgp_add_point(ctx, p_0, p_1, NVGP_PT_CORNER); i += 3; break; } case NVGP_BEZIERTO: last = nvgp_last_point(ctx); if (last != NULL) { floatptr_t cp1_0 = nvgp_darray_get(commands, i + 1, floatptr_t); floatptr_t cp1_1 = nvgp_darray_get(commands, i + 2, floatptr_t); floatptr_t cp2_0 = nvgp_darray_get(commands, i + 3, floatptr_t); floatptr_t cp2_1 = nvgp_darray_get(commands, i + 4, floatptr_t); p_0 = nvgp_darray_get(commands, i + 5, floatptr_t); p_1 = nvgp_darray_get(commands, i + 6, floatptr_t); nvgp_tesselate_bezier(ctx, last->x,last->y, cp1_0, cp1_1, cp2_0, cp2_1, p_0, p_1, 0, NVGP_PT_CORNER); } i += 7; break; case NVGP_CLOSE:{ nvgp_close_last_path(ctx); i++; break; } case NVGP_WINDING: { floatptr_t p = nvgp_darray_get(commands, i + 1, floatptr_t); nvgp_path_winding(ctx, (int)p); i += 2; break; } default: { i++; } } } cache->bounds[0] = cache->bounds[1] = 1e6f; cache->bounds[2] = cache->bounds[3] = -1e6f; // Calculate the direction and length of line segments. for (j = 0; j < cache->paths.size; j++) { path = nvgp_darray_get_ptr(&cache->paths, j, nvgp_path_t); pts = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); // If the first and last points are the same, remove the last, mark as closed path. p0 = nvgp_darray_get_ptr(&cache->points, path->first + path->count - 1, nvgp_point_t); p1 = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); if (nvgp_pt_equals(p0->x,p0->y, p1->x,p1->y, ctx->dist_tol)) { path->count--; p0 = nvgp_darray_get_ptr(&cache->points, path->first + path->count - 1, nvgp_point_t); path->closed = 1; } // Enforce winding. if (path->count > 2) { area = nvgp_poly_area(&cache->points, path->first, path->count); if (path->winding == NVGP_CCW && area < 0.0f) { nvgp_poly_reverse(&cache->points, path->first, path->count); p0 = nvgp_darray_get_ptr(&cache->points, path->first + path->count - 1, nvgp_point_t); p1 = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); } if (path->winding == NVGP_CW && area > 0.0f) { nvgp_poly_reverse(&cache->points, path->first, path->count); p0 = nvgp_darray_get_ptr(&cache->points, path->first + path->count - 1, nvgp_point_t); p1 = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); } } for(i = 0; i < path->count; i++) { // Calculate segment direction and length p0->dx = p1->x - p0->x; p0->dy = p1->y - p0->y; p0->len = nvgp_normalize(&p0->dx, &p0->dy); // Update bounds cache->bounds[0] = nvgp_min(cache->bounds[0], p0->x); cache->bounds[1] = nvgp_min(cache->bounds[1], p0->y); cache->bounds[2] = nvgp_max(cache->bounds[2], p0->x); cache->bounds[3] = nvgp_max(cache->bounds[3], p0->y); // Advance p0 = nvgp_darray_get_ptr(&cache->points, path->first + i, nvgp_point_t); p1 = nvgp_darray_get_ptr(&cache->points, path->first + 1 + i, nvgp_point_t); } } } static void nvgp_calculate_joins(nvgp_context_t* ctx, float w, nvgp_line_join_t lineJoin, float miterLimit) { int32_t i, j; float iw = 0.0f; nvgp_path_cache_t* cache = &ctx->cache; if (w > 0.0f) { iw = 1.0f / w; } // Calculate which joins needs extra vertices to append, and gather vertex count. for (i = 0; i < cache->paths.size; i++) { int32_t nleft = 0; nvgp_path_t* path =nvgp_darray_get_ptr(&cache->paths, i, nvgp_path_t); nvgp_point_t* pts = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); nvgp_point_t* p0 = nvgp_darray_get_ptr(&cache->points, path->first + path->count-1, nvgp_point_t); nvgp_point_t* p1 = pts; path->nbevel = 0; for (j = 0; j < path->count; j++) { float dlx0, dly0, dlx1, dly1, dmr2, cross, limit; dlx0 = p0->dy; dly0 = -p0->dx; dlx1 = p1->dy; dly1 = -p1->dx; // Calculate extrusions p1->dmx = (dlx0 + dlx1) * 0.5f; p1->dmy = (dly0 + dly1) * 0.5f; dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy; if (dmr2 > 0.000001f) { float scale = 1.0f / dmr2; if (scale > 600.0f) { scale = 600.0f; } p1->dmx *= scale; p1->dmy *= scale; } // Clear flags, but keep the corner. p1->flags = (p1->flags & NVGP_PT_CORNER) ? NVGP_PT_CORNER : 0; // Keep track of left turns. cross = p1->dx * p0->dy - p0->dx * p1->dy; if (cross > 0.0f) { nleft++; p1->flags |= NVGP_PT_LEFT; } // Calculate if we should use bevel or miter for inner join. limit = nvgp_max(1.01f, nvgp_min(p0->len, p1->len) * iw); if ((dmr2 * limit*limit) < 1.0f) p1->flags |= NVGP_PR_INNERBEVEL; // Check to see if the corner needs to be beveled. if (p1->flags & NVGP_PT_CORNER) { if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == NVGP_BEVEL || lineJoin == NVGP_ROUND) { p1->flags |= NVGP_PT_BEVEL; } } if ((p1->flags & (NVGP_PT_BEVEL | NVGP_PR_INNERBEVEL)) != 0) path->nbevel++; p0 = p1; p1 = nvgp_darray_get_ptr(&cache->points, path->first + j + 1, nvgp_point_t); } path->convex = (nleft == path->count) ? 1 : 0; } } static void nvgp_vset(nvgp_vertex_t* vtx, float x, float y, float u, float v) { vtx->x = x; vtx->y = y; vtx->u = u; vtx->v = v; } static void nvgp_choose_bevel(int32_t bevel, nvgp_point_t* p0, nvgp_point_t* p1, float w, float* x0, float* y0, float* x1, float* y1) { if (bevel) { *x0 = p1->x + p0->dy * w; *y0 = p1->y - p0->dx * w; *x1 = p1->x + p1->dy * w; *y1 = p1->y - p1->dx * w; } else { *x0 = p1->x + p1->dmx * w; *y0 = p1->y + p1->dmy * w; *x1 = p1->x + p1->dmx * w; *y1 = p1->y + p1->dmy * w; } } static nvgp_vertex_t* nvgp_bevel_join(nvgp_vertex_t* dst, nvgp_point_t* p0, nvgp_point_t* p1, float lw, float rw, float lu, float ru, float fringe) { float rx0,ry0,rx1,ry1; float lx0,ly0,lx1,ly1; float dlx0 = p0->dy; float dly0 = -p0->dx; float dlx1 = p1->dy; float dly1 = -p1->dx; (void)fringe; if (p1->flags & NVGP_PT_LEFT) { nvgp_choose_bevel(p1->flags & NVGP_PR_INNERBEVEL, p0, p1, lw, &lx0, &ly0, &lx1, &ly1); nvgp_vset(dst, lx0, ly0, lu,1); dst++; nvgp_vset(dst, p1->x - dlx0 * rw, p1->y - dly0 * rw, ru, 1); dst++; if (p1->flags & NVGP_PT_BEVEL) { nvgp_vset(dst, lx0, ly0, lu,1); dst++; nvgp_vset(dst, p1->x - dlx0 * rw, p1->y - dly0 * rw, ru, 1); dst++; nvgp_vset(dst, lx1, ly1, lu,1); dst++; nvgp_vset(dst, p1->x - dlx1 * rw, p1->y - dly1 * rw, ru, 1); dst++; } else { rx0 = p1->x - p1->dmx * rw; ry0 = p1->y - p1->dmy * rw; nvgp_vset(dst, p1->x, p1->y, 0.5f,1); dst++; nvgp_vset(dst, p1->x - dlx0 * rw, p1->y - dly0 * rw, ru, 1); dst++; nvgp_vset(dst, rx0, ry0, ru,1); dst++; nvgp_vset(dst, rx0, ry0, ru,1); dst++; nvgp_vset(dst, p1->x, p1->y, 0.5f,1); dst++; nvgp_vset(dst, p1->x - dlx1 * rw, p1->y - dly1 * rw, ru, 1); dst++; } nvgp_vset(dst, lx1, ly1, lu,1); dst++; nvgp_vset(dst, p1->x - dlx1 * rw, p1->y - dly1 * rw, ru, 1); dst++; } else { nvgp_choose_bevel(p1->flags & NVGP_PR_INNERBEVEL, p0, p1, -rw, &rx0, &ry0, &rx1, &ry1); nvgp_vset(dst, p1->x + dlx0 * lw, p1->y + dly0 * lw, lu, 1); dst++; nvgp_vset(dst, rx0, ry0, ru,1); dst++; if (p1->flags & NVGP_PT_BEVEL) { nvgp_vset(dst, p1->x + dlx0 * lw, p1->y + dly0 * lw, lu, 1); dst++; nvgp_vset(dst, rx0, ry0, ru,1); dst++; nvgp_vset(dst, p1->x + dlx1 * lw, p1->y + dly1 * lw, lu, 1); dst++; nvgp_vset(dst, rx1, ry1, ru,1); dst++; } else { lx0 = p1->x + p1->dmx * lw; ly0 = p1->y + p1->dmy * lw; nvgp_vset(dst, p1->x + dlx0 * lw, p1->y + dly0 * lw, lu, 1); dst++; nvgp_vset(dst, p1->x, p1->y, 0.5f,1); dst++; nvgp_vset(dst, lx0, ly0, lu,1); dst++; nvgp_vset(dst, lx0, ly0, lu,1); dst++; nvgp_vset(dst, p1->x + dlx1 * lw, p1->y + dly1 * lw, lu, 1); dst++; nvgp_vset(dst, p1->x, p1->y, 0.5f,1); dst++; } nvgp_vset(dst, p1->x + dlx1 * lw, p1->y + dly1 * lw, lu, 1); dst++; nvgp_vset(dst, rx1, ry1, ru,1); dst++; } return dst; } static nvgp_vertex_t* nvgp_alloc_temp_verts(nvgp_context_t* ctx, int nverts) { if (nverts > ctx->cache.cverts) { nvgp_vertex_t* verts; int cverts = (nverts + 0xff) & ~0xff; // Round up to prevent allocations when things change just slightly. verts = NVGP_REALLOCT(nvgp_vertex_t, ctx->cache.verts, cverts); if (verts == NULL) return NULL; ctx->cache.verts = verts; ctx->cache.cverts = cverts; } return ctx->cache.verts; } static nvgp_error_t nvgp_expand_fill(nvgp_context_t* ctx, float w, nvgp_line_join_t lineJoin, float miterLimit) { nvgp_vertex_t* dst; nvgp_vertex_t* verts; int fringe = w > 0.0f; int cverts, convex, i, j; float aa = ctx->fringe_width; nvgp_path_cache_t* cache = &ctx->cache; nvgp_calculate_joins(ctx, w, lineJoin, miterLimit); // Calculate max vertex usage. cverts = 0; for (i = 0; i < cache->paths.size; i++) { nvgp_path_t* path = nvgp_darray_get_ptr(&cache->paths, i, nvgp_path_t); cverts += path->count + path->nbevel + 1; if (fringe) cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop } verts = nvgp_alloc_temp_verts(ctx, cverts); if (verts == NULL) { return NVGP_OOM; } convex = cache->paths.size == 1 && nvgp_darray_get_ptr(&cache->paths, 0, nvgp_path_t)->convex; for (i = 0; i < cache->paths.size; i++) { float ru, lu; float rw, lw, woff; nvgp_point_t* p0; nvgp_point_t* p1; nvgp_path_t* path = nvgp_darray_get_ptr(&cache->paths, i, nvgp_path_t); nvgp_point_t* pts = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); // Calculate shape vertices. woff = 0.5f * aa; dst = verts; path->fill = dst; if (fringe) { // Looping p0 = nvgp_darray_get_ptr(&cache->points, path->first + path->count - 1, nvgp_point_t); p1 = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); for (j = 0; j < path->count; ++j) { if (p1->flags & NVGP_PT_BEVEL) { float dlx0 = p0->dy; float dly0 = -p0->dx; float dlx1 = p1->dy; float dly1 = -p1->dx; if (p1->flags & NVGP_PT_LEFT) { float lx = p1->x + p1->dmx * woff; float ly = p1->y + p1->dmy * woff; nvgp_vset(dst, lx, ly, 0.5f,1); dst++; } else { float lx0 = p1->x + dlx0 * woff; float ly0 = p1->y + dly0 * woff; float lx1 = p1->x + dlx1 * woff; float ly1 = p1->y + dly1 * woff; nvgp_vset(dst, lx0, ly0, 0.5f,1); dst++; nvgp_vset(dst, lx1, ly1, 0.5f,1); dst++; } } else { nvgp_vset(dst, p1->x + (p1->dmx * woff), p1->y + (p1->dmy * woff), 0.5f,1); dst++; } p0 = p1; p1 = nvgp_darray_get_ptr(&cache->points, path->first + j + 1, nvgp_point_t); } } else { for (j = 0; j < path->count; ++j) { nvgp_point_t* p0 = nvgp_darray_get_ptr(&cache->points, path->first + j, nvgp_point_t); nvgp_vset(dst, p0->x, p0->y, 0.5f,1); dst++; } } path->nfill = (int)(dst - verts); verts = dst; // Calculate fringe if (fringe) { lw = w + woff; rw = w - woff; lu = 0; ru = 1; dst = verts; path->stroke = dst; // Create only half a fringe for convex shapes so that // the shape can be rendered without stenciling. if (convex) { lw = woff; // This should generate the same vertex as fill inset above. lu = 0.5f; // Set outline fade at middle. } // Looping p0 = nvgp_darray_get_ptr(&cache->points, path->first + path->count - 1, nvgp_point_t); p1 = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); for (j = 0; j < path->count; ++j) { if ((p1->flags & (NVGP_PT_BEVEL | NVGP_PR_INNERBEVEL)) != 0) { dst = nvgp_bevel_join(dst, p0, p1, lw, rw, lu, ru, ctx->fringe_width); } else { nvgp_vset(dst, p1->x + (p1->dmx * lw), p1->y + (p1->dmy * lw), lu,1); dst++; nvgp_vset(dst, p1->x - (p1->dmx * rw), p1->y - (p1->dmy * rw), ru,1); dst++; } p0 = p1; p1 = nvgp_darray_get_ptr(&cache->points, path->first + j + 1, nvgp_point_t); } // Loop it nvgp_vset(dst, verts[0].x, verts[0].y, lu,1); dst++; nvgp_vset(dst, verts[1].x, verts[1].y, ru,1); dst++; path->nstroke = (int)(dst - verts); verts = dst; } else { path->stroke = NULL; path->nstroke = 0; } } return NVGP_OK; } static nvgp_vertex_t* nvgp_butt_cap_start(nvgp_vertex_t* dst, nvgp_point_t* p, float dx, float dy, float w, float d, float aa, float u0, float u1) { float px = p->x - dx*d; float py = p->y - dy*d; float dlx = dy; float dly = -dx; nvgp_vset(dst, px + dlx*w - dx*aa, py + dly*w - dy*aa, u0,0); dst++; nvgp_vset(dst, px - dlx*w - dx*aa, py - dly*w - dy*aa, u1,0); dst++; nvgp_vset(dst, px + dlx*w, py + dly*w, u0,1); dst++; nvgp_vset(dst, px - dlx*w, py - dly*w, u1,1); dst++; return dst; } static nvgp_vertex_t* nvgp_round_cap_start(nvgp_vertex_t* dst, nvgp_point_t* p, float dx, float dy, float w, int ncap, float aa, float u0, float u1) { int32_t i; float px = p->x; float py = p->y; float dlx = dy; float dly = -dx; (void)aa; for (i = 0; i < ncap; i++) { float a = i/(float)(ncap-1)*NVGP_PI; float ax = cosf(a) * w, ay = sinf(a) * w; nvgp_vset(dst, px - dlx*ax - dx*ay, py - dly*ax - dy*ay, u0,1); dst++; nvgp_vset(dst, px, py, 0.5f,1); dst++; } nvgp_vset(dst, px + dlx*w, py + dly*w, u0,1); dst++; nvgp_vset(dst, px - dlx*w, py - dly*w, u1,1); dst++; return dst; } static nvgp_vertex_t* nvgp_round_join(nvgp_vertex_t* dst, nvgp_point_t* p0, nvgp_point_t* p1, float lw, float rw, float lu, float ru, int ncap, float fringe) { int i, n; float dlx0 = p0->dy; float dly0 = -p0->dx; float dlx1 = p1->dy; float dly1 = -p1->dx; (void)fringe; if (p1->flags & NVGP_PT_LEFT) { float lx0,ly0,lx1,ly1,a0,a1; nvgp_choose_bevel(p1->flags & NVGP_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1); a0 = nvgp_atan2f(-dly0, -dlx0); a1 = nvgp_atan2f(-dly1, -dlx1); if (a1 > a0) { a1 -= NVGP_PI*2; } nvgp_vset(dst, lx0, ly0, lu,1); dst++; nvgp_vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++; n = nvgp_clamp((int)ceilf(((a0 - a1) / NVGP_PI) * ncap), 2, ncap); for (i = 0; i < n; i++) { float u = i/(float)(n-1); float a = a0 + u*(a1-a0); float rx = p1->x + nvgp_cosf(a) * rw; float ry = p1->y + nvgp_sinf(a) * rw; nvgp_vset(dst, p1->x, p1->y, 0.5f,1); dst++; nvgp_vset(dst, rx, ry, ru,1); dst++; } nvgp_vset(dst, lx1, ly1, lu,1); dst++; nvgp_vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++; } else { float rx0,ry0,rx1,ry1,a0,a1; nvgp_choose_bevel(p1->flags & NVGP_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1); a0 = nvgp_atan2f(dly0, dlx0); a1 = nvgp_atan2f(dly1, dlx1); if (a1 < a0) { a1 += NVGP_PI*2; } nvgp_vset(dst, p1->x + dlx0*rw, p1->y + dly0*rw, lu,1); dst++; nvgp_vset(dst, rx0, ry0, ru,1); dst++; n = nvgp_clamp((int)ceilf(((a1 - a0) / NVGP_PI) * ncap), 2, ncap); for (i = 0; i < n; i++) { float u = i/(float)(n-1); float a = a0 + u*(a1-a0); float lx = p1->x + nvgp_cosf(a) * lw; float ly = p1->y + nvgp_sinf(a) * lw; nvgp_vset(dst, lx, ly, lu,1); dst++; nvgp_vset(dst, p1->x, p1->y, 0.5f,1); dst++; } nvgp_vset(dst, p1->x + dlx1 * rw, p1->y + dly1 * rw, lu, 1); dst++; nvgp_vset(dst, rx1, ry1, ru, 1); dst++; } return dst; } static nvgp_vertex_t* nvgp_butt_cap_end(nvgp_vertex_t* dst, nvgp_point_t* p, float dx, float dy, float w, float d, float aa, float u0, float u1) { float px = p->x + dx*d; float py = p->y + dy*d; float dlx = dy; float dly = -dx; nvgp_vset(dst, px + dlx*w, py + dly*w, u0,1); dst++; nvgp_vset(dst, px - dlx*w, py - dly*w, u1,1); dst++; nvgp_vset(dst, px + dlx*w + dx*aa, py + dly*w + dy*aa, u0,0); dst++; nvgp_vset(dst, px - dlx*w + dx*aa, py - dly*w + dy*aa, u1,0); dst++; return dst; } static nvgp_vertex_t* nvgp_round_cap_end(nvgp_vertex_t* dst, nvgp_point_t* p, float dx, float dy, float w, int ncap, float aa, float u0, float u1) { int i; float px = p->x; float py = p->y; float dlx = dy; float dly = -dx; (void)aa; nvgp_vset(dst, px + dlx * w, py + dly * w, u0, 1); dst++; nvgp_vset(dst, px - dlx * w, py - dly * w, u1, 1); dst++; for (i = 0; i < ncap; i++) { float a = i/(float)(ncap - 1) * NVGP_PI; float ax = nvgp_cosf(a) * w, ay = nvgp_sinf(a) * w; nvgp_vset(dst, px, py, 0.5f,1); dst++; nvgp_vset(dst, px - dlx * ax + dx * ay, py - dly * ax + dy * ay, u0, 1); dst++; } return dst; } static nvgp_error_t nvgp_expand_stroke(nvgp_context_t* ctx, float w, float fringe, int line_cap, int line_join, float miter_limit) { int cverts, i, j; float aa = fringe;//ctx->fringeWidth; float u0 = 0.0f, u1 = 1.0f; nvgp_vertex_t* dst; nvgp_vertex_t* verts; nvgp_path_cache_t* cache = &ctx->cache; int ncap = nvgp_curve_divs(w, NVGP_PI, ctx->tess_tol); // Calculate divisions per half circle. w += aa * 0.5f; // Disable the gradient used for antialiasing when antialiasing is not used. if (aa == 0.0f) { u0 = 0.5f; u1 = 0.5f; } nvgp_calculate_joins(ctx, w, line_join, miter_limit); // Calculate max vertex usage. cverts = 0; for (i = 0; i < cache->paths.size; i++) { nvgp_path_t* path = nvgp_darray_get_ptr(&cache->paths, i, nvgp_path_t); int loop = (path->closed == 0) ? 0 : 1; if (line_join == NVGP_ROUND) { cverts += (path->count + path->nbevel * (ncap + 2) + 1) * 2; // plus one for loop } else { cverts += (path->count + path->nbevel * 5 + 1) * 2; // plus one for loop } if (loop == 0) { // space for caps if (line_cap == NVGP_ROUND) { cverts += (ncap * 2 + 2) * 2; } else { cverts += (3 + 3) * 2; } } } verts = nvgp_alloc_temp_verts(ctx, cverts); if (verts == NULL) { return NVGP_OOM; } for (i = 0; i < cache->paths.size; i++) { float dx, dy; int32_t s, e, loop, nn, first; nvgp_point_t* p0; nvgp_point_t* p1; nvgp_path_t* path = nvgp_darray_get_ptr(&cache->paths, i, nvgp_path_t); nvgp_point_t* pts = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); path->fill = 0; path->nfill = 0; // Calculate fringe or stroke loop = (path->closed == 0) ? 0 : 1; dst = verts; path->stroke = dst; if (loop) { // Looping p0 = nvgp_darray_get_ptr(&cache->points, path->first + path->count - 1, nvgp_point_t); p1 = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); s = 0; first = path->first; e = path->count; } else { // Add cap p0 = nvgp_darray_get_ptr(&cache->points, path->first, nvgp_point_t); p1 = nvgp_darray_get_ptr(&cache->points, path->first + 1, nvgp_point_t); first = path->first + 1; s = 1; e = path->count - 1; } if (loop == 0) { // Add cap dx = p1->x - p0->x; dy = p1->y - p0->y; nvgp_normalize(&dx, &dy); if (line_cap == NVGP_BUTT) dst = nvgp_butt_cap_start(dst, p0, dx, dy, w, -aa * 0.5f, aa, u0, u1); else if (line_cap == NVGP_BUTT || line_cap == NVGP_SQUARE) dst = nvgp_butt_cap_start(dst, p0, dx, dy, w, w-aa, aa, u0, u1); else if (line_cap == NVGP_ROUND) dst = nvgp_round_cap_start(dst, p0, dx, dy, w, ncap, aa, u0, u1); } for (j = s, nn = 1; j < e; ++j, ++nn) { if ((p1->flags & (NVGP_PT_BEVEL | NVGP_PR_INNERBEVEL)) != 0) { if (line_join == NVGP_ROUND) { dst = nvgp_round_join(dst, p0, p1, w, w, u0, u1, ncap, aa); } else { dst = nvgp_bevel_join(dst, p0, p1, w, w, u0, u1, aa); } } else { nvgp_vset(dst, p1->x + (p1->dmx * w), p1->y + (p1->dmy * w), u0,1); dst++; nvgp_vset(dst, p1->x - (p1->dmx * w), p1->y - (p1->dmy * w), u1,1); dst++; } p0 = p1; p1 = nvgp_darray_get_ptr(&cache->points, first + nn, nvgp_point_t); } if (loop) { // Loop it nvgp_vset(dst, verts[0].x, verts[0].y, u0,1); dst++; nvgp_vset(dst, verts[1].x, verts[1].y, u1,1); dst++; } else { // Add cap dx = p1->x - p0->x; dy = p1->y - p0->y; nvgp_normalize(&dx, &dy); if (line_cap == NVGP_BUTT) dst = nvgp_butt_cap_end(dst, p1, dx, dy, w, -aa * 0.5f, aa, u0, u1); else if (line_cap == NVGP_BUTT || line_cap == NVGP_SQUARE) dst = nvgp_butt_cap_end(dst, p1, dx, dy, w, w - aa, aa, u0, u1); else if (line_cap == NVGP_ROUND) dst = nvgp_round_cap_end(dst, p1, dx, dy, w, ncap, aa, u0, u1); } path->nstroke = (int)(dst - verts); verts = dst; } return 1; } nvgp_error_t nvgp_fill(nvgp_context_t* ctx) { int32_t i; nvgp_paint_t fill_paint; nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); CHECK_OBJECT_IS_NULL(state); fill_paint = state->fill; nvgp_flatten_paths(ctx); if (ctx->vt->get_edge_anti_alias(ctx->vt_ctx) && state->shape_anti_alias) nvgp_expand_fill(ctx, ctx->fringe_width, NVGP_MITER, 2.4f); else nvgp_expand_fill(ctx, 0.0f, NVGP_MITER, 2.4f); fill_paint.inner_color.rgba.a = fill_paint.inner_color.rgba.a * state->alpha / 255; fill_paint.outer_color.rgba.a = fill_paint.outer_color.rgba.a * state->alpha / 255; ctx->vt->render_fill(ctx->vt_ctx, &fill_paint, &state->scissor, ctx->fringe_width, ctx->cache.bounds, &ctx->cache.paths); // Count triangles for (i = 0; i < ctx->cache.paths.size; i++) { const nvgp_path_t* path = nvgp_darray_get_ptr(&ctx->cache.paths, i, nvgp_path_t); ctx->fillTriCount += path->nfill-2; ctx->fillTriCount += path->nstroke-2; ctx->drawCallCount += 2; } return NVGP_OK; } nvgp_error_t nvgp_stroke(nvgp_context_t* ctx) { int32_t i; float scale; float stroke_width; nvgp_paint_t stroke_paint; nvgp_state_t* state = NULL; CHECK_OBJECT_IS_NULL(ctx); state = nvgp_get_state(ctx); CHECK_OBJECT_IS_NULL(state); scale = nvgp_get_average_scale(&state->matrix); stroke_width = nvgp_clamp(state->stroke_width * scale, 0.0f, 200.0f); stroke_paint = state->stroke; if (stroke_width < ctx->fringe_width) { // If the stroke width is less than pixel size, use alpha to emulate coverage. // Since coverage is area, scale by alpha*alpha. float alpha = nvgp_clamp(stroke_width / ctx->fringe_width, 0.0f, 1.0f); stroke_paint.inner_color.rgba.a = (uint8_t)(stroke_paint.inner_color.rgba.a * alpha * alpha); stroke_paint.outer_color.rgba.a = (uint8_t)(stroke_paint.outer_color.rgba.a * alpha * alpha); stroke_width = ctx->fringe_width; } // Apply global alpha stroke_paint.inner_color.rgba.a = stroke_paint.inner_color.rgba.a * state->alpha / 255; stroke_paint.outer_color.rgba.a = stroke_paint.outer_color.rgba.a * state->alpha / 255; nvgp_flatten_paths(ctx); if (ctx->vt->get_edge_anti_alias(ctx->vt_ctx) && state->shape_anti_alias) { nvgp_expand_stroke(ctx, stroke_width * 0.5f, ctx->fringe_width, state->line_cap, state->line_join, state->miter_limit); } else { nvgp_expand_stroke(ctx, stroke_width * 0.5f, 0.0f, state->line_cap, state->line_join, state->miter_limit); } ctx->vt->render_stroke(ctx->vt_ctx, &stroke_paint, &state->scissor, ctx->fringe_width, stroke_width, &ctx->cache.paths); // Count triangles for (i = 0; i < ctx->cache.paths.size; i++) { const nvgp_path_t* path = nvgp_darray_get_ptr(&ctx->cache.paths, i, nvgp_path_t); ctx->strokeTriCount += path->nstroke - 2; ctx->drawCallCount++; } return NVGP_OK; } /***********************************************************************************************/
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\base\nanovg_plus.h
/** * File: nanovg_plus.h * Author: AWTK Develop Team * Brief: nanovg plus head file. * * Copyright (c) 2018 - 2021 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-10-27 Luo Zhiming <luozhiming@zlg.cn> created * */ #ifndef __NANOVG_PLUS_H__ #define __NANOVG_PLUS_H__ #ifdef __cplusplus extern "C" { #endif #include "nanovg_plus_type.h" #include "nvgp_darray.h" #ifndef NVGP_INIT_STATES #define NVGP_INIT_STATES 16 #endif #ifndef NVGP_INIT_COMMANDS_SIZE #define NVGP_INIT_COMMANDS_SIZE 256 #endif #ifndef NVGP_INIT_CACHE_PATHS_SIZE #define NVGP_INIT_CACHE_PATHS_SIZE 16 #endif #ifndef NVGP_INIT_CACHE_POINTS_SIZE #define NVGP_INIT_CACHE_POINTS_SIZE 128 #endif #ifndef NVGP_INIT_CACHE_VERTS_SIZE #define NVGP_INIT_CACHE_VERTS_SIZE 256 #endif typedef enum _nvgp_mode_t { NVGP_MODE_NONE = 0, NVGP_MODE_CPU, NVGP_MODE_GPU, NVGP_MODE_SPECIAL, } nvgp_mode_t; typedef enum _nvgp_line_cap_t { NVGP_BUTT = 0, NVGP_ROUND, NVGP_SQUARE, } nvgp_line_cap_t; typedef enum _nvgp_line_join_t { NVGP_MITER = 0, NVGP_BEVEL, } nvgp_line_join_t; typedef enum _nvgp_texture_t { NVGP_TEXTURE_ALPHA = 1, NVGP_TEXTURE_RGBA = 2, NVGP_TEXTURE_BGRA = 4, NVGP_TEXTURE_RGB = 8, NVGP_TEXTURE_BGR = 16, NVGP_TEXTURE_RGB565 = 32, NVGP_TEXTURE_BGR565 = 64 }nvgp_texture_t; typedef enum _nvgp_draw_image_type_t { NVGP_IMAGE_DRAW_DEFAULT = 0, NVGP_IMAGE_DRAW_REPEAT, } nvgp_draw_image_type_t; typedef enum _nvgp_point_flags_t { NVGP_PT_CORNER = 0x01, NVGP_PT_LEFT = 0x02, NVGP_PT_BEVEL = 0x04, NVGP_PR_INNERBEVEL = 0x08, } nvgp_point_flags_t; typedef enum _nvgp_align_t { // Horizontal align NVGP_ALIGN_LEFT = 1<<0, // Default, align text horizontally to left. NVGP_ALIGN_CENTER = 1<<1, // Align text horizontally to center. NVGP_ALIGN_RIGHT = 1<<2, // Align text horizontally to right. // Vertical align NVGP_ALIGN_TOP = 1<<3, // Align text vertically to top. NVGP_ALIGN_MIDDLE = 1<<4, // Align text vertically to middle. NVGP_ALIGN_BOTTOM = 1<<5, // Align text vertically to bottom. NVGP_ALIGN_BASELINE = 1<<6, // Default, align text vertically to baseline. } nvgp_align_t; typedef enum _nvgp_texture_format_t { NVGP_TEXTURE_FMT_ALPHA = 1, NVGP_TEXTURE_FMT_RGBA = 2, NVGP_TEXTURE_FMT_BGRA = 4, NVGP_TEXTURE_FMT_RGB = 8, NVGP_TEXTURE_FMT_BGR = 16, NVGP_TEXTURE_FMT_RGB565 = 32, NVGP_TEXTURE_FMT_BGR565 = 64 }nvgp_texture_format_t; typedef struct _nvgp_vertex_t { float x,y,u,v; } nvgp_vertex_t; /* * | scale_x skew_x trans_x | * | skew_y scale_y trans_y | * | pers0 pers1 pers2 | * * xform 为 nanovg 的矩阵 * scale_x = xform[0] * scale_y = xform[3] * skew_x = xform[2] * skew_y = xform[1] * trans_x = xform[4] * trans_y = xform[5] */ typedef union _nvgp_matrix_t { float m[3][3]; struct { float scale_x, skew_x, trans_x; float skew_y, scale_y, trans_y; float pers0, pers1, pers2; } mat; } nvgp_matrix_t; typedef struct _nvgp_scissor_t { float extent[2]; nvgp_matrix_t matrix; } nvgp_scissor_t; typedef struct _nvgp_paint_t { int image; float radius; float feather; float extent[2]; float draw_info[2]; float draw_image_rect[4]; nvgp_matrix_t mat; nvgp_color_t inner_color; nvgp_color_t outer_color; nvgp_draw_image_type_t draw_type; } nvgp_paint_t; typedef struct _nvgp_path_t { uint32_t first; uint32_t count; uint32_t closed; uint32_t nbevel; uint32_t nfill; nvgp_vertex_t* fill; uint32_t nstroke; nvgp_vertex_t* stroke; uint32_t winding; uint32_t convex; } nvgp_path_t; typedef struct _nvgp_state_t nvgp_state_t; typedef struct _nvgp_context_t nvgp_context_t; typedef struct _nvgp_vtable_t { nvgp_bool_t (*clear_cache)(void* uptr); int (*find_texture)(void* uptr, const void* data); int (*create_texture)(void* uptr, int type, int w, int h, int stride, int image_flags, const unsigned char* data); nvgp_bool_t (*delete_texture)(void* uptr, int image); nvgp_bool_t (*update_texture)(void* uptr, int image, int x, int y, int w, int h, const unsigned char* data); nvgp_bool_t (*get_texture_size)(void* uptr, int image, int* w, int* h); int (*get_edge_anti_alias)(void* uptr); void (*end_frame)(void* uptr); void (*begin_frame)(void* uptr, float width, float height, float pixel_ratio); void (*set_line_cap)(void* uptr, int line_cap); void (*set_line_join)(void* uptr, int line_join); void (*render_cancel)(void* uptr); void (*render_fill)(void* uptr, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, const float* bounds, const nvgp_darray_t* paths); void (*render_stroke)(void* uptr, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, float stroke_width, const nvgp_darray_t* paths); void (*render_draw_text)(void* uptr, nvgp_paint_t* paint, nvgp_scissor_t* scissor, nvgp_vertex_t* verts, uint32_t nverts); void (*destroy)(void* uptr); } nvgp_vtable_t; /** * @method nvgp_create_by_vt * 创建矢量画布对象 * @annotation ["constructor", "scriptable"] * @param {uint32_t} w 矢量画布宽 * @param {uint32_t} h 矢量画布高 * @param {const nvgp_vtable_t* } vt 矢量画布函数虚构表 * @param {void* } ctx 矢量画布上下文 * * @return {nvgp_context_t*} 成功返回矢量画布对象。 */ nvgp_context_t* nvgp_create_by_vt(uint32_t w, uint32_t h, const nvgp_vtable_t* vt, void* ctx); /** * @method nvgp_create * 创建矢量画布对象 * @annotation ["constructor", "scriptable"] * @param {nvgp_mode_t} nvgp_mode 矢量画布类型 * @param {uint32_t} w 矢量画布宽 * @param {uint32_t} h 矢量画布高 * * @return {nvgp_context_t*} 成功返回矢量画布对象。 */ nvgp_context_t* nvgp_create(nvgp_mode_t nvgp_mode, uint32_t w, uint32_t h); /** * @method nvgp_destroy * 释放矢量画布对象 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * */ void nvgp_destroy(nvgp_context_t* ctx); /** * @method nvgp_reset_curr_state * 刷新当前状态 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * */ void nvgp_reset_curr_state(nvgp_context_t* ctx); /** * @method nvgp_begin_frame_ex * 开始当前帧 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} width 矢量画布宽 * @param {float} height 矢量画布高 * @param {float} pixel_ratio 矢量画布屏幕比例 * @param {nvgp_bool_t} reset 是否重新刷新当前状态 * */ void nvgp_begin_frame_ex(nvgp_context_t *ctx, float width, float height, float pixel_ratio, nvgp_bool_t reset); /** * @method nvgp_begin_frame * 开始当前帧 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} width 矢量画布宽 * @param {float} height 矢量画布高 * @param {float} pixel_ratio 矢量画布屏幕比例 * */ void nvgp_begin_frame(nvgp_context_t *ctx, float width, float height, float pixel_ratio); /** * @method nvgp_end_frame * 结束当前帧 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * */ void nvgp_end_frame(nvgp_context_t *ctx); /** * @method nvgp_save * 保存当前状态 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * */ void nvgp_save(nvgp_context_t *ctx); /** * @method nvgp_restore * 回退上一级状态 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * */ void nvgp_restore(nvgp_context_t *ctx); /** * @method nvgp_get_image_size * 获取贴图宽高 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {int} image 贴图的数据长度 * @param {int*} w 返回贴图的宽度 * @param {int*} h 返回贴图的高度 * */ void nvgp_get_image_size(nvgp_context_t* ctx, int image, int* w, int* h); /** * @method nvgp_create_image_rgba * 创建贴图(rgba格式) * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {int} w 贴图的宽度 * @param {int} h 贴图的高度 * @param {int} imageFlags 贴图的属性 * @param {const unsigned char*} rgba_data 贴图的数据 * * @return {int32_t} 成功返回贴图 id。 */ int32_t nvgp_create_image_rgba(nvgp_context_t* ctx, int w, int h, int imageFlags, const unsigned char* rgba_data); /** * @method nvgp_update_image_rgba * 更新贴图数据(rgba格式) * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {int} image 贴图的数据长度 * @param {const unsigned char*} rgba_data 贴图的数据 * */ void nvgp_update_image_rgba(nvgp_context_t* ctx, int image, const unsigned char* rgba_data); /** * @method nvgp_create_font_mem * 创建新的字库 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {const char*} name 字库的名字 * @param {unsigned char*} data 字库的数据 * @param {int} ndata 字库的数据长度 * @param {nvgp_bool_t} freeData 是否需要自动释放 * * @return {int} 成功返回 字库 id。 */ int nvgp_create_font_mem(nvgp_context_t* ctx, const char* name, unsigned char* data, int ndata, nvgp_bool_t freeData); /** * @method nvgp_find_font * 查找字库 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {const char*} name 查找对应名字的字库 * * @return {int} 成功返回 字库 id。 */ int nvgp_find_font(nvgp_context_t* ctx, const char* name); /** * @method nvgp_delete_font_by_name * 删除字库 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {const char*} name 删除对应名字的字库,如果为 NULL 则删除全部字库。 * */ void nvgp_delete_font_by_name(nvgp_context_t* ctx, const char* name); /** * @method nvgp_delete_image * 删除贴图 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {int} image 贴图 id * * @return {void} 无。 */ void nvgp_delete_image(nvgp_context_t* ctx, int image); /** * @method nvgp_clear_cache * 清除矢量画布临时缓存 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * * @return {nvgp_bool_t} 成功返回 TRUE。 */ nvgp_bool_t nvgp_clear_cache(nvgp_context_t* ctx); /** * @method nvgp_begin_path * 开始新一条线段 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * * @return {void} 无。 */ void nvgp_begin_path(nvgp_context_t *ctx); /** * @method nvgp_close_path * 闭合线段 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * * @return {void} 无。 */ void nvgp_close_path(nvgp_context_t *ctx); /** * @method nvgp_move_to * 设置线段起始点 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x x坐标 * @param {float} y y坐标 * * @return {void} 无。 */ void nvgp_move_to(nvgp_context_t *ctx, float x, float y); /** * @method nvgp_line_to * 设置连接点 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x x坐标 * @param {float} y y坐标 * * @return {void} 无。 */ void nvgp_line_to(nvgp_context_t *ctx, float x, float y); /** * @method nvgp_bezier_to * 设置三阶贝塞尔曲线路径 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} c1x 锚点1 x坐标 * @param {float} c1y 锚点1 y坐标 * @param {float} c2x 锚点2 x坐标 * @param {float} c2y 锚点2 y坐标 * @param {float} x 终点x坐标 * @param {float} y 终点y坐标 * * @return {void} 无。 */ void nvgp_bezier_to(nvgp_context_t *ctx, float c1x, float c1y, float c2x, float c2y, float x, float y); /** * @method nvgp_quad_to * 设置二阶贝塞尔曲线路径 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} cx 锚点 x坐标 * @param {float} cy 锚点 y坐标 * @param {float} x x 终点x坐标 * @param {float} y y 终点y坐标 * * @return {void} 无。 */ void nvgp_quad_to(nvgp_context_t *ctx, float cx, float cy, float x, float y); /** * @method nvgp_arc * 设置圆弧路径 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} cx 圆心 x 坐标 * @param {float} cy 圆心 y 坐标 * @param {float} r 半径 * @param {float} a0 始点角度(单位弧度) * @param {float} a1 终点角度(单位弧度) * @param {nvgp_bool_t} ccw 是否为顺序针 * * @return {void} 无。 */ void nvgp_arc(nvgp_context_t *ctx, float cx, float cy, float r, float a0, float a1, nvgp_bool_t ccw); /** * @method nvgp_arc_to * 设置圆弧路径 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x1 始点 x 坐标 * @param {float} y1 始点 y 坐标 * @param {float} x2 终点 x 坐标 * @param {float} y2 终点 y 坐标 * @param {float} radius 半径 * * @return {void} 无。 */ void nvgp_arc_to(nvgp_context_t *ctx, float x1, float y1, float x2, float y2, float radius); /** * @method nvgp_rect * 设置矩形路径 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x x 坐标 * @param {float} y y 坐标 * @param {float} w 宽度 * @param {float} h 高度 * * @return {void} 无。 */ void nvgp_rect(nvgp_context_t *ctx, float x, float y, float w, float h); /** * @method nvgp_rounded_rect_varying * 设置圆角矩形路径 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x x 坐标 * @param {float} y y 坐标 * @param {float} w 宽度 * @param {float} h 高度 * @param {float} rad_top_left 左上角圆角半径 * @param {float} rad_top_right 右上角圆角半径 * @param {float} rad_bottom_right 右下角圆角半径 * @param {float} rad_bottom_left 左下角圆角半径 * * @return {void} 无。 */ void nvgp_rounded_rect_varying(nvgp_context_t *ctx, float x, float y, float w, float h, float rad_top_left, float rad_top_right, float rad_bottom_right, float rad_bottom_left); /** * @method nvgp_rounded_rect * 设置圆角矩形路径 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x x 坐标 * @param {float} y y 坐标 * @param {float} w 宽度 * @param {float} h 高度 * @param {float} r 圆角半径 * * @return {void} 无。 */ void nvgp_rounded_rect(nvgp_context_t *ctx, float x, float y, float w, float h, float r); /** * @method nvgp_ellipse * 设置椭圆路径 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} cx 圆心 x * @param {float} cy 圆心 y * @param {float} rx x 轴半径 * @param {float} ry y 轴半径 * * @return {void} 成功返回 NVGP_OK。 */ void nvgp_ellipse(nvgp_context_t *ctx, float cx, float cy, float rx, float ry); /** * @method nvgp_circle * 设置圆路径 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} cx 圆心 x * @param {float} cy 圆心 y * @param {float} r 半径 * * @return {void} 成功返回 NVGP_OK。 */ void nvgp_circle(nvgp_context_t *ctx, float cx, float cy, float r); /** * @method nvgp_translate * 偏移 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x 偏移 x * @param {float} y 偏移 y * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_translate(nvgp_context_t *ctx, float x, float y); /** * @method nvgp_rotate * 旋转(单位为弧度) * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} angle 旋转弧度 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_rotate(nvgp_context_t *ctx, float angle); /** * @method nvgp_scale * 缩放 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x 缩放 x * @param {float} y 缩放 y * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_scale(nvgp_context_t *ctx, float x, float y); /** * @method nvgp_reset_transform * 重置当前旋转矩阵 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_reset_transform(nvgp_context_t *ctx); /** * @method nvgp_transform * 叠加旋转矩阵 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} a 缩放 x * @param {float} b 拉伸 y * @param {float} c 拉伸 x * @param {float} d 缩放 y * @param {float} e 偏移 x * @param {float} f 偏移 y * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_transform(nvgp_context_t *ctx, float a, float b, float c, float d, float e, float f); /** * @method nvgp_scissor * 设置当前裁剪区 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x 裁剪区 x * @param {float} y 裁剪区 y * @param {float} w 裁剪区 w * @param {float} h 裁剪区 h * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_scissor(nvgp_context_t* ctx, float x, float y, float w, float h); /** * @method nvgp_intersect_scissor * 叠加裁剪区,同时返回叠加后的裁剪区 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float*} x 设置裁剪区 x,同时返回新的裁剪区 x * @param {float*} y 设置裁剪区 y, 同时返回裁剪区 y * @param {float*} w 设置裁剪区 w,同时返回裁剪区 w * @param {float*} h 设置裁剪区 h,同时返回裁剪区 h * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_intersect_scissor(nvgp_context_t* ctx, float* x, float* y, float* w, float* h); /** * @method nvgp_get_curr_clip_rect * 获取当前裁剪区 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float*} x 返回裁剪区 x * @param {float*} y 返回裁剪区 y * @param {float*} w 返回裁剪区 w * @param {float*} h 返回裁剪区 h * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_get_curr_clip_rect(nvgp_context_t* ctx, float* x, float* y, float* w, float* h); /** * @method nvgp_text_metrics * 设置字符串基线等信息 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float*} ascender 上边界 * @param {float*} descender 下边界 * @param {float*} lineh 基线 * * @return {void} 无。 */ void nvgp_text_metrics(nvgp_context_t* ctx, float* ascender, float* descender, float* lineh); /** * @method nvgp_text_bounds * 获取字符串宽度 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x 坐标 x * @param {float} y 坐标 y * @param {const char*} string 字符串开头 * @param {const char*} end 字符串结尾 * @param {float*} bounds 返回一个字符串矩形区域(是一个长度为四的数组) * * @return {float} 字符宽度。 */ float nvgp_text_bounds(nvgp_context_t* ctx, float x, float y, const char* string, const char* end, float* bounds); /** * @method nvgp_text * 渲染字体 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} x 坐标 x * @param {float} y 坐标 y * @param {const char*} string 字符串开头 * @param {const char*} end 字符串结尾 * * @return {float} 。 */ float nvgp_text(nvgp_context_t* ctx, float x, float y, const char* string, const char* end); /** * @method nvgp_set_stroke_color * 设置线颜色 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {nvgp_color_t} color 线颜色 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_stroke_color(nvgp_context_t *ctx, nvgp_color_t color); /** * @method nvgp_set_fill_color * 设置填充色 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {nvgp_color_t} color 填充色 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_fill_color(nvgp_context_t *ctx, nvgp_color_t color); /** * @method nvgp_set_shape_anti_alias * 设置抗锯齿 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {nvgp_bool_t} enabled 是否启用抗锯齿 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_shape_anti_alias(nvgp_context_t* ctx, nvgp_bool_t enabled); /** * @method nvgp_set_miter_limit * 设置线斜面 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} limit limit * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_miter_limit(nvgp_context_t *ctx, float limit); /** * @method nvgp_set_line_cap * 设置线帽 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {nvgp_line_cap_t} cap 线帽 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_line_cap(nvgp_context_t* ctx, nvgp_line_cap_t cap); /** * @method nvgp_set_line_join * 设置线连接处样式 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {nvgp_line_join_t} join 线连接处样式 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_line_join(nvgp_context_t* ctx, nvgp_line_join_t join); /** * @method nvgp_set_stroke_width * 设置线宽 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} stroke_width 线宽 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_stroke_width(nvgp_context_t *ctx, float stroke_width); /** * @method nvgp_set_global_alpha * 设置全局透明度 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {uint8_t} alpha 全局透明度 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_global_alpha(nvgp_context_t *ctx, uint8_t alpha); /** * @method nvgp_text_align * 设置字对齐 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {int32_t} align 对齐枚举 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_text_align(nvgp_context_t* ctx, int32_t align); /** * @method nvgp_font_face_id * 设置字库id * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {int32_t} font_id 字库id * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_font_face_id(nvgp_context_t* ctx, int32_t font_id); /** * @method nvgp_set_font_size * 设置字号(单位px) * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} font_size 字号(单位px) * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_font_size(nvgp_context_t *ctx, float font_size); /** * @method nvgp_set_fill_paint * 设置填充画笔 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {nvgp_paint_t} paint 画笔 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_fill_paint(nvgp_context_t* ctx, nvgp_paint_t paint); /** * @method nvgp_set_stroke_paint * 设置画线画笔 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {nvgp_paint_t} paint 画笔 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_set_stroke_paint(nvgp_context_t* ctx, nvgp_paint_t paint); /** * @method nvgp_linear_gradient * 创建直线渐变画笔 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} sx 起始坐标x * @param {float} sy 起始坐标y * @param {float} ex 结束坐标x * @param {float} ey 结束坐标y * @param {nvgp_color_t} icol 起始颜色 * @param {nvgp_color_t} ocol 结束颜色 * * @return {nvgp_paint_t} 成功返回画笔。 */ nvgp_paint_t nvgp_linear_gradient(nvgp_context_t* ctx, float sx, float sy, float ex, float ey, nvgp_color_t icol, nvgp_color_t ocol); /** * @method nvgp_radial_gradient * 创建圆形渐变画笔 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} cx 渐变中心坐标 * @param {float} cy 渐变中心坐标 * @param {float} inr 内半径 * @param {float} outr 外半径 * @param {nvgp_color_t} icol 内半径颜色 * @param {nvgp_color_t} ocol 外半径颜色 * * @return {nvgp_paint_t} 成功返回画笔。 */ nvgp_paint_t nvgp_radial_gradient(nvgp_context_t* ctx, float cx, float cy, float inr, float outr, nvgp_color_t icol, nvgp_color_t ocol); /** * @method nvgp_image_pattern * 创建贴图画笔 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} cx 截取原图中心坐标 * @param {float} cy 截取原图中心坐标 * @param {float} w 截取原图宽度 * @param {float} h 截取原图高度 * @param {float} angle 旋转角度 * @param {int} image 贴图 id * @param {uint8_t} alpha 透明度 * * @return {nvgp_paint_t} 成功返回画笔。 */ nvgp_paint_t nvgp_image_pattern(nvgp_context_t* ctx, float cx, float cy, float w, float h, float angle, int image, uint8_t alpha); /** * @method nvgp_image_pattern_repeat * 创建重复贴图画笔 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * @param {float} sx 截取原图 x 坐标 * @param {float} sy 截取原图 y 坐标 * @param {float} sw 截取原图宽度 * @param {float} sh 截取原图高度 * @param {float} dw 目标宽度 * @param {float} dh 目标高度 * @param {float} image_w 原图宽度 * @param {float} image_h 原图高度 * @param {float} angle 旋转角度 * @param {int} image 贴图 id * @param {uint8_t} alpha 透明度 * * @return {nvgp_paint_t} 成功返回画笔。 */ nvgp_paint_t nvgp_image_pattern_repeat(nvgp_context_t* ctx, float sx, float sy, float sw, float sh, float dw, float dh, float image_w, float image_h, float angle, int image, uint8_t alpha); /** * @method nvgp_fill * 填充颜色 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_fill(nvgp_context_t* ctx); /** * @method nvgp_stroke * 画线 * @annotation ["constructor", "scriptable"] * @param {nvgp_context_t*} ctx 矢量画布上下文 * * @return {nvgp_error_t} 成功返回 NVGP_OK。 */ nvgp_error_t nvgp_stroke(nvgp_context_t* ctx); /* private */ void* nvgp_get_vt_ctx(nvgp_context_t* ctx); void nvgp_transform_scale(nvgp_matrix_t* mat, float sx, float sy); void nvgp_transform_translate(nvgp_matrix_t* mat, float tx, float ty); nvgp_matrix_t* nvgp_transform_multiply_to_t(nvgp_matrix_t* t, nvgp_matrix_t* s); nvgp_bool_t nvgp_transform_inverse(nvgp_matrix_t* inv, const nvgp_matrix_t* t); #ifdef __cplusplus } #endif #endif
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\base\nanovg_plus_type.h
/** * File: nanovg_plus_type.c * Author: AWTK Develop Team * Brief: nanovg plus base type. * * Copyright (c) 2018 - 2021 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-10-27 Luo Zhiming <luozhiming@zlg.cn> created * */ #ifndef __NANOVG_PLUS_TYPE_H__ #define __NANOVG_PLUS_TYPE_H__ #ifdef __cplusplus extern "C" { #endif #include <math.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #define NVGP_PI 3.14159265358979323846264338327f #define NVGP_KAPPA90 0.5522847493f // Length proportional to radius of a cubic bezier handle for 90deg arcs. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4201) // nonstandard extension used : nameless struct/union #endif typedef union _nvgp_color_t { uint32_t color; struct { uint8_t r; uint8_t g; uint8_t b; uint8_t a; } rgba; } nvgp_color_t; typedef enum _nvgp_error_t { NVGP_OK = 0, NVGP_BAD_PARAMS, NVGP_FAIL, NVGP_OOM, } nvgp_error_t; #define nvgp_sqrtf(a) sqrtf(a) #define nvgp_modf(a, b) fmodf(a, b) #define nvgp_sinf(a) sinf(a) #define nvgp_cosf(a) cosf(a) #define nvgp_tanf(a) tanf(a) #define nvgp_acosf(a) acosf(a) #define nvgp_atan2f(a, b) atan2f(a, b) #define nvgp_abs(a) ((a) < (0) ? (-(a)) : (a)) #define nvgp_min(a, b) ((a) < (b) ? (a) : (b)) #define nvgp_max(a, b) ((a) > (b) ? (a) : (b)) #define nvgp_signf(a) ((a) >= 0.0f ? 1.0f : -1.0f) #define nvgp_cross(dx0, dy0, dx1, dy1) (dx1) * (dy0) - (dx0) * (dy1) #define nvgp_clamp(a, mn, mx) (a) < (mn) ? (mn) : ((a) > (mx) ? (mx) : (a)) #define nvgp_get_arrary_size(arr) (sizeof(arr) / sizeof(0[(arr)])) #ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void *)0) #endif #endif #ifndef FALSE #define FALSE 0u #endif #ifndef TRUE #define TRUE 1u #endif #ifndef nvgp_bool_t typedef uint8_t nvgp_bool_t; #endif #ifndef NVGP_MALLOC #define NVGP_MALLOC(size) malloc(size) #endif #ifndef NVGP_CALLOC #define NVGP_CALLOC(nmemb, size) calloc(nmemb, size) #endif #ifndef NVGP_REALLOC #define NVGP_REALLOC(p, size) realloc(p, size) #endif #ifndef NVGP_FREE #define NVGP_FREE(p) free(p); p = NULL; #endif #ifndef NVGP_MEMSET #define NVGP_MEMSET(ptr, data, n) memset(ptr, data, n) #endif #ifndef NVGP_MEMCPY #define NVGP_MEMCPY(dst, src, n) memcpy(dst, src, n) #endif #ifndef NVGP_MEMCMP #define NVGP_MEMCMP(dst, src, n) memcmp(dst, src, n) #endif #define NVGP_ZALLOC(type) (type*)NVGP_CALLOC(1, sizeof(type)) #define NVGP_ZALLOCN(type, n) (type*)NVGP_CALLOC(n, sizeof(type)) #define NVGP_REALLOCT(type, p, n) (type*)NVGP_REALLOC(p, (n) * sizeof(type)) #ifndef NVGP_PRINTF #if defined(_MSC_VER) #define NVGP_PRINTF(format, ...) printf(format, __VA_ARGS__); #elif defined(__GNUC__) #define NVGP_PRINTF(format, args...) printf(format, ##args) #else #define NVGP_PRINTF(format, ...) #endif #endif inline static nvgp_color_t nvgp_color_init(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { nvgp_color_t c; c.rgba.r = r; c.rgba.g = g; c.rgba.b = b; c.rgba.a = a; return c; } #ifdef __cplusplus } #endif #endif
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\base\nvgp_darray.c
/** * File: nvgp_darray.c * Author: AWTK Develop Team * Brief: nanovg darry. * * Copyright (c) 2018 - 2021 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-10-27 Luo Zhiming <luozhiming@zlg.cn> created * */ #include "nvgp_darray.h" nvgp_darray_t* nvgp_darray_init(nvgp_darray_t* darray, uint32_t capacity, uint32_t data_type_size) { if (darray->elms != NULL) { return NULL; } darray->size = 0; darray->data_type_size = 0; darray->capacity = capacity; darray->elms = NVGP_ZALLOCN(void*, capacity); if (data_type_size > 0) { uint32_t i = 0; darray->data_type_size = data_type_size; for (i = 0; i < capacity; i++) { darray->elms[i] = NVGP_MALLOC(data_type_size); } } return darray; } void nvgp_darray_deinit(nvgp_darray_t* darray) { if (darray == NULL) { return; } if (darray->elms != NULL) { if (darray->data_type_size > 0) { for (uint32_t i = 0; i < darray->capacity; i++) { NVGP_FREE(darray->elms[i]); } } NVGP_FREE(darray->elms); } NVGP_MEMSET(darray, 0x0, sizeof(nvgp_darray_t)); } nvgp_darray_t* nvgp_darray_create(uint32_t capacity, uint32_t data_type_size) { nvgp_darray_t* darray = NVGP_ZALLOC(nvgp_darray_t); if (darray == NULL) { return NULL; } NVGP_MEMSET(darray, 0x0, sizeof(nvgp_darray_t)); return nvgp_darray_init(darray, capacity, data_type_size); } void nvgp_darray_destroy(nvgp_darray_t* darray) { if (darray == NULL) { return; } nvgp_darray_deinit(darray); NVGP_FREE(darray); } void* nvgp_darray_get_empty_data_by_tail(nvgp_darray_t* darray) { if (darray == NULL) { return NULL; } if (darray->size >= darray->capacity) { uint32_t n = nvgp_max(darray->size + 1, 4) + darray->capacity / 2; darray->elms = NVGP_REALLOCT(void*, darray->elms, n); if (darray->elms == NULL) { return NULL; } darray->capacity = n; if (darray->data_type_size > 0) { for (uint32_t i = darray->size; i < darray->capacity; i++) { darray->elms[i] = NVGP_MALLOC(darray->data_type_size); } } else { for (uint32_t i = darray->size; i < darray->capacity; i++) { darray->elms[i] = NULL; } } } return darray->elms[darray->size++]; } void* nvgp_darray_get_empty_data_ptr_by_tail(nvgp_darray_t* darray) { if (darray == NULL && darray->data_type_size == 0) { return NULL; } if (darray->size >= darray->capacity) { uint32_t n = nvgp_max(darray->size + 1, 4) + darray->capacity / 2; darray->elms = NVGP_REALLOCT(void*, darray->elms, n); if (darray->elms == NULL) { return NULL; } darray->capacity = n; for (uint32_t i = darray->size; i < darray->capacity; i++) { darray->elms[i] = NULL; } } return &(darray->elms[darray->size++]); } nvgp_error_t nvgp_darray_push(nvgp_darray_t* darray, void* data) { if (darray == NULL || data == NULL) { return NVGP_BAD_PARAMS; } if (darray->size >= darray->capacity) { uint32_t n = nvgp_max(darray->size + 1, 4) + darray->capacity / 2; darray->elms = NVGP_REALLOCT(void*, darray->elms, n); if (darray->elms == NULL) { return NVGP_OOM; } darray->capacity = n; if (darray->data_type_size > 0) { for (uint32_t i = darray->size; i < darray->capacity; i++) { darray->elms[i] = NVGP_MALLOC(darray->data_type_size); } } else { for (uint32_t i = darray->size; i < darray->capacity; i++) { darray->elms[i] = NULL; } } } if (darray->data_type_size > 0) { NVGP_MEMCPY(&(darray->elms[darray->size++]), data, darray->data_type_size); } else { darray->elms[darray->size++] = data; } return NVGP_OK; } nvgp_error_t nvgp_darray_pop(nvgp_darray_t* darray) { int32_t n = 0; if (darray == NULL) { return NVGP_BAD_PARAMS; } n = darray->size - 1; if (0 <= n && n < darray->capacity) { NVGP_MEMSET(darray->elms[--darray->size], 0x0, darray->data_type_size); return NVGP_OK; } return NVGP_FAIL; } static void nvgp_darray_memset_elms(void* data, void* ctx) { uint32_t data_type_size = *(uint32_t*)ctx; NVGP_MEMSET(data, 0x0, data_type_size); } nvgp_error_t nvgp_darray_remove(nvgp_darray_t* darray, uint32_t index, nvgp_destroy_t destroy_func, void* ctx) { int32_t i = 0; int32_t size = 0; if (darray == NULL || darray->elms == NULL || darray->size <= index || !(darray->data_type_size > 0 && destroy_func == NULL)) { return NVGP_BAD_PARAMS; } if (darray->data_type_size == 0 && destroy_func != NULL) { destroy_func(darray->elms[index], ctx); } if (darray->data_type_size == 0) { for (size = darray->size - 1, i = index; i < size; i++) { darray->elms[i] = darray->elms[i + 1]; } darray->elms[i] = NULL; } else { for (size = darray->size - 1, i = index; i < size; i++) { NVGP_MEMCPY(darray->elms[i], darray->elms[i + 1], darray->data_type_size); } NVGP_MEMSET(darray->elms[i], 0x0, darray->data_type_size); } darray->size--; return NVGP_OK; } nvgp_error_t nvgp_darray_clear(nvgp_darray_t* darray) { return nvgp_darray_clear_by_destroy_function(darray, nvgp_darray_memset_elms, &darray->data_type_size); } nvgp_error_t nvgp_darray_clear_by_destroy_function(nvgp_darray_t* darray, nvgp_destroy_t destroy_func, void* ctx) { int32_t i = 0; if (darray == NULL || darray->elms == NULL || destroy_func == NULL) { return NVGP_BAD_PARAMS; } for (i = 0; i < darray->size; i++) { destroy_func(darray->elms[i], ctx); } if (darray->data_type_size == 0) { for (i = 0; i < darray->size; i++) { darray->elms[i] = NULL; } } darray->size = 0; return NVGP_OK; } nvgp_error_t nvgp_darray_remove_empty_cache(nvgp_darray_t* darray) { int32_t n = 0; if (darray == NULL || darray->elms == NULL) { return NVGP_BAD_PARAMS; } n = darray->capacity - darray->size; if (n > 0) { if (darray->data_type_size > 0) { for (uint32_t i = darray->size; i < darray->capacity; i++) { NVGP_FREE(darray->elms[i]); darray->elms[i] = NULL; } } darray->elms = NVGP_REALLOCT(void*, darray->elms, n); darray->capacity = n; } return NVGP_OK; } nvgp_error_t nvgp_darray_reverse(nvgp_darray_t* darray) { int32_t i = 0, j = 0; void* tmp = NULL; if (darray == NULL || darray->elms == NULL) { return NVGP_BAD_PARAMS; } j = darray->size - 1; while (i < j) { tmp = darray->elms[i]; darray->elms[i] = darray->elms[j]; darray->elms[j] = tmp; i++; j--; } return NVGP_OK; }
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\base\nvgp_darray.h
/** * File: nvgp_darray.h * Author: AWTK Develop Team * Brief: nanovg darry. * * Copyright (c) 2018 - 2021 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-10-27 Luo Zhiming <luozhiming@zlg.cn> created * */ #ifndef __NANOVG_PLUS_DARRAY_H__ #define __NANOVG_PLUS_DARRAY_H__ #ifdef __cplusplus extern "C" { #endif #include "nanovg_plus_type.h" typedef struct _nvgp_darray_t { uint32_t size; uint32_t capacity; uint32_t data_type_size; void** elms; } nvgp_darray_t; typedef void (*nvgp_destroy_t)(void* data, void* ctx); void nvgp_darray_destroy(nvgp_darray_t* darray); nvgp_darray_t* nvgp_darray_create(uint32_t capacity, uint32_t data_type_size); void nvgp_darray_deinit(nvgp_darray_t* darray); nvgp_darray_t* nvgp_darray_init(nvgp_darray_t* darray, uint32_t capacity, uint32_t data_type_size); void* nvgp_darray_get_empty_data_by_tail(nvgp_darray_t* darray); void* nvgp_darray_get_empty_data_ptr_by_tail(nvgp_darray_t* darray); nvgp_error_t nvgp_darray_push(nvgp_darray_t* darray, void* data); nvgp_error_t nvgp_darray_pop(nvgp_darray_t* darray); nvgp_error_t nvgp_darray_remove(nvgp_darray_t* darray, uint32_t index, nvgp_destroy_t destroy_func, void* ctx); nvgp_error_t nvgp_darray_clear(nvgp_darray_t* darray); nvgp_error_t nvgp_darray_clear_by_destroy_function(nvgp_darray_t* darray, nvgp_destroy_t destroy_func, void* ctx); nvgp_error_t nvgp_darray_remove_empty_cache(nvgp_darray_t* darray); nvgp_error_t nvgp_darray_reverse(nvgp_darray_t* darray); #define nvgp_darray_get_empty_by_tail(darray, type) ((type*)(nvgp_darray_get_empty_data_by_tail(darray))) #define nvgp_darray_get_empty_ptr_by_tail(darray, type) ((type*)(nvgp_darray_get_empty_data_ptr_by_tail(darray))) #define nvgp_darray_get_ptr(darray, index, type) (((darray) == NULL || (darray)->size <= (index)) ? NULL : (type*)((darray)->elms[index])) /* 只能在指针内存大小等于 type 的内存大小才可以使用 */ #define nvgp_darray_get(darray, index, type) (((darray) == NULL || (darray)->size <= (index)) ? 0 : (assert(sizeof(void*) == sizeof(type*)), *(type*)(&(darray)->elms[index]))) /* 只能在指针内存大小等于 type 的内存大小才可以使用 */ #define nvgp_darray_memcpy(darray, type, dst, n) { \ uint32_t i = 0; \ assert(sizeof(void*) == sizeof(type*)); \ if ((darray) == NULL) { \ return; \ } \ for (i = 0; i < (n); i++) { \ type* d = (type*)nvgp_darray_get_empty_data_ptr_by_tail(darray); \ NVGP_MEMCPY(d, (dst) + i, sizeof(void*)); \ } \ } \ #ifdef __cplusplus } #endif #endif
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\base\stb_truetype.h
// stb_truetype.h - v1.24 - public domain // authored from 2009-2020 by Sean Barrett / RAD Game Tools // // ======================================================================= // // NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES // // This library does no range checking of the offsets found in the file, // meaning an attacker can use it to read arbitrary memory. // // ======================================================================= // // This library processes TrueType files: // parse files // extract glyph metrics // extract glyph shapes // render glyphs to one-channel bitmaps with antialiasing (box filter) // render glyphs to one-channel SDF bitmaps (signed-distance field/function) // // Todo: // non-MS cmaps // crashproof on bad data // hinting? (no longer patented) // cleartype-style AA? // optimize: use simple memory allocator for intermediates // optimize: build edge-list directly from curves // optimize: rasterize directly from curves? // // ADDITIONAL CONTRIBUTORS // // Mikko Mononen: compound shape support, more cmap formats // Tor Andersson: kerning, subpixel rendering // Dougall Johnson: OpenType / Type 2 font handling // Daniel Ribeiro Maciel: basic GPOS-based kerning // // Misc other: // Ryan Gordon // Simon Glass // github:IntellectualKitty // Imanol Celaya // Daniel Ribeiro Maciel // // Bug/warning reports/fixes: // "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe // Cass Everitt Martins Mozeiko github:aloucks // stoiko (Haemimont Games) Cap Petschulat github:oyvindjam // Brian Hook Omar Cornut github:vassvik // Walter van Niftrik Ryan Griege // David Gow Peter LaValle // David Given Sergey Popov // Ivan-Assen Ivanov Giumo X. Clanjor // Anthony Pesch Higor Euripedes // Johan Duparc Thomas Fields // Hou Qiming Derek Vinyard // Rob Loach Cort Stratton // Kenney Phillis Jr. Brian Costabile // Ken Voskuil (kaesve) // // VERSION HISTORY // // 1.24 (2020-02-05) fix warning // 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) // 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined // 1.21 (2019-02-25) fix warning // 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod // 1.18 (2018-01-29) add missing function // 1.17 (2017-07-23) make more arguments const; doc fix // 1.16 (2017-07-12) SDF support // 1.15 (2017-03-03) make more arguments const // 1.14 (2017-01-16) num-fonts-in-TTC function // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual // 1.11 (2016-04-02) fix unused-variable warning // 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; // variant PackFontRanges to pack and render in separate phases; // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); // fixed an assert() bug in the new rasterizer // replace assert() with STBTT_assert() in new rasterizer // // Full history can be found at the end of this file. // // LICENSE // // See end of file for license information. // // USAGE // // Include this file in whatever places need to refer to it. In ONE C/C++ // file, write: // #define STB_TRUETYPE_IMPLEMENTATION // before the #include of this file. This expands out the actual // implementation into that C/C++ file. // // To make the implementation private to the file that generates the implementation, // #define STBTT_STATIC // // Simple 3D API (don't ship this, but it's fine for tools and quick start) // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture // stbtt_GetBakedQuad() -- compute quad to draw for a given char // // Improved 3D API (more shippable): // #include "stb_rect_pack.h" -- optional, but you really want it // stbtt_PackBegin() // stbtt_PackSetOversampling() -- for improved quality on small fonts // stbtt_PackFontRanges() -- pack and renders // stbtt_PackEnd() // stbtt_GetPackedQuad() // // "Load" a font file from a memory buffer (you have to keep the buffer loaded) // stbtt_InitFont() // stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections // stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections // // Render a unicode codepoint to a bitmap // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be // // Character advance/positioning // stbtt_GetCodepointHMetrics() // stbtt_GetFontVMetrics() // stbtt_GetFontVMetricsOS2() // stbtt_GetCodepointKernAdvance() // // Starting with version 1.06, the rasterizer was replaced with a new, // faster and generally-more-precise rasterizer. The new rasterizer more // accurately measures pixel coverage for anti-aliasing, except in the case // where multiple shapes overlap, in which case it overestimates the AA pixel // coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If // this turns out to be a problem, you can re-enable the old rasterizer with // #define STBTT_RASTERIZER_VERSION 1 // which will incur about a 15% speed hit. // // ADDITIONAL DOCUMENTATION // // Immediately after this block comment are a series of sample programs. // // After the sample programs is the "header file" section. This section // includes documentation for each API function. // // Some important concepts to understand to use this library: // // Codepoint // Characters are defined by unicode codepoints, e.g. 65 is // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is // the hiragana for "ma". // // Glyph // A visual character shape (every codepoint is rendered as // some glyph) // // Glyph index // A font-specific integer ID representing a glyph // // Baseline // Glyph shapes are defined relative to a baseline, which is the // bottom of uppercase characters. Characters extend both above // and below the baseline. // // Current Point // As you draw text to the screen, you keep track of a "current point" // which is the origin of each character. The current point's vertical // position is the baseline. Even "baked fonts" use this model. // // Vertical Font Metrics // The vertical qualities of the font, used to vertically position // and space the characters. See docs for stbtt_GetFontVMetrics. // // Font Size in Pixels or Points // The preferred interface for specifying font sizes in stb_truetype // is to specify how tall the font's vertical extent should be in pixels. // If that sounds good enough, skip the next paragraph. // // Most font APIs instead use "points", which are a common typographic // measurement for describing font size, defined as 72 points per inch. // stb_truetype provides a point API for compatibility. However, true // "per inch" conventions don't make much sense on computer displays // since different monitors have different number of pixels per // inch. For example, Windows traditionally uses a convention that // there are 96 pixels per inch, thus making 'inch' measurements have // nothing to do with inches, and thus effectively defining a point to // be 1.333 pixels. Additionally, the TrueType font data provides // an explicit scale factor to scale a given font's glyphs to points, // but the author has observed that this scale factor is often wrong // for non-commercial fonts, thus making fonts scaled in points // according to the TrueType spec incoherently sized in practice. // // DETAILED USAGE: // // Scale: // Select how high you want the font to be, in points or pixels. // Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute // a scale factor SF that will be used by all other functions. // // Baseline: // You need to select a y-coordinate that is the baseline of where // your text will appear. Call GetFontBoundingBox to get the baseline-relative // bounding box for all characters. SF*-y0 will be the distance in pixels // that the worst-case character could extend above the baseline, so if // you want the top edge of characters to appear at the top of the // screen where y=0, then you would set the baseline to SF*-y0. // // Current point: // Set the current point where the first character will appear. The // first character could extend left of the current point; this is font // dependent. You can either choose a current point that is the leftmost // point and hope, or add some padding, or check the bounding box or // left-side-bearing of the first character to be displayed and set // the current point based on that. // // Displaying a character: // Compute the bounding box of the character. It will contain signed values // relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1, // then the character should be displayed in the rectangle from // <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1). // // Advancing for the next character: // Call GlyphHMetrics, and compute 'current_point += SF * advance'. // // // ADVANCED USAGE // // Quality: // // - Use the functions with Subpixel at the end to allow your characters // to have subpixel positioning. Since the font is anti-aliased, not // hinted, this is very import for quality. (This is not possible with // baked fonts.) // // - Kerning is now supported, and if you're supporting subpixel rendering // then kerning is worth using to give your text a polished look. // // Performance: // // - Convert Unicode codepoints to glyph indexes and operate on the glyphs; // if you don't do this, stb_truetype is forced to do the conversion on // every call. // // - There are a lot of memory allocations. We should modify it to take // a temp buffer and allocate from the temp buffer (without freeing), // should help performance a lot. // // NOTES // // The system uses the raw data found in the .ttf file without changing it // and without building auxiliary data structures. This is a bit inefficient // on little-endian systems (the data is big-endian), but assuming you're // caching the bitmaps or glyph shapes this shouldn't be a big deal. // // It appears to be very hard to programmatically determine what font a // given file is in a general way. I provide an API for this, but I don't // recommend it. // // // PERFORMANCE MEASUREMENTS FOR 1.06: // // 32-bit 64-bit // Previous release: 8.83 s 7.68 s // Pool allocations: 7.72 s 6.34 s // Inline sort : 6.54 s 5.65 s // New rasterizer : 5.63 s 5.00 s ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //// //// SAMPLE PROGRAMS //// // // Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless // #if 0 #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" unsigned char ttf_buffer[1<<20]; unsigned char temp_bitmap[512*512]; stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs GLuint ftex; void my_stbtt_initfont(void) { fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb")); stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! // can free ttf_buffer at this point glGenTextures(1, &ftex); glBindTexture(GL_TEXTURE_2D, ftex); glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap); // can free temp_bitmap at this point glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } void my_stbtt_print(float x, float y, char *text) { // assume orthographic projection with units = screen pixels, origin at top left glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, ftex); glBegin(GL_QUADS); while (*text) { if (*text >= 32 && *text < 128) { stbtt_aligned_quad q; stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0); glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0); glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1); glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1); } ++text; } glEnd(); } #endif // // ////////////////////////////////////////////////////////////////////////////// // // Complete program (this compiles): get a single bitmap, print as ASCII art // #if 0 #include <stdio.h> #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" char ttf_buffer[1<<25]; int main(int argc, char **argv) { stbtt_fontinfo font; unsigned char *bitmap; int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); for (j=0; j < h; ++j) { for (i=0; i < w; ++i) putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); putchar('\n'); } return 0; } #endif // // Output: // // .ii. // @@@@@@. // V@Mio@@o // :i. V@V // :oM@@M // :@@@MM@M // @@o o@M // :@@. M@M // @@@o@@@@ // :M@@V:@@. // ////////////////////////////////////////////////////////////////////////////// // // Complete program: print "Hello World!" banner, with bugs // #if 0 char buffer[24<<20]; unsigned char screen[20][79]; int main(int arg, char **argv) { stbtt_fontinfo font; int i,j,ascent,baseline,ch=0; float scale, xpos=2; // leave a little padding in case the character extends left char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, buffer, 0); scale = stbtt_ScaleForPixelHeight(&font, 15); stbtt_GetFontVMetrics(&font, &ascent,0,0); baseline = (int) (ascent*scale); while (text[ch]) { int advance,lsb,x0,y0,x1,y1; float x_shift = xpos - (float) floor(xpos); stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong // because this API is really for baking character bitmaps into textures. if you want to render // a sequence of characters, you really need to render each bitmap to a temp buffer, then // "alpha blend" that into the working buffer xpos += (advance * scale); if (text[ch+1]) xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); ++ch; } for (j=0; j < 20; ++j) { for (i=0; i < 78; ++i) putchar(" .:ioVM@"[screen[j][i]>>5]); putchar('\n'); } return 0; } #endif ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //// //// INTEGRATION WITH YOUR CODEBASE //// //// The following sections allow you to supply alternate definitions //// of C library functions used by stb_truetype, e.g. if you don't //// link with the C runtime library. #ifdef STB_TRUETYPE_IMPLEMENTATION // #define your own (u)stbtt_int8/16/32 before including to override this #ifndef stbtt_uint8 typedef unsigned char stbtt_uint8; typedef signed char stbtt_int8; typedef unsigned short stbtt_uint16; typedef signed short stbtt_int16; typedef unsigned int stbtt_uint32; typedef signed int stbtt_int32; #endif typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h #ifndef STBTT_ifloor #include <math.h> #define STBTT_ifloor(x) ((int) floor(x)) #define STBTT_iceil(x) ((int) ceil(x)) #endif #ifndef STBTT_sqrt #include <math.h> #define STBTT_sqrt(x) sqrt(x) #define STBTT_pow(x,y) pow(x,y) #endif #ifndef STBTT_fmod #include <math.h> #define STBTT_fmod(x,y) fmod(x,y) #endif #ifndef STBTT_cos #include <math.h> #define STBTT_cos(x) cos(x) #define STBTT_acos(x) acos(x) #endif #ifndef STBTT_fabs #include <math.h> #define STBTT_fabs(x) fabs(x) #endif // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h #ifndef STBTT_malloc #include <stdlib.h> #define STBTT_malloc(x,u) ((void)(u),malloc(x)) #define STBTT_free(x,u) ((void)(u),free(x)) #endif #ifndef STBTT_assert #include <assert.h> #define STBTT_assert(x) assert(x) #endif #ifndef STBTT_strlen #include <string.h> #define STBTT_strlen(x) strlen(x) #endif #ifndef STBTT_memcpy #include <string.h> #define STBTT_memcpy memcpy #define STBTT_memset memset #endif #endif /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //// //// INTERFACE //// //// #ifndef __STB_INCLUDE_STB_TRUETYPE_H__ #define __STB_INCLUDE_STB_TRUETYPE_H__ #ifdef STBTT_STATIC #define STBTT_DEF static #else #define STBTT_DEF extern #endif #ifdef __cplusplus extern "C" { #endif // private structure typedef struct { unsigned char *data; int cursor; int size; } stbtt__buf; ////////////////////////////////////////////////////////////////////////////// // // TEXTURE BAKING API // // If you use this API, you only have to call two functions ever. // typedef struct { unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap float xoff,yoff,xadvance; } stbtt_bakedchar; STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake stbtt_bakedchar *chardata); // you allocate this, it's num_chars long // if return is positive, the first unused row of the bitmap // if return is negative, returns the negative of the number of characters that fit // if return is 0, no characters fit and no rows were used // This uses a very crappy packing. typedef struct { float x0,y0,s0,t0; // top-left float x1,y1,s1,t1; // bottom-right } stbtt_aligned_quad; STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display float *xpos, float *ypos, // pointers to current position in screen pixel space stbtt_aligned_quad *q, // output: quad to draw int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier // Call GetBakedQuad with char_index = 'character - first_char', and it // creates the quad you need to draw and advances the current position. // // The coordinate system used assumes y increases downwards. // // Characters will extend both above and below the current position; // see discussion of "BASELINE" above. // // It's inefficient; you might want to c&p it and optimize it. STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); // Query the font vertical metrics without having to create a font first. ////////////////////////////////////////////////////////////////////////////// // // NEW TEXTURE BAKING API // // This provides options for packing multiple fonts into one atlas, not // perfectly but better than nothing. typedef struct { unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap float xoff,yoff,xadvance; float xoff2,yoff2; } stbtt_packedchar; typedef struct stbtt_pack_context stbtt_pack_context; typedef struct stbtt_fontinfo stbtt_fontinfo; #ifndef STB_RECT_PACK_VERSION typedef struct stbrp_rect stbrp_rect; #endif STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); // Initializes a packing context stored in the passed-in stbtt_pack_context. // Future calls using this context will pack characters into the bitmap passed // in here: a 1-channel bitmap that is width * height. stride_in_bytes is // the distance from one row to the next (or 0 to mean they are packed tightly // together). "padding" is the amount of padding to leave between each // character (normally you want '1' for bitmaps you'll use as textures with // bilinear filtering). // // Returns 0 on failure, 1 on success. STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); // Cleans up the packing context and frees all memory. #define STBTT_POINT_SIZE(x) (-(x)) STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); // Creates character bitmaps from the font_index'th font found in fontdata (use // font_index=0 if you don't know what that is). It creates num_chars_in_range // bitmaps for characters with unicode values starting at first_unicode_char_in_range // and increasing. Data for how to render them is stored in chardata_for_range; // pass these to stbtt_GetPackedQuad to get back renderable quads. // // font_size is the full height of the character from ascender to descender, // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() // and pass that result as 'font_size': // ..., 20 , ... // font max minus min y is 20 pixels tall // ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall typedef struct { float font_size; int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints int num_chars; stbtt_packedchar *chardata_for_range; // output unsigned char h_oversample, v_oversample; // don't set these, they're used internally } stbtt_pack_range; STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); // Creates character bitmaps from multiple ranges of characters stored in // ranges. This will usually create a better-packed bitmap than multiple // calls to stbtt_PackFontRange. Note that you can call this multiple // times within a single PackBegin/PackEnd. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); // Oversampling a font increases the quality by allowing higher-quality subpixel // positioning, and is especially valuable at smaller text sizes. // // This function sets the amount of oversampling for all following calls to // stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given // pack context. The default (no oversampling) is achieved by h_oversample=1 // and v_oversample=1. The total number of pixels required is // h_oversample*v_oversample larger than the default; for example, 2x2 // oversampling requires 4x the storage of 1x1. For best results, render // oversampled textures with bilinear filtering. Look at the readme in // stb/tests/oversample for information about oversampled fonts // // To use with PackFontRangesGather etc., you must set it before calls // call to PackFontRangesGatherRects. STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); // If skip != 0, this tells stb_truetype to skip any codepoints for which // there is no corresponding glyph. If skip=0, which is the default, then // codepoints without a glyph recived the font's "missing character" glyph, // typically an empty box by convention. STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display float *xpos, float *ypos, // pointers to current position in screen pixel space stbtt_aligned_quad *q, // output: quad to draw int align_to_integer); STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); // Calling these functions in sequence is roughly equivalent to calling // stbtt_PackFontRanges(). If you more control over the packing of multiple // fonts, or if you want to pack custom data into a font texture, take a look // at the source to of stbtt_PackFontRanges() and create a custom version // using these functions, e.g. call GatherRects multiple times, // building up a single array of rects, then call PackRects once, // then call RenderIntoRects repeatedly. This may result in a // better packing than calling PackFontRanges multiple times // (or it may not). // this is an opaque structure that you shouldn't mess with which holds // all the context needed from PackBegin to PackEnd. struct stbtt_pack_context { void *user_allocator_context; void *pack_info; int width; int height; int stride_in_bytes; int padding; int skip_missing; unsigned int h_oversample, v_oversample; unsigned char *pixels; void *nodes; }; ////////////////////////////////////////////////////////////////////////////// // // FONT LOADING // // STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); // This function will determine the number of fonts in a font file. TrueType // collection (.ttc) files may contain multiple fonts, while TrueType font // (.ttf) files only contain one font. The number of fonts can be used for // indexing with the previous function where the index is between zero and one // less than the total fonts. If an error occurs, -1 is returned. STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); // Each .ttf/.ttc file may have more than one font. Each font has a sequential // index number starting from 0. Call this function to get the font offset for // a given index; it returns -1 if the index is out of range. A regular .ttf // file will only define one font and it always be at offset 0, so it will // return '0' for index 0, and -1 for all other indices. // The following structure is defined publicly so you can declare one on // the stack or as a global or etc, but you should treat it as opaque. struct stbtt_fontinfo { void * userdata; unsigned char * data; // pointer to .ttf file int fontstart; // offset of start of font int numGlyphs; // number of glyphs, needed for range checking int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph stbtt__buf cff; // cff font data stbtt__buf charstrings; // the charstring index stbtt__buf gsubrs; // global charstring subroutines index stbtt__buf subrs; // private charstring subroutines index stbtt__buf fontdicts; // array of font dicts stbtt__buf fdselect; // map from glyph to fontdict }; STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); // Given an offset into the file that defines a font, this function builds // the necessary cached info for the rest of the system. You must allocate // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't // need to do anything special to free it, because the contents are pure // value data with no additional data structures. Returns 0 on failure. ////////////////////////////////////////////////////////////////////////////// // // CHARACTER TO GLYPH-INDEX CONVERSIOn STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); // If you're going to perform multiple operations on the same character // and you want a speed-up, call this function with the character you're // going to process, then use glyph-based functions instead of the // codepoint-based functions. // Returns 0 if the character codepoint is not defined in the font. ////////////////////////////////////////////////////////////////////////////// // // CHARACTER PROPERTIES // STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose "height" is 'pixels' tall. // Height is measured as the distance from the highest ascender to the lowest // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics // and computing: // scale = pixels / (ascent - descent) // so if you prefer to measure height by the ascent only, use a similar calculation. STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose EM size is mapped to // 'pixels' tall. This is probably what traditional APIs compute, but // I'm not positive. STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); // ascent is the coordinate above the baseline the font extends; descent // is the coordinate below the baseline the font extends (i.e. it is typically negative) // lineGap is the spacing between one row's descent and the next row's ascent... // so you should advance the vertical position by "*ascent - *descent + *lineGap" // these are expressed in unscaled coordinates, so you must multiply by // the scale factor for a given size STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 // table (specific to MS/Windows TTF files). // // Returns 1 on success (table present), 0 on failure. STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); // the bounding box around all possible characters STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); // leftSideBearing is the offset from the current horizontal position to the left edge of the character // advanceWidth is the offset from the current horizontal position to the next horizontal position // these are expressed in unscaled coordinates STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); // an additional amount to add to the 'advance' value between ch1 and ch2 STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); // Gets the bounding box of the visible part of the glyph, in unscaled coordinates STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); // as above, but takes one or more glyph indices for greater efficiency typedef struct stbtt_kerningentry { int glyph1; // use stbtt_FindGlyphIndex int glyph2; int advance; } stbtt_kerningentry; STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); // Retrieves a complete list of all of the kerning pairs provided by the font // stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. // The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) ////////////////////////////////////////////////////////////////////////////// // // GLYPH SHAPES (you probably don't need these, but they have to go before // the bitmaps for C declaration-order reasons) // #ifndef STBTT_vmove // you can predefine these to use different values (but why?) enum { STBTT_vmove=1, STBTT_vline, STBTT_vcurve, STBTT_vcubic }; #endif #ifndef stbtt_vertex // you can predefine this to use different values // (we share this with other code at RAD) #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file typedef struct { stbtt_vertex_type x,y,cx,cy,cx1,cy1; unsigned char type,padding; } stbtt_vertex; #endif STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); // returns non-zero if nothing is drawn for this glyph STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); // returns # of vertices and fills *vertices with the pointer to them // these are expressed in "unscaled" coordinates // // The shape is a series of contours. Each one starts with // a STBTT_moveto, then consists of a series of mixed // STBTT_lineto and STBTT_curveto segments. A lineto // draws a line from previous endpoint to its x,y; a curveto // draws a quadratic bezier from previous endpoint to // its x,y, using cx,cy as the bezier control point. STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); // frees the data allocated above STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); // fills svg with the character's SVG data. // returns data size or 0 if SVG not found. ////////////////////////////////////////////////////////////////////////////// // // BITMAP RENDERING // STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); // frees the bitmap allocated below STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); // allocates a large-enough single-channel 8bpp bitmap and renders the // specified character/glyph at the specified scale into it, with // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). // *width & *height are filled out with the width & height of the bitmap, // which is stored left-to-right, top-to-bottom. // // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel // shift for the character STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the // width and height and positioning info for it first. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel // shift for the character STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); // same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering // is performed (see stbtt_PackSetOversampling) STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); // get the bbox of the bitmap centered around the glyph origin; so the // bitmap width is ix1-ix0, height is iy1-iy0, and location to place // the bitmap top left is (leftSideBearing*scale,iy0). // (Note that the bitmap uses y-increases-down, but the shape uses // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel // shift for the character // the following functions are equivalent to the above functions, but operate // on glyph indices instead of Unicode codepoints (for efficiency) STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); // @TODO: don't expose this structure typedef struct { int w,h,stride; unsigned char *pixels; } stbtt__bitmap; // rasterize a shape with quadratic beziers into a bitmap STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into float flatness_in_pixels, // allowable error of curve in pixels stbtt_vertex *vertices, // array of vertices defining shape int num_verts, // number of vertices in above array float scale_x, float scale_y, // scale applied to input vertices float shift_x, float shift_y, // translation applied to input vertices int x_off, int y_off, // another translation applied to input int invert, // if non-zero, vertically flip shape void *userdata); // context for to STBTT_MALLOC ////////////////////////////////////////////////////////////////////////////// // // Signed Distance Function (or Field) rendering STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); // frees the SDF bitmap allocated below STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); // These functions compute a discretized SDF field for a single character, suitable for storing // in a single-channel texture, sampling with bilinear filtering, and testing against // larger than some threshold to produce scalable fonts. // info -- the font // scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap // glyph/codepoint -- the character to generate the SDF for // padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), // which allows effects like bit outlines // onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) // pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) // if positive, > onedge_value is inside; if negative, < onedge_value is inside // width,height -- output height & width of the SDF bitmap (including padding) // xoff,yoff -- output origin of the character // return value -- a 2D array of bytes 0..255, width*height in size // // pixel_dist_scale & onedge_value are a scale & bias that allows you to make // optimal use of the limited 0..255 for your application, trading off precision // and special effects. SDF values outside the range 0..255 are clamped to 0..255. // // Example: // scale = stbtt_ScaleForPixelHeight(22) // padding = 5 // onedge_value = 180 // pixel_dist_scale = 180/5.0 = 36.0 // // This will create an SDF bitmap in which the character is about 22 pixels // high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled // shape, sample the SDF at each pixel and fill the pixel if the SDF value // is greater than or equal to 180/255. (You'll actually want to antialias, // which is beyond the scope of this example.) Additionally, you can compute // offset outlines (e.g. to stroke the character border inside & outside, // or only outside). For example, to fill outside the character up to 3 SDF // pixels, you would compare against (180-36.0*3)/255 = 72/255. The above // choice of variables maps a range from 5 pixels outside the shape to // 2 pixels inside the shape to 0..255; this is intended primarily for apply // outside effects only (the interior range is needed to allow proper // antialiasing of the font at *smaller* sizes) // // The function computes the SDF analytically at each SDF pixel, not by e.g. // building a higher-res bitmap and approximating it. In theory the quality // should be as high as possible for an SDF of this size & representation, but // unclear if this is true in practice (perhaps building a higher-res bitmap // and computing from that can allow drop-out prevention). // // The algorithm has not been optimized at all, so expect it to be slow // if computing lots of characters or very large sizes. ////////////////////////////////////////////////////////////////////////////// // // Finding the right font... // // You should really just solve this offline, keep your own tables // of what font is what, and don't try to get it out of the .ttf file. // That's because getting it out of the .ttf file is really hard, because // the names in the file can appear in many possible encodings, in many // possible languages, and e.g. if you need a case-insensitive comparison, // the details of that depend on the encoding & language in a complex way // (actually underspecified in truetype, but also gigantic). // // But you can use the provided functions in two possible ways: // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on // unicode-encoded names to try to find the font you want; // you can run this before calling stbtt_InitFont() // // stbtt_GetFontNameString() lets you get any of the various strings // from the file yourself and do your own comparisons on them. // You have to have called stbtt_InitFont() first. STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); // returns the offset (not index) of the font that matches, or -1 if none // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". // if you use any other flag, use a font name like "Arial"; this checks // the 'macStyle' header field; i don't know if fonts set this consistently #define STBTT_MACSTYLE_DONTCARE 0 #define STBTT_MACSTYLE_BOLD 1 #define STBTT_MACSTYLE_ITALIC 2 #define STBTT_MACSTYLE_UNDERSCORE 4 #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); // returns 1/0 whether the first string interpreted as utf8 is identical to // the second string interpreted as big-endian utf16... useful for strings from next func STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); // returns the string (which may be big-endian double byte, e.g. for unicode) // and puts the length in bytes in *length. // // some of the values for the IDs are below; for more see the truetype spec: // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html // http://www.microsoft.com/typography/otspec/name.htm enum { // platformID STBTT_PLATFORM_ID_UNICODE =0, STBTT_PLATFORM_ID_MAC =1, STBTT_PLATFORM_ID_ISO =2, STBTT_PLATFORM_ID_MICROSOFT =3 }; enum { // encodingID for STBTT_PLATFORM_ID_UNICODE STBTT_UNICODE_EID_UNICODE_1_0 =0, STBTT_UNICODE_EID_UNICODE_1_1 =1, STBTT_UNICODE_EID_ISO_10646 =2, STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 }; enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT STBTT_MS_EID_SYMBOL =0, STBTT_MS_EID_UNICODE_BMP =1, STBTT_MS_EID_SHIFTJIS =2, STBTT_MS_EID_UNICODE_FULL =10 }; enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 }; enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D }; enum { // languageID for STBTT_PLATFORM_ID_MAC STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 }; #ifdef __cplusplus } #endif #endif // __STB_INCLUDE_STB_TRUETYPE_H__ /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //// //// IMPLEMENTATION //// //// #ifdef STB_TRUETYPE_IMPLEMENTATION #ifndef STBTT_MAX_OVERSAMPLE #define STBTT_MAX_OVERSAMPLE 8 #endif #if STBTT_MAX_OVERSAMPLE > 255 #error "STBTT_MAX_OVERSAMPLE cannot be > 255" #endif typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; #ifndef STBTT_RASTERIZER_VERSION #define STBTT_RASTERIZER_VERSION 2 #endif #ifdef _MSC_VER #define STBTT__NOTUSED(v) (void)(v) #else #define STBTT__NOTUSED(v) (void)sizeof(v) #endif ////////////////////////////////////////////////////////////////////////// // // stbtt__buf helpers to parse data from file // static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) { if (b->cursor >= b->size) return 0; return b->data[b->cursor++]; } static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) { if (b->cursor >= b->size) return 0; return b->data[b->cursor]; } static void stbtt__buf_seek(stbtt__buf *b, int o) { STBTT_assert(!(o > b->size || o < 0)); b->cursor = (o > b->size || o < 0) ? b->size : o; } static void stbtt__buf_skip(stbtt__buf *b, int o) { stbtt__buf_seek(b, b->cursor + o); } static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) { stbtt_uint32 v = 0; int i; STBTT_assert(n >= 1 && n <= 4); for (i = 0; i < n; i++) v = (v << 8) | stbtt__buf_get8(b); return v; } static stbtt__buf stbtt__new_buf(const void *p, size_t size) { stbtt__buf r; STBTT_assert(size < 0x40000000); r.data = (stbtt_uint8*) p; r.size = (int) size; r.cursor = 0; return r; } #define stbtt__buf_get16(b) stbtt__buf_get((b), 2) #define stbtt__buf_get32(b) stbtt__buf_get((b), 4) static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) { stbtt__buf r = stbtt__new_buf(NULL, 0); if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; r.data = b->data + o; r.size = s; return r; } static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) { int count, start, offsize; start = b->cursor; count = stbtt__buf_get16(b); if (count) { offsize = stbtt__buf_get8(b); STBTT_assert(offsize >= 1 && offsize <= 4); stbtt__buf_skip(b, offsize * count); stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); } return stbtt__buf_range(b, start, b->cursor - start); } static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) { int b0 = stbtt__buf_get8(b); if (b0 >= 32 && b0 <= 246) return b0 - 139; else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; else if (b0 == 28) return stbtt__buf_get16(b); else if (b0 == 29) return stbtt__buf_get32(b); STBTT_assert(0); return 0; } static void stbtt__cff_skip_operand(stbtt__buf *b) { int v, b0 = stbtt__buf_peek8(b); STBTT_assert(b0 >= 28); if (b0 == 30) { stbtt__buf_skip(b, 1); while (b->cursor < b->size) { v = stbtt__buf_get8(b); if ((v & 0xF) == 0xF || (v >> 4) == 0xF) break; } } else { stbtt__cff_int(b); } } static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) { stbtt__buf_seek(b, 0); while (b->cursor < b->size) { int start = b->cursor, end, op; while (stbtt__buf_peek8(b) >= 28) stbtt__cff_skip_operand(b); end = b->cursor; op = stbtt__buf_get8(b); if (op == 12) op = stbtt__buf_get8(b) | 0x100; if (op == key) return stbtt__buf_range(b, start, end-start); } return stbtt__buf_range(b, 0, 0); } static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) { int i; stbtt__buf operands = stbtt__dict_get(b, key); for (i = 0; i < outcount && operands.cursor < operands.size; i++) out[i] = stbtt__cff_int(&operands); } static int stbtt__cff_index_count(stbtt__buf *b) { stbtt__buf_seek(b, 0); return stbtt__buf_get16(b); } static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) { int count, offsize, start, end; stbtt__buf_seek(&b, 0); count = stbtt__buf_get16(&b); offsize = stbtt__buf_get8(&b); STBTT_assert(i >= 0 && i < count); STBTT_assert(offsize >= 1 && offsize <= 4); stbtt__buf_skip(&b, i*offsize); start = stbtt__buf_get(&b, offsize); end = stbtt__buf_get(&b, offsize); return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); } ////////////////////////////////////////////////////////////////////////// // // accessors to parse data from file // // on platforms that don't allow misaligned reads, if we want to allow // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE #define ttBYTE(p) (* (stbtt_uint8 *) (p)) #define ttCHAR(p) (* (stbtt_int8 *) (p)) #define ttFixed(p) ttLONG(p) static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) static int stbtt__isfont(stbtt_uint8 *font) { // check the version number if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts return 0; } // @OPTIMIZE: binary search static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) { stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); stbtt_uint32 tabledir = fontstart + 12; stbtt_int32 i; for (i=0; i < num_tables; ++i) { stbtt_uint32 loc = tabledir + 16*i; if (stbtt_tag(data+loc+0, tag)) return ttULONG(data+loc+8); } return 0; } static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) { // if it's just a font, there's only one valid index if (stbtt__isfont(font_collection)) return index == 0 ? 0 : -1; // check if it's a TTC if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { stbtt_int32 n = ttLONG(font_collection+8); if (index >= n) return -1; return ttULONG(font_collection+12+index*4); } } return -1; } static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) { // if it's just a font, there's only one valid font if (stbtt__isfont(font_collection)) return 1; // check if it's a TTC if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { return ttLONG(font_collection+8); } } return 0; } static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) { stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; stbtt__buf pdict; stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); if (!subrsoff) return stbtt__new_buf(NULL, 0); stbtt__buf_seek(&cff, private_loc[1]+subrsoff); return stbtt__cff_get_index(&cff); } // since most people won't use this, find this table the first time it's needed static int stbtt__get_svg(stbtt_fontinfo *info) { stbtt_uint32 t; if (info->svg < 0) { t = stbtt__find_table(info->data, info->fontstart, "SVG "); if (t) { stbtt_uint32 offset = ttULONG(info->data + t + 2); info->svg = t + offset; } else { info->svg = 0; } } return info->svg; } static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) { stbtt_uint32 cmap, t; stbtt_int32 i,numTables; info->data = data; info->fontstart = fontstart; info->cff = stbtt__new_buf(NULL, 0); cmap = stbtt__find_table(data, fontstart, "cmap"); // required info->loca = stbtt__find_table(data, fontstart, "loca"); // required info->head = stbtt__find_table(data, fontstart, "head"); // required info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required info->kern = stbtt__find_table(data, fontstart, "kern"); // not required info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required if (!cmap || !info->head || !info->hhea || !info->hmtx) return 0; if (info->glyf) { // required for truetype if (!info->loca) return 0; } else { // initialization for CFF / Type2 fonts (OTF) stbtt__buf b, topdict, topdictidx; stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; stbtt_uint32 cff; cff = stbtt__find_table(data, fontstart, "CFF "); if (!cff) return 0; info->fontdicts = stbtt__new_buf(NULL, 0); info->fdselect = stbtt__new_buf(NULL, 0); // @TODO this should use size from table (not 512MB) info->cff = stbtt__new_buf(data+cff, 512*1024*1024); b = info->cff; // read the header stbtt__buf_skip(&b, 2); stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize // @TODO the name INDEX could list multiple fonts, // but we just use the first one. stbtt__cff_get_index(&b); // name INDEX topdictidx = stbtt__cff_get_index(&b); topdict = stbtt__cff_index_get(topdictidx, 0); stbtt__cff_get_index(&b); // string INDEX info->gsubrs = stbtt__cff_get_index(&b); stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); info->subrs = stbtt__get_subrs(b, topdict); // we only support Type 2 charstrings if (cstype != 2) return 0; if (charstrings == 0) return 0; if (fdarrayoff) { // looks like a CID font if (!fdselectoff) return 0; stbtt__buf_seek(&b, fdarrayoff); info->fontdicts = stbtt__cff_get_index(&b); info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); } stbtt__buf_seek(&b, charstrings); info->charstrings = stbtt__cff_get_index(&b); } t = stbtt__find_table(data, fontstart, "maxp"); if (t) info->numGlyphs = ttUSHORT(data+t+4); else info->numGlyphs = 0xffff; info->svg = -1; // find a cmap encoding table we understand *now* to avoid searching // later. (todo: could make this installable) // the same regardless of glyph. numTables = ttUSHORT(data + cmap + 2); info->index_map = 0; for (i=0; i < numTables; ++i) { stbtt_uint32 encoding_record = cmap + 4 + 8 * i; // find an encoding we understand: switch(ttUSHORT(data+encoding_record)) { case STBTT_PLATFORM_ID_MICROSOFT: switch (ttUSHORT(data+encoding_record+2)) { case STBTT_MS_EID_UNICODE_BMP: case STBTT_MS_EID_UNICODE_FULL: // MS/Unicode info->index_map = cmap + ttULONG(data+encoding_record+4); break; } break; case STBTT_PLATFORM_ID_UNICODE: // Mac/iOS has these // all the encodingIDs are unicode, so we don't bother to check it info->index_map = cmap + ttULONG(data+encoding_record+4); break; } } if (info->index_map == 0) return 0; info->indexToLocFormat = ttUSHORT(data+info->head + 50); return 1; } STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) { stbtt_uint8 *data = info->data; stbtt_uint32 index_map = info->index_map; stbtt_uint16 format = ttUSHORT(data + index_map + 0); if (format == 0) { // apple byte encoding stbtt_int32 bytes = ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) return ttBYTE(data + index_map + 6 + unicode_codepoint); return 0; } else if (format == 6) { stbtt_uint32 first = ttUSHORT(data + index_map + 6); stbtt_uint32 count = ttUSHORT(data + index_map + 8); if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); return 0; } else if (format == 2) { STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean return 0; } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; // do a binary search of the segments stbtt_uint32 endCount = index_map + 14; stbtt_uint32 search = endCount; if (unicode_codepoint > 0xffff) return 0; // they lie from endCount .. endCount + segCount // but searchRange is the nearest power of two, so... if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) search += rangeShift*2; // now decrement to bias correctly to find smallest search -= 2; while (entrySelector) { stbtt_uint16 end; searchRange >>= 1; end = ttUSHORT(data + search + searchRange*2); if (unicode_codepoint > end) search += searchRange*2; --entrySelector; } search += 2; { stbtt_uint16 offset, start; stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); if (unicode_codepoint < start) return 0; offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); if (offset == 0) return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); } } else if (format == 12 || format == 13) { stbtt_uint32 ngroups = ttULONG(data+index_map+12); stbtt_int32 low,high; low = 0; high = (stbtt_int32)ngroups; // Binary search the right group. while (low < high) { stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); if ((stbtt_uint32) unicode_codepoint < start_char) high = mid; else if ((stbtt_uint32) unicode_codepoint > end_char) low = mid+1; else { stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); if (format == 12) return start_glyph + unicode_codepoint-start_char; else // format == 13 return start_glyph; } } return 0; // not found } // @TODO STBTT_assert(0); return 0; } STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) { return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); } static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) { v->type = type; v->x = (stbtt_int16) x; v->y = (stbtt_int16) y; v->cx = (stbtt_int16) cx; v->cy = (stbtt_int16) cy; } static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) { int g1,g2; STBTT_assert(!info->cff.size); if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format if (info->indexToLocFormat == 0) { g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; } else { g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); } return g1==g2 ? -1 : g1; // if length is 0, return -1 } static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { if (info->cff.size) { stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); } else { int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; if (x0) *x0 = ttSHORT(info->data + g + 2); if (y0) *y0 = ttSHORT(info->data + g + 4); if (x1) *x1 = ttSHORT(info->data + g + 6); if (y1) *y1 = ttSHORT(info->data + g + 8); } return 1; } STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) { return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); } STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) { stbtt_int16 numberOfContours; int g; if (info->cff.size) return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 1; numberOfContours = ttSHORT(info->data + g); return numberOfContours == 0; } static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) { if (start_off) { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); } return num_vertices; } static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { stbtt_int16 numberOfContours; stbtt_uint8 *endPtsOfContours; stbtt_uint8 *data = info->data; stbtt_vertex *vertices=0; int num_vertices=0; int g = stbtt__GetGlyfOffset(info, glyph_index); *pvertices = NULL; if (g < 0) return 0; numberOfContours = ttSHORT(data + g); if (numberOfContours > 0) { stbtt_uint8 flags=0,flagcount; stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; stbtt_uint8 *points; endPtsOfContours = (data + g + 10); ins = ttUSHORT(data + g + 10 + numberOfContours * 2); points = data + g + 10 + numberOfContours * 2 + 2 + ins; n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); m = n + 2*numberOfContours; // a loose bound on how many vertices we might need vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); if (vertices == 0) return 0; next_move = 0; flagcount=0; // in first pass, we load uninterpreted data into the allocated array // above, shifted to the end of the array so we won't overwrite it when // we create our final data starting from the front off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated // first load flags for (i=0; i < n; ++i) { if (flagcount == 0) { flags = *points++; if (flags & 8) flagcount = *points++; } else --flagcount; vertices[off+i].type = flags; } // now load x coordinates x=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 2) { stbtt_int16 dx = *points++; x += (flags & 16) ? dx : -dx; // ??? } else { if (!(flags & 16)) { x = x + (stbtt_int16) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].x = (stbtt_int16) x; } // now load y coordinates y=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 4) { stbtt_int16 dy = *points++; y += (flags & 32) ? dy : -dy; // ??? } else { if (!(flags & 32)) { y = y + (stbtt_int16) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].y = (stbtt_int16) y; } // now convert them to our format num_vertices=0; sx = sy = cx = cy = scx = scy = 0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; x = (stbtt_int16) vertices[off+i].x; y = (stbtt_int16) vertices[off+i].y; if (next_move == i) { if (i != 0) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); // now start the new one start_off = !(flags & 1); if (start_off) { // if we start off with an off-curve point, then when we need to find a point on the curve // where we can start, and we need to save some state for when we wraparound. scx = x; scy = y; if (!(vertices[off+i+1].type & 1)) { // next point is also a curve point, so interpolate an on-point curve sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; } else { // otherwise just use the next point as our start point sx = (stbtt_int32) vertices[off+i+1].x; sy = (stbtt_int32) vertices[off+i+1].y; ++i; // we're using point i+1 as the starting point, so skip it } } else { sx = x; sy = y; } stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); was_off = 0; next_move = 1 + ttUSHORT(endPtsOfContours+j*2); ++j; } else { if (!(flags & 1)) { // if it's a curve if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); cx = x; cy = y; was_off = 1; } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); was_off = 0; } } } num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); } else if (numberOfContours < 0) { // Compound shapes. int more = 1; stbtt_uint8 *comp = data + g + 10; num_vertices = 0; vertices = 0; while (more) { stbtt_uint16 flags, gidx; int comp_num_verts = 0, i; stbtt_vertex *comp_verts = 0, *tmp = 0; float mtx[6] = {1,0,0,1,0,0}, m, n; flags = ttSHORT(comp); comp+=2; gidx = ttSHORT(comp); comp+=2; if (flags & 2) { // XY values if (flags & 1) { // shorts mtx[4] = ttSHORT(comp); comp+=2; mtx[5] = ttSHORT(comp); comp+=2; } else { mtx[4] = ttCHAR(comp); comp+=1; mtx[5] = ttCHAR(comp); comp+=1; } } else { // @TODO handle matching point STBTT_assert(0); } if (flags & (1<<3)) { // WE_HAVE_A_SCALE mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } // Find transformation scales. m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); // Get indexed glyph. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); if (comp_num_verts > 0) { // Transform vertices. for (i = 0; i < comp_num_verts; ++i) { stbtt_vertex* v = &comp_verts[i]; stbtt_vertex_type x,y; x=v->x; y=v->y; v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); x=v->cx; y=v->cy; v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); } // Append vertices. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); if (!tmp) { if (vertices) STBTT_free(vertices, info->userdata); if (comp_verts) STBTT_free(comp_verts, info->userdata); return 0; } if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); if (vertices) STBTT_free(vertices, info->userdata); vertices = tmp; STBTT_free(comp_verts, info->userdata); num_vertices += comp_num_verts; } // More components ? more = flags & (1<<5); } } else { // numberOfCounters == 0, do nothing } *pvertices = vertices; return num_vertices; } typedef struct { int bounds; int started; float first_x, first_y; float x, y; stbtt_int32 min_x, max_x, min_y, max_y; stbtt_vertex *pvertices; int num_vertices; } stbtt__csctx; #define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) { if (x > c->max_x || !c->started) c->max_x = x; if (y > c->max_y || !c->started) c->max_y = y; if (x < c->min_x || !c->started) c->min_x = x; if (y < c->min_y || !c->started) c->min_y = y; c->started = 1; } static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) { if (c->bounds) { stbtt__track_vertex(c, x, y); if (type == STBTT_vcubic) { stbtt__track_vertex(c, cx, cy); stbtt__track_vertex(c, cx1, cy1); } } else { stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; } c->num_vertices++; } static void stbtt__csctx_close_shape(stbtt__csctx *ctx) { if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); } static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) { stbtt__csctx_close_shape(ctx); ctx->first_x = ctx->x = ctx->x + dx; ctx->first_y = ctx->y = ctx->y + dy; stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); } static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) { ctx->x += dx; ctx->y += dy; stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); } static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { float cx1 = ctx->x + dx1; float cy1 = ctx->y + dy1; float cx2 = cx1 + dx2; float cy2 = cy1 + dy2; ctx->x = cx2 + dx3; ctx->y = cy2 + dy3; stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); } static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) { int count = stbtt__cff_index_count(&idx); int bias = 107; if (count >= 33900) bias = 32768; else if (count >= 1240) bias = 1131; n += bias; if (n < 0 || n >= count) return stbtt__new_buf(NULL, 0); return stbtt__cff_index_get(idx, n); } static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) { stbtt__buf fdselect = info->fdselect; int nranges, start, end, v, fmt, fdselector = -1, i; stbtt__buf_seek(&fdselect, 0); fmt = stbtt__buf_get8(&fdselect); if (fmt == 0) { // untested stbtt__buf_skip(&fdselect, glyph_index); fdselector = stbtt__buf_get8(&fdselect); } else if (fmt == 3) { nranges = stbtt__buf_get16(&fdselect); start = stbtt__buf_get16(&fdselect); for (i = 0; i < nranges; i++) { v = stbtt__buf_get8(&fdselect); end = stbtt__buf_get16(&fdselect); if (glyph_index >= start && glyph_index < end) { fdselector = v; break; } start = end; } } if (fdselector == -1) stbtt__new_buf(NULL, 0); return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); } static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) { int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; int has_subrs = 0, clear_stack; float s[48]; stbtt__buf subr_stack[10], subrs = info->subrs, b; float f; #define STBTT__CSERR(s) (0) // this currently ignores the initial width value, which isn't needed if we have hmtx b = stbtt__cff_index_get(info->charstrings, glyph_index); while (b.cursor < b.size) { i = 0; clear_stack = 1; b0 = stbtt__buf_get8(&b); switch (b0) { // @TODO implement hinting case 0x13: // hintmask case 0x14: // cntrmask if (in_header) maskbits += (sp / 2); // implicit "vstem" in_header = 0; stbtt__buf_skip(&b, (maskbits + 7) / 8); break; case 0x01: // hstem case 0x03: // vstem case 0x12: // hstemhm case 0x17: // vstemhm maskbits += (sp / 2); break; case 0x15: // rmoveto in_header = 0; if (sp < 2) return STBTT__CSERR("rmoveto stack"); stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); break; case 0x04: // vmoveto in_header = 0; if (sp < 1) return STBTT__CSERR("vmoveto stack"); stbtt__csctx_rmove_to(c, 0, s[sp-1]); break; case 0x16: // hmoveto in_header = 0; if (sp < 1) return STBTT__CSERR("hmoveto stack"); stbtt__csctx_rmove_to(c, s[sp-1], 0); break; case 0x05: // rlineto if (sp < 2) return STBTT__CSERR("rlineto stack"); for (; i + 1 < sp; i += 2) stbtt__csctx_rline_to(c, s[i], s[i+1]); break; // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical // starting from a different place. case 0x07: // vlineto if (sp < 1) return STBTT__CSERR("vlineto stack"); goto vlineto; case 0x06: // hlineto if (sp < 1) return STBTT__CSERR("hlineto stack"); for (;;) { if (i >= sp) break; stbtt__csctx_rline_to(c, s[i], 0); i++; vlineto: if (i >= sp) break; stbtt__csctx_rline_to(c, 0, s[i]); i++; } break; case 0x1F: // hvcurveto if (sp < 4) return STBTT__CSERR("hvcurveto stack"); goto hvcurveto; case 0x1E: // vhcurveto if (sp < 4) return STBTT__CSERR("vhcurveto stack"); for (;;) { if (i + 3 >= sp) break; stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); i += 4; hvcurveto: if (i + 3 >= sp) break; stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); i += 4; } break; case 0x08: // rrcurveto if (sp < 6) return STBTT__CSERR("rcurveline stack"); for (; i + 5 < sp; i += 6) stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); break; case 0x18: // rcurveline if (sp < 8) return STBTT__CSERR("rcurveline stack"); for (; i + 5 < sp - 2; i += 6) stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); stbtt__csctx_rline_to(c, s[i], s[i+1]); break; case 0x19: // rlinecurve if (sp < 8) return STBTT__CSERR("rlinecurve stack"); for (; i + 1 < sp - 6; i += 2) stbtt__csctx_rline_to(c, s[i], s[i+1]); if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); break; case 0x1A: // vvcurveto case 0x1B: // hhcurveto if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); f = 0.0; if (sp & 1) { f = s[i]; i++; } for (; i + 3 < sp; i += 4) { if (b0 == 0x1B) stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); else stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); f = 0.0; } break; case 0x0A: // callsubr if (!has_subrs) { if (info->fdselect.size) subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); has_subrs = 1; } // fallthrough case 0x1D: // callgsubr if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); v = (int) s[--sp]; if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); subr_stack[subr_stack_height++] = b; b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); if (b.size == 0) return STBTT__CSERR("subr not found"); b.cursor = 0; clear_stack = 0; break; case 0x0B: // return if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); b = subr_stack[--subr_stack_height]; clear_stack = 0; break; case 0x0E: // endchar stbtt__csctx_close_shape(c); return 1; case 0x0C: { // two-byte escape float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; float dx, dy; int b1 = stbtt__buf_get8(&b); switch (b1) { // @TODO These "flex" implementations ignore the flex-depth and resolution, // and always draw beziers. case 0x22: // hflex if (sp < 7) return STBTT__CSERR("hflex stack"); dx1 = s[0]; dx2 = s[1]; dy2 = s[2]; dx3 = s[3]; dx4 = s[4]; dx5 = s[5]; dx6 = s[6]; stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); break; case 0x23: // flex if (sp < 13) return STBTT__CSERR("flex stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dy3 = s[5]; dx4 = s[6]; dy4 = s[7]; dx5 = s[8]; dy5 = s[9]; dx6 = s[10]; dy6 = s[11]; //fd is s[12] stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); break; case 0x24: // hflex1 if (sp < 9) return STBTT__CSERR("hflex1 stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dx4 = s[5]; dx5 = s[6]; dy5 = s[7]; dx6 = s[8]; stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); break; case 0x25: // flex1 if (sp < 11) return STBTT__CSERR("flex1 stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dy3 = s[5]; dx4 = s[6]; dy4 = s[7]; dx5 = s[8]; dy5 = s[9]; dx6 = dy6 = s[10]; dx = dx1+dx2+dx3+dx4+dx5; dy = dy1+dy2+dy3+dy4+dy5; if (STBTT_fabs(dx) > STBTT_fabs(dy)) dy6 = -dy; else dx6 = -dx; stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); break; default: return STBTT__CSERR("unimplemented"); } } break; default: if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254)) return STBTT__CSERR("reserved operator"); // push immediate if (b0 == 255) { f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; } else { stbtt__buf_skip(&b, -1); f = (float)(stbtt_int16)stbtt__cff_int(&b); } if (sp >= 48) return STBTT__CSERR("push stack overflow"); s[sp++] = f; clear_stack = 0; break; } if (clear_stack) sp = 0; } return STBTT__CSERR("no endchar"); #undef STBTT__CSERR } static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { // runs the charstring twice, once to count and once to output (to avoid realloc) stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); output_ctx.pvertices = *pvertices; if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); return output_ctx.num_vertices; } } *pvertices = NULL; return 0; } static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { stbtt__csctx c = STBTT__CSCTX_INIT(1); int r = stbtt__run_charstring(info, glyph_index, &c); if (x0) *x0 = r ? c.min_x : 0; if (y0) *y0 = r ? c.min_y : 0; if (x1) *x1 = r ? c.max_x : 0; if (y1) *y1 = r ? c.max_y : 0; return r ? c.num_vertices : 0; } STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { if (!info->cff.size) return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); else return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); } STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) { stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); if (glyph_index < numOfLongHorMetrics) { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); } else { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); } } STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) { stbtt_uint8 *data = info->data + info->kern; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; return ttUSHORT(data+10); } STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length) { stbtt_uint8 *data = info->data + info->kern; int k, length; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; length = ttUSHORT(data+10); if (table_length < length) length = table_length; for (k = 0; k < length; k++) { table[k].glyph1 = ttUSHORT(data+18+(k*6)); table[k].glyph2 = ttUSHORT(data+20+(k*6)); table[k].advance = ttSHORT(data+22+(k*6)); } return length; } static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) { stbtt_uint8 *data = info->data + info->kern; stbtt_uint32 needle, straw; int l, r, m; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; l = 0; r = ttUSHORT(data+10) - 1; needle = glyph1 << 16 | glyph2; while (l <= r) { m = (l + r) >> 1; straw = ttULONG(data+18+(m*6)); // note: unaligned read if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else return ttSHORT(data+22+(m*6)); } return 0; } static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) { stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); switch(coverageFormat) { case 1: { stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); // Binary search. stbtt_int32 l=0, r=glyphCount-1, m; int straw, needle=glyph; while (l <= r) { stbtt_uint8 *glyphArray = coverageTable + 4; stbtt_uint16 glyphID; m = (l + r) >> 1; glyphID = ttUSHORT(glyphArray + 2 * m); straw = glyphID; if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else { return m; } } } break; case 2: { stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); stbtt_uint8 *rangeArray = coverageTable + 4; // Binary search. stbtt_int32 l=0, r=rangeCount-1, m; int strawStart, strawEnd, needle=glyph; while (l <= r) { stbtt_uint8 *rangeRecord; m = (l + r) >> 1; rangeRecord = rangeArray + 6 * m; strawStart = ttUSHORT(rangeRecord); strawEnd = ttUSHORT(rangeRecord + 2); if (needle < strawStart) r = m - 1; else if (needle > strawEnd) l = m + 1; else { stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); return startCoverageIndex + glyph - strawStart; } } } break; default: { // There are no other cases. STBTT_assert(0); } break; } return -1; } static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) { stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); switch(classDefFormat) { case 1: { stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); stbtt_uint8 *classDef1ValueArray = classDefTable + 6; if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); classDefTable = classDef1ValueArray + 2 * glyphCount; } break; case 2: { stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); stbtt_uint8 *classRangeRecords = classDefTable + 4; // Binary search. stbtt_int32 l=0, r=classRangeCount-1, m; int strawStart, strawEnd, needle=glyph; while (l <= r) { stbtt_uint8 *classRangeRecord; m = (l + r) >> 1; classRangeRecord = classRangeRecords + 6 * m; strawStart = ttUSHORT(classRangeRecord); strawEnd = ttUSHORT(classRangeRecord + 2); if (needle < strawStart) r = m - 1; else if (needle > strawEnd) l = m + 1; else return (stbtt_int32)ttUSHORT(classRangeRecord + 4); } classDefTable = classRangeRecords + 6 * classRangeCount; } break; default: { // There are no other cases. STBTT_assert(0); } break; } return -1; } // Define to STBTT_assert(x) if you want to break on unimplemented formats. #define STBTT_GPOS_TODO_assert(x) static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) { stbtt_uint16 lookupListOffset; stbtt_uint8 *lookupList; stbtt_uint16 lookupCount; stbtt_uint8 *data; stbtt_int32 i; if (!info->gpos) return 0; data = info->data + info->gpos; if (ttUSHORT(data+0) != 1) return 0; // Major version 1 if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 lookupListOffset = ttUSHORT(data+8); lookupList = data + lookupListOffset; lookupCount = ttUSHORT(lookupList); for (i=0; i<lookupCount; ++i) { stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i); stbtt_uint8 *lookupTable = lookupList + lookupOffset; stbtt_uint16 lookupType = ttUSHORT(lookupTable); stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4); stbtt_uint8 *subTableOffsets = lookupTable + 6; switch(lookupType) { case 2: { // Pair Adjustment Positioning Subtable stbtt_int32 sti; for (sti=0; sti<subTableCount; sti++) { stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti); stbtt_uint8 *table = lookupTable + subtableOffset; stbtt_uint16 posFormat = ttUSHORT(table); stbtt_uint16 coverageOffset = ttUSHORT(table + 2); stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1); if (coverageIndex == -1) continue; switch (posFormat) { case 1: { stbtt_int32 l, r, m; int straw, needle; stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); stbtt_int32 valueRecordPairSizeInBytes = 2; stbtt_uint16 pairSetCount = ttUSHORT(table + 8); stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex); stbtt_uint8 *pairValueTable = table + pairPosOffset; stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable); stbtt_uint8 *pairValueArray = pairValueTable + 2; // TODO: Support more formats. STBTT_GPOS_TODO_assert(valueFormat1 == 4); if (valueFormat1 != 4) return 0; STBTT_GPOS_TODO_assert(valueFormat2 == 0); if (valueFormat2 != 0) return 0; STBTT_assert(coverageIndex < pairSetCount); STBTT__NOTUSED(pairSetCount); needle=glyph2; r=pairValueCount-1; l=0; // Binary search. while (l <= r) { stbtt_uint16 secondGlyph; stbtt_uint8 *pairValue; m = (l + r) >> 1; pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; secondGlyph = ttUSHORT(pairValue); straw = secondGlyph; if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else { stbtt_int16 xAdvance = ttSHORT(pairValue + 2); return xAdvance; } } } break; case 2: { stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); stbtt_uint16 class1Count = ttUSHORT(table + 12); stbtt_uint16 class2Count = ttUSHORT(table + 14); STBTT_assert(glyph1class < class1Count); STBTT_assert(glyph2class < class2Count); // TODO: Support more formats. STBTT_GPOS_TODO_assert(valueFormat1 == 4); if (valueFormat1 != 4) return 0; STBTT_GPOS_TODO_assert(valueFormat2 == 0); if (valueFormat2 != 0) return 0; if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) { stbtt_uint8 *class1Records = table + 16; stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count); stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class); return xAdvance; } } break; default: { // There are no other cases. STBTT_assert(0); break; }; } } break; }; default: // TODO: Implement other stuff. break; } } return 0; } STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) { int xAdvance = 0; if (info->gpos) xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); else if (info->kern) xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); return xAdvance; } STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) { if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs return 0; return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); } STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) { stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); } STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) { if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); if (descent) *descent = ttSHORT(info->data+info->hhea + 6); if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); } STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) { int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); if (!tab) return 0; if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); return 1; } STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) { *x0 = ttSHORT(info->data + info->head + 36); *y0 = ttSHORT(info->data + info->head + 38); *x1 = ttSHORT(info->data + info->head + 40); *y1 = ttSHORT(info->data + info->head + 42); } STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) { int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); return (float) height / fheight; } STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) { int unitsPerEm = ttUSHORT(info->data + info->head + 18); return pixels / unitsPerEm; } STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) { STBTT_free(v, info->userdata); } STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl) { int i; stbtt_uint8 *data = info->data; stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info); int numEntries = ttUSHORT(svg_doc_list); stbtt_uint8 *svg_docs = svg_doc_list + 2; for(i=0; i<numEntries; i++) { stbtt_uint8 *svg_doc = svg_docs + (12 * i); if ((gl >= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2))) return svg_doc; } return 0; } STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg) { stbtt_uint8 *data = info->data; stbtt_uint8 *svg_doc; if (info->svg == 0) return 0; svg_doc = stbtt_FindSVGDoc(info, gl); if (svg_doc != NULL) { *svg = (char *) data + info->svg + ttULONG(svg_doc + 4); return ttULONG(svg_doc + 8); } else { return 0; } } STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg) { return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg); } ////////////////////////////////////////////////////////////////////////////// // // antialiasing software rasterizer // STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { // e.g. space character if (ix0) *ix0 = 0; if (iy0) *iy0 = 0; if (ix1) *ix1 = 0; if (iy1) *iy1 = 0; } else { // move to integral bboxes (treating pixels as little squares, what pixels get touched)? if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); } } STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); } STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); } STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); } ////////////////////////////////////////////////////////////////////////////// // // Rasterizer typedef struct stbtt__hheap_chunk { struct stbtt__hheap_chunk *next; } stbtt__hheap_chunk; typedef struct stbtt__hheap { struct stbtt__hheap_chunk *head; void *first_free; int num_remaining_in_head_chunk; } stbtt__hheap; static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) { if (hh->first_free) { void *p = hh->first_free; hh->first_free = * (void **) p; return p; } else { if (hh->num_remaining_in_head_chunk == 0) { int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); if (c == NULL) return NULL; c->next = hh->head; hh->head = c; hh->num_remaining_in_head_chunk = count; } --hh->num_remaining_in_head_chunk; return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; } } static void stbtt__hheap_free(stbtt__hheap *hh, void *p) { *(void **) p = hh->first_free; hh->first_free = p; } static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) { stbtt__hheap_chunk *c = hh->head; while (c) { stbtt__hheap_chunk *n = c->next; STBTT_free(c, userdata); c = n; } } typedef struct stbtt__edge { float x0,y0, x1,y1; int invert; } stbtt__edge; typedef struct stbtt__active_edge { struct stbtt__active_edge *next; #if STBTT_RASTERIZER_VERSION==1 int x,dx; float ey; int direction; #elif STBTT_RASTERIZER_VERSION==2 float fx,fdx,fdy; float direction; float sy; float ey; #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif } stbtt__active_edge; #if STBTT_RASTERIZER_VERSION == 1 #define STBTT_FIXSHIFT 10 #define STBTT_FIX (1 << STBTT_FIXSHIFT) #define STBTT_FIXMASK (STBTT_FIX-1) static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) { stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); STBTT_assert(z != NULL); if (!z) return z; // round dx down to avoid overshooting if (dxdy < 0) z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); else z->dx = STBTT_ifloor(STBTT_FIX * dxdy); z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount z->x -= off_x * STBTT_FIX; z->ey = e->y1; z->next = 0; z->direction = e->invert ? 1 : -1; return z; } #elif STBTT_RASTERIZER_VERSION == 2 static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) { stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); STBTT_assert(z != NULL); //STBTT_assert(e->y0 <= start_point); if (!z) return z; z->fdx = dxdy; z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; z->fx = e->x0 + dxdy * (start_point - e->y0); z->fx -= off_x; z->direction = e->invert ? 1.0f : -1.0f; z->sy = e->y0; z->ey = e->y1; z->next = 0; return z; } #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif #if STBTT_RASTERIZER_VERSION == 1 // note: this routine clips fills that extend off the edges... ideally this // wouldn't happen, but it could happen if the truetype glyph bounding boxes // are wrong, or if the user supplies a too-small bitmap static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) { // non-zero winding fill int x0=0, w=0; while (e) { if (w == 0) { // if we're currently at zero, we need to record the edge start point x0 = e->x; w += e->direction; } else { int x1 = e->x; w += e->direction; // if we went to zero, we need to draw if (w == 0) { int i = x0 >> STBTT_FIXSHIFT; int j = x1 >> STBTT_FIXSHIFT; if (i < len && j >= 0) { if (i == j) { // x0,x1 are the same pixel, so compute combined coverage scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); } else { if (i >= 0) // add antialiasing for x0 scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); else i = -1; // clip if (j < len) // add antialiasing for x1 scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); else j = len; // clip for (++i; i < j; ++i) // fill pixels between x0 and x1 scanline[i] = scanline[i] + (stbtt_uint8) max_weight; } } } } e = e->next; } } static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0; int max_weight = (255 / vsubsample); // weight per vertical scanline int s; // vertical subsample index unsigned char scanline_data[512], *scanline; if (result->w > 512) scanline = (unsigned char *) STBTT_malloc(result->w, userdata); else scanline = scanline_data; y = off_y * vsubsample; e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; while (j < result->h) { STBTT_memset(scanline, 0, result->w); for (s=0; s < vsubsample; ++s) { // find center of pixel for this scanline float scan_y = y + 0.5f; stbtt__active_edge **step = &active; // update all active edges; // remove all active edges that terminate before the center of this scanline while (*step) { stbtt__active_edge * z = *step; if (z->ey <= scan_y) { *step = z->next; // delete from list STBTT_assert(z->direction); z->direction = 0; stbtt__hheap_free(&hh, z); } else { z->x += z->dx; // advance to position for current scanline step = &((*step)->next); // advance through list } } // resort the list if needed for(;;) { int changed=0; step = &active; while (*step && (*step)->next) { if ((*step)->x > (*step)->next->x) { stbtt__active_edge *t = *step; stbtt__active_edge *q = t->next; t->next = q->next; q->next = t; *step = q; changed = 1; } step = &(*step)->next; } if (!changed) break; } // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline while (e->y0 <= scan_y) { if (e->y1 > scan_y) { stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); if (z != NULL) { // find insertion point if (active == NULL) active = z; else if (z->x < active->x) { // insert at front z->next = active; active = z; } else { // find thing to insert AFTER stbtt__active_edge *p = active; while (p->next && p->next->x < z->x) p = p->next; // at this point, p->next->x is NOT < z->x z->next = p->next; p->next = z; } } } ++e; } // now process all active edges in XOR fashion if (active) stbtt__fill_active_edges(scanline, result->w, active, max_weight); ++y; } STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); ++j; } stbtt__hheap_cleanup(&hh, userdata); if (scanline != scanline_data) STBTT_free(scanline, userdata); } #elif STBTT_RASTERIZER_VERSION == 2 // the edge passed in here does not cross the vertical line at x or the vertical line at x+1 // (i.e. it has already been clipped to those) static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) { if (y0 == y1) return; STBTT_assert(y0 < y1); STBTT_assert(e->sy <= e->ey); if (y0 > e->ey) return; if (y1 < e->sy) return; if (y0 < e->sy) { x0 += (x1-x0) * (e->sy - y0) / (y1-y0); y0 = e->sy; } if (y1 > e->ey) { x1 += (x1-x0) * (e->ey - y1) / (y1-y0); y1 = e->ey; } if (x0 == x) STBTT_assert(x1 <= x+1); else if (x0 == x+1) STBTT_assert(x1 >= x); else if (x0 <= x) STBTT_assert(x1 <= x); else if (x0 >= x+1) STBTT_assert(x1 >= x+1); else STBTT_assert(x1 >= x && x1 <= x+1); if (x0 <= x && x1 <= x) scanline[x] += e->direction * (y1-y0); else if (x0 >= x+1 && x1 >= x+1) ; else { STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position } } static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) { float y_bottom = y_top+1; while (e) { // brute force every pixel // compute intersection points with top & bottom STBTT_assert(e->ey >= y_top); if (e->fdx == 0) { float x0 = e->fx; if (x0 < len) { if (x0 >= 0) { stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); } else { stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); } } } else { float x0 = e->fx; float dx = e->fdx; float xb = x0 + dx; float x_top, x_bottom; float sy0,sy1; float dy = e->fdy; STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); // compute endpoints of line segment clipped to this scanline (if the // line segment starts on this scanline. x0 is the intersection of the // line with y_top, but that may be off the line segment. if (e->sy > y_top) { x_top = x0 + dx * (e->sy - y_top); sy0 = e->sy; } else { x_top = x0; sy0 = y_top; } if (e->ey < y_bottom) { x_bottom = x0 + dx * (e->ey - y_top); sy1 = e->ey; } else { x_bottom = xb; sy1 = y_bottom; } if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { // from here on, we don't have to range check x values if ((int) x_top == (int) x_bottom) { float height; // simple case, only spans one pixel int x = (int) x_top; height = sy1 - sy0; STBTT_assert(x >= 0 && x < len); scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height; scanline_fill[x] += e->direction * height; // everything right of this pixel is filled } else { int x,x1,x2; float y_crossing, step, sign, area; // covers 2+ pixels if (x_top > x_bottom) { // flip scanline vertically; signed area is the same float t; sy0 = y_bottom - (sy0 - y_top); sy1 = y_bottom - (sy1 - y_top); t = sy0, sy0 = sy1, sy1 = t; t = x_bottom, x_bottom = x_top, x_top = t; dx = -dx; dy = -dy; t = x0, x0 = xb, xb = t; } x1 = (int) x_top; x2 = (int) x_bottom; // compute intersection with y axis at x1+1 y_crossing = (x1+1 - x0) * dy + y_top; sign = e->direction; // area of the rectangle covered from y0..y_crossing area = sign * (y_crossing-sy0); // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing) scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2); step = sign * dy; for (x = x1+1; x < x2; ++x) { scanline[x] += area + step/2; area += step; } y_crossing += dy * (x2 - (x1+1)); STBTT_assert(STBTT_fabs(area) <= 1.01f); scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing); scanline_fill[x2] += sign * (sy1-sy0); } } else { // if edge goes outside of box we're drawing, we require // clipping logic. since this does not match the intended use // of this library, we use a different, very slow brute // force implementation int x; for (x=0; x < len; ++x) { // cases: // // there can be up to two intersections with the pixel. any intersection // with left or right edges can be handled by splitting into two (or three) // regions. intersections with top & bottom do not necessitate case-wise logic. // // the old way of doing this found the intersections with the left & right edges, // then used some simple logic to produce up to three segments in sorted order // from top-to-bottom. however, this had a problem: if an x edge was epsilon // across the x border, then the corresponding y position might not be distinct // from the other y segment, and it might ignored as an empty segment. to avoid // that, we need to explicitly produce segments based on x positions. // rename variables to clearly-defined pairs float y0 = y_top; float x1 = (float) (x); float x2 = (float) (x+1); float x3 = xb; float y3 = y_bottom; // x = e->x + e->dx * (y-y_top) // (y-y_top) = (x - e->x) / e->dx // y = (x - e->x) / e->dx + y_top float y1 = (x - x0) / dx + y_top; float y2 = (x+1 - x0) / dx + y_top; if (x0 < x1 && x3 > x2) { // three segments descending down-right stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else if (x3 < x1 && x0 > x2) { // three segments descending down-left stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else { // one segment stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); } } } } e = e->next; } } // directly AA rasterize edges w/o supersampling static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0, i; float scanline_data[129], *scanline, *scanline2; STBTT__NOTUSED(vsubsample); if (result->w > 64) scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); else scanline = scanline_data; scanline2 = scanline + result->w; y = off_y; e[n].y0 = (float) (off_y + result->h) + 1; while (j < result->h) { // find center of pixel for this scanline float scan_y_top = y + 0.0f; float scan_y_bottom = y + 1.0f; stbtt__active_edge **step = &active; STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); // update all active edges; // remove all active edges that terminate before the top of this scanline while (*step) { stbtt__active_edge * z = *step; if (z->ey <= scan_y_top) { *step = z->next; // delete from list STBTT_assert(z->direction); z->direction = 0; stbtt__hheap_free(&hh, z); } else { step = &((*step)->next); // advance through list } } // insert all edges that start before the bottom of this scanline while (e->y0 <= scan_y_bottom) { if (e->y0 != e->y1) { stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); if (z != NULL) { if (j == 0 && off_y != 0) { if (z->ey < scan_y_top) { // this can happen due to subpixel positioning and some kind of fp rounding error i think z->ey = scan_y_top; } } STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds // insert at front z->next = active; active = z; } } ++e; } // now process all active edges if (active) stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); { float sum = 0; for (i=0; i < result->w; ++i) { float k; int m; sum += scanline2[i]; k = scanline[i] + sum; k = (float) STBTT_fabs(k)*255 + 0.5f; m = (int) k; if (m > 255) m = 255; result->pixels[j*result->stride + i] = (unsigned char) m; } } // advance all the edges step = &active; while (*step) { stbtt__active_edge *z = *step; z->fx += z->fdx; // advance to position for current scanline step = &((*step)->next); // advance through list } ++y; ++j; } stbtt__hheap_cleanup(&hh, userdata); if (scanline != scanline_data) STBTT_free(scanline, userdata); } #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif #define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) { int i,j; for (i=1; i < n; ++i) { stbtt__edge t = p[i], *a = &t; j = i; while (j > 0) { stbtt__edge *b = &p[j-1]; int c = STBTT__COMPARE(a,b); if (!c) break; p[j] = p[j-1]; --j; } if (i != j) p[j] = t; } } static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) { /* threshold for transitioning to insertion sort */ while (n > 12) { stbtt__edge t; int c01,c12,c,m,i,j; /* compute median of three */ m = n >> 1; c01 = STBTT__COMPARE(&p[0],&p[m]); c12 = STBTT__COMPARE(&p[m],&p[n-1]); /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ if (c01 != c12) { /* otherwise, we'll need to swap something else to middle */ int z; c = STBTT__COMPARE(&p[0],&p[n-1]); /* 0>mid && mid<n: 0>n => n; 0<n => 0 */ /* 0<mid && mid>n: 0>n => 0; 0<n => n */ z = (c == c12) ? 0 : n-1; t = p[z]; p[z] = p[m]; p[m] = t; } /* now p[m] is the median-of-three */ /* swap it to the beginning so it won't move around */ t = p[0]; p[0] = p[m]; p[m] = t; /* partition loop */ i=1; j=n-1; for(;;) { /* handling of equality is crucial here */ /* for sentinels & efficiency with duplicates */ for (;;++i) { if (!STBTT__COMPARE(&p[i], &p[0])) break; } for (;;--j) { if (!STBTT__COMPARE(&p[0], &p[j])) break; } /* make sure we haven't crossed */ if (i >= j) break; t = p[i]; p[i] = p[j]; p[j] = t; ++i; --j; } /* recurse on smaller side, iterate on larger */ if (j < (n-i)) { stbtt__sort_edges_quicksort(p,j); p = p+i; n = n-i; } else { stbtt__sort_edges_quicksort(p+i, n-i); n = j; } } } static void stbtt__sort_edges(stbtt__edge *p, int n) { stbtt__sort_edges_quicksort(p, n); stbtt__sort_edges_ins_sort(p, n); } typedef struct { float x,y; } stbtt__point; static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) { float y_scale_inv = invert ? -scale_y : scale_y; stbtt__edge *e; int n,i,j,k,m; #if STBTT_RASTERIZER_VERSION == 1 int vsubsample = result->h < 8 ? 15 : 5; #elif STBTT_RASTERIZER_VERSION == 2 int vsubsample = 1; #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif // vsubsample should divide 255 evenly; otherwise we won't reach full opacity // now we have to blow out the windings into explicit edge lists n = 0; for (i=0; i < windings; ++i) n += wcount[i]; e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel if (e == 0) return; n = 0; m=0; for (i=0; i < windings; ++i) { stbtt__point *p = pts + m; m += wcount[i]; j = wcount[i]-1; for (k=0; k < wcount[i]; j=k++) { int a=k,b=j; // skip the edge if horizontal if (p[j].y == p[k].y) continue; // add edge from j to k to the list e[n].invert = 0; if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { e[n].invert = 1; a=j,b=k; } e[n].x0 = p[a].x * scale_x + shift_x; e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; e[n].x1 = p[b].x * scale_x + shift_x; e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; ++n; } } // now sort the edges by their highest point (should snap to integer, and then by x) //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); stbtt__sort_edges(e, n); // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); STBTT_free(e, userdata); } static void stbtt__add_point(stbtt__point *points, int n, float x, float y) { if (!points) return; // during first pass, it's unallocated points[n].x = x; points[n].y = y; } // tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) { // midpoint float mx = (x0 + 2*x1 + x2)/4; float my = (y0 + 2*y1 + y2)/4; // versus directly drawn line float dx = (x0+x2)/2 - mx; float dy = (y0+y2)/2 - my; if (n > 16) // 65536 segments on one curve better be enough! return 1; if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); } else { stbtt__add_point(points, *num_points,x2,y2); *num_points = *num_points+1; } return 1; } static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) { // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough float dx0 = x1-x0; float dy0 = y1-y0; float dx1 = x2-x1; float dy1 = y2-y1; float dx2 = x3-x2; float dy2 = y3-y2; float dx = x3-x0; float dy = y3-y0; float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); float flatness_squared = longlen*longlen-shortlen*shortlen; if (n > 16) // 65536 segments on one curve better be enough! return; if (flatness_squared > objspace_flatness_squared) { float x01 = (x0+x1)/2; float y01 = (y0+y1)/2; float x12 = (x1+x2)/2; float y12 = (y1+y2)/2; float x23 = (x2+x3)/2; float y23 = (y2+y3)/2; float xa = (x01+x12)/2; float ya = (y01+y12)/2; float xb = (x12+x23)/2; float yb = (y12+y23)/2; float mx = (xa+xb)/2; float my = (ya+yb)/2; stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); } else { stbtt__add_point(points, *num_points,x3,y3); *num_points = *num_points+1; } } // returns number of contours static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) { stbtt__point *points=0; int num_points=0; float objspace_flatness_squared = objspace_flatness * objspace_flatness; int i,n=0,start=0, pass; // count how many "moves" there are to get the contour count for (i=0; i < num_verts; ++i) if (vertices[i].type == STBTT_vmove) ++n; *num_contours = n; if (n == 0) return 0; *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); if (*contour_lengths == 0) { *num_contours = 0; return 0; } // make two passes through the points so we don't need to realloc for (pass=0; pass < 2; ++pass) { float x=0,y=0; if (pass == 1) { points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); if (points == NULL) goto error; } num_points = 0; n= -1; for (i=0; i < num_verts; ++i) { switch (vertices[i].type) { case STBTT_vmove: // start the next contour if (n >= 0) (*contour_lengths)[n] = num_points - start; ++n; start = num_points; x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x,y); break; case STBTT_vline: x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x, y); break; case STBTT_vcurve: stbtt__tesselate_curve(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; case STBTT_vcubic: stbtt__tesselate_cubic(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].cx1, vertices[i].cy1, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; } } (*contour_lengths)[n] = num_points - start; } return points; error: STBTT_free(points, userdata); STBTT_free(*contour_lengths, userdata); *contour_lengths = 0; *num_contours = 0; return NULL; } STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) { float scale = scale_x > scale_y ? scale_y : scale_x; int winding_count = 0; int *winding_lengths = NULL; stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); if (windings) { stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); STBTT_free(winding_lengths, userdata); STBTT_free(windings, userdata); } } STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) { STBTT_free(bitmap, userdata); } STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) { int ix0,iy0,ix1,iy1; stbtt__bitmap gbm; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { if (scale_x == 0) { STBTT_free(vertices, info->userdata); return NULL; } scale_y = scale_x; } stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); // now we get the size gbm.w = (ix1 - ix0); gbm.h = (iy1 - iy0); gbm.pixels = NULL; // in case we error if (width ) *width = gbm.w; if (height) *height = gbm.h; if (xoff ) *xoff = ix0; if (yoff ) *yoff = iy0; if (gbm.w && gbm.h) { gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); if (gbm.pixels) { gbm.stride = gbm.w; stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); } } STBTT_free(vertices, info->userdata); return gbm.pixels; } STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); } STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) { int ix0,iy0; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); stbtt__bitmap gbm; stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); gbm.pixels = output; gbm.w = out_w; gbm.h = out_h; gbm.stride = out_stride; if (gbm.w && gbm.h) stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); STBTT_free(vertices, info->userdata); } STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); } STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); } STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) { stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); } STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); } STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); } STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) { stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); } ////////////////////////////////////////////////////////////////////////////// // // bitmap baking // // This is SUPER-CRAPPY packing to keep source code small static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake stbtt_bakedchar *chardata) { float scale; int x,y,bottom_y, i; stbtt_fontinfo f; f.userdata = NULL; if (!stbtt_InitFont(&f, data, offset)) return -1; STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels x=y=1; bottom_y = 1; scale = stbtt_ScaleForPixelHeight(&f, pixel_height); for (i=0; i < num_chars; ++i) { int advance, lsb, x0,y0,x1,y1,gw,gh; int g = stbtt_FindGlyphIndex(&f, first_char + i); stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); gw = x1-x0; gh = y1-y0; if (x + gw + 1 >= pw) y = bottom_y, x = 1; // advance to next row if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row return -i; STBTT_assert(x+gw < pw); STBTT_assert(y+gh < ph); stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); chardata[i].x0 = (stbtt_int16) x; chardata[i].y0 = (stbtt_int16) y; chardata[i].x1 = (stbtt_int16) (x + gw); chardata[i].y1 = (stbtt_int16) (y + gh); chardata[i].xadvance = scale * advance; chardata[i].xoff = (float) x0; chardata[i].yoff = (float) y0; x = x + gw + 1; if (y+gh+1 > bottom_y) bottom_y = y+gh+1; } return bottom_y; } STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) { float d3d_bias = opengl_fillrule ? 0 : -0.5f; float ipw = 1.0f / pw, iph = 1.0f / ph; const stbtt_bakedchar *b = chardata + char_index; int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = round_x + d3d_bias; q->y0 = round_y + d3d_bias; q->x1 = round_x + b->x1 - b->x0 + d3d_bias; q->y1 = round_y + b->y1 - b->y0 + d3d_bias; q->s0 = b->x0 * ipw; q->t0 = b->y0 * iph; q->s1 = b->x1 * ipw; q->t1 = b->y1 * iph; *xpos += b->xadvance; } ////////////////////////////////////////////////////////////////////////////// // // rectangle packing replacement routines if you don't have stb_rect_pack.h // #ifndef STB_RECT_PACK_VERSION typedef int stbrp_coord; //////////////////////////////////////////////////////////////////////////////////// // // // // // COMPILER WARNING ?!?!? // // // // // // if you get a compile warning due to these symbols being defined more than // // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // // // //////////////////////////////////////////////////////////////////////////////////// typedef struct { int width,height; int x,y,bottom_y; } stbrp_context; typedef struct { unsigned char x; } stbrp_node; struct stbrp_rect { stbrp_coord x,y; int id,w,h,was_packed; }; static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) { con->width = pw; con->height = ph; con->x = 0; con->y = 0; con->bottom_y = 0; STBTT__NOTUSED(nodes); STBTT__NOTUSED(num_nodes); } static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) { int i; for (i=0; i < num_rects; ++i) { if (con->x + rects[i].w > con->width) { con->x = 0; con->y = con->bottom_y; } if (con->y + rects[i].h > con->height) break; rects[i].x = con->x; rects[i].y = con->y; rects[i].was_packed = 1; con->x += rects[i].w; if (con->y + rects[i].h > con->bottom_y) con->bottom_y = con->y + rects[i].h; } for ( ; i < num_rects; ++i) rects[i].was_packed = 0; } #endif ////////////////////////////////////////////////////////////////////////////// // // bitmap baking // // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) { stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); int num_nodes = pw - padding; stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); if (context == NULL || nodes == NULL) { if (context != NULL) STBTT_free(context, alloc_context); if (nodes != NULL) STBTT_free(nodes , alloc_context); return 0; } spc->user_allocator_context = alloc_context; spc->width = pw; spc->height = ph; spc->pixels = pixels; spc->pack_info = context; spc->nodes = nodes; spc->padding = padding; spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; spc->h_oversample = 1; spc->v_oversample = 1; spc->skip_missing = 0; stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); if (pixels) STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels return 1; } STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) { STBTT_free(spc->nodes , spc->user_allocator_context); STBTT_free(spc->pack_info, spc->user_allocator_context); } STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) { STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); if (h_oversample <= STBTT_MAX_OVERSAMPLE) spc->h_oversample = h_oversample; if (v_oversample <= STBTT_MAX_OVERSAMPLE) spc->v_oversample = v_oversample; } STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) { spc->skip_missing = skip; } #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_w = w - kernel_width; int j; STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < h; ++j) { int i; unsigned int total; STBTT_memset(buffer, 0, kernel_width); total = 0; // make kernel_width a constant in common cases so compiler can optimize out the divide switch (kernel_width) { case 2: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 2); } break; case 3: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 3); } break; case 4: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 4); } break; case 5: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 5); } break; default: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / kernel_width); } break; } for (; i < w; ++i) { STBTT_assert(pixels[i] == 0); total -= buffer[i & STBTT__OVER_MASK]; pixels[i] = (unsigned char) (total / kernel_width); } pixels += stride_in_bytes; } } static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_h = h - kernel_width; int j; STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < w; ++j) { int i; unsigned int total; STBTT_memset(buffer, 0, kernel_width); total = 0; // make kernel_width a constant in common cases so compiler can optimize out the divide switch (kernel_width) { case 2: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 2); } break; case 3: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 3); } break; case 4: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 4); } break; case 5: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 5); } break; default: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); } break; } for (; i < h; ++i) { STBTT_assert(pixels[i*stride_in_bytes] == 0); total -= buffer[i & STBTT__OVER_MASK]; pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); } pixels += 1; } } static float stbtt__oversample_shift(int oversample) { if (!oversample) return 0.0f; // The prefilter is a box filter of width "oversample", // which shifts phase by (oversample - 1)/2 pixels in // oversampled space. We want to shift in the opposite // direction to counter this. return (float)-(oversample - 1) / (2.0f * (float)oversample); } // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { int i,j,k; int missing_glyph_added = 0; k=0; for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); ranges[i].h_oversample = (unsigned char) spc->h_oversample; ranges[i].v_oversample = (unsigned char) spc->v_oversample; for (j=0; j < ranges[i].num_chars; ++j) { int x0,y0,x1,y1; int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = stbtt_FindGlyphIndex(info, codepoint); if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) { rects[k].w = rects[k].h = 0; } else { stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, scale * spc->h_oversample, scale * spc->v_oversample, 0,0, &x0,&y0,&x1,&y1); rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); if (glyph == 0) missing_glyph_added = 1; } ++k; } } return k; } STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph); if (prefilter_x > 1) stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); if (prefilter_y > 1) stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); *sub_x = stbtt__oversample_shift(prefilter_x); *sub_y = stbtt__oversample_shift(prefilter_y); } // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { int i,j,k, missing_glyph = -1, return_value = 1; // save current values int old_h_over = spc->h_oversample; int old_v_over = spc->v_oversample; k = 0; for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); float recip_h,recip_v,sub_x,sub_y; spc->h_oversample = ranges[i].h_oversample; spc->v_oversample = ranges[i].v_oversample; recip_h = 1.0f / spc->h_oversample; recip_v = 1.0f / spc->v_oversample; sub_x = stbtt__oversample_shift(spc->h_oversample); sub_y = stbtt__oversample_shift(spc->v_oversample); for (j=0; j < ranges[i].num_chars; ++j) { stbrp_rect *r = &rects[k]; if (r->was_packed && r->w != 0 && r->h != 0) { stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; int advance, lsb, x0,y0,x1,y1; int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = stbtt_FindGlyphIndex(info, codepoint); stbrp_coord pad = (stbrp_coord) spc->padding; // pad on left and top r->x += pad; r->y += pad; r->w -= pad; r->h -= pad; stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); stbtt_GetGlyphBitmapBox(info, glyph, scale * spc->h_oversample, scale * spc->v_oversample, &x0,&y0,&x1,&y1); stbtt_MakeGlyphBitmapSubpixel(info, spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w - spc->h_oversample+1, r->h - spc->v_oversample+1, spc->stride_in_bytes, scale * spc->h_oversample, scale * spc->v_oversample, 0,0, glyph); if (spc->h_oversample > 1) stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w, r->h, spc->stride_in_bytes, spc->h_oversample); if (spc->v_oversample > 1) stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w, r->h, spc->stride_in_bytes, spc->v_oversample); bc->x0 = (stbtt_int16) r->x; bc->y0 = (stbtt_int16) r->y; bc->x1 = (stbtt_int16) (r->x + r->w); bc->y1 = (stbtt_int16) (r->y + r->h); bc->xadvance = scale * advance; bc->xoff = (float) x0 * recip_h + sub_x; bc->yoff = (float) y0 * recip_v + sub_y; bc->xoff2 = (x0 + r->w) * recip_h + sub_x; bc->yoff2 = (y0 + r->h) * recip_v + sub_y; if (glyph == 0) missing_glyph = j; } else if (spc->skip_missing) { return_value = 0; } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; } else { return_value = 0; // if any fail, report failure } ++k; } } // restore original values spc->h_oversample = old_h_over; spc->v_oversample = old_v_over; return return_value; } STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) { stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); } STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) { stbtt_fontinfo info; int i,j,n, return_value = 1; //stbrp_context *context = (stbrp_context *) spc->pack_info; stbrp_rect *rects; // flag all characters as NOT packed for (i=0; i < num_ranges; ++i) for (j=0; j < ranges[i].num_chars; ++j) ranges[i].chardata_for_range[j].x0 = ranges[i].chardata_for_range[j].y0 = ranges[i].chardata_for_range[j].x1 = ranges[i].chardata_for_range[j].y1 = 0; n = 0; for (i=0; i < num_ranges; ++i) n += ranges[i].num_chars; rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); if (rects == NULL) return 0; info.userdata = spc->user_allocator_context; stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); stbtt_PackFontRangesPackRects(spc, rects, n); return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); STBTT_free(rects, spc->user_allocator_context); return return_value; } STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) { stbtt_pack_range range; range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; range.array_of_unicode_codepoints = NULL; range.num_chars = num_chars_in_range; range.chardata_for_range = chardata_for_range; range.font_size = font_size; return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); } STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) { int i_ascent, i_descent, i_lineGap; float scale; stbtt_fontinfo info; stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); *ascent = (float) i_ascent * scale; *descent = (float) i_descent * scale; *lineGap = (float) i_lineGap * scale; } STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) { float ipw = 1.0f / pw, iph = 1.0f / ph; const stbtt_packedchar *b = chardata + char_index; if (align_to_integer) { float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = x; q->y0 = y; q->x1 = x + b->xoff2 - b->xoff; q->y1 = y + b->yoff2 - b->yoff; } else { q->x0 = *xpos + b->xoff; q->y0 = *ypos + b->yoff; q->x1 = *xpos + b->xoff2; q->y1 = *ypos + b->yoff2; } q->s0 = b->x0 * ipw; q->t0 = b->y0 * iph; q->s1 = b->x1 * ipw; q->t1 = b->y1 * iph; *xpos += b->xadvance; } ////////////////////////////////////////////////////////////////////////////// // // sdf computation // #define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) #define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) { float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; float roperp = orig[1]*ray[0] - orig[0]*ray[1]; float a = q0perp - 2*q1perp + q2perp; float b = q1perp - q0perp; float c = q0perp - roperp; float s0 = 0., s1 = 0.; int num_s = 0; if (a != 0.0) { float discr = b*b - a*c; if (discr > 0.0) { float rcpna = -1 / a; float d = (float) STBTT_sqrt(discr); s0 = (b+d) * rcpna; s1 = (b-d) * rcpna; if (s0 >= 0.0 && s0 <= 1.0) num_s = 1; if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { if (num_s == 0) s0 = s1; ++num_s; } } } else { // 2*b*s + c = 0 // s = -c / (2*b) s0 = c / (-2 * b); if (s0 >= 0.0 && s0 <= 1.0) num_s = 1; } if (num_s == 0) return 0; else { float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; float q0d = q0[0]*rayn_x + q0[1]*rayn_y; float q1d = q1[0]*rayn_x + q1[1]*rayn_y; float q2d = q2[0]*rayn_x + q2[1]*rayn_y; float rod = orig[0]*rayn_x + orig[1]*rayn_y; float q10d = q1d - q0d; float q20d = q2d - q0d; float q0rd = q0d - rod; hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; hits[0][1] = a*s0+b; if (num_s > 1) { hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; hits[1][1] = a*s1+b; return 2; } else { return 1; } } } static int equal(float *a, float *b) { return (a[0] == b[0] && a[1] == b[1]); } static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) { int i; float orig[2], ray[2] = { 1, 0 }; float y_frac; int winding = 0; orig[0] = x; orig[1] = y; // make sure y never passes through a vertex of the shape y_frac = (float) STBTT_fmod(y, 1.0f); if (y_frac < 0.01f) y += 0.01f; else if (y_frac > 0.99f) y -= 0.01f; orig[1] = y; // test a ray from (-infinity,y) to (x,y) for (i=0; i < nverts; ++i) { if (verts[i].type == STBTT_vline) { int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; if (x_inter < x) winding += (y0 < y1) ? 1 : -1; } } if (verts[i].type == STBTT_vcurve) { int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); int by = STBTT_max(y0,STBTT_max(y1,y2)); if (y > ay && y < by && x > ax) { float q0[2],q1[2],q2[2]; float hits[2][2]; q0[0] = (float)x0; q0[1] = (float)y0; q1[0] = (float)x1; q1[1] = (float)y1; q2[0] = (float)x2; q2[1] = (float)y2; if (equal(q0,q1) || equal(q1,q2)) { x0 = (int)verts[i-1].x; y0 = (int)verts[i-1].y; x1 = (int)verts[i ].x; y1 = (int)verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; if (x_inter < x) winding += (y0 < y1) ? 1 : -1; } } else { int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); if (num_hits >= 1) if (hits[0][0] < 0) winding += (hits[0][1] < 0 ? -1 : 1); if (num_hits >= 2) if (hits[1][0] < 0) winding += (hits[1][1] < 0 ? -1 : 1); } } } } return winding; } static float stbtt__cuberoot( float x ) { if (x<0) return -(float) STBTT_pow(-x,1.0f/3.0f); else return (float) STBTT_pow( x,1.0f/3.0f); } // x^3 + c*x^2 + b*x + a = 0 static int stbtt__solve_cubic(float a, float b, float c, float* r) { float s = -a / 3; float p = b - a*a / 3; float q = a * (2*a*a - 9*b) / 27 + c; float p3 = p*p*p; float d = q*q + 4*p3 / 27; if (d >= 0) { float z = (float) STBTT_sqrt(d); float u = (-q + z) / 2; float v = (-q - z) / 2; u = stbtt__cuberoot(u); v = stbtt__cuberoot(v); r[0] = s + u + v; return 1; } else { float u = (float) STBTT_sqrt(-p/3); float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative float m = (float) STBTT_cos(v); float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; r[0] = s + u * 2 * m; r[1] = s - u * (m + n); r[2] = s - u * (m - n); //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); return 3; } } STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) { float scale_x = scale, scale_y = scale; int ix0,iy0,ix1,iy1; int w,h; unsigned char *data; if (scale == 0) return NULL; stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); // if empty, return NULL if (ix0 == ix1 || iy0 == iy1) return NULL; ix0 -= padding; iy0 -= padding; ix1 += padding; iy1 += padding; w = (ix1 - ix0); h = (iy1 - iy0); if (width ) *width = w; if (height) *height = h; if (xoff ) *xoff = ix0; if (yoff ) *yoff = iy0; // invert for y-downwards bitmaps scale_y = -scale_y; { int x,y,i,j; float *precompute; stbtt_vertex *verts; int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); data = (unsigned char *) STBTT_malloc(w * h, info->userdata); precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); for (i=0,j=num_verts-1; i < num_verts; j=i++) { if (verts[i].type == STBTT_vline) { float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float len2 = bx*bx + by*by; if (len2 != 0.0f) precompute[i] = 1.0f / (bx*bx + by*by); else precompute[i] = 0.0f; } else precompute[i] = 0.0f; } for (y=iy0; y < iy1; ++y) { for (x=ix0; x < ix1; ++x) { float val; float min_dist = 999999.0f; float sx = (float) x + 0.5f; float sy = (float) y + 0.5f; float x_gspace = (sx / scale_x); float y_gspace = (sy / scale_y); int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path for (i=0; i < num_verts; ++i) { float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; // check against every point here rather than inside line/curve primitives -- @TODO: wrong if multiple 'moves' in a row produce a garbage point, and given culling, probably more efficient to do within line/curve float dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); if (dist2 < min_dist*min_dist) min_dist = (float) STBTT_sqrt(dist2); if (verts[i].type == STBTT_vline) { float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; // coarse culling against bbox //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) float dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; STBTT_assert(i != 0); if (dist < min_dist) { // check position along line // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) float dx = x1-x0, dy = y1-y0; float px = x0-sx, py = y0-sy; // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve float t = -(px*dx + py*dy) / (dx*dx + dy*dy); if (t >= 0.0f && t <= 1.0f) min_dist = dist; } } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); // coarse culling against bbox to avoid computing cubic unnecessarily if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { int num=0; float ax = x1-x0, ay = y1-y0; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float mx = x0 - sx, my = y0 - sy; float res[3],px,py,t,it; float a_inv = precompute[i]; if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula float a = 3*(ax*bx + ay*by); float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); float c = mx*ax+my*ay; if (a == 0.0) { // if a is 0, it's linear if (b != 0.0) { res[num++] = -c/b; } } else { float discriminant = b*b - 4*a*c; if (discriminant < 0) num = 0; else { float root = (float) STBTT_sqrt(discriminant); res[0] = (-b - root)/(2*a); res[1] = (-b + root)/(2*a); num = 2; // don't bother distinguishing 1-solution case, as code below will still work } } } else { float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; float d = (mx*ax+my*ay) * a_inv; num = stbtt__solve_cubic(b, c, d, res); } if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { t = res[0], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { t = res[1], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { t = res[2], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } } } } if (winding == 0) min_dist = -min_dist; // if outside the shape, value is negative val = onedge_value + pixel_dist_scale * min_dist; if (val < 0) val = 0; else if (val > 255) val = 255; data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; } } STBTT_free(precompute, info->userdata); STBTT_free(verts, info->userdata); } return data; } STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); } STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) { STBTT_free(bitmap, userdata); } ////////////////////////////////////////////////////////////////////////////// // // font name matching -- recommended not to use this // // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) { stbtt_int32 i=0; // convert utf16 to utf8 and compare the results while converting while (len2) { stbtt_uint16 ch = s2[0]*256 + s2[1]; if (ch < 0x80) { if (i >= len1) return -1; if (s1[i++] != ch) return -1; } else if (ch < 0x800) { if (i+1 >= len1) return -1; if (s1[i++] != 0xc0 + (ch >> 6)) return -1; if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; } else if (ch >= 0xd800 && ch < 0xdc00) { stbtt_uint32 c; stbtt_uint16 ch2 = s2[2]*256 + s2[3]; if (i+3 >= len1) return -1; c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; if (s1[i++] != 0xf0 + (c >> 18)) return -1; if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; s2 += 2; // plus another 2 below len2 -= 2; } else if (ch >= 0xdc00 && ch < 0xe000) { return -1; } else { if (i+2 >= len1) return -1; if (s1[i++] != 0xe0 + (ch >> 12)) return -1; if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; } s2 += 2; len2 -= 2; } return i; } static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) { return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); } // returns results in whatever encoding you request... but note that 2-byte encodings // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) { stbtt_int32 i,count,stringOffset; stbtt_uint8 *fc = font->data; stbtt_uint32 offset = font->fontstart; stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); if (!nm) return NULL; count = ttUSHORT(fc+nm+2); stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { stbtt_uint32 loc = nm + 6 + 12 * i; if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { *length = ttUSHORT(fc+loc+8); return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); } } return NULL; } static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) { stbtt_int32 i; stbtt_int32 count = ttUSHORT(fc+nm+2); stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { stbtt_uint32 loc = nm + 6 + 12 * i; stbtt_int32 id = ttUSHORT(fc+loc+6); if (id == target_id) { // find the encoding stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); // is this a Unicode encoding? if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { stbtt_int32 slen = ttUSHORT(fc+loc+8); stbtt_int32 off = ttUSHORT(fc+loc+10); // check if there's a prefix match stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); if (matchlen >= 0) { // check for target_id+1 immediately following, with same encoding & language if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { slen = ttUSHORT(fc+loc+12+8); off = ttUSHORT(fc+loc+12+10); if (slen == 0) { if (matchlen == nlen) return 1; } else if (matchlen < nlen && name[matchlen] == ' ') { ++matchlen; if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) return 1; } } else { // if nothing immediately following if (matchlen == nlen) return 1; } } } // @TODO handle other encodings } } return 0; } static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) { stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); stbtt_uint32 nm,hd; if (!stbtt__isfont(fc+offset)) return 0; // check italics/bold/underline flags in macStyle... if (flags) { hd = stbtt__find_table(fc, offset, "head"); if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; } nm = stbtt__find_table(fc, offset, "name"); if (!nm) return 0; if (flags) { // if we checked the macStyle flags, then just check the family and ignore the subfamily if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; } else { if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; } return 0; } static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) { stbtt_int32 i; for (i=0;;++i) { stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); if (off < 0) return off; if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) return off; } } #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, float pixel_height, unsigned char *pixels, int pw, int ph, int first_char, int num_chars, stbtt_bakedchar *chardata) { return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); } STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) { return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); } STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) { return stbtt_GetNumberOfFonts_internal((unsigned char *) data); } STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) { return stbtt_InitFont_internal(info, (unsigned char *) data, offset); } STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) { return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); } STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) { return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); } #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic pop #endif #endif // STB_TRUETYPE_IMPLEMENTATION // FULL VERSION HISTORY // // 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod // 1.18 (2018-01-29) add missing function // 1.17 (2017-07-23) make more arguments const; doc fix // 1.16 (2017-07-12) SDF support // 1.15 (2017-03-03) make more arguments const // 1.14 (2017-01-16) num-fonts-in-TTC function // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual // 1.11 (2016-04-02) fix unused-variable warning // 1.10 (2016-04-02) allow user-defined fabs() replacement // fix memory leak if fontsize=0.0 // fix warning from duplicate typedef // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; // allow PackFontRanges to pack and render in separate phases; // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); // fixed an assert() bug in the new rasterizer // replace assert() with STBTT_assert() in new rasterizer // 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) // also more precise AA rasterizer, except if shapes overlap // remove need for STBTT_sort // 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC // 1.04 (2015-04-15) typo in example // 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes // 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ // 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match // non-oversampled; STBTT_POINT_SIZE for packed case only // 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling // 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) // 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID // 0.8b (2014-07-07) fix a warning // 0.8 (2014-05-25) fix a few more warnings // 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back // 0.6c (2012-07-24) improve documentation // 0.6b (2012-07-20) fix a few more warnings // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty // 0.5 (2011-12-09) bugfixes: // subpixel glyph renderer computed wrong bounding box // first vertex of shape can be off-curve (FreeSans) // 0.4b (2011-12-03) fixed an error in the font baking example // 0.4 (2011-12-01) kerning, subpixel rendering (tor) // bugfixes for: // codepoint-to-glyph conversion using table fmt=12 // codepoint-to-glyph conversion using table fmt=4 // stbtt_GetBakedQuad with non-square texture (Zer) // updated Hello World! sample to use kerning and subpixel // fixed some warnings // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) // userdata, malloc-from-userdata, non-zero fill (stb) // 0.2 (2009-03-11) Fix unsigned/signed char warnings // 0.1 (2009-03-09) First public release // /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\gl\nanovg_plus_gl.c
/** * File: nanovg_plus_gl.c * Author: AWTK Develop Team * Brief: nanovg plus by opengl. * * Copyright (c) 2018 - 2021 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-10-27 Luo Zhiming <luozhiming@zlg.cn> created * */ #ifdef WITHOUT_GLAD #include <SDL.h> #ifdef IOS #include <OpenGLES/gltypes.h> #include <OpenGLES/ES2/gl.h> #include <OpenGLES/ES2/glext.h> #else #define GL_GLEXT_PROTOTYPES 1 #include <SDL_opengl.h> #include <SDL_opengl_glext.h> #endif /*IOS*/ #else #include <glad/glad.h> #endif /*WITHOUT_GLAD*/ #include "nanovg_plus_gl.h" #ifdef NVGP_GL3 #define NVGP_GL_USE_UNIFORMBUFFER 1 #endif #define UNIFORM_OFFSET_ALIGNMENT 4 #define NVGP_GL_USE_STATE_FILTER 1 typedef enum _nvgp_gl_shader_type_t { NVGP_GL_SHADER_FILLGRAD, NVGP_GL_SHADER_FILLCOLOR, NVGP_GL_SHADER_FILLGLYPH, NVGP_GL_SHADER_FAST_FILLGLYPH, NVGP_GL_SHADER_FILLIMG, NVGP_GL_SHADER_FAST_FILLIMG, NVGP_GL_SHADER_FILLIMG_RGBA, NVGP_GL_SHADER_FAST_FILLIMG_RGBA, NVGP_GL_SHADER_REPEAT_FILLIMG, NVGP_GL_SHADER_FAST_REPEAT_FILLIMG, NVGP_GL_SHADER_REPEAT_FILLIMG_RGBA, NVGP_GL_SHADER_FAST_REPEAT_FILLIMG_RGBA, NVGP_GL_SHADER_FILL_STROKE, NVGP_GL_SHADER_FAST_FILL_COLOR, NVGP_GL_SHADER_COUNT, }nvgp_gl_shader_type_t; typedef enum _nvgp_gl_call_type_t { NVGP_GL_CALL_FAST_FILL_RECT, NVGP_GL_CALL_CONVEX_FILL, NVGP_GL_CALL_FILL, NVGP_GL_CALL_FAST_FILL_COLOR, NVGP_GL_CALL_IMAGE, NVGP_GL_CALL_STROKE, NVGP_GL_CALL_STROKE_IMAGE, NVGP_GL_CALL_TEXT, } nvgp_gl_call_type_t; typedef enum _nvgp_gl_uniform_loc_t { NVGP_GL_LOC_VIEWSIZE, NVGP_GL_LOC_TEX, NVGP_GL_LOC_FRAG, NVGP_GL_MAX_LOCS }nvgp_gl_uniform_loc_t; typedef enum _nvgp_gl_uniform_bindings_t { NVGP_GL_FRAG_BINDING = 0, }nvgp_gl_uniform_bindings_t; typedef struct _nvgp_gl_texture_t { int32_t id; GLuint tex; uint32_t width, height; int32_t type; int32_t flags; const void* data; } nvgp_gl_texture_t; typedef struct _nvgp_gl_frag_uniforms_t { #if NVGP_GL_USE_UNIFORMBUFFER float scissorMat[12]; // matrices are actually 3 vec4s float paintMat[12]; nvgp_gl_color_t innerCol; union { nvgp_gl_color_t outerCol; float draw_image_rect[4]; } other_info; float scissorExt[2]; float scissorScale[2]; float extent[2]; float radius; float feather; float strokeMult; float strokeThr; float draw_info[2]; #else // note: after modifying layout or size of uniform array, // don't forget to also update the fragment shader source! #define NVGP_GL_UNIFORMARRAY_SIZE 11 union { struct { float scissorMat[12]; // matrices are actually 3 vec4s float paintMat[12]; nvgp_gl_color_t innerCol; union { nvgp_gl_color_t outerCol; float draw_image_rect[4]; } other_info; float scissorExt[2]; float scissorScale[2]; float extent[2]; float radius; float feather; float strokeMult; float strokeThr; float draw_info[2]; }; float uniformArray[NVGP_GL_UNIFORMARRAY_SIZE][4]; }; #endif } nvgp_gl_frag_uniforms_t; typedef struct _nvgp_gl_blend_t { GLenum src_rgb; GLenum dst_rgb; GLenum src_alpha; GLenum dst_alpha; } nvgp_gl_blend_t; typedef struct _nvgp_gl_path_t { uint32_t fill_offset; uint32_t fill_count; uint32_t stroke_offset; uint32_t stroke_count; } nvgp_gl_path_t; typedef struct _nvgp_gl_shader_t { GLuint prog; GLuint frag; GLuint vert; GLint loc[NVGP_GL_MAX_LOCS]; #ifdef NVGP_GL3 GLuint vert_arr; #endif #ifdef NVGP_GL_USE_UNIFORMBUFFER GLuint frag_buf; #endif int32_t frag_size; GLuint vert_buf; uint32_t setted_data; uint32_t cverts; uint32_t nverts; nvgp_vertex_t* verts; uint8_t* uniforms; int cuniforms; int nuniforms; } nvgp_gl_shader_t; typedef struct _nvgp_gl_call_t { nvgp_gl_shader_type_t shader_type; nvgp_gl_call_type_t call_type; } nvgp_gl_call_t; typedef struct _nvgp_gl_call_fast_fill_rect_t { nvgp_gl_call_t base; float x; float y; float w; float h; nvgp_gl_color_t color; } nvgp_gl_call_fast_fill_rect_t; typedef struct _nvgp_gl_call_convex_fill_t { nvgp_gl_call_t base; uint32_t path_index; uint32_t path_count; uint32_t uniform_offset; nvgp_gl_blend_t blend_func; } nvgp_gl_call_convex_fill_t; typedef struct _nvgp_gl_call_fast_fill_t { nvgp_gl_call_t base; GLenum mode; uint32_t path_index; uint32_t path_count; uint32_t uniform_offset; } nvgp_gl_call_fast_fill_t; typedef struct _nvgp_gl_call_fill_t { nvgp_gl_call_t base; uint32_t path_index; uint32_t path_count; uint32_t triangle_offset; uint32_t triangle_count; uint32_t uniform_offset; nvgp_gl_blend_t blend_func; } nvgp_gl_call_fill_t; typedef struct _nvgp_gl_call_stroke_t { nvgp_gl_call_t base; uint32_t path_index; uint32_t path_count; uint32_t triangle_offset; uint32_t triangle_count; uint32_t uniform_offset; nvgp_gl_blend_t blend_func; } nvgp_gl_call_stroke_t; typedef struct _nvgp_gl_call_stroke_image_t { nvgp_gl_call_t base; uint32_t path_index; uint32_t path_count; uint32_t triangle_offset; uint32_t triangle_count; uint32_t uniform_offset; int32_t image; nvgp_gl_blend_t blend_func; } nvgp_gl_call_stroke_image_t; typedef struct _nvgp_gl_call_image_t { nvgp_gl_call_t base; uint32_t path_index; uint32_t path_count; uint32_t triangle_offset; uint32_t triangle_count; uint32_t uniform_offset; int32_t image; nvgp_gl_blend_t blend_func; } nvgp_gl_call_image_t; typedef struct _nvgp_gl_call_text_t { nvgp_gl_call_t base; int32_t image; uint32_t triangle_offset; uint32_t triangle_count; uint32_t uniform_offset; nvgp_gl_blend_t blend_func; } nvgp_gl_call_text_t; typedef struct _nvgp_gl_context_t { int32_t flags; int32_t edge_anti_alias; float view[2]; float pixel_ratio; float pixel_scale; nvgp_gl_shader_t shader_list[NVGP_GL_SHADER_COUNT]; nvgp_darray_t calls; nvgp_darray_t paths; nvgp_darray_t textures; uint32_t texture_id; nvgp_line_cap_t line_cap; // cached state GLuint curr_prog; GLuint bound_texture; GLuint stencil_mask; GLenum stencil_func; GLint stencil_func_ref; GLuint stencil_func_mask; nvgp_gl_blend_t blend_func; } nvgp_gl_context_t; #include "shader_prog/fill_vert_shader.inc" #include "shader_prog/fill_frag_shader_0.inc" #include "shader_prog/fill_frag_shader_1.inc" #include "shader_prog/fill_frag_shader_2.inc" #include "shader_prog/fill_frag_shader_4.inc" #include "shader_prog/fill_frag_shader_3.inc" #include "shader_prog/fill_frag_shader_5.inc" #include "shader_prog/fill_frag_shader_6.inc" #include "shader_prog/fill_frag_shader_7.inc" #include "shader_prog/fill_frag_shader_8.inc" #include "shader_prog/fill_frag_shader_9.inc" #include "shader_prog/fill_frag_shader_10.inc" #include "shader_prog/fill_frag_shader_11.inc" #include "shader_prog/fill_frag_shader_12.inc" #include "shader_prog/fill_frag_shader_13.inc" static nvgp_gl_color_t nvgp_gl_to_color(nvgp_color_t color) { nvgp_gl_color_t gl_color; gl_color.r = color.rgba.r / 255.0f; gl_color.g = color.rgba.g / 255.0f; gl_color.b = color.rgba.b / 255.0f; gl_color.a = color.rgba.a / 255.0f; return gl_color; } static nvgp_gl_color_t nvgp_gl_to_premul_color(nvgp_color_t color) { nvgp_gl_color_t gl_color; gl_color.a = color.rgba.a / 255.0f; gl_color.r = color.rgba.r / 255.0f * gl_color.a; gl_color.g = color.rgba.g / 255.0f * gl_color.a; gl_color.b = color.rgba.b / 255.0f * gl_color.a; return gl_color; } static void nvgp_gl_vset(nvgp_vertex_t* vtx, float x, float y, float u, float v) { vtx->x = x; vtx->y = y; vtx->u = u; vtx->v = v; } static void nvgp_gl_call_destroy(void* data, void* ctx) { if (data != NULL) { NVGP_FREE(data); } } static void nvgp_gl_texture_destroy(void* data, void* ctx) { if (data != NULL) { nvgp_gl_texture_t* texture = (nvgp_gl_texture_t*)data; glDeleteTextures(1, &texture->tex); } } static void nvgp_gl_stencil_mask(nvgp_gl_context_t* gl, GLuint mask) { if (gl->stencil_mask != mask) { gl->stencil_mask = mask; glStencilMask(mask); } } static void nvgp_gl_stencil_func(nvgp_gl_context_t* gl, GLenum func, GLint ref, GLuint mask) { if ((gl->stencil_func != func) || (gl->stencil_func_ref != ref) || (gl->stencil_func_mask != mask)) { gl->stencil_func = func; gl->stencil_func_ref = ref; gl->stencil_func_mask = mask; glStencilFunc(func, ref, mask); } } static void nvgp_gl_blend_func_separate(nvgp_gl_context_t* gl, const nvgp_gl_blend_t* blend) { if ((gl->blend_func.src_rgb != blend->src_rgb) || (gl->blend_func.dst_rgb != blend->dst_rgb) || (gl->blend_func.src_alpha != blend->src_alpha) || (gl->blend_func.dst_alpha != blend->dst_alpha)) { gl->blend_func = *blend; glBlendFuncSeparate(blend->src_rgb, blend->dst_rgb, blend->src_alpha, blend->dst_alpha); } } static nvgp_gl_blend_t nvgp_gl_composite_operation_state(nvgp_gl_composite_operation_t op){ nvgp_gl_blend_t state; GLenum sfactor, dfactor; switch (op) { case NVGP_GL_SOURCE_OVER: sfactor = GL_ONE; dfactor = GL_ONE_MINUS_SRC_ALPHA; break; case NVGP_GL_SOURCE_IN: sfactor = GL_DST_ALPHA; dfactor = GL_ZERO; break; case NVGP_GL_SOURCE_OUT: sfactor = GL_ONE_MINUS_DST_ALPHA; dfactor = GL_ZERO; break; case NVGP_GL_ATOP: sfactor = GL_DST_ALPHA; dfactor = GL_ONE_MINUS_SRC_ALPHA; break; case NVGP_GL_DESTINATION_OVER: sfactor = GL_ONE_MINUS_DST_ALPHA; dfactor = GL_ONE; break; case NVGP_GL_DESTINATION_IN: sfactor = GL_ZERO; dfactor = GL_SRC_ALPHA; break; case NVGP_GL_DESTINATION_OUT: sfactor = GL_ZERO; dfactor = GL_ONE_MINUS_SRC_ALPHA; break; case NVGP_GL_DESTINATION_ATOP: sfactor = GL_ONE_MINUS_DST_ALPHA; dfactor = GL_SRC_ALPHA; break; case NVGP_GL_LIGHTER: sfactor = GL_ONE; dfactor = GL_ONE; break; case NVGP_GL_COPY: sfactor = GL_ONE; dfactor = GL_ZERO; break; case NVGP_GL_XOR: sfactor = GL_ONE_MINUS_DST_ALPHA; dfactor = GL_ONE_MINUS_SRC_ALPHA; break; default: sfactor = GL_ONE; dfactor = GL_ZERO; break; } state.src_rgb = sfactor; state.dst_rgb = dfactor; state.src_alpha = sfactor; state.dst_alpha = dfactor; if (state.src_rgb == GL_INVALID_ENUM || state.dst_rgb == GL_INVALID_ENUM || state.src_alpha == GL_INVALID_ENUM || state.dst_alpha == GL_INVALID_ENUM) { state.src_rgb = GL_ONE; state.dst_rgb = GL_ONE_MINUS_SRC_ALPHA; state.src_alpha = GL_ONE; state.dst_alpha = GL_ONE_MINUS_SRC_ALPHA; } return state; } static int nvgp_gl_alloc_verts(nvgp_gl_shader_t* shader, int32_t n) { int32_t ret = 0; if (shader->nverts + n > shader->cverts) { nvgp_vertex_t* verts; int32_t cverts = nvgp_max(shader->nverts + n, 4096) + shader->cverts / 2; // 1.5x Overallocate verts = NVGP_REALLOCT(nvgp_vertex_t, shader->verts, cverts); if (verts == NULL) { return -1; } shader->verts = verts; shader->cverts = cverts; } ret = shader->nverts; shader->nverts += n; return ret; } static int nvgp_gl_alloc_frag_uniforms(nvgp_gl_shader_t* shader, int n) { int32_t ret = 0, structSize = shader->frag_size; if (shader->nuniforms + n > shader->cuniforms) { uint8_t* uniforms; int cuniforms = nvgp_max(shader->nuniforms + n, 128) + shader->cuniforms / 2; // 1.5x Overallocate uniforms = NVGP_REALLOCT(uint8_t, shader->uniforms, structSize * cuniforms); if (uniforms == NULL) return -1; shader->uniforms = uniforms; shader->cuniforms = cuniforms; } ret = shader->nuniforms * structSize; shader->nuniforms += n; return ret; } static void nvgp_gl_dump_shader_error(GLuint shader, const char* name, const char* type) { GLchar str[512 + 1]; GLsizei len = 0; glGetShaderInfoLog(shader, 512, &len, str); if (len > 512) { len = 512; } str[len] = '\0'; NVGP_PRINTF("Shader %s/%s error:\n%s\n", name, type, str); } static void nvgp_gl_dump_program_error(GLuint prog, const char* name) { GLsizei len = 0; GLchar str[512 + 1]; glGetProgramInfoLog(prog, 512, &len, str); if (len > 512) { len = 512; } str[len] = '\0'; NVGP_PRINTF("Program %s error:\n%s\n", name, str); } static void nvgp_gl_check_error(nvgp_gl_context_t* gl, const char* str) { GLenum err; if ((gl->flags & NVGP_GL_FLAG_DEBUG) == 0) return; err = glGetError(); if (err != GL_NO_ERROR) { NVGP_PRINTF("Error %08x after %s\n", err, str); return; } } static void nvgp_gl_delete_shader(nvgp_gl_shader_t* shader) { if (shader->prog != 0) { glDeleteProgram(shader->prog); } if (shader->vert != 0) { glDeleteShader(shader->vert); } if (shader->frag != 0) { glDeleteShader(shader->frag); } #if NANOVG_GL3 #if NANOVG_GL_USE_UNIFORMBUFFER if (shader->frag_buf != 0) { glDeleteBuffers(1, &shader->frag_buf); } #endif if (shader->vert_arr != 0) { glDeleteVertexArrays(1, &shader->vert_arr); } #endif if (shader->vert_buf != 0) { glDeleteBuffers(1, &shader->vert_buf); } NVGP_FREE(shader->verts); NVGP_FREE(shader->uniforms); NVGP_MEMSET(shader, 0x0, sizeof(nvgp_gl_shader_t)); } static void nvgp_gl_get_uniforms(nvgp_gl_shader_t* shader) { shader->loc[NVGP_GL_LOC_VIEWSIZE] = glGetUniformLocation(shader->prog, "viewSize"); shader->loc[NVGP_GL_LOC_TEX] = glGetUniformLocation(shader->prog, "tex"); #if NVGP_GL_USE_UNIFORMBUFFER shader->loc[NVGP_GL_LOC_FRAG] = glGetUniformBlockIndex(shader->prog, "frag"); #else shader->loc[NVGP_GL_LOC_FRAG] = glGetUniformLocation(shader->prog, "frag"); #endif } static void nvgp_gl_init_shader(nvgp_gl_shader_t* shader, int32_t align) { nvgp_gl_get_uniforms(shader); #if NVGP_GL_USE_UNIFORMBUFFER glUniformBlockBinding(shader->prog, shader->loc[NVGP_GL_LOC_FRAG], NVGP_GL_FRAG_BINDING); #endif // Create dynamic vertex array #ifdef NVGP_GL3 glGenVertexArrays(1, &shader->vert_arr); #endif glGenBuffers(1, &shader->vert_buf); #if NVGP_GL_USE_UNIFORMBUFFER // Create UBOs glGenBuffers(1, &shader->frag_buf); glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &align); #endif shader->frag_size = sizeof(nvgp_gl_frag_uniforms_t) + align - sizeof(nvgp_gl_frag_uniforms_t) % align; } static nvgp_bool_t nvgp_gl_create_shader(nvgp_gl_shader_t* shader, const char* name, const char* header, const char* opts, const char* vshader, const char* fshader) { GLint status; GLuint prog, vert, frag; const char* str[3]; str[0] = header; str[1] = opts != NULL ? opts : ""; NVGP_MEMSET(shader, 0, sizeof(nvgp_gl_shader_t)); prog = glCreateProgram(); vert = glCreateShader(GL_VERTEX_SHADER); frag = glCreateShader(GL_FRAGMENT_SHADER); str[2] = vshader; glShaderSource(vert, 3, str, 0); str[2] = fshader; glShaderSource(frag, 3, str, 0); glCompileShader(vert); glGetShaderiv(vert, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { nvgp_gl_dump_shader_error(vert, name, "vert"); return FALSE; } glCompileShader(frag); glGetShaderiv(frag, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { nvgp_gl_dump_shader_error(frag, name, "frag"); return FALSE; } glAttachShader(prog, vert); glAttachShader(prog, frag); glBindAttribLocation(prog, 0, "vertex"); glBindAttribLocation(prog, 1, "tcoord"); glLinkProgram(prog); glGetProgramiv(prog, GL_LINK_STATUS, &status); if (status != GL_TRUE) { nvgp_gl_dump_program_error(prog, name); return FALSE; } shader->prog = prog; shader->vert = vert; shader->frag = frag; return TRUE; } static nvgp_bool_t nvgp_gl_render_create(nvgp_gl_context_t* gl_ctx) { int32_t i = 0; static const char* shader_header = #if defined NVGP_GL2 "#define NVGP_GL2 1\n" #elif defined NVGP_GL3 "#version 150 core\n" "#define NVGP_GL3 1\n" #elif defined NVGP_GLES2 "#version 100\n" "#define NVGP_GL2 1\n" #elif defined NVGP_GLES3 "#version 300 es\n" "#define NVGP_GL3 1\n" #else ""; #endif #if NVGP_GL_USE_UNIFORMBUFFER "#define USE_UNIFORMBUFFER 1\n" #else "#define UNIFORMARRAY_SIZE 11\n" #endif "\n"; const char* fill_frag_shader_list[NVGP_GL_SHADER_COUNT] = { fill_frag_shader_0, fill_frag_shader_1, fill_frag_shader_2, fill_frag_shader_3, fill_frag_shader_4, fill_frag_shader_5, fill_frag_shader_6, fill_frag_shader_7, fill_frag_shader_8, fill_frag_shader_9, fill_frag_shader_10, fill_frag_shader_11, fill_frag_shader_12, fill_frag_shader_13 }; nvgp_gl_check_error(gl_ctx, "init"); for (i = 0; i < NVGP_GL_SHADER_COUNT; i++) { const char* tmp_fill_frag_shader = fill_frag_shader_list[i]; if (tmp_fill_frag_shader != NULL) { if (gl_ctx->flags & NVGP_GL_FLAG_ANTIALIAS) { if (nvgp_gl_create_shader(&(gl_ctx->shader_list[i]), "shader", shader_header, "#define EDGE_AA 1\n", fill_vert_shader, tmp_fill_frag_shader) == 0) return FALSE; } else { if (nvgp_gl_create_shader(&(gl_ctx->shader_list[i]), "shader", shader_header, NULL, fill_vert_shader, tmp_fill_frag_shader) == 0) return FALSE; } nvgp_gl_init_shader(&(gl_ctx->shader_list[i]), UNIFORM_OFFSET_ALIGNMENT); nvgp_gl_check_error(gl_ctx, "uniform locations"); } } nvgp_gl_check_error(gl_ctx, "create done"); glFinish(); return TRUE; } static void nvgp_gl_begin_frame(void* uptr, float width, float height, float pixel_ratio) { nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; gl->view[0] = width; gl->view[1] = height; gl->pixel_ratio = pixel_ratio; gl->pixel_scale = 1.0f / pixel_ratio; } static void nvgp_gl_reset_gl_state(nvgp_gl_context_t* gl) { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CCW); glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glStencilMask(0xffffffff); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glStencilFunc(GL_ALWAYS, 0, 0xffffffff); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); #if NVGP_GL_USE_STATE_FILTER gl->bound_texture = 0; gl->stencil_mask = 0xffffffff; gl->stencil_func = GL_ALWAYS; gl->stencil_func_ref = 0; gl->stencil_func_mask = 0xffffffff; gl->blend_func.src_rgb = GL_INVALID_ENUM; gl->blend_func.src_alpha = GL_INVALID_ENUM; gl->blend_func.dst_rgb = GL_INVALID_ENUM; gl->blend_func.dst_alpha = GL_INVALID_ENUM; #endif } static void nvgp_gl_set_shader_data(nvgp_gl_context_t* gl, nvgp_gl_shader_t* shader, int32_t is_same_shader_prog) { if (is_same_shader_prog) { return; } #ifdef NVGP_GL3 if (!shader->setted_data) { shader->setted_data = 1; #endif #ifdef NVGP_GL_USE_UNIFORMBUFFER // Upload ubo for frag shaders glBindBuffer(GL_UNIFORM_BUFFER, shader->frag_buf); glBufferData(GL_UNIFORM_BUFFER, shader->nuniforms * shader->frag_size, shader->uniforms, GL_STREAM_DRAW); #endif // Upload vertex data #ifdef NVGP_GL3 glBindVertexArray(shader->vert_arr); #endif glBindBuffer(GL_ARRAY_BUFFER, shader->vert_buf); glBufferData(GL_ARRAY_BUFFER, shader->nverts * sizeof(nvgp_vertex_t), shader->verts, GL_STREAM_DRAW); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(nvgp_vertex_t), (const GLvoid*)(size_t)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(nvgp_vertex_t), (const GLvoid*)(0 + 2 * sizeof(float))); // Set view and texture just once per frame. if (shader->loc[NVGP_GL_LOC_TEX] >= 0) { glUniform1i(shader->loc[NVGP_GL_LOC_TEX], 0); } glUniform2fv(shader->loc[NVGP_GL_LOC_VIEWSIZE], 1, gl->view); #ifdef NVGP_GL3 } else { glBindVertexArray(shader->vert_arr); glBindBuffer(GL_ARRAY_BUFFER, shader->vert_buf); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); } #endif #if NVGP_GL_USE_UNIFORMBUFFER glBindBuffer(GL_UNIFORM_BUFFER, shader->frag_buf); #endif } static void nvgp_gl_bind_texture(nvgp_gl_context_t* gl, GLuint tex) { #if NVGP_GL_USE_STATE_FILTER if (gl->bound_texture != tex) { gl->bound_texture = tex; glBindTexture(GL_TEXTURE_2D, tex); } #else glBindTexture(GL_TEXTURE_2D, tex); #endif } static nvgp_gl_texture_t* nvgp_gl_find_texture(nvgp_gl_context_t* gl, int32_t id) { uint32_t i; if (id > 0) { for (i = 0; i < gl->textures.size; i++) { nvgp_gl_texture_t* texture = nvgp_darray_get_ptr(&gl->textures, i, nvgp_gl_texture_t); if (texture->id == id) { return texture; } } } return NULL; } static nvgp_gl_frag_uniforms_t* nvgp_gl_frag_uniform_ptr(nvgp_gl_shader_t* shader, uint32_t i) { return (nvgp_gl_frag_uniforms_t*)&shader->uniforms[i]; } static void nvgp_gl_set_uniforms(nvgp_gl_context_t* gl, nvgp_gl_shader_t* shader, uint32_t uniform_offset, int32_t image) { #if NVGP_GL_USE_UNIFORMBUFFER glBindBufferRange(GL_UNIFORM_BUFFER, NVGP_GL_FRAG_BINDING, shader->frag_buf, uniform_offset, sizeof(nvgp_gl_frag_uniforms_t)); #else nvgp_gl_frag_uniforms_t* frag = nvgp_gl_frag_uniform_ptr(shader, uniform_offset); glUniform4fv(shader->loc[NVGP_GL_LOC_FRAG], NVGP_GL_UNIFORMARRAY_SIZE, &(frag->uniformArray[0][0])); #endif if (image != 0) { nvgp_gl_texture_t* tex = nvgp_gl_find_texture(gl, image); nvgp_gl_bind_texture(gl, tex != NULL ? tex->tex : 0); nvgp_gl_check_error(gl, "tex paint tex"); } else { nvgp_gl_bind_texture(gl, 0); } } static void nvgp_gl_reset_shader(nvgp_gl_context_t* gl) { uint32_t i = 0; for (i = 0; i < nvgp_get_arrary_size(gl->shader_list); i++) { gl->shader_list[i].nverts = 0; gl->shader_list[i].nuniforms = 0; gl->shader_list[i].setted_data = 0; } } static nvgp_bool_t nvgp_gl_is_same_shader_prog(nvgp_gl_context_t* gl, nvgp_gl_shader_t* shader) { return gl->curr_prog == shader->prog; } static void nvgp_gl_use_shader_prog(nvgp_gl_context_t* gl, nvgp_gl_shader_t* shader) { if (gl->curr_prog != shader->prog) { glUseProgram(shader->prog); gl->curr_prog = shader->prog; } } static void nvgp_gl_flush_by_fast_fill_rect(nvgp_gl_context_t* gl, nvgp_gl_call_t* call_base) { nvgp_gl_call_fast_fill_rect_t* call = (nvgp_gl_call_fast_fill_rect_t*)call_base; uint32_t is_fill = call->w >= gl->view[0] * gl->pixel_ratio && call->h >= gl->view[1] * gl->pixel_ratio; if (!is_fill) { glScissor(call->x, call->y, call->w, call->h); glEnable(GL_SCISSOR_TEST); } glClearColor(call->color.r, call->color.g, call->color.b, call->color.a); glClear(GL_COLOR_BUFFER_BIT); if (!is_fill) { glDisable(GL_SCISSOR_TEST); } } static void nvgp_gl_flush_by_convex_fill_by_color(nvgp_gl_context_t* gl, nvgp_gl_call_t* call_base) { int32_t i; nvgp_gl_shader_t* shader = &gl->shader_list[call_base->shader_type]; nvgp_gl_call_convex_fill_t* call = (nvgp_gl_call_convex_fill_t*)call_base; nvgp_gl_path_t* paths = nvgp_darray_get_ptr(&gl->paths, call->path_index, nvgp_gl_path_t); int32_t is_same_shader_prog = nvgp_gl_is_same_shader_prog(gl, shader); nvgp_gl_use_shader_prog(gl, shader); nvgp_gl_set_shader_data(gl, shader, is_same_shader_prog); nvgp_gl_blend_func_separate(gl, &call->blend_func); nvgp_gl_set_uniforms(gl, shader, call->uniform_offset, 0); nvgp_gl_check_error(gl, "convex fill"); for (i = 0; i < call->path_count; i++) { glDrawArrays(GL_TRIANGLE_FAN, paths[i].fill_offset, paths[i].fill_count); // Draw fringes if (paths[i].stroke_count > 0) { glDrawArrays(GL_TRIANGLE_STRIP, paths[i].stroke_offset, paths[i].stroke_count); } } } static void nvgp_gl_flush_fill_by_color(nvgp_gl_context_t* gl, nvgp_gl_call_t* call_base) { int32_t i; nvgp_gl_shader_t* shader = &gl->shader_list[call_base->shader_type]; nvgp_gl_call_fill_t* call = (nvgp_gl_call_fill_t*)call_base; int32_t is_same_shader_prog = nvgp_gl_is_same_shader_prog(gl, shader); nvgp_gl_use_shader_prog(gl, shader); nvgp_gl_set_shader_data(gl, shader, is_same_shader_prog); nvgp_gl_check_error(gl, "convex fill"); nvgp_gl_blend_func_separate(gl, &call->blend_func); // Draw shapes glEnable(GL_STENCIL_TEST); nvgp_gl_stencil_mask(gl, 0xff); nvgp_gl_stencil_func(gl, GL_ALWAYS, 0, 0xff); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // set bindpoint for solid loc nvgp_gl_set_uniforms(gl, shader, call->uniform_offset, 0); nvgp_gl_check_error(gl, "fill simple"); glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_INCR_WRAP); glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_DECR_WRAP); glDisable(GL_CULL_FACE); for (i = 0; i < call->path_count; i++) { nvgp_gl_path_t* paths = nvgp_darray_get_ptr(&gl->paths, call->path_index + i, nvgp_gl_path_t); glDrawArrays(GL_TRIANGLE_FAN, paths->fill_offset, paths->fill_count); } glEnable(GL_CULL_FACE); // Draw anti-aliased pixels glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); nvgp_gl_set_uniforms(gl, shader, call->uniform_offset + shader->frag_size, 0); nvgp_gl_check_error(gl, "fill fill"); if (gl->flags & NVGP_GL_FLAG_ANTIALIAS) { nvgp_gl_stencil_func(gl, GL_EQUAL, 0x00, 0xff); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // Draw fringes for (i = 0; i < call->path_count; i++) { nvgp_gl_path_t* paths = nvgp_darray_get_ptr(&gl->paths, call->path_index + i, nvgp_gl_path_t); glDrawArrays(GL_TRIANGLE_STRIP, paths->stroke_offset, paths->stroke_count); } } // Draw fill nvgp_gl_stencil_func(gl, GL_NOTEQUAL, 0x0, 0xff); glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO); glDrawArrays(GL_TRIANGLE_STRIP, call->triangle_offset, call->triangle_count); glDisable(GL_STENCIL_TEST); } static void nvgp_gl_flush_fast_fill_by_color(nvgp_gl_context_t* gl, nvgp_gl_call_t* call_base) { int32_t i; nvgp_gl_shader_t* shader = &gl->shader_list[call_base->shader_type]; nvgp_gl_call_fast_fill_t* call = (nvgp_gl_call_fast_fill_t*)call_base; nvgp_gl_path_t* paths = nvgp_darray_get_ptr(&gl->paths, call->path_index, nvgp_gl_path_t); int32_t is_same_shader_prog = nvgp_gl_is_same_shader_prog(gl, shader); nvgp_gl_use_shader_prog(gl, shader); nvgp_gl_set_shader_data(gl, shader, is_same_shader_prog); nvgp_gl_set_uniforms(gl, shader, call->uniform_offset, 0); nvgp_gl_check_error(gl, "fast fill"); for (i = 0; i < call->path_count; i++) { if (paths[i].fill_count > 0) { glDrawArrays(call->mode, paths[i].fill_offset, paths[i].fill_count); } if (paths[i].stroke_count > 0) { glDrawArrays(call->mode, paths[i].stroke_offset, paths[i].stroke_count); } } } static void nvgp_gl_flush_stroke_by_color(nvgp_gl_context_t* gl, nvgp_gl_call_t* call_base) { int32_t i; nvgp_gl_shader_t* shader = &gl->shader_list[call_base->shader_type]; nvgp_gl_call_stroke_t* call = (nvgp_gl_call_stroke_t*)call_base; int32_t is_same_shader_prog = nvgp_gl_is_same_shader_prog(gl, shader); nvgp_gl_use_shader_prog(gl, shader); nvgp_gl_set_shader_data(gl, shader, is_same_shader_prog); nvgp_gl_check_error(gl, "convex fill"); nvgp_gl_blend_func_separate(gl, &call->blend_func); if (gl->flags & NVGP_GL_FLAG_STENCIL_STROKES) { glEnable(GL_STENCIL_TEST); nvgp_gl_stencil_mask(gl, 0xff); // Fill the stroke base without overlap nvgp_gl_stencil_func(gl, GL_EQUAL, 0x0, 0xff); glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); nvgp_gl_set_uniforms(gl, shader, call->uniform_offset + shader->frag_size, 0); nvgp_gl_check_error(gl, "stroke fill 0"); for (i = 0; i < call->path_count; i++) { nvgp_gl_path_t* path = nvgp_darray_get_ptr(&gl->paths, call->path_index + i, nvgp_gl_path_t); glDrawArrays(GL_TRIANGLE_STRIP, path->stroke_offset, path->stroke_count); } // Draw anti-aliased pixels. nvgp_gl_set_uniforms(gl, shader, call->uniform_offset, 0); nvgp_gl_stencil_func(gl, GL_EQUAL, 0x00, 0xff); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); for (i = 0; i < call->path_count; i++) { nvgp_gl_path_t* path = nvgp_darray_get_ptr(&gl->paths, call->path_index + i, nvgp_gl_path_t); glDrawArrays(GL_TRIANGLE_STRIP, path->stroke_offset, path->stroke_count); } // Clear stencil buffer. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); nvgp_gl_stencil_func(gl, GL_ALWAYS, 0x0, 0xff); glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO); nvgp_gl_check_error(gl, "stroke fill 1"); for (i = 0; i < call->path_count; i++) { nvgp_gl_path_t* path = nvgp_darray_get_ptr(&gl->paths, call->path_index + i, nvgp_gl_path_t); glDrawArrays(GL_TRIANGLE_STRIP, path->stroke_offset, path->stroke_count); } glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDisable(GL_STENCIL_TEST); // glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset + gl->fragSize), // paint, scissor, strokeWidth, fringe, 1.0f - 0.5f/255.0f); } else { nvgp_gl_set_uniforms(gl, shader, call->uniform_offset, 0); nvgp_gl_check_error(gl, "stroke fill"); // Draw Strokes for (i = 0; i < call->path_count; i++) { nvgp_gl_path_t* path = nvgp_darray_get_ptr(&gl->paths, call->path_index + i, nvgp_gl_path_t); glDrawArrays(GL_TRIANGLE_STRIP, path->stroke_offset, path->stroke_count); } } } static void nvgp_gl_flush_stroke_by_image(nvgp_gl_context_t* gl, nvgp_gl_call_t* call_base) { int32_t i; nvgp_gl_shader_t* shader = &gl->shader_list[call_base->shader_type]; nvgp_gl_call_stroke_image_t* call = (nvgp_gl_call_stroke_image_t*)call_base; int32_t is_same_shader_prog = nvgp_gl_is_same_shader_prog(gl, shader); nvgp_gl_use_shader_prog(gl, shader); nvgp_gl_set_shader_data(gl, shader, is_same_shader_prog); nvgp_gl_check_error(gl, "convex fill"); nvgp_gl_blend_func_separate(gl, &call->blend_func); if (gl->flags & NVGP_GL_FLAG_STENCIL_STROKES) { glEnable(GL_STENCIL_TEST); nvgp_gl_stencil_mask(gl, 0xff); // Fill the stroke base without overlap nvgp_gl_stencil_func(gl, GL_EQUAL, 0x0, 0xff); glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); nvgp_gl_set_uniforms(gl, shader, call->uniform_offset + shader->frag_size, call->image); nvgp_gl_check_error(gl, "stroke fill 0"); for (i = 0; i < call->path_count; i++) { nvgp_gl_path_t* path = nvgp_darray_get_ptr(&gl->paths, call->path_index + i, nvgp_gl_path_t); glDrawArrays(GL_TRIANGLE_STRIP, path->stroke_offset, path->stroke_count); } // Draw anti-aliased pixels. nvgp_gl_set_uniforms(gl, shader, call->uniform_offset, call->image); nvgp_gl_stencil_func(gl, GL_EQUAL, 0x00, 0xff); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); for (i = 0; i < call->path_count; i++) { nvgp_gl_path_t* path = nvgp_darray_get_ptr(&gl->paths, call->path_index + i, nvgp_gl_path_t); glDrawArrays(GL_TRIANGLE_STRIP, path->stroke_offset, path->stroke_count); } // Clear stencil buffer. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); nvgp_gl_stencil_func(gl, GL_ALWAYS, 0x0, 0xff); glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO); nvgp_gl_check_error(gl, "stroke fill 1"); for (i = 0; i < call->path_count; i++) { nvgp_gl_path_t* path = nvgp_darray_get_ptr(&gl->paths, call->path_index + i, nvgp_gl_path_t); glDrawArrays(GL_TRIANGLE_STRIP, path->stroke_offset, path->stroke_count); } glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDisable(GL_STENCIL_TEST); // glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset + gl->fragSize), // paint, scissor, strokeWidth, fringe, 1.0f - 0.5f/255.0f); } else { nvgp_gl_set_uniforms(gl, shader, call->uniform_offset, 0); nvgp_gl_check_error(gl, "stroke fill"); // Draw Strokes for (i = 0; i < call->path_count; i++) { nvgp_gl_path_t* path = nvgp_darray_get_ptr(&gl->paths, call->path_index + i, nvgp_gl_path_t); glDrawArrays(GL_TRIANGLE_STRIP, path->stroke_offset, path->stroke_count); } } } static void nvgp_gl_flush_draw_image(nvgp_gl_context_t* gl, nvgp_gl_call_t* call_base) { int32_t i; nvgp_gl_shader_t* shader = &gl->shader_list[call_base->shader_type]; nvgp_gl_call_image_t* call = (nvgp_gl_call_image_t*)call_base; int32_t is_same_shader_prog = nvgp_gl_is_same_shader_prog(gl, shader); if (call->path_count == 1) { nvgp_gl_path_t* paths = nvgp_darray_get_ptr(&gl->paths, call->path_index, nvgp_gl_path_t); nvgp_gl_use_shader_prog(gl, shader); nvgp_gl_set_shader_data(gl, shader, is_same_shader_prog); nvgp_gl_blend_func_separate(gl, &call->blend_func); nvgp_gl_set_uniforms(gl, shader, call->uniform_offset, call->image); nvgp_gl_check_error(gl, "convex fill"); for (i = 0; i < call->path_count; i++) { glDrawArrays(GL_TRIANGLE_FAN, paths[i].fill_offset, paths[i].fill_count); // Draw fringes if (paths[i].stroke_count > 0) { glDrawArrays(GL_TRIANGLE_STRIP, paths[i].stroke_offset, paths[i].stroke_count); } } } else { assert("not impl"); } } static void nvgp_gl_flush_draw_text(nvgp_gl_context_t* gl, nvgp_gl_call_t* call_base) { nvgp_gl_shader_t* shader = &gl->shader_list[call_base->shader_type]; nvgp_gl_call_text_t* call = (nvgp_gl_call_text_t*)call_base; int32_t is_same_shader_prog = nvgp_gl_is_same_shader_prog(gl, shader); nvgp_gl_use_shader_prog(gl, shader); nvgp_gl_set_shader_data(gl, shader, is_same_shader_prog); nvgp_gl_blend_func_separate(gl, &call->blend_func); nvgp_gl_set_uniforms(gl, shader, call->uniform_offset, call->image); nvgp_gl_check_error(gl, "triangles fill"); glDrawArrays(GL_TRIANGLES, call->triangle_offset, call->triangle_count); } static void nvgp_gl_flush(nvgp_gl_context_t* gl) { uint32_t i = 0; nvgp_gl_reset_gl_state(gl); for (i = 0; i < gl->calls.size; i++) { nvgp_gl_call_t* call_base = nvgp_darray_get_ptr(&gl->calls, i, nvgp_gl_call_t); switch (call_base->call_type) { case NVGP_GL_CALL_FAST_FILL_RECT: nvgp_gl_flush_by_fast_fill_rect(gl, call_base); break; case NVGP_GL_CALL_CONVEX_FILL: nvgp_gl_flush_by_convex_fill_by_color(gl, call_base); break; case NVGP_GL_CALL_FILL: nvgp_gl_flush_fill_by_color(gl, call_base); break; case NVGP_GL_CALL_FAST_FILL_COLOR : nvgp_gl_flush_fast_fill_by_color(gl, call_base); break; case NVGP_GL_CALL_STROKE: nvgp_gl_flush_stroke_by_color(gl, call_base); break; case NVGP_GL_CALL_STROKE_IMAGE: nvgp_gl_flush_stroke_by_image(gl, call_base); break; case NVGP_GL_CALL_IMAGE: nvgp_gl_flush_draw_image(gl, call_base); break; case NVGP_GL_CALL_TEXT : nvgp_gl_flush_draw_text(gl, call_base); break; default: break; } } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); #if defined NANOVG_GL3 glBindVertexArray(0); #endif glDisable(GL_CULL_FACE); glBindBuffer(GL_ARRAY_BUFFER, 0); glUseProgram(0); nvgp_gl_bind_texture(gl, 0); // Reset gl->curr_prog = 0; nvgp_gl_reset_shader(gl); nvgp_darray_clear(&gl->paths); nvgp_darray_clear_by_destroy_function(&gl->calls, nvgp_gl_call_destroy, NULL); } static void nvgp_gl_end_frame(void* uptr) { nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; nvgp_gl_flush(gl); } static nvgp_bool_t nvgp_gl_rect_intersect_f(float r1_x, float r1_y, float r1_w, float r1_h, float* r2_x, float* r2_y, float* r2_w, float* r2_h) { int32_t top = 0; int32_t left = 0; int32_t bottom = 0; int32_t right = 0; int32_t bottom1 = 0; int32_t right1 = 0; int32_t bottom2 = 0; int32_t right2 = 0; bottom1 = r1_y + r1_h - 1; bottom2 = *r2_y + *r2_h - 1; right1 = r1_x + r1_w - 1; right2 = *r2_x + *r2_w - 1; top = nvgp_max(r1_y, *r2_y); left = nvgp_max(r1_x, *r2_x); right = nvgp_min(right1, right2); bottom = nvgp_min(bottom1, bottom2); *r2_x = left; *r2_y = top; *r2_w = right >= left ? (right - left + 1) : 0; *r2_h = bottom >= top ? (bottom - top + 1) : 0; return *r2_w != 0 && *r2_h != 0; } static nvgp_bool_t nvgp_gl_color_is_translucent(nvgp_paint_t* paint) { if (paint->inner_color.rgba.a > 0xf8) { return FALSE; } return TRUE; } static nvgp_bool_t nvgp_gl_is_fast_draw_rect(nvgp_darray_t* paths) { if (paths->size == 1) { nvgp_path_t* path = nvgp_darray_get_ptr(paths, 0, nvgp_path_t); if (path->nfill == 4 && path->nstroke == 0) { if ((path->fill[0].x == path->fill[1].x && path->fill[0].y == path->fill[3].y && path->fill[2].x == path->fill[3].x && path->fill[2].y == path->fill[1].y) || (path->fill[0].x == path->fill[3].x && path->fill[0].y == path->fill[1].y && path->fill[2].x == path->fill[1].x && path->fill[2].y == path->fill[3].y)) { return TRUE; } } } return FALSE; } static nvgp_bool_t nvgp_gl_is_fast_stroke(const nvgp_darray_t* paths) { if (paths->size == 1) { nvgp_path_t* path = nvgp_darray_get_ptr(paths, 0, nvgp_path_t); if (path->nfill == 0 && path->nstroke == 8) { if ((path->stroke[0].x == path->stroke[1].x && path->stroke[2].x == path->stroke[3].x && path->stroke[4].x == path->stroke[5].x && path->stroke[6].x == path->stroke[7].x && path->stroke[0].y == path->stroke[2].y && path->stroke[2].y == path->stroke[4].y && path->stroke[4].y == path->stroke[6].y && path->stroke[1].y == path->stroke[3].y && path->stroke[3].y == path->stroke[5].y && path->stroke[5].y == path->stroke[7].y) || (path->stroke[0].x == path->stroke[2].x && path->stroke[2].x == path->stroke[4].x && path->stroke[4].x == path->stroke[6].x && path->stroke[1].x == path->stroke[3].x && path->stroke[3].x == path->stroke[5].x && path->stroke[5].x == path->stroke[7].x && path->stroke[0].y == path->stroke[1].y && path->stroke[2].y == path->stroke[3].y && path->stroke[4].y == path->stroke[5].y && path->stroke[6].y == path->stroke[7].y)) { return TRUE; } } } return FALSE; } static nvgp_bool_t nvgp_gl_is_fast_draw_image(nvgp_darray_t* paths) { if (paths->size == 1) { nvgp_path_t* path = nvgp_darray_get_ptr(paths, 0, nvgp_path_t); if (path->nfill == 4) { if ((path->fill[0].x == path->fill[1].x && path->fill[0].y == path->fill[3].y && path->fill[2].x == path->fill[3].x && path->fill[2].y == path->fill[1].y) || (path->fill[0].x == path->fill[3].x && path->fill[0].y == path->fill[1].y && path->fill[2].x == path->fill[1].x && path->fill[2].y == path->fill[3].y)) { return TRUE; } } } return FALSE; } static nvgp_bool_t nvgp_gl_check_is_matrix_skew(nvgp_matrix_t* mat) { if (mat->mat.skew_x == 0.0f && mat->mat.skew_y == 0.0f) { return FALSE; } return TRUE; } static nvgp_bool_t nvgp_gl_check_is_matrix_transformer(nvgp_matrix_t* mat, float scale) { if (mat->mat.scale_x == scale && mat->mat.scale_y == scale && mat->mat.skew_x == 0.0f && mat->mat.skew_y == 0.0f) { return FALSE; } return TRUE; } static nvgp_bool_t nvgp_gl_verts_in_scissor(nvgp_gl_context_t* gl, const nvgp_vertex_t* verts, uint32_t nverts, nvgp_scissor_t* scissor) { if (verts != NULL && nverts > 0) { int32_t i = 0; float cx = scissor->matrix.mat.trans_x * gl->pixel_ratio; float cy = scissor->matrix.mat.trans_y * gl->pixel_ratio; float hw = scissor->extent[0] * gl->pixel_ratio; float hh = scissor->extent[1] * gl->pixel_ratio; float l = cx - hw; float t = cy - hh; float r = l + 2 * hw; float b = t + 2 * hh; for (i = 0; i < nverts; i++) { const nvgp_vertex_t* iter = verts + i; int x = iter->x * gl->pixel_ratio; int y = iter->y * gl->pixel_ratio; if (x < l || x > r || y < t || y > b) { return FALSE; } } } return TRUE; } static int32_t nvgp_gl_paths_in_scissor(nvgp_gl_context_t* gl, const nvgp_darray_t* paths, nvgp_scissor_t* scissor) { uint32_t i = 0; for (i = 0; i < paths->size; i++) { const nvgp_path_t* path = nvgp_darray_get_ptr(paths, i, nvgp_path_t); if (!nvgp_gl_verts_in_scissor(gl, path->fill, path->nfill, scissor) || !nvgp_gl_verts_in_scissor(gl, path->stroke, path->nstroke, scissor)) { return FALSE; } } return TRUE; } static void nvgp_gl_mat_to_mat3x4(float* m3, nvgp_matrix_t* t) { m3[0] = t->mat.scale_x; m3[1] = t->mat.skew_y; m3[2] = 0.0f; m3[3] = 0.0f; m3[4] = t->mat.skew_x; m3[5] = t->mat.scale_y; m3[6] = 0.0f; m3[7] = 0.0f; m3[8] = t->mat.trans_x; m3[9] = t->mat.trans_y; m3[10] = 1.0f; m3[11] = 0.0f; } static nvgp_bool_t nvgp_gl_convert_paint(nvgp_gl_context_t* gl, nvgp_gl_frag_uniforms_t* frag, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float width, float fringe, float strokeThr) { nvgp_matrix_t invxform; nvgp_gl_texture_t* tex = NULL; NVGP_MEMSET(frag, 0, sizeof(*frag)); frag->innerCol = nvgp_gl_to_premul_color(paint->inner_color); if (paint->image == 0) { frag->other_info.outerCol = nvgp_gl_to_premul_color(paint->outer_color); } if (scissor->extent[0] < -0.5f || scissor->extent[1] < -0.5f) { NVGP_MEMSET(frag->scissorMat, 0, sizeof(frag->scissorMat)); frag->scissorExt[0] = 1.0f; frag->scissorExt[1] = 1.0f; frag->scissorScale[0] = 1.0f; frag->scissorScale[1] = 1.0f; } else { nvgp_transform_inverse(&invxform, &scissor->matrix); nvgp_gl_mat_to_mat3x4(frag->scissorMat, &invxform); frag->scissorExt[0] = scissor->extent[0]; frag->scissorExt[1] = scissor->extent[1]; frag->scissorScale[0] = nvgp_sqrtf(scissor->matrix.mat.scale_x * scissor->matrix.mat.scale_x + scissor->matrix.mat.skew_x * scissor->matrix.mat.skew_x) / fringe; frag->scissorScale[1] = nvgp_sqrtf(scissor->matrix.mat.scale_y * scissor->matrix.mat.scale_y + scissor->matrix.mat.skew_y * scissor->matrix.mat.skew_y) / fringe; } NVGP_MEMCPY(frag->extent, paint->extent, sizeof(frag->extent)); frag->strokeMult = (width * 0.5f + fringe * 0.5f) / fringe; frag->strokeThr = strokeThr; if (paint->image != 0) { tex = nvgp_gl_find_texture(gl, paint->image); if (tex == NULL) { return FALSE; } if ((tex->flags & NVGP_GL_IMAGE_FLIPY) != 0) { nvgp_matrix_t m1, m2; nvgp_transform_translate(&m1, 0.0f, frag->extent[1] * 0.5f); nvgp_transform_multiply_to_t(&m1, &paint->mat); nvgp_transform_scale(&m2, 1.0f, -1.0f); nvgp_transform_multiply_to_t(&m2, &m1); nvgp_transform_translate(&m1, 0.0f, -frag->extent[1] * 0.5f); nvgp_transform_multiply_to_t(&m1, &m2); nvgp_transform_inverse(&invxform, &m1); } else { nvgp_transform_inverse(&invxform, &paint->mat); } if (paint->draw_type == NVGP_IMAGE_DRAW_REPEAT) { NVGP_MEMCPY(frag->draw_info, paint->draw_info, sizeof(frag->draw_info)); NVGP_MEMCPY(frag->other_info.draw_image_rect, paint->draw_image_rect, sizeof(paint->draw_image_rect)); } } else { frag->radius = paint->radius; frag->feather = paint->feather; nvgp_transform_inverse(&invxform, &paint->mat); } nvgp_gl_mat_to_mat3x4(frag->paintMat, &invxform); return TRUE; } static uint32_t nvgp_gl_max_vert_count(const nvgp_darray_t* paths) { uint32_t i, count = 0; for (i = 0; i < paths->size; i++) { nvgp_path_t* path = nvgp_darray_get_ptr(paths, i, nvgp_path_t); count += path->nfill; count += path->nstroke; } return count; } static nvgp_bool_t nvgp_gl_render_fast_fill_rect(nvgp_gl_context_t* gl, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, const float* bounds, const nvgp_darray_t* paths) { if (paint->image == 0 && !nvgp_gl_color_is_translucent(paint) && !nvgp_gl_check_is_matrix_transformer(&paint->mat, 1.0f) && !nvgp_gl_check_is_matrix_transformer(&scissor->matrix, 1.0f) && nvgp_gl_is_fast_draw_rect((nvgp_darray_t*)paths)) { nvgp_path_t* path = nvgp_darray_get_ptr(paths, 0, nvgp_path_t); float l = path->fill[0].x * gl->pixel_ratio; float t = path->fill[0].y * gl->pixel_ratio; float r = path->fill[2].x * gl->pixel_ratio; float b = path->fill[2].y * gl->pixel_ratio; float w = r - l; float h = b - t; float cx = scissor->matrix.mat.trans_x * gl->pixel_ratio; float cy = scissor->matrix.mat.trans_y * gl->pixel_ratio; float hw = scissor->extent[0] * gl->pixel_ratio; float hh = scissor->extent[1] * gl->pixel_ratio; if(nvgp_gl_rect_intersect_f(cx - hw, cy - hh, hw * 2, hh * 2, &l, &t, &w, &h)){ nvgp_gl_call_fast_fill_rect_t* call = NVGP_ZALLOC(nvgp_gl_call_fast_fill_rect_t); if (call == NULL) { return FALSE; } call->x = l; call->y = gl->view[1] * gl->pixel_ratio - t - h; call->w = w; call->h = h; call->color = nvgp_gl_to_color(paint->inner_color); call->base.call_type = NVGP_GL_CALL_FAST_FILL_RECT; nvgp_darray_push(&gl->calls, call); } return TRUE; } return FALSE; } static nvgp_bool_t nvgp_gl_render_convex_fill_by_color(nvgp_gl_context_t* gl, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, const float* bounds, const nvgp_darray_t* paths, int32_t is_gradient) { nvgp_gl_shader_t* shader; int32_t max_verts, offset; nvgp_gl_frag_uniforms_t* frag = NULL; nvgp_path_t* path = nvgp_darray_get_ptr(paths, 0, nvgp_path_t); if (paint->image == 0 && paths->size == 1 && path->convex) { nvgp_gl_call_convex_fill_t* call = NVGP_ZALLOC(nvgp_gl_call_convex_fill_t); nvgp_gl_path_t* gl_path = nvgp_darray_get_empty_data_by_tail(&gl->paths); if (call == NULL || gl_path == NULL) { goto error; } NVGP_MEMSET(gl_path, 0x0, sizeof(nvgp_gl_path_t)); call->base.call_type = NVGP_GL_CALL_CONVEX_FILL; call->base.shader_type = is_gradient ? NVGP_GL_SHADER_FILLGRAD : NVGP_GL_SHADER_FILLCOLOR; call->path_count = 1; call->path_index = gl->paths.size - 1; call->blend_func = nvgp_gl_composite_operation_state(NVGP_GL_SOURCE_OVER); shader = &(gl->shader_list[call->base.shader_type]); // Allocate vertices for all the paths. max_verts = path->nfill + path->nstroke; offset = nvgp_gl_alloc_verts(shader, max_verts); if (offset == -1) { NVGP_FREE(call); goto error; } if (path->nfill > 0) { gl_path->fill_offset = offset; gl_path->fill_count = path->nfill; NVGP_MEMCPY(shader->verts + offset, path->fill, sizeof(nvgp_vertex_t) * path->nfill); offset += path->nfill; } if (path->nstroke > 0) { gl_path->stroke_offset = offset; gl_path->stroke_count = path->nstroke; NVGP_MEMCPY(shader->verts + offset, path->stroke, sizeof(nvgp_vertex_t) * path->nstroke); offset += path->nstroke; } call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 1); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } // Fill shader frag = nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset); nvgp_gl_convert_paint(gl, frag, paint, scissor, fringe, fringe, -1.0f); nvgp_darray_push(&gl->calls, call); return TRUE; } error: return FALSE; } static nvgp_bool_t nvgp_gl_render_fill_by_color(nvgp_gl_context_t* gl, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, const float* bounds, const nvgp_darray_t* paths, int32_t is_gradient) { nvgp_vertex_t* quad; nvgp_gl_shader_t* shader; int32_t i, max_verts, offset; nvgp_gl_frag_uniforms_t* frag = NULL; if (paint->image == 0) { nvgp_gl_call_fill_t* call = NVGP_ZALLOC(nvgp_gl_call_fill_t); if (call == NULL) { goto error; } call->base.call_type = NVGP_GL_CALL_FILL; call->base.shader_type = is_gradient ? NVGP_GL_SHADER_FILLGRAD : NVGP_GL_SHADER_FILLCOLOR; call->triangle_count = 4; call->path_count = paths->size; call->path_index = gl->paths.size; call->blend_func = nvgp_gl_composite_operation_state(NVGP_GL_SOURCE_OVER); shader = &(gl->shader_list[call->base.shader_type]); max_verts = nvgp_gl_max_vert_count(paths) + call->triangle_count; offset = nvgp_gl_alloc_verts(shader, max_verts); if (offset == -1) { NVGP_FREE(call); goto error; } for (i = 0; i < paths->size; i++) { const nvgp_path_t* path = nvgp_darray_get_ptr(paths, i, nvgp_path_t); nvgp_gl_path_t* gl_path = nvgp_darray_get_empty_data_by_tail(&gl->paths); if (gl_path == NULL) { NVGP_FREE(call); goto error; } NVGP_MEMSET(gl_path, 0x0, sizeof(nvgp_gl_path_t)); if (path->nfill > 0) { gl_path->fill_offset = offset; gl_path->fill_count = path->nfill; NVGP_MEMCPY(&shader->verts[offset], path->fill, sizeof(nvgp_vertex_t) * path->nfill); offset += path->nfill; } if (path->nstroke > 0) { gl_path->stroke_offset = offset; gl_path->stroke_count = path->nstroke; NVGP_MEMCPY(&shader->verts[offset], path->stroke, sizeof(nvgp_vertex_t) * path->nstroke); offset += path->nstroke; } } call->triangle_offset = offset; quad = &shader->verts[call->triangle_offset]; nvgp_gl_vset(&quad[0], bounds[2], bounds[3], 0.5f, 1.0f); nvgp_gl_vset(&quad[1], bounds[2], bounds[1], 0.5f, 1.0f); nvgp_gl_vset(&quad[2], bounds[0], bounds[3], 0.5f, 1.0f); nvgp_gl_vset(&quad[3], bounds[0], bounds[1], 0.5f, 1.0f); call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 2); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } // Simple shader for stencil frag = nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset); NVGP_MEMSET(frag, 0, sizeof(*frag)); frag->strokeThr = -1.0f; // Fill shader nvgp_gl_convert_paint(gl, nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset + shader->frag_size), paint, scissor, fringe, fringe, -1.0f); nvgp_darray_push(&gl->calls, call); return TRUE; } error: return FALSE; } static int32_t nvgp_gl_texture_is_premulti(nvgp_gl_texture_t* tex) { return tex->flags & NVGP_GL_IMAGE_PREMULTIPLIED; } static nvgp_bool_t nvgp_gl_render_draw_image(nvgp_gl_context_t* gl, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, const float* bounds, const nvgp_darray_t* paths) { nvgp_vertex_t* quad; nvgp_gl_shader_t* shader; int32_t i, max_verts, offset; nvgp_gl_frag_uniforms_t* frag = NULL; nvgp_gl_texture_t* tex = nvgp_gl_find_texture(gl, paint->image); if (paint->image != 0 && tex != NULL) { int32_t is_premulti = nvgp_gl_texture_is_premulti(tex); nvgp_gl_call_image_t* call = NVGP_ZALLOC(nvgp_gl_call_image_t); int32_t support_fast_draw = !nvgp_gl_check_is_matrix_transformer(&scissor->matrix, 1.0f) && nvgp_gl_is_fast_draw_image((nvgp_darray_t*)paths) && nvgp_gl_paths_in_scissor(gl, paths, scissor); if (call == NULL) { goto error; } call->base.call_type = NVGP_GL_CALL_IMAGE; if (is_premulti) { support_fast_draw = support_fast_draw && !nvgp_gl_check_is_matrix_transformer(&paint->mat, gl->pixel_scale); call->base.shader_type = support_fast_draw ? NVGP_GL_SHADER_FAST_FILLIMG : NVGP_GL_SHADER_FILLIMG; } else { if (paint->draw_type == NVGP_IMAGE_DRAW_DEFAULT) { support_fast_draw = support_fast_draw && !nvgp_gl_check_is_matrix_transformer(&paint->mat, gl->pixel_scale); call->base.shader_type = support_fast_draw ? NVGP_GL_SHADER_FAST_FILLIMG_RGBA : NVGP_GL_SHADER_FILLIMG_RGBA; } else if (paint->draw_type == NVGP_IMAGE_DRAW_REPEAT) { support_fast_draw = support_fast_draw && !nvgp_gl_check_is_matrix_skew(&paint->mat); call->base.shader_type = support_fast_draw ? NVGP_GL_SHADER_FAST_REPEAT_FILLIMG_RGBA : NVGP_GL_SHADER_REPEAT_FILLIMG_RGBA; } } call->image = paint->image; call->triangle_count = 4; call->path_count = paths->size; call->path_index = gl->paths.size; call->blend_func = nvgp_gl_composite_operation_state(NVGP_GL_SOURCE_OVER); shader = &(gl->shader_list[call->base.shader_type]); max_verts = nvgp_gl_max_vert_count(paths) + call->triangle_count; offset = nvgp_gl_alloc_verts(shader, max_verts); if (offset == -1) { NVGP_FREE(call); goto error; } for (i = 0; i < paths->size; i++) { const nvgp_path_t* path = nvgp_darray_get_ptr(paths, i, nvgp_path_t); nvgp_gl_path_t* gl_path = nvgp_darray_get_empty_data_by_tail(&gl->paths); if (gl_path == NULL) { NVGP_FREE(call); goto error; } NVGP_MEMSET(gl_path, 0x0, sizeof(nvgp_gl_path_t)); if (path->nfill > 0) { gl_path->fill_offset = offset; gl_path->fill_count = path->nfill; NVGP_MEMCPY(&shader->verts[offset], path->fill, sizeof(nvgp_vertex_t) * path->nfill); offset += path->nfill; } if (path->nstroke > 0) { gl_path->stroke_offset = offset; gl_path->stroke_count = path->nstroke; NVGP_MEMCPY(&shader->verts[offset], path->stroke, sizeof(nvgp_vertex_t) * path->nstroke); offset += path->nstroke; } } if (paths->size == 1) { call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 1); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } frag = nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset); nvgp_gl_convert_paint(gl, frag, paint, scissor, fringe, fringe, -1.0f); } else { call->triangle_offset = offset; quad = &shader->verts[call->triangle_offset]; nvgp_gl_vset(&quad[0], bounds[2], bounds[3], 0.5f, 1.0f); nvgp_gl_vset(&quad[1], bounds[2], bounds[1], 0.5f, 1.0f); nvgp_gl_vset(&quad[2], bounds[0], bounds[3], 0.5f, 1.0f); nvgp_gl_vset(&quad[3], bounds[0], bounds[1], 0.5f, 1.0f); call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 2); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } // Simple shader for stencil frag = nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset); NVGP_MEMSET(frag, 0, sizeof(*frag)); frag->strokeThr = -1.0f; // Fill shader nvgp_gl_convert_paint(gl, nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset + shader->frag_size), paint, scissor, fringe, fringe, -1.0f); } nvgp_darray_push(&gl->calls, call); return TRUE; } error: return FALSE; } static nvgp_bool_t nvgp_gl_render_fast_stroke_by_color(nvgp_gl_context_t* gl, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, const nvgp_darray_t* paths) { nvgp_gl_shader_t* shader; int32_t max_verts, offset; if (paint->image == 0 && paths->size == 1 && !nvgp_gl_check_is_matrix_transformer(&paint->mat, 1.0f) && !nvgp_gl_check_is_matrix_transformer(&scissor->matrix, 1.0f) && nvgp_gl_paths_in_scissor(gl, paths, scissor) && nvgp_gl_is_fast_stroke(paths)) { nvgp_gl_frag_uniforms_t* frag = NULL; nvgp_gl_call_fast_fill_t* call = NULL; const nvgp_path_t* path = nvgp_darray_get_ptr(paths, 0, nvgp_path_t); nvgp_gl_path_t* gl_path = nvgp_darray_get_empty_data_by_tail(&gl->paths); if (gl_path == NULL) { goto error; } NVGP_MEMSET(gl_path, 0x0, sizeof(nvgp_gl_path_t)); call = NVGP_ZALLOC(nvgp_gl_call_fast_fill_t); if (call == NULL) { return FALSE; } call->base.call_type = NVGP_GL_CALL_FAST_FILL_COLOR; call->base.shader_type = NVGP_GL_SHADER_FAST_FILL_COLOR; call->mode = GL_TRIANGLE_STRIP; call->path_count = paths->size; call->path_index = gl->paths.size - 1; shader = &(gl->shader_list[call->base.shader_type]); max_verts = nvgp_gl_max_vert_count(paths); offset = nvgp_gl_alloc_verts(shader, max_verts); if (offset == -1) { NVGP_FREE(call); goto error; } gl_path->stroke_offset = offset; gl_path->stroke_count = path->nstroke; memcpy(&shader->verts[offset], path->stroke, sizeof(nvgp_vertex_t) * path->nstroke); offset += path->nstroke; call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 1); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } frag = nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset); nvgp_gl_convert_paint(gl, frag, paint, scissor, fringe, fringe, -1.0f); nvgp_darray_push(&gl->calls, call); return TRUE; } error: return FALSE; } static nvgp_bool_t nvgp_gl_render_stroke_by_color(nvgp_gl_context_t* gl, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, float stroke_width, const nvgp_darray_t* paths, int32_t is_gradient) { nvgp_gl_shader_t* shader; int32_t i, max_verts, offset; if (paint->image == 0) { nvgp_gl_call_stroke_t* call = NVGP_ZALLOC(nvgp_gl_call_stroke_t); if (call == NULL) { return FALSE; } call->base.call_type = NVGP_GL_CALL_STROKE; call->base.shader_type = is_gradient ? NVGP_GL_SHADER_FILLGRAD : NVGP_GL_SHADER_FILL_STROKE; call->path_count = paths->size; call->path_index = gl->paths.size; call->blend_func = nvgp_gl_composite_operation_state(NVGP_GL_SOURCE_OVER); shader = &(gl->shader_list[call->base.shader_type]); max_verts = nvgp_gl_max_vert_count(paths); offset = nvgp_gl_alloc_verts(shader, max_verts); if (offset == -1) { NVGP_FREE(call); goto error; } for (i = 0; i < paths->size; i++) { const nvgp_path_t* path = nvgp_darray_get_ptr(paths, i, nvgp_path_t); nvgp_gl_path_t* gl_path = nvgp_darray_get_empty_data_by_tail(&gl->paths); if (gl_path == NULL) { NVGP_FREE(call); goto error; } NVGP_MEMSET(gl_path, 0x0, sizeof(nvgp_gl_path_t)); if (path->nstroke) { gl_path->stroke_offset = offset; gl_path->stroke_count = path->nstroke; memcpy(&shader->verts[offset], path->stroke, sizeof(nvgp_vertex_t) * path->nstroke); offset += path->nstroke; } } if (gl->flags & NVGP_GL_FLAG_STENCIL_STROKES) { // Fill shader call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 2); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } nvgp_gl_convert_paint(gl, nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset), paint, scissor, stroke_width, fringe, -1.0f); nvgp_gl_convert_paint(gl, nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset + shader->frag_size), paint, scissor, stroke_width, fringe, 1.0f - 0.5f / 255.0f); } else { // Fill shader call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 1); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } nvgp_gl_convert_paint(gl, nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset), paint, scissor, stroke_width, fringe, -1.0f); } nvgp_darray_push(&gl->calls, call); return TRUE; } error: return FALSE; } static nvgp_bool_t nvgp_gl_render_stroke_by_image(nvgp_gl_context_t* gl, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, float stroke_width, const nvgp_darray_t* paths) { nvgp_gl_shader_t* shader; int32_t i, max_verts, offset; nvgp_gl_texture_t* tex = nvgp_gl_find_texture(gl, paint->image); if (paint->image != 0 && tex != NULL) { int32_t is_premulti = nvgp_gl_texture_is_premulti(tex); nvgp_gl_call_stroke_image_t* call = NVGP_ZALLOC(nvgp_gl_call_stroke_image_t); if (call == NULL) { return FALSE; } call->base.call_type = NVGP_GL_CALL_STROKE_IMAGE; call->base.shader_type = is_premulti ? NVGP_GL_SHADER_FILLIMG : NVGP_GL_SHADER_FILLIMG_RGBA; call->image = paint->image; call->path_count = paths->size; call->path_index = gl->paths.size; call->blend_func = nvgp_gl_composite_operation_state(NVGP_GL_SOURCE_OVER); shader = &(gl->shader_list[call->base.shader_type]); max_verts = nvgp_gl_max_vert_count(paths); offset = nvgp_gl_alloc_verts(shader, max_verts); if (offset == -1) { NVGP_FREE(call); goto error; } for (i = 0; i < paths->size; i++) { const nvgp_path_t* path = nvgp_darray_get_ptr(paths, i, nvgp_path_t); nvgp_gl_path_t* gl_path = nvgp_darray_get_empty_data_by_tail(&gl->paths); if (gl_path == NULL) { NVGP_FREE(call); goto error; } NVGP_MEMSET(gl_path, 0x0, sizeof(nvgp_gl_path_t)); if (path->nstroke) { gl_path->stroke_offset = offset; gl_path->stroke_count = path->nstroke; memcpy(&shader->verts[offset], path->stroke, sizeof(nvgp_vertex_t) * path->nstroke); offset += path->nstroke; } } if (gl->flags & NVGP_GL_FLAG_STENCIL_STROKES) { // Fill shader call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 2); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } nvgp_gl_convert_paint(gl, nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset), paint, scissor, stroke_width, fringe, -1.0f); nvgp_gl_convert_paint(gl, nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset + shader->frag_size), paint, scissor, stroke_width, fringe, 1.0f - 0.5f / 255.0f); } else { // Fill shader call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 1); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } nvgp_gl_convert_paint(gl, nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset), paint, scissor, stroke_width, fringe, -1.0f); } nvgp_darray_push(&gl->calls, call); return TRUE; } error: return FALSE; } static nvgp_bool_t nvgp_gl_render_fast_draw_text(nvgp_gl_context_t* gl, nvgp_paint_t* paint, nvgp_scissor_t* scissor, nvgp_vertex_t* verts, uint32_t nverts) { if (!nvgp_gl_check_is_matrix_transformer(&paint->mat, 1.0f) && !nvgp_gl_check_is_matrix_transformer(&scissor->matrix, 1.0f) && nvgp_gl_verts_in_scissor(gl, verts, nverts, scissor)) { nvgp_gl_shader_t* shader; nvgp_gl_frag_uniforms_t* frag; float fringe = 1.0f / gl->pixel_ratio; nvgp_gl_call_text_t* call = NVGP_ZALLOC(nvgp_gl_call_text_t); if (call == NULL) { goto error; } call->base.call_type = NVGP_GL_CALL_TEXT; call->base.shader_type = NVGP_GL_SHADER_FAST_FILLGLYPH; call->blend_func = nvgp_gl_composite_operation_state(NVGP_GL_SOURCE_OVER); call->image = paint->image; shader = &(gl->shader_list[call->base.shader_type]); // Allocate vertices for all the paths. call->triangle_offset = nvgp_gl_alloc_verts(shader, nverts); if (call->triangle_offset == -1) { NVGP_FREE(call); goto error; } call->triangle_count = nverts; NVGP_MEMCPY(&shader->verts[call->triangle_offset], verts, sizeof(nvgp_vertex_t) * nverts); // Fill shader call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 1); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } frag = nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset); nvgp_gl_convert_paint(gl, frag, paint, scissor, 1.0f, fringe, -1.0f); nvgp_darray_push(&gl->calls, call); return TRUE; } error: return FALSE; } static int32_t nvgp_gl_render_draw_text_by_transformer(nvgp_gl_context_t* gl, nvgp_paint_t* paint, nvgp_scissor_t* scissor, nvgp_vertex_t* verts, uint32_t nverts) { nvgp_gl_shader_t* shader; nvgp_gl_frag_uniforms_t* frag; float fringe = 1.0f / gl->pixel_ratio; nvgp_gl_call_text_t* call = NVGP_ZALLOC(nvgp_gl_call_text_t); if (call == NULL) { goto error; } call->base.call_type = NVGP_GL_CALL_TEXT; call->base.shader_type = NVGP_GL_SHADER_FILLGLYPH; call->blend_func = nvgp_gl_composite_operation_state(NVGP_GL_SOURCE_OVER); call->image = paint->image; shader = &(gl->shader_list[call->base.shader_type]); // Allocate vertices for all the paths. call->triangle_offset = nvgp_gl_alloc_verts(shader, nverts); if (call->triangle_offset == -1) { NVGP_FREE(call); goto error; } call->triangle_count = nverts; NVGP_MEMCPY(&shader->verts[call->triangle_offset], verts, sizeof(nvgp_vertex_t) * nverts); // Fill shader call->uniform_offset = nvgp_gl_alloc_frag_uniforms(shader, 1); if (call->uniform_offset == -1) { NVGP_FREE(call); goto error; } frag = nvgp_gl_frag_uniform_ptr(shader, call->uniform_offset); nvgp_gl_convert_paint(gl, frag, paint, scissor, 1.0f, fringe, -1.0f); nvgp_darray_push(&gl->calls, call); return TRUE; error: return FALSE; } static void nvgp_gl_render_fill(void* uptr, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, const float* bounds, const nvgp_darray_t* paths) { nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; int32_t is_gradient = NVGP_MEMCMP(&(paint->inner_color), &(paint->outer_color), sizeof(paint->outer_color)); if (paths->size <= 0) { return; } if (!is_gradient) { if (nvgp_gl_render_fast_fill_rect(gl, paint, scissor, fringe, bounds, paths)) { return; } } if (nvgp_gl_render_convex_fill_by_color(gl, paint, scissor, fringe, bounds, paths, is_gradient)) { return; } else if (nvgp_gl_render_fill_by_color(gl, paint, scissor, fringe, bounds, paths, is_gradient)) { return; } else if (nvgp_gl_render_draw_image(gl, paint, scissor, fringe, bounds, paths)) { return; } } static void nvgp_gl_render_stroke(void* uptr, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, float stroke_width, const nvgp_darray_t* paths) { nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; int32_t is_gradient = NVGP_MEMCMP(&(paint->inner_color), &(paint->outer_color), sizeof(paint->outer_color)); if (!is_gradient && gl->line_cap == NVGP_BUTT){ if (nvgp_gl_render_fast_stroke_by_color(gl, paint, scissor, fringe, paths)) { return; } } if (nvgp_gl_render_stroke_by_color(gl, paint, scissor, fringe, stroke_width, paths, is_gradient)){ return; } else if (nvgp_gl_render_stroke_by_image(gl, paint, scissor, fringe, stroke_width, paths)) { return; } } static void nvgp_gl_render_draw_text(void* uptr, nvgp_paint_t* paint, nvgp_scissor_t* scissor, nvgp_vertex_t* verts, uint32_t nverts) { nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; if (nvgp_gl_render_fast_draw_text(gl, paint, scissor, verts, nverts)) { return; } else if (nvgp_gl_render_draw_text_by_transformer(gl, paint, scissor, verts, nverts)) { return; } } static int32_t nvgp_gl_get_edge_anti_alias(void* uptr) { nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; return gl->edge_anti_alias; } #ifdef NVGP_GLES2 static uint32_t nvgp_gl_nearest_pow2(uint32_t num) { unsigned n = num > 0 ? num - 1 : 0; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n; } #endif static int nvgp_gl_create_texture(void* uptr, int type, int w, int h, int stride, int image_flags, const unsigned char* data) { nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; nvgp_gl_texture_t* tex = nvgp_darray_get_empty_by_tail(&gl->textures, nvgp_gl_texture_t); if (tex != NULL) { #ifdef NVGP_GLES2 // Check for non-power of 2. if (nvgp_gl_nearest_pow2(w) != (uint32_t)w || nvgp_gl_nearest_pow2(h) != (uint32_t)h) { // No repeat if ((image_flags & NVGP_GL_IMAGE_REPEATX) != 0 || (image_flags & NVGP_GL_IMAGE_REPEATY) != 0) { // printf("Repeat X/Y is not supported for non power-of-two textures (%d x %d)\n", w, h); image_flags &= ~(NVGP_GL_IMAGE_REPEATX | NVGP_GL_IMAGE_REPEATY); } // No mips. if (image_flags & NVGP_GL_IMAGE_GENERATE_MIPMAPS) { // printf("Mip-maps is not support for non power-of-two textures (%d x %d)\n", w, h); image_flags &= ~NVGP_GL_IMAGE_GENERATE_MIPMAPS; } } #endif glGenTextures(1, &tex->tex); tex->width = w; tex->height = h; tex->type = type; tex->id = ++gl->texture_id; tex->flags = image_flags; tex->data = data; nvgp_gl_bind_texture(gl, tex->tex); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); #ifndef NVGP_GLES2 glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->width); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); #endif #ifdef NVGP_GL2 // GL 1.4 and later has support for generating mipmaps using a tex parameter. if (image_flags & NVGP_GL_IMAGE_GENERATE_MIPMAPS) { glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); } #endif if (type == NVGP_TEXTURE_RGBA) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); } else { #if defined(NVGP_GLES2) || defined(NVGP_GL2) glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, data); #elif defined(NVGP_GLES3) glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, data); #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, data); #endif } if (image_flags & NVGP_GL_IMAGE_GENERATE_MIPMAPS) { if (image_flags & NVGP_GL_IMAGE_NEAREST) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } } else { if (image_flags & NVGP_GL_IMAGE_NEAREST) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } } if (image_flags & NVGP_GL_IMAGE_NEAREST) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } if (image_flags & NVGP_GL_IMAGE_REPEATX) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); if (image_flags & NVGP_GL_IMAGE_REPEATY) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); #ifndef NVGP_GLES2 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); #endif // The new way to build mipmaps on GLES and GL3 #ifndef NVGP_GL2 if (image_flags & NVGP_GL_IMAGE_GENERATE_MIPMAPS) { glGenerateMipmap(GL_TEXTURE_2D); } #endif nvgp_gl_check_error(gl, "create tex"); nvgp_gl_bind_texture(gl, 0); return tex->id; } return 0; } static int nvgp_gl_find_texture_by_data(void* uptr, const void* data) { uint32_t i; nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; for (i = 0; i < gl->textures.size; i++) { nvgp_gl_texture_t* texture = nvgp_darray_get_ptr(&gl->textures, i, nvgp_gl_texture_t); if (texture->data == data) { return texture->id; } } return -1; } static nvgp_bool_t nvgp_gl_delete_texture(void* uptr, int image) { uint32_t i; nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; for (i = 0; i < gl->textures.size; i++) { nvgp_gl_texture_t* texture = nvgp_darray_get_ptr(&gl->textures, i, nvgp_gl_texture_t); if (texture->id == image) { glDeleteTextures(1, &texture->tex); nvgp_darray_remove(&gl->textures, i, NULL, NULL); return TRUE; } } return FALSE; } static nvgp_bool_t nvgp_gl_update_texture(void* uptr, int image, int x, int y, int w, int h, const unsigned char* data) { nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; nvgp_gl_texture_t* tex = nvgp_gl_find_texture(gl, image); if (tex == NULL) { return FALSE; } nvgp_gl_bind_texture(gl, tex->tex); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); #ifndef NVGP_GLES2 glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->width); glPixelStorei(GL_UNPACK_SKIP_PIXELS, x); glPixelStorei(GL_UNPACK_SKIP_ROWS, y); #else // No support for all of skip, need to update a whole row at a time. if (tex->type == NVGP_TEXTURE_RGBA) { data += y * tex->width * 4; } else { data += y * tex->width; } x = 0; w = tex->width; #endif if (tex->type == NVGP_TEXTURE_RGBA) { glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, data); } else { #if defined(NVGP_GLES2) || defined(NVGP_GL2) glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_LUMINANCE, GL_UNSIGNED_BYTE, data); #else glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RED, GL_UNSIGNED_BYTE, data); #endif } glPixelStorei(GL_UNPACK_ALIGNMENT, 4); #ifndef NVGP_GLES2 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); #endif nvgp_gl_bind_texture(gl, 0); return TRUE; } static nvgp_bool_t nvgp_gl_get_texture_size(void* uptr, int image, int* w, int* h) { nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; nvgp_gl_texture_t* tex = nvgp_gl_find_texture(gl, image); if (tex == NULL) { return FALSE; } *w = tex->width; *h = tex->height; return TRUE; } static void nvgp_gl_render_cancel(void* uptr) { uint32_t i = 0; nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; for (i = 0; i < nvgp_get_arrary_size(gl->shader_list); i++) { nvgp_darray_clear(&gl->paths); gl->shader_list[i].nverts = 0; gl->shader_list[i].nuniforms = 0; } nvgp_darray_clear_by_destroy_function(&gl->calls, nvgp_gl_call_destroy, NULL); } static void nvgp_gl_set_line_cap(void* uptr, int line_cap) { nvgp_gl_context_t* gl = (nvgp_gl_context_t*)uptr; gl->line_cap = line_cap; } static void nvgp_gl_destroy(void* uptr) { int32_t i = 0; nvgp_gl_context_t* ctx = (nvgp_gl_context_t*)uptr; if (ctx == NULL) { return; } for (i = 0; i < NVGP_GL_SHADER_COUNT; i++) { nvgp_gl_delete_shader(&ctx->shader_list[i]); } nvgp_darray_clear_by_destroy_function(&ctx->calls, nvgp_gl_call_destroy, NULL); nvgp_darray_clear_by_destroy_function(&ctx->textures, nvgp_gl_texture_destroy, NULL); nvgp_darray_deinit(&ctx->calls); nvgp_darray_deinit(&ctx->paths); nvgp_darray_deinit(&ctx->textures); NVGP_FREE(ctx); } int32_t nvgp_gl_get_gpu_texture_id(nvgp_gl_context_t* gl, int32_t image_id) { int32_t i; for (i = 0; i < gl->textures.size; i++){ nvgp_gl_texture_t* texture = nvgp_darray_get_ptr(&gl->textures, i, nvgp_gl_texture_t); if (texture->id == image_id) { return texture->tex; } } return -1; } nvgp_gl_context_t* nvgp_gl_create(int flags) { nvgp_gl_context_t* context = NVGP_ZALLOC(nvgp_gl_context_t); if (context != NULL) { context->flags = flags; context->edge_anti_alias = flags & NVGP_GL_FLAG_ANTIALIAS ? 1 : 0; if (!nvgp_gl_render_create(context)) { goto error; } context->curr_prog = 0; context->texture_id = 0; nvgp_darray_init(&context->calls, NVGP_GL_INIT_CALL_NUMBER, 0); nvgp_darray_init(&context->paths, NVGP_GL_INIT_PATH_NUMBER, sizeof(nvgp_gl_path_t)); nvgp_darray_init(&context->textures, NVGP_GL_INIT_CALL_NUMBER, sizeof(nvgp_gl_texture_t)); } return context; error: nvgp_gl_destroy(context); return NULL; } static const nvgp_vtable_t vt = { .clear_cache = NULL, .find_texture = nvgp_gl_find_texture_by_data, .create_texture = nvgp_gl_create_texture, .delete_texture = nvgp_gl_delete_texture, .update_texture = nvgp_gl_update_texture, .get_texture_size = nvgp_gl_get_texture_size, .get_edge_anti_alias = nvgp_gl_get_edge_anti_alias, .end_frame = nvgp_gl_end_frame, .begin_frame = nvgp_gl_begin_frame, .set_line_cap = nvgp_gl_set_line_cap, .set_line_join = NULL, .render_cancel = nvgp_gl_render_cancel, .render_fill = nvgp_gl_render_fill, .render_stroke = nvgp_gl_render_stroke, .render_draw_text = nvgp_gl_render_draw_text, .destroy = nvgp_gl_destroy, }; const nvgp_vtable_t* nvgp_gl_vtable() { return &vt; }
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\gl\nanovg_plus_gl.h
/** * File: nanovg_plus_gl.h * Author: AWTK Develop Team * Brief: nanovg plus by opengl. * * Copyright (c) 2018 - 2021 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-10-27 Luo Zhiming <luozhiming@zlg.cn> created * */ #ifndef __NANOVG_PLUS_GL_H__ #define __NANOVG_PLUS_GL_H__ #ifdef __cplusplus extern "C" { #endif #include "../base/nanovg_plus.h" #ifndef NVGP_GL_INIT_CALL_NUMBER #define NVGP_GL_INIT_CALL_NUMBER 128 #endif #ifndef NVGP_GL_INIT_PATH_NUMBER #define NVGP_GL_INIT_PATH_NUMBER 128 #endif typedef struct _nvgp_gl_context_t nvgp_gl_context_t; typedef enum _nvgp_gl_flag_t { // Flag indicating if geometry based anti-aliasing is used (may not be needed when using MSAA). NVGP_GL_FLAG_ANTIALIAS = 1 << 0, // Flag indicating if strokes should be drawn using stencil buffer. The rendering will be a little // slower, but path overlaps (i.e. self-intersecting or sharp turns) will be drawn just once. NVGP_GL_FLAG_STENCIL_STROKES = 1 << 1, // Flag indicating that additional debug checks are done. NVGP_GL_FLAG_DEBUG = 1 << 2, } nvgp_gl_flag_t; typedef enum _nvgp_gl_image_flags_t { NVGP_GL_IMAGE_GENERATE_MIPMAPS = 1<<0, // Generate mipmaps during creation of the image. NVGP_GL_IMAGE_REPEATX = 1<<1, // Repeat image in X direction. NVGP_GL_IMAGE_REPEATY = 1<<2, // Repeat image in Y direction. NVGP_GL_IMAGE_FLIPY = 1<<3, // Flips (inverses) image in Y direction when rendered. NVGP_GL_IMAGE_PREMULTIPLIED = 1<<4, // Image data has premultiplied alpha. NVGP_GL_IMAGE_NEAREST = 1<<5, // Image interpolation is Nearest instead Linear }nvg_gl_image_flags_t; typedef enum _nvgp_gl_composite_operation_t { NVGP_GL_SOURCE_OVER, NVGP_GL_SOURCE_IN, NVGP_GL_SOURCE_OUT, NVGP_GL_ATOP, NVGP_GL_DESTINATION_OVER, NVGP_GL_DESTINATION_IN, NVGP_GL_DESTINATION_OUT, NVGP_GL_DESTINATION_ATOP, NVGP_GL_LIGHTER, NVGP_GL_COPY, NVGP_GL_XOR, } nvgp_gl_composite_operation_t; typedef struct _nvgp_gl_color_t { union { float rgba[4]; struct { float r,g,b,a; }; }; } nvgp_gl_color_t; const nvgp_vtable_t* nvgp_gl_vtable(); nvgp_gl_context_t* nvgp_gl_create(int flags); int32_t nvgp_gl_get_gpu_texture_id(nvgp_gl_context_t* gl, int32_t image_id); #ifdef __cplusplus } #endif #endif
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\gl\nanovg_plus_gl_utils.h
/** * File: nanovg_plus_gl_utils.h * Author: AWTK Develop Team * Brief: opengl utils function. * * Copyright (c) 2018 - 2021 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-10-27 Luo Zhiming <luozhiming@zlg.cn> created * */ #ifndef __NANOVG_PLUS_GL_UTILS_H__ #define __NANOVG_PLUS_GL_UTILS_H__ #ifdef WITHOUT_GLAD #include <SDL.h> #ifdef IOS #include <OpenGLES/gltypes.h> #include <OpenGLES/ES2/gl.h> #include <OpenGLES/ES2/glext.h> #else #define GL_GLEXT_PROTOTYPES 1 #include <SDL_opengl.h> #include <SDL_opengl_glext.h> #endif /*IOS*/ #else #include <glad/glad.h> #endif /*WITHOUT_GLAD*/ #include "nanovg_plus_gl.h" typedef struct _nvgp_gl_util_framebuffer { nvgp_context_t* ctx; GLuint fbo; GLuint rbo; GLuint texture; int32_t image; } nvgp_gl_util_framebuffer; #if defined(NVGP_GL3) || defined(NVGP_GLES2) || defined(NVGP_GLES3) #define NVGP_FBO_VALID 1 #elif defined(NVGP_GL2) #ifdef __APPLE__ #include <OpenGL/glext.h> #define NVGP_FBO_VALID 1 #endif #endif static GLint s_nvgp_gl_default_fbo = -1; int nvgp_gl_get_curr_framebuffer() { #ifdef NVGP_FBO_VALID GLint s_nvgp_gl_default_fbo; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &s_nvgp_gl_default_fbo); return s_nvgp_gl_default_fbo; #else return -1; #endif } void nvgp_gl_delete_framebuffer(nvgp_gl_util_framebuffer* fb) { #ifdef NVGP_FBO_VALID if (fb == NULL) { return; } if (fb->fbo != 0) { glDeleteFramebuffers(1, &fb->fbo); } if (fb->rbo != 0) { glDeleteRenderbuffers(1, &fb->rbo); } if (fb->image >= 0) { nvgp_delete_image(fb->ctx, fb->image); } fb->ctx = NULL; fb->fbo = 0; fb->rbo = 0; fb->texture = 0; fb->image = -1; NVGP_FREE(fb); #else (void)(fb); #endif } nvgp_gl_util_framebuffer* nvgp_gl_create_framebuffer(nvgp_context_t* ctx, int32_t w, int32_t h, int32_t imageFlags) { #ifdef NVGP_FBO_VALID GLint s_nvgp_gl_default_fbo; GLint defaultRBO; nvgp_gl_util_framebuffer* fb = NULL; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &s_nvgp_gl_default_fbo); glGetIntegerv(GL_RENDERBUFFER_BINDING, &defaultRBO); fb = NVGP_ZALLOC(nvgp_gl_util_framebuffer); if (fb == NULL) { goto error; } NVGP_MEMSET(fb, 0, sizeof(nvgp_gl_util_framebuffer)); fb->image = nvgp_create_image_rgba(ctx, w, h, imageFlags | NVGP_GL_IMAGE_FLIPY | NVGP_GL_IMAGE_PREMULTIPLIED, NULL); fb->texture = nvgp_gl_get_gpu_texture_id((nvgp_gl_context_t*)nvgp_get_vt_ctx(ctx), fb->image); fb->ctx = ctx; // frame buffer object glGenFramebuffers(1, &fb->fbo); glBindFramebuffer(GL_FRAMEBUFFER, fb->fbo); // render buffer object glGenRenderbuffers(1, &fb->rbo); glBindRenderbuffer(GL_RENDERBUFFER, fb->rbo); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, w, h); // combine all glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb->texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb->rbo); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { #ifdef GL_DEPTH24_STENCIL8 // If GL_STENCIL_INDEX8 is not supported, try GL_DEPTH24_STENCIL8 as a fallback. // Some graphics cards require a depth buffer along with a stencil. glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w, h); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb->texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb->rbo); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) #endif // GL_DEPTH24_STENCIL8 goto error; } glBindFramebuffer(GL_FRAMEBUFFER, s_nvgp_gl_default_fbo); glBindRenderbuffer(GL_RENDERBUFFER, defaultRBO); return fb; error: glBindFramebuffer(GL_FRAMEBUFFER, s_nvgp_gl_default_fbo); glBindRenderbuffer(GL_RENDERBUFFER, defaultRBO); nvgp_gl_delete_framebuffer(fb); return NULL; #else (void)(ctx); (void)(w); (void)(h); (void)(imageFlags); return NULL; #endif } void nvgp_gl_bind_framebuffer(nvgp_gl_util_framebuffer* fb) { #ifdef NVGP_FBO_VALID if (s_nvgp_gl_default_fbo == -1) { glGetIntegerv(GL_FRAMEBUFFER_BINDING, &s_nvgp_gl_default_fbo); } glBindFramebuffer(GL_FRAMEBUFFER, fb != NULL ? fb->fbo : s_nvgp_gl_default_fbo); #else (void)(fb); #endif } void nvgp_gl_read_current_framebuffer_data(unsigned int x, unsigned int y, unsigned int w, unsigned int h, unsigned int width, unsigned int height, void* pixels) { if(x + w <= width && y + h <= height && pixels != NULL) { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); } } #endif // NVGP_GL_UTILS_H
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\tests\gtest_nvpg.c
#include "gtest_nvpg.h" static nvgp_bool_t gtest_clear_cache(void* uptr) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; return TRUE; } static int gtest_find_texture(void* uptr, const void* data) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; if (ctx->data == data) { return ctx->image; } else { return 0; } } static int gtest_create_texture(void* uptr, int type, int w, int h, int stride, int image_flags, const unsigned char* data) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->type = type; ctx->w = w; ctx->h = h; ctx->stride = stride; ctx->image_flags = image_flags; ctx->data = (void*)data; return ctx->image; } static nvgp_bool_t gtest_delete_texture(void* uptr, int image) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->image = 0; return TRUE; } static nvgp_bool_t gtest_update_texture(void* uptr, int image, int x, int y, int w, int h, const unsigned char* data) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->x = x; ctx->y = y; ctx->w = w; ctx->h = h; ctx->image = image; ctx->data = (void*)data; return TRUE; } static int gtest_get_texture_size(void* uptr, int image, int* w, int* h) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; if (ctx->image != 0) { *w = ctx->w; *h = ctx->h; return 1; } return 0; } static int gtest_get_edge_anti_alias(void* uptr) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; return ctx->edge_anti_alias; } static void gtest_end_frame(void* uptr) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->test_info = END_FRAME_INFO; } static void gtest_begin_frame(void* uptr, float width, float height, float pixel_ratio) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->width = width; ctx->height = height; ctx->pixel_ratio = pixel_ratio; } static void gtest_set_line_cap(void* uptr, int line_cap) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->line_cap = line_cap; } static void gtest_set_line_join(void* uptr, int line_join) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->line_join = line_join; } static void gtest_render_cancel(void* uptr) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->test_info = RENDER_CANCEL_INFO; } static void gtest_render_fill(void* uptr, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, const float* bounds, const nvgp_darray_t* paths) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->fringe = fringe; memcpy(&ctx->paint, paint, sizeof(nvgp_paint_t)); memcpy(&ctx->paths, paths, sizeof(nvgp_darray_t)); memcpy(ctx->bounds, bounds, sizeof(ctx->bounds)); memcpy(&ctx->scissor, scissor, sizeof(nvgp_scissor_t)); } static void gtest_render_stroke(void* uptr, nvgp_paint_t* paint, nvgp_scissor_t* scissor, float fringe, float stroke_width, const nvgp_darray_t* paths) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->fringe = fringe; ctx->stroke_width = stroke_width; memcpy(&ctx->paint, paint, sizeof(nvgp_paint_t)); memcpy(&ctx->paths, paths, sizeof(nvgp_darray_t)); memcpy(&ctx->scissor, scissor, sizeof(nvgp_scissor_t)); } static void gtest_render_draw_text(void* uptr, nvgp_paint_t* paint, nvgp_scissor_t* scissor, nvgp_vertex_t* verts, uint32_t nverts) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->verts = verts; ctx->nverts = nverts; memcpy(&ctx->paint, paint, sizeof(nvgp_paint_t)); memcpy(&ctx->scissor, scissor, sizeof(nvgp_scissor_t)); } static void gtest_destroy(void* uptr) { gtest_nvgp_ctx_t* ctx = (gtest_nvgp_ctx_t*)uptr; ctx->test_info = DESTROY_INFO; } static const nvgp_vtable_t vt = { .clear_cache = gtest_clear_cache, .find_texture = gtest_find_texture, .create_texture = gtest_create_texture, .delete_texture = gtest_delete_texture, .update_texture = gtest_update_texture, .get_texture_size = gtest_get_texture_size, .get_edge_anti_alias = gtest_get_edge_anti_alias, .end_frame = gtest_end_frame, .begin_frame = gtest_begin_frame, .set_line_cap = gtest_set_line_cap, .set_line_join = gtest_set_line_join, .render_cancel = gtest_render_cancel, .render_fill = gtest_render_fill, .render_stroke = gtest_render_stroke, .render_draw_text = gtest_render_draw_text, .destroy = gtest_destroy, }; const nvgp_vtable_t* nvgp_gtest_vtable() { return &vt; }
0
D://workCode//uploadProject\awtk\3rd\nanovg_plus
D://workCode//uploadProject\awtk\3rd\nanovg_plus\tests\gtest_nvpg.h
#ifndef __GTEST_NVPG_H__ #define __GTEST_NVPG_H__ #include "nanovg_plus.h" #ifdef __cplusplus extern "C" { #endif typedef struct _gtest_nvgp_ctx_t { void* data; int type; int x; int y; int w; int h; int stride; int image_flags; int image; int edge_anti_alias; float width; float height; float pixel_ratio; int line_cap; int line_join; nvgp_paint_t paint; nvgp_scissor_t scissor; float fringe; float bounds[4]; nvgp_darray_t paths; float stroke_width; nvgp_vertex_t* verts; uint32_t nverts; int clear_cache; int test_info; } gtest_nvgp_ctx_t; #define END_FRAME_INFO 0xff #define RENDER_CANCEL_INFO 0xee #define DESTROY_INFO 0xcc const nvgp_vtable_t* nvgp_gtest_vtable(); #ifdef __cplusplus } #endif #endif
0
D://workCode//uploadProject\awtk\3rd\nativefiledialog
D://workCode//uploadProject\awtk\3rd\nativefiledialog\src\common.h
/* Native File Dialog Internal, common across platforms http://www.frogtoss.com/labs */ #ifndef _NFD_COMMON_H #define _NFD_COMMON_H #define NFD_MAX_STRLEN 256 #define _NFD_UNUSED(x) ((void)x) void *NFDi_Malloc( size_t bytes ); void NFDi_Free( void *ptr ); void NFDi_SetError( const char *msg ); void NFDi_SafeStrncpy( char *dst, const char *src, size_t maxCopy ); #endif
0
D://workCode//uploadProject\awtk\3rd\nativefiledialog
D://workCode//uploadProject\awtk\3rd\nativefiledialog\src\nfd_common.c
/* Native File Dialog http://www.frogtoss.com/labs */ #include <stdlib.h> #include <assert.h> #include <string.h> #include "nfd_common.h" static char g_errorstr[NFD_MAX_STRLEN] = {0}; /* public routines */ const char *NFD_GetError( void ) { return g_errorstr; } size_t NFD_PathSet_GetCount( const nfdpathset_t *pathset ) { assert(pathset); return pathset->count; } nfdchar_t *NFD_PathSet_GetPath( const nfdpathset_t *pathset, size_t num ) { assert(pathset); assert(num < pathset->count); return pathset->buf + pathset->indices[num]; } void NFD_PathSet_Free( nfdpathset_t *pathset ) { assert(pathset); NFDi_Free( pathset->indices ); NFDi_Free( pathset->buf ); } /* internal routines */ void *NFDi_Malloc( size_t bytes ) { void *ptr = malloc(bytes); if ( !ptr ) NFDi_SetError("NFDi_Malloc failed."); return ptr; } void NFDi_Free( void *ptr ) { assert(ptr); free(ptr); } void NFDi_SetError( const char *msg ) { int bTruncate = NFDi_SafeStrncpy( g_errorstr, msg, NFD_MAX_STRLEN ); assert( !bTruncate ); _NFD_UNUSED(bTruncate); } int NFDi_SafeStrncpy( char *dst, const char *src, size_t maxCopy ) { size_t n = maxCopy; char *d = dst; assert( src ); assert( dst ); while ( n > 0 && *src != '\0' ) { *d++ = *src++; --n; } /* Truncation case - terminate string and return true */ if ( n == 0 ) { dst[maxCopy-1] = '\0'; return 1; } /* No truncation. Append a single NULL and return. */ *d = '\0'; return 0; } /* adapted from microutf8 */ int32_t NFDi_UTF8_Strlen( const nfdchar_t *str ) { /* This function doesn't properly check validity of UTF-8 character sequence, it is supposed to use only with valid UTF-8 strings. */ int32_t character_count = 0; int32_t i = 0; /* Counter used to iterate over string. */ nfdchar_t maybe_bom[4]; /* If there is UTF-8 BOM ignore it. */ if (strlen(str) > 2) { strncpy(maybe_bom, str, 3); maybe_bom[3] = 0; if (strcmp(maybe_bom, (nfdchar_t*)NFD_UTF8_BOM) == 0) i += 3; } while(str[i]) { if (str[i] >> 7 == 0) { /* If bit pattern begins with 0 we have ascii character. */ ++character_count; } else if (str[i] >> 6 == 3) { /* If bit pattern begins with 11 it is beginning of UTF-8 byte sequence. */ ++character_count; } else if (str[i] >> 6 == 2) ; /* If bit pattern begins with 10 it is middle of utf-8 byte sequence. */ else { /* In any other case this is not valid UTF-8. */ return -1; } ++i; } return character_count; } int NFDi_IsFilterSegmentChar( char ch ) { return (ch==','||ch==';'||ch=='\0'); }
0
D://workCode//uploadProject\awtk\3rd\nativefiledialog
D://workCode//uploadProject\awtk\3rd\nativefiledialog\src\nfd_common.h
/* Native File Dialog Internal, common across platforms http://www.frogtoss.com/labs */ #ifndef _NFD_COMMON_H #define _NFD_COMMON_H #include "nfd.h" #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define NFD_MAX_STRLEN 256 #define _NFD_UNUSED(x) ((void)x) #define NFD_UTF8_BOM "\xEF\xBB\xBF" void *NFDi_Malloc( size_t bytes ); void NFDi_Free( void *ptr ); void NFDi_SetError( const char *msg ); int NFDi_SafeStrncpy( char *dst, const char *src, size_t maxCopy ); int32_t NFDi_UTF8_Strlen( const nfdchar_t *str ); int NFDi_IsFilterSegmentChar( char ch ); #ifdef __cplusplus } #endif #endif
0
D://workCode//uploadProject\awtk\3rd\nativefiledialog
D://workCode//uploadProject\awtk\3rd\nativefiledialog\src\nfd_gtk.c
/* Native File Dialog http://www.frogtoss.com/labs */ #include <stdio.h> #include <assert.h> #include <string.h> #include <gtk/gtk.h> #include "nfd.h" #include "nfd_common.h" const char INIT_FAIL_MSG[] = "gtk_init_check failed to initilaize GTK+"; static void AddTypeToFilterName( const char *typebuf, char *filterName, size_t bufsize ) { const char SEP[] = ", "; size_t len = strlen(filterName); if ( len != 0 ) { strncat( filterName, SEP, bufsize - len - 1 ); len += strlen(SEP); } strncat( filterName, typebuf, bufsize - len - 1 ); } static void AddFiltersToDialog( GtkWidget *dialog, const char *filterList ) { GtkFileFilter *filter; char typebuf[NFD_MAX_STRLEN] = {0}; const char *p_filterList = filterList; char *p_typebuf = typebuf; char filterName[NFD_MAX_STRLEN] = {0}; if ( !filterList || strlen(filterList) == 0 ) return; filter = gtk_file_filter_new(); while ( 1 ) { if ( NFDi_IsFilterSegmentChar(*p_filterList) ) { char typebufWildcard[NFD_MAX_STRLEN]; /* add another type to the filter */ assert( strlen(typebuf) > 0 ); assert( strlen(typebuf) < NFD_MAX_STRLEN-1 ); snprintf( typebufWildcard, NFD_MAX_STRLEN, "*.%s", typebuf ); AddTypeToFilterName( typebuf, filterName, NFD_MAX_STRLEN ); gtk_file_filter_add_pattern( filter, typebufWildcard ); p_typebuf = typebuf; memset( typebuf, 0, sizeof(char) * NFD_MAX_STRLEN ); } if ( *p_filterList == ';' || *p_filterList == '\0' ) { /* end of filter -- add it to the dialog */ gtk_file_filter_set_name( filter, filterName ); gtk_file_chooser_add_filter( GTK_FILE_CHOOSER(dialog), filter ); filterName[0] = '\0'; if ( *p_filterList == '\0' ) break; filter = gtk_file_filter_new(); } if ( !NFDi_IsFilterSegmentChar( *p_filterList ) ) { *p_typebuf = *p_filterList; p_typebuf++; } p_filterList++; } /* always append a wildcard option to the end*/ filter = gtk_file_filter_new(); gtk_file_filter_set_name( filter, "*.*" ); gtk_file_filter_add_pattern( filter, "*" ); gtk_file_chooser_add_filter( GTK_FILE_CHOOSER(dialog), filter ); } static void SetDefaultPath( GtkWidget *dialog, const char *defaultPath ) { if ( !defaultPath || strlen(defaultPath) == 0 ) return; /* GTK+ manual recommends not specifically setting the default path. We do it anyway in order to be consistent across platforms. If consistency with the native OS is preferred, this is the line to comment out. -ml */ gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER(dialog), defaultPath ); } static nfdresult_t AllocPathSet( GSList *fileList, nfdpathset_t *pathSet ) { size_t bufSize = 0; GSList *node; nfdchar_t *p_buf; size_t count = 0; assert(fileList); assert(pathSet); pathSet->count = (size_t)g_slist_length( fileList ); assert( pathSet->count > 0 ); pathSet->indices = NFDi_Malloc( sizeof(size_t)*pathSet->count ); if ( !pathSet->indices ) { return NFD_ERROR; } /* count the total space needed for buf */ for ( node = fileList; node; node = node->next ) { assert(node->data); bufSize += strlen( (const gchar*)node->data ) + 1; } pathSet->buf = NFDi_Malloc( sizeof(nfdchar_t) * bufSize ); /* fill buf */ p_buf = pathSet->buf; for ( node = fileList; node; node = node->next ) { nfdchar_t *path = (nfdchar_t*)(node->data); size_t byteLen = strlen(path)+1; ptrdiff_t index; memcpy( p_buf, path, byteLen ); g_free(node->data); index = p_buf - pathSet->buf; assert( index >= 0 ); pathSet->indices[count] = (size_t)index; p_buf += byteLen; ++count; } g_slist_free( fileList ); return NFD_OKAY; } static void WaitForCleanup(void) { while (gtk_events_pending()) gtk_main_iteration(); } /* public */ nfdresult_t NFD_OpenDialog( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath ) { GtkWidget *dialog; nfdresult_t result; if ( !gtk_init_check( NULL, NULL ) ) { NFDi_SetError(INIT_FAIL_MSG); return NFD_ERROR; } dialog = gtk_file_chooser_dialog_new( "Open File", NULL, GTK_FILE_CHOOSER_ACTION_OPEN, "_Cancel", GTK_RESPONSE_CANCEL, "_Open", GTK_RESPONSE_ACCEPT, NULL ); /* Build the filter list */ AddFiltersToDialog(dialog, filterList); /* Set the default path */ SetDefaultPath(dialog, defaultPath); result = NFD_CANCEL; if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT ) { char *filename; filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dialog) ); { size_t len = strlen(filename); *outPath = NFDi_Malloc( len + 1 ); memcpy( *outPath, filename, len + 1 ); if ( !*outPath ) { g_free( filename ); gtk_widget_destroy(dialog); return NFD_ERROR; } } g_free( filename ); result = NFD_OKAY; } WaitForCleanup(); gtk_widget_destroy(dialog); WaitForCleanup(); return result; } nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdpathset_t *outPaths ) { GtkWidget *dialog; nfdresult_t result; if ( !gtk_init_check( NULL, NULL ) ) { NFDi_SetError(INIT_FAIL_MSG); return NFD_ERROR; } dialog = gtk_file_chooser_dialog_new( "Open Files", NULL, GTK_FILE_CHOOSER_ACTION_OPEN, "_Cancel", GTK_RESPONSE_CANCEL, "_Open", GTK_RESPONSE_ACCEPT, NULL ); gtk_file_chooser_set_select_multiple( GTK_FILE_CHOOSER(dialog), TRUE ); /* Build the filter list */ AddFiltersToDialog(dialog, filterList); /* Set the default path */ SetDefaultPath(dialog, defaultPath); result = NFD_CANCEL; if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT ) { GSList *fileList = gtk_file_chooser_get_filenames( GTK_FILE_CHOOSER(dialog) ); if ( AllocPathSet( fileList, outPaths ) == NFD_ERROR ) { gtk_widget_destroy(dialog); return NFD_ERROR; } result = NFD_OKAY; } WaitForCleanup(); gtk_widget_destroy(dialog); WaitForCleanup(); return result; } nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath ) { GtkWidget *dialog; nfdresult_t result; if ( !gtk_init_check( NULL, NULL ) ) { NFDi_SetError(INIT_FAIL_MSG); return NFD_ERROR; } dialog = gtk_file_chooser_dialog_new( "Save File", NULL, GTK_FILE_CHOOSER_ACTION_SAVE, "_Cancel", GTK_RESPONSE_CANCEL, "_Save", GTK_RESPONSE_ACCEPT, NULL ); gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dialog), TRUE ); /* Build the filter list */ AddFiltersToDialog(dialog, filterList); /* Set the default path */ SetDefaultPath(dialog, defaultPath); result = NFD_CANCEL; if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT ) { char *filename; filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dialog) ); { size_t len = strlen(filename); *outPath = NFDi_Malloc( len + 1 ); memcpy( *outPath, filename, len + 1 ); if ( !*outPath ) { g_free( filename ); gtk_widget_destroy(dialog); return NFD_ERROR; } } g_free(filename); result = NFD_OKAY; } WaitForCleanup(); gtk_widget_destroy(dialog); WaitForCleanup(); return result; } nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, nfdchar_t **outPath) { GtkWidget *dialog; nfdresult_t result; if (!gtk_init_check(NULL, NULL)) { NFDi_SetError(INIT_FAIL_MSG); return NFD_ERROR; } dialog = gtk_file_chooser_dialog_new( "Select folder", NULL, GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, "_Cancel", GTK_RESPONSE_CANCEL, "_Select", GTK_RESPONSE_ACCEPT, NULL ); gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dialog), TRUE ); /* Set the default path */ SetDefaultPath(dialog, defaultPath); result = NFD_CANCEL; if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT ) { char *filename; filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dialog) ); { size_t len = strlen(filename); *outPath = NFDi_Malloc( len + 1 ); memcpy( *outPath, filename, len + 1 ); if ( !*outPath ) { g_free( filename ); gtk_widget_destroy(dialog); return NFD_ERROR; } } g_free(filename); result = NFD_OKAY; } WaitForCleanup(); gtk_widget_destroy(dialog); WaitForCleanup(); return result; }
0
D://workCode//uploadProject\awtk\3rd\nativefiledialog
D://workCode//uploadProject\awtk\3rd\nativefiledialog\src\nfd_zenity.c
/* Native File Dialog http://www.frogtoss.com/labs */ #include <stdio.h> #include <assert.h> #include <string.h> #include "nfd.h" #include "nfd_common.h" #define SIMPLE_EXEC_IMPLEMENTATION #include "simple_exec.h" const char NO_ZENITY_MSG[] = "zenity not installed"; static void AddTypeToFilterName( const char *typebuf, char *filterName, size_t bufsize ) { size_t len = strlen(filterName); if( len > 0 ) strncat( filterName, " *.", bufsize - len - 1 ); else strncat( filterName, "--file-filter=*.", bufsize - len - 1 ); len = strlen(filterName); strncat( filterName, typebuf, bufsize - len - 1 ); } static void AddFiltersToCommandArgs(char** commandArgs, int commandArgsLen, const char *filterList ) { char typebuf[NFD_MAX_STRLEN] = {0}; const char *p_filterList = filterList; char *p_typebuf = typebuf; char filterName[NFD_MAX_STRLEN] = {0}; int i; if ( !filterList || strlen(filterList) == 0 ) return; while ( 1 ) { if ( NFDi_IsFilterSegmentChar(*p_filterList) ) { char typebufWildcard[NFD_MAX_STRLEN]; /* add another type to the filter */ assert( strlen(typebuf) > 0 ); assert( strlen(typebuf) < NFD_MAX_STRLEN-1 ); snprintf( typebufWildcard, NFD_MAX_STRLEN, "*.%s", typebuf ); AddTypeToFilterName( typebuf, filterName, NFD_MAX_STRLEN ); p_typebuf = typebuf; memset( typebuf, 0, sizeof(char) * NFD_MAX_STRLEN ); } if ( *p_filterList == ';' || *p_filterList == '\0' ) { /* end of filter -- add it to the dialog */ for(i = 0; commandArgs[i] != NULL && i < commandArgsLen; i++); commandArgs[i] = strdup(filterName); filterName[0] = '\0'; if ( *p_filterList == '\0' ) break; } if ( !NFDi_IsFilterSegmentChar( *p_filterList ) ) { *p_typebuf = *p_filterList; p_typebuf++; } p_filterList++; } /* always append a wildcard option to the end*/ for(i = 0; commandArgs[i] != NULL && i < commandArgsLen; i++); commandArgs[i] = strdup("--file-filter=*.*"); } static nfdresult_t ZenityCommon(char** command, int commandLen, const char* defaultPath, const char* filterList, char** stdOut) { if(defaultPath != NULL) { char* prefix = "--filename="; int len = strlen(prefix) + strlen(defaultPath) + 1; char* tmp = (char*) calloc(len, 1); strcat(tmp, prefix); strcat(tmp, defaultPath); int i; for(i = 0; command[i] != NULL && i < commandLen; i++); command[i] = tmp; } AddFiltersToCommandArgs(command, commandLen, filterList); int byteCount = 0; int exitCode = 0; int processInvokeError = runCommandArray(stdOut, &byteCount, &exitCode, 0, command); for(int i = 0; command[i] != NULL && i < commandLen; i++) free(command[i]); nfdresult_t result = NFD_OKAY; if(processInvokeError == COMMAND_NOT_FOUND) { NFDi_SetError(NO_ZENITY_MSG); result = NFD_ERROR; } else { if(exitCode == 1) result = NFD_CANCEL; } return result; } static nfdresult_t AllocPathSet(char* zenityList, nfdpathset_t *pathSet ) { assert(zenityList); assert(pathSet); size_t len = strlen(zenityList) + 1; pathSet->buf = NFDi_Malloc(len); int numEntries = 1; for(size_t i = 0; i < len; i++) { char ch = zenityList[i]; if(ch == '|') { numEntries++; ch = '\0'; } pathSet->buf[i] = ch; } pathSet->count = numEntries; assert( pathSet->count > 0 ); pathSet->indices = NFDi_Malloc( sizeof(size_t)*pathSet->count ); int entry = 0; pathSet->indices[0] = 0; for(size_t i = 0; i < len; i++) { char ch = zenityList[i]; if(ch == '|') { entry++; pathSet->indices[entry] = i + 1; } } return NFD_OKAY; } /* public */ nfdresult_t NFD_OpenDialog( const char *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath ) { int commandLen = 100; char* command[commandLen]; memset(command, 0, commandLen * sizeof(char*)); command[0] = strdup("zenity"); command[1] = strdup("--file-selection"); command[2] = strdup("--title=Open File"); char* stdOut = NULL; nfdresult_t result = ZenityCommon(command, commandLen, defaultPath, filterList, &stdOut); if(stdOut != NULL) { size_t len = strlen(stdOut); *outPath = NFDi_Malloc(len); memcpy(*outPath, stdOut, len); (*outPath)[len-1] = '\0'; // trim out the final \n with a null terminator free(stdOut); } else { *outPath = NULL; } return result; } nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdpathset_t *outPaths ) { int commandLen = 100; char* command[commandLen]; memset(command, 0, commandLen * sizeof(char*)); command[0] = strdup("zenity"); command[1] = strdup("--file-selection"); command[2] = strdup("--title=Open Files"); command[3] = strdup("--multiple"); char* stdOut = NULL; nfdresult_t result = ZenityCommon(command, commandLen, defaultPath, filterList, &stdOut); if(stdOut != NULL) { size_t len = strlen(stdOut); stdOut[len-1] = '\0'; // remove trailing newline if ( AllocPathSet( stdOut, outPaths ) == NFD_ERROR ) result = NFD_ERROR; free(stdOut); } else { result = NFD_ERROR; } return result; } nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath ) { int commandLen = 100; char* command[commandLen]; memset(command, 0, commandLen * sizeof(char*)); command[0] = strdup("zenity"); command[1] = strdup("--file-selection"); command[2] = strdup("--title=Save File"); command[3] = strdup("--save"); char* stdOut = NULL; nfdresult_t result = ZenityCommon(command, commandLen, defaultPath, filterList, &stdOut); if(stdOut != NULL) { size_t len = strlen(stdOut); *outPath = NFDi_Malloc(len); memcpy(*outPath, stdOut, len); (*outPath)[len-1] = '\0'; // trim out the final \n with a null terminator free(stdOut); } else { *outPath = NULL; } return result; } nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, nfdchar_t **outPath) { int commandLen = 100; char* command[commandLen]; memset(command, 0, commandLen * sizeof(char*)); command[0] = strdup("zenity"); command[1] = strdup("--file-selection"); command[2] = strdup("--directory"); command[3] = strdup("--title=Select folder"); char* stdOut = NULL; nfdresult_t result = ZenityCommon(command, commandLen, defaultPath, "", &stdOut); if(stdOut != NULL) { size_t len = strlen(stdOut); *outPath = NFDi_Malloc(len); memcpy(*outPath, stdOut, len); (*outPath)[len-1] = '\0'; // trim out the final \n with a null terminator free(stdOut); } else { *outPath = NULL; } return result; }
0
D://workCode//uploadProject\awtk\3rd\nativefiledialog
D://workCode//uploadProject\awtk\3rd\nativefiledialog\src\simple_exec.h
// copied from: https://github.com/wheybags/simple_exec/blob/5a74c507c4ce1b2bb166177ead4cca7cfa23cb35/simple_exec.h // simple_exec.h, single header library to run external programs + retrieve their status code and output (unix only for now) // // do this: // #define SIMPLE_EXEC_IMPLEMENTATION // before you include this file in *one* C or C++ file to create the implementation. // i.e. it should look like this: // #define SIMPLE_EXEC_IMPLEMENTATION // #include "simple_exec.h" #ifndef SIMPLE_EXEC_H #define SIMPLE_EXEC_H int runCommand(char** stdOut, int* stdOutByteCount, int* returnCode, int includeStdErr, char* command, ...); int runCommandArray(char** stdOut, int* stdOutByteCount, int* returnCode, int includeStdErr, char* const* allArgs); #endif // SIMPLE_EXEC_H #ifdef SIMPLE_EXEC_IMPLEMENTATION #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <sys/wait.h> #include <stdarg.h> #include <fcntl.h> #define release_assert(exp) { if (!(exp)) { abort(); } } enum PIPE_FILE_DESCRIPTORS { READ_FD = 0, WRITE_FD = 1 }; enum RUN_COMMAND_ERROR { COMMAND_RAN_OK = 0, COMMAND_NOT_FOUND = 1 }; int runCommandArray(char** stdOut, int* stdOutByteCount, int* returnCode, int includeStdErr, char* const* allArgs) { // adapted from: https://stackoverflow.com/a/479103 int bufferSize = 256; char buffer[bufferSize + 1]; int dataReadFromChildDefaultSize = bufferSize * 5; int dataReadFromChildSize = dataReadFromChildDefaultSize; int dataReadFromChildUsed = 0; char* dataReadFromChild = (char*)malloc(dataReadFromChildSize); int parentToChild[2]; release_assert(pipe(parentToChild) == 0); int childToParent[2]; release_assert(pipe(childToParent) == 0); int errPipe[2]; release_assert(pipe(errPipe) == 0); pid_t pid; switch( pid = fork() ) { case -1: { release_assert(0 && "Fork failed"); break; } case 0: // child { release_assert(dup2(parentToChild[READ_FD ], STDIN_FILENO ) != -1); release_assert(dup2(childToParent[WRITE_FD], STDOUT_FILENO) != -1); if(includeStdErr) { release_assert(dup2(childToParent[WRITE_FD], STDERR_FILENO) != -1); } else { int devNull = open("/dev/null", O_WRONLY); release_assert(dup2(devNull, STDERR_FILENO) != -1); } // unused release_assert(close(parentToChild[WRITE_FD]) == 0); release_assert(close(childToParent[READ_FD ]) == 0); release_assert(close(errPipe[READ_FD]) == 0); const char* command = allArgs[0]; execvp(command, allArgs); char err = 1; ssize_t result = write(errPipe[WRITE_FD], &err, 1); release_assert(result != -1); close(errPipe[WRITE_FD]); close(parentToChild[READ_FD]); close(childToParent[WRITE_FD]); exit(0); } default: // parent { // unused release_assert(close(parentToChild[READ_FD]) == 0); release_assert(close(childToParent[WRITE_FD]) == 0); release_assert(close(errPipe[WRITE_FD]) == 0); while(1) { ssize_t bytesRead = 0; switch(bytesRead = read(childToParent[READ_FD], buffer, bufferSize)) { case 0: // End-of-File, or non-blocking read. { int status = 0; release_assert(waitpid(pid, &status, 0) == pid); // done with these now release_assert(close(parentToChild[WRITE_FD]) == 0); release_assert(close(childToParent[READ_FD]) == 0); char errChar = 0; ssize_t result = read(errPipe[READ_FD], &errChar, 1); release_assert(result != -1); close(errPipe[READ_FD]); if(errChar) { free(dataReadFromChild); return COMMAND_NOT_FOUND; } // free any un-needed memory with realloc + add a null terminator for convenience dataReadFromChild = (char*)realloc(dataReadFromChild, dataReadFromChildUsed + 1); dataReadFromChild[dataReadFromChildUsed] = '\0'; if(stdOut != NULL) *stdOut = dataReadFromChild; else free(dataReadFromChild); if(stdOutByteCount != NULL) *stdOutByteCount = dataReadFromChildUsed; if(returnCode != NULL) *returnCode = WEXITSTATUS(status); return COMMAND_RAN_OK; } case -1: { release_assert(0 && "read() failed"); break; } default: { if(dataReadFromChildUsed + bytesRead + 1 >= dataReadFromChildSize) { dataReadFromChildSize += dataReadFromChildDefaultSize; dataReadFromChild = (char*)realloc(dataReadFromChild, dataReadFromChildSize); } memcpy(dataReadFromChild + dataReadFromChildUsed, buffer, bytesRead); dataReadFromChildUsed += bytesRead; break; } } } } } } int runCommand(char** stdOut, int* stdOutByteCount, int* returnCode, int includeStdErr, char* command, ...) { va_list vl; va_start(vl, command); char* currArg = NULL; int allArgsInitialSize = 16; int allArgsSize = allArgsInitialSize; char** allArgs = (char**)malloc(sizeof(char*) * allArgsSize); allArgs[0] = command; int i = 1; do { currArg = va_arg(vl, char*); allArgs[i] = currArg; i++; if(i >= allArgsSize) { allArgsSize += allArgsInitialSize; allArgs = (char**)realloc(allArgs, sizeof(char*) * allArgsSize); } } while(currArg != NULL); va_end(vl); int retval = runCommandArray(stdOut, stdOutByteCount, returnCode, includeStdErr, allArgs); free(allArgs); return retval; } #endif //SIMPLE_EXEC_IMPLEMENTATION
0
D://workCode//uploadProject\awtk\3rd\nativefiledialog\src
D://workCode//uploadProject\awtk\3rd\nativefiledialog\src\include\nfd.h
/* Native File Dialog User API http://www.frogtoss.com/labs */ #ifndef _NFD_H #define _NFD_H #ifdef __cplusplus extern "C" { #endif #include <stddef.h> /* denotes UTF-8 char */ typedef char nfdchar_t; /* opaque data structure -- see NFD_PathSet_* */ typedef struct { nfdchar_t *buf; size_t *indices; /* byte offsets into buf */ size_t count; /* number of indices into buf */ }nfdpathset_t; typedef enum { NFD_ERROR, /* programmatic error */ NFD_OKAY, /* user pressed okay, or successful return */ NFD_CANCEL /* user pressed cancel */ }nfdresult_t; /* nfd_<targetplatform>.c */ /* single file open dialog */ nfdresult_t NFD_OpenDialog( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath ); /* multiple file open dialog */ nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdpathset_t *outPaths ); /* save dialog */ nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath ); /* select folder dialog */ nfdresult_t NFD_PickFolder( const nfdchar_t *defaultPath, nfdchar_t **outPath); /* nfd_common.c */ /* get last error -- set when nfdresult_t returns NFD_ERROR */ const char *NFD_GetError( void ); /* get the number of entries stored in pathSet */ size_t NFD_PathSet_GetCount( const nfdpathset_t *pathSet ); /* Get the UTF-8 path at offset index */ nfdchar_t *NFD_PathSet_GetPath( const nfdpathset_t *pathSet, size_t index ); /* Free the pathSet */ void NFD_PathSet_Free( nfdpathset_t *pathSet ); #ifdef __cplusplus } #endif #endif
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\config.h
/* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ /* #undef AC_APPLE_UNIVERSAL_BUILD */ /* Whether we have alarm() */ //#define HAVE_ALARM 1 /* Whether the compiler supports __builtin_clz */ //#define HAVE_BUILTIN_CLZ /**/ /* Define to 1 if you have the <dlfcn.h> header file. */ //#define HAVE_DLFCN_H 1 /* Whether we have FE_DIVBYZERO */ //#define HAVE_FEDIVBYZERO 1 /* Whether we have feenableexcept() */ //#define HAVE_FEENABLEEXCEPT 1 /* Define to 1 if we have <fenv.h> */ //#define HAVE_FENV_H 1 /* Whether the tool chain supports __float128 */ //#define HAVE_FLOAT128 /**/ /* Whether the compiler supports GCC vector extensions */ //#define HAVE_GCC_VECTOR_EXTENSIONS /**/ /* Define to 1 if you have the `getisax' function. */ /* #undef HAVE_GETISAX */ /* Whether we have getpagesize() */ //#define HAVE_GETPAGESIZE 1 /* Whether we have gettimeofday() */ //#define HAVE_GETTIMEOFDAY 1 /* Define to 1 if you have the <inttypes.h> header file. */ //#define HAVE_INTTYPES_H 1 /* Define to 1 if you have the `pixman-1' library (-lpixman-1). */ /* #undef HAVE_LIBPIXMAN_1 */ /* Whether we have libpng */ //#define HAVE_LIBPNG 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Whether we have mmap() */ //#define HAVE_MMAP 1 /* Whether we have mprotect() */ //#define HAVE_MPROTECT 1 /* Whether we have posix_memalign() */ //#define HAVE_POSIX_MEMALIGN 1 /* Whether pthreads is supported */ //#define HAVE_PTHREADS /**/ /* Whether we have sigaction() */ //#define HAVE_SIGACTION 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if we have <sys/mman.h> */ //#define HAVE_SYS_MMAN_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ //#define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ //#define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <unistd.h> header file. */ //#define HAVE_UNISTD_H 1 /* Define to the sub-directory where libtool stores uninstalled libraries. */ //#define LT_OBJDIR ".libs/" /* Name of package */ #define PACKAGE "pixman" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "pixman@lists.freedesktop.org" /* Define to the full name of this package. */ #define PACKAGE_NAME "pixman" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "pixman 0.38.5" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "pixman" /* Define to the home page for this package. */ #define PACKAGE_URL "" /* Define to the version of this package. */ #define PACKAGE_VERSION "0.38.5" /* enable output that can be piped to gnuplot */ /* #undef PIXMAN_GNUPLOT */ /* enable TIMER_BEGIN/TIMER_END macros */ /* #undef PIXMAN_TIMERS */ /* The size of `long', as computed by sizeof. */ #define SIZEOF_LONG 4 /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* The compiler supported TLS storage class */ //#define TLS __thread /* Whether the tool chain supports __attribute__((constructor)) */ //#define TOOLCHAIN_SUPPORTS_ATTRIBUTE_CONSTRUCTOR /**/ /* use ARM IWMMXT compiler intrinsics */ /* #undef USE_ARM_IWMMXT */ /* use ARM NEON assembly optimizations */ /* #undef USE_ARM_NEON */ /* use ARM SIMD assembly optimizations */ /* #undef USE_ARM_SIMD */ /* use GNU-style inline assembler */ //#define USE_GCC_INLINE_ASM 1 /* use Loongson Multimedia Instructions */ /* #undef USE_LOONGSON_MMI */ /* use MIPS DSPr2 assembly optimizations */ /* #undef USE_MIPS_DSPR2 */ /* use OpenMP in the test suite */ //#define USE_OPENMP 1 /* use SSE2 compiler intrinsics */ //#define USE_SSE2 1 /* use SSSE3 compiler intrinsics */ //#define USE_SSSE3 1 /* use VMX compiler intrinsics */ /* #undef USE_VMX */ /* use x86 MMX compiler intrinsics */ //#define USE_X86_MMX 1 /* Version number of package */ #define VERSION "0.38.5" /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN /* # undef WORDS_BIGENDIAN */ # endif #endif /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus /* #undef inline */ #endif /* Define to sqrt if you do not have the `sqrtf' function. */ /* #undef sqrtf */
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\loongson-mmintrin.h
/* The gcc-provided loongson intrinsic functions are way too fucking broken * to be of any use, otherwise I'd use them. * * - The hardware instructions are very similar to MMX or iwMMXt. Certainly * close enough that they could have implemented the _mm_*-style intrinsic * interface and had a ton of optimized code available to them. Instead they * implemented something much, much worse. * * - pshuf takes a dead first argument, causing extra instructions to be * generated. * * - There are no 64-bit shift or logical intrinsics, which means you have * to implement them with inline assembly, but this is a nightmare because * gcc doesn't understand that the integer vector datatypes are actually in * floating-point registers, so you end up with braindead code like * * punpcklwd $f9,$f9,$f5 * dmtc1 v0,$f8 * punpcklwd $f19,$f19,$f5 * dmfc1 t9,$f9 * dmtc1 v0,$f9 * dmtc1 t9,$f20 * dmfc1 s0,$f19 * punpcklbh $f20,$f20,$f2 * * where crap just gets copied back and forth between integer and floating- * point registers ad nauseum. * * Instead of trying to workaround the problems from these crap intrinsics, I * just implement the _mm_* intrinsics needed for pixman-mmx.c using inline * assembly. */ #include <stdint.h> /* vectors are stored in 64-bit floating-point registers */ typedef double __m64; /* having a 32-bit datatype allows us to use 32-bit loads in places like load8888 */ typedef float __m32; extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_setzero_si64 (void) { return 0.0; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_add_pi16 (__m64 __m1, __m64 __m2) { __m64 ret; asm("paddh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_add_pi32 (__m64 __m1, __m64 __m2) { __m64 ret; asm("paddw %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_adds_pu16 (__m64 __m1, __m64 __m2) { __m64 ret; asm("paddush %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_adds_pu8 (__m64 __m1, __m64 __m2) { __m64 ret; asm("paddusb %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_and_si64 (__m64 __m1, __m64 __m2) { __m64 ret; asm("and %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_cmpeq_pi32 (__m64 __m1, __m64 __m2) { __m64 ret; asm("pcmpeqw %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline void __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_empty (void) { } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_madd_pi16 (__m64 __m1, __m64 __m2) { __m64 ret; asm("pmaddhw %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_mulhi_pu16 (__m64 __m1, __m64 __m2) { __m64 ret; asm("pmulhuh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_mullo_pi16 (__m64 __m1, __m64 __m2) { __m64 ret; asm("pmullh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_or_si64 (__m64 __m1, __m64 __m2) { __m64 ret; asm("or %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_packs_pu16 (__m64 __m1, __m64 __m2) { __m64 ret; asm("packushb %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_packs_pi32 (__m64 __m1, __m64 __m2) { __m64 ret; asm("packsswh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } #define _MM_SHUFFLE(fp3,fp2,fp1,fp0) \ (((fp3) << 6) | ((fp2) << 4) | ((fp1) << 2) | (fp0)) extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_set_pi16 (uint16_t __w3, uint16_t __w2, uint16_t __w1, uint16_t __w0) { if (__builtin_constant_p (__w3) && __builtin_constant_p (__w2) && __builtin_constant_p (__w1) && __builtin_constant_p (__w0)) { uint64_t val = ((uint64_t)__w3 << 48) | ((uint64_t)__w2 << 32) | ((uint64_t)__w1 << 16) | ((uint64_t)__w0 << 0); return *(__m64 *)&val; } else if (__w3 == __w2 && __w2 == __w1 && __w1 == __w0) { /* TODO: handle other cases */ uint64_t val = __w3; uint64_t imm = _MM_SHUFFLE (0, 0, 0, 0); __m64 ret; asm("pshufh %0, %1, %2\n\t" : "=f" (ret) : "f" (*(__m64 *)&val), "f" (*(__m64 *)&imm) ); return ret; } uint64_t val = ((uint64_t)__w3 << 48) | ((uint64_t)__w2 << 32) | ((uint64_t)__w1 << 16) | ((uint64_t)__w0 << 0); return *(__m64 *)&val; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_set_pi32 (unsigned __i1, unsigned __i0) { if (__builtin_constant_p (__i1) && __builtin_constant_p (__i0)) { uint64_t val = ((uint64_t)__i1 << 32) | ((uint64_t)__i0 << 0); return *(__m64 *)&val; } else if (__i1 == __i0) { uint64_t imm = _MM_SHUFFLE (1, 0, 1, 0); __m64 ret; asm("pshufh %0, %1, %2\n\t" : "=f" (ret) : "f" (*(__m32 *)&__i1), "f" (*(__m64 *)&imm) ); return ret; } uint64_t val = ((uint64_t)__i1 << 32) | ((uint64_t)__i0 << 0); return *(__m64 *)&val; } #undef _MM_SHUFFLE extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_shuffle_pi16 (__m64 __m, int64_t __n) { __m64 ret; asm("pshufh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m), "f" (*(__m64 *)&__n) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_slli_pi16 (__m64 __m, int64_t __count) { __m64 ret; asm("psllh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m), "f" (*(__m64 *)&__count) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_slli_si64 (__m64 __m, int64_t __count) { __m64 ret; asm("dsll %0, %1, %2\n\t" : "=f" (ret) : "f" (__m), "f" (*(__m64 *)&__count) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_srli_pi16 (__m64 __m, int64_t __count) { __m64 ret; asm("psrlh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m), "f" (*(__m64 *)&__count) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_srli_pi32 (__m64 __m, int64_t __count) { __m64 ret; asm("psrlw %0, %1, %2\n\t" : "=f" (ret) : "f" (__m), "f" (*(__m64 *)&__count) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_srli_si64 (__m64 __m, int64_t __count) { __m64 ret; asm("dsrl %0, %1, %2\n\t" : "=f" (ret) : "f" (__m), "f" (*(__m64 *)&__count) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_sub_pi16 (__m64 __m1, __m64 __m2) { __m64 ret; asm("psubh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_unpackhi_pi8 (__m64 __m1, __m64 __m2) { __m64 ret; asm("punpckhbh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_unpackhi_pi16 (__m64 __m1, __m64 __m2) { __m64 ret; asm("punpckhhw %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_unpacklo_pi8 (__m64 __m1, __m64 __m2) { __m64 ret; asm("punpcklbh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } /* Since punpcklbh doesn't care about the high 32-bits, we use the __m32 datatype which * allows load8888 to use 32-bit loads */ extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_unpacklo_pi8_f (__m32 __m1, __m64 __m2) { __m64 ret; asm("punpcklbh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_unpacklo_pi16 (__m64 __m1, __m64 __m2) { __m64 ret; asm("punpcklhw %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_xor_si64 (__m64 __m1, __m64 __m2) { __m64 ret; asm("xor %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) loongson_extract_pi16 (__m64 __m, int64_t __pos) { __m64 ret; asm("pextrh %0, %1, %2\n\t" : "=f" (ret) : "f" (__m), "f" (*(__m64 *)&__pos) ); return ret; } extern __inline __m64 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) loongson_insert_pi16 (__m64 __m1, __m64 __m2, int64_t __pos) { __m64 ret; asm("pinsrh_%3 %0, %1, %2\n\t" : "=f" (ret) : "f" (__m1), "f" (__m2), "i" (__pos) ); return ret; }
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-access-accessors.c
#define PIXMAN_FB_ACCESSORS #include "pixman-access.c"
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-access.c
/* * * Copyright © 2000 Keith Packard, member of The XFree86 Project, Inc. * 2005 Lars Knoll & Zack Rusin, Trolltech * 2008 Aaron Plattner, NVIDIA Corporation * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #include "pixman-accessor.h" #include "pixman-private.h" #define CONVERT_RGB24_TO_Y15(s) \ (((((s) >> 16) & 0xff) * 153 + \ (((s) >> 8) & 0xff) * 301 + \ (((s) ) & 0xff) * 58) >> 2) #define CONVERT_RGB24_TO_RGB15(s) \ ((((s) >> 3) & 0x001f) | \ (((s) >> 6) & 0x03e0) | \ (((s) >> 9) & 0x7c00)) /* Fetch macros */ #ifdef WORDS_BIGENDIAN #define FETCH_1(img,l,o) \ (((READ ((img), ((uint32_t *)(l)) + ((o) >> 5))) >> (0x1f - ((o) & 0x1f))) & 0x1) #else #define FETCH_1(img,l,o) \ ((((READ ((img), ((uint32_t *)(l)) + ((o) >> 5))) >> ((o) & 0x1f))) & 0x1) #endif #define FETCH_8(img,l,o) (READ (img, (((uint8_t *)(l)) + ((o) >> 3)))) #ifdef WORDS_BIGENDIAN #define FETCH_4(img,l,o) \ (((4 * (o)) & 4) ? (FETCH_8 (img,l, 4 * (o)) & 0xf) : (FETCH_8 (img,l,(4 * (o))) >> 4)) #else #define FETCH_4(img,l,o) \ (((4 * (o)) & 4) ? (FETCH_8 (img, l, 4 * (o)) >> 4) : (FETCH_8 (img, l, (4 * (o))) & 0xf)) #endif #ifdef WORDS_BIGENDIAN #define FETCH_24(img,l,o) \ ((READ (img, (((uint8_t *)(l)) + ((o) * 3) + 0)) << 16) | \ (READ (img, (((uint8_t *)(l)) + ((o) * 3) + 1)) << 8) | \ (READ (img, (((uint8_t *)(l)) + ((o) * 3) + 2)) << 0)) #else #define FETCH_24(img,l,o) \ ((READ (img, (((uint8_t *)(l)) + ((o) * 3) + 0)) << 0) | \ (READ (img, (((uint8_t *)(l)) + ((o) * 3) + 1)) << 8) | \ (READ (img, (((uint8_t *)(l)) + ((o) * 3) + 2)) << 16)) #endif /* Store macros */ #ifdef WORDS_BIGENDIAN #define STORE_1(img,l,o,v) \ do \ { \ uint32_t *__d = ((uint32_t *)(l)) + ((o) >> 5); \ uint32_t __m, __v; \ \ __m = 1 << (0x1f - ((o) & 0x1f)); \ __v = (v)? __m : 0; \ \ WRITE((img), __d, (READ((img), __d) & ~__m) | __v); \ } \ while (0) #else #define STORE_1(img,l,o,v) \ do \ { \ uint32_t *__d = ((uint32_t *)(l)) + ((o) >> 5); \ uint32_t __m, __v; \ \ __m = 1 << ((o) & 0x1f); \ __v = (v)? __m : 0; \ \ WRITE((img), __d, (READ((img), __d) & ~__m) | __v); \ } \ while (0) #endif #define STORE_8(img,l,o,v) (WRITE (img, (uint8_t *)(l) + ((o) >> 3), (v))) #ifdef WORDS_BIGENDIAN #define STORE_4(img,l,o,v) \ do \ { \ int bo = 4 * (o); \ int v4 = (v) & 0x0f; \ \ STORE_8 (img, l, bo, ( \ bo & 4 ? \ (FETCH_8 (img, l, bo) & 0xf0) | (v4) : \ (FETCH_8 (img, l, bo) & 0x0f) | (v4 << 4))); \ } while (0) #else #define STORE_4(img,l,o,v) \ do \ { \ int bo = 4 * (o); \ int v4 = (v) & 0x0f; \ \ STORE_8 (img, l, bo, ( \ bo & 4 ? \ (FETCH_8 (img, l, bo) & 0x0f) | (v4 << 4) : \ (FETCH_8 (img, l, bo) & 0xf0) | (v4))); \ } while (0) #endif #ifdef WORDS_BIGENDIAN #define STORE_24(img,l,o,v) \ do \ { \ uint8_t *__tmp = (l) + 3 * (o); \ \ WRITE ((img), __tmp++, ((v) & 0x00ff0000) >> 16); \ WRITE ((img), __tmp++, ((v) & 0x0000ff00) >> 8); \ WRITE ((img), __tmp++, ((v) & 0x000000ff) >> 0); \ } \ while (0) #else #define STORE_24(img,l,o,v) \ do \ { \ uint8_t *__tmp = (l) + 3 * (o); \ \ WRITE ((img), __tmp++, ((v) & 0x000000ff) >> 0); \ WRITE ((img), __tmp++, ((v) & 0x0000ff00) >> 8); \ WRITE ((img), __tmp++, ((v) & 0x00ff0000) >> 16); \ } \ while (0) #endif /* * YV12 setup and access macros */ #define YV12_SETUP(image) \ bits_image_t *__bits_image = (bits_image_t *)image; \ uint32_t *bits = __bits_image->bits; \ int stride = __bits_image->rowstride; \ int offset0 = stride < 0 ? \ ((-stride) >> 1) * ((__bits_image->height - 1) >> 1) - stride : \ stride * __bits_image->height; \ int offset1 = stride < 0 ? \ offset0 + ((-stride) >> 1) * ((__bits_image->height) >> 1) : \ offset0 + (offset0 >> 2) /* Note no trailing semicolon on the above macro; if it's there, then * the typical usage of YV12_SETUP(image); will have an extra trailing ; * that some compilers will interpret as a statement -- and then any further * variable declarations will cause an error. */ #define YV12_Y(line) \ ((uint8_t *) ((bits) + (stride) * (line))) #define YV12_U(line) \ ((uint8_t *) ((bits) + offset1 + \ ((stride) >> 1) * ((line) >> 1))) #define YV12_V(line) \ ((uint8_t *) ((bits) + offset0 + \ ((stride) >> 1) * ((line) >> 1))) /* Misc. helpers */ static force_inline void get_shifts (pixman_format_code_t format, int *a, int *r, int *g, int *b) { switch (PIXMAN_FORMAT_TYPE (format)) { case PIXMAN_TYPE_A: *b = 0; *g = 0; *r = 0; *a = 0; break; case PIXMAN_TYPE_ARGB: case PIXMAN_TYPE_ARGB_SRGB: *b = 0; *g = *b + PIXMAN_FORMAT_B (format); *r = *g + PIXMAN_FORMAT_G (format); *a = *r + PIXMAN_FORMAT_R (format); break; case PIXMAN_TYPE_ABGR: *r = 0; *g = *r + PIXMAN_FORMAT_R (format); *b = *g + PIXMAN_FORMAT_G (format); *a = *b + PIXMAN_FORMAT_B (format); break; case PIXMAN_TYPE_BGRA: /* With BGRA formats we start counting at the high end of the pixel */ *b = PIXMAN_FORMAT_BPP (format) - PIXMAN_FORMAT_B (format); *g = *b - PIXMAN_FORMAT_B (format); *r = *g - PIXMAN_FORMAT_G (format); *a = *r - PIXMAN_FORMAT_R (format); break; case PIXMAN_TYPE_RGBA: /* With BGRA formats we start counting at the high end of the pixel */ *r = PIXMAN_FORMAT_BPP (format) - PIXMAN_FORMAT_R (format); *g = *r - PIXMAN_FORMAT_R (format); *b = *g - PIXMAN_FORMAT_G (format); *a = *b - PIXMAN_FORMAT_B (format); break; default: assert (0); break; } } static force_inline uint32_t convert_channel (uint32_t pixel, uint32_t def_value, int n_from_bits, int from_shift, int n_to_bits, int to_shift) { uint32_t v; if (n_from_bits && n_to_bits) v = unorm_to_unorm (pixel >> from_shift, n_from_bits, n_to_bits); else if (n_to_bits) v = def_value; else v = 0; return (v & ((1 << n_to_bits) - 1)) << to_shift; } static force_inline uint32_t convert_pixel (pixman_format_code_t from, pixman_format_code_t to, uint32_t pixel) { int a_from_shift, r_from_shift, g_from_shift, b_from_shift; int a_to_shift, r_to_shift, g_to_shift, b_to_shift; uint32_t a, r, g, b; get_shifts (from, &a_from_shift, &r_from_shift, &g_from_shift, &b_from_shift); get_shifts (to, &a_to_shift, &r_to_shift, &g_to_shift, &b_to_shift); a = convert_channel (pixel, ~0, PIXMAN_FORMAT_A (from), a_from_shift, PIXMAN_FORMAT_A (to), a_to_shift); r = convert_channel (pixel, 0, PIXMAN_FORMAT_R (from), r_from_shift, PIXMAN_FORMAT_R (to), r_to_shift); g = convert_channel (pixel, 0, PIXMAN_FORMAT_G (from), g_from_shift, PIXMAN_FORMAT_G (to), g_to_shift); b = convert_channel (pixel, 0, PIXMAN_FORMAT_B (from), b_from_shift, PIXMAN_FORMAT_B (to), b_to_shift); return a | r | g | b; } static force_inline uint32_t convert_pixel_to_a8r8g8b8 (bits_image_t *image, pixman_format_code_t format, uint32_t pixel) { if (PIXMAN_FORMAT_TYPE (format) == PIXMAN_TYPE_GRAY || PIXMAN_FORMAT_TYPE (format) == PIXMAN_TYPE_COLOR) { return image->indexed->rgba[pixel]; } else { return convert_pixel (format, PIXMAN_a8r8g8b8, pixel); } } static force_inline uint32_t convert_pixel_from_a8r8g8b8 (pixman_image_t *image, pixman_format_code_t format, uint32_t pixel) { if (PIXMAN_FORMAT_TYPE (format) == PIXMAN_TYPE_GRAY) { pixel = CONVERT_RGB24_TO_Y15 (pixel); return image->bits.indexed->ent[pixel & 0x7fff]; } else if (PIXMAN_FORMAT_TYPE (format) == PIXMAN_TYPE_COLOR) { pixel = convert_pixel (PIXMAN_a8r8g8b8, PIXMAN_x1r5g5b5, pixel); return image->bits.indexed->ent[pixel & 0x7fff]; } else { return convert_pixel (PIXMAN_a8r8g8b8, format, pixel); } } static force_inline uint32_t fetch_and_convert_pixel (bits_image_t * image, const uint8_t * bits, int offset, pixman_format_code_t format) { uint32_t pixel; switch (PIXMAN_FORMAT_BPP (format)) { case 1: pixel = FETCH_1 (image, bits, offset); break; case 4: pixel = FETCH_4 (image, bits, offset); break; case 8: pixel = READ (image, bits + offset); break; case 16: pixel = READ (image, ((uint16_t *)bits + offset)); break; case 24: pixel = FETCH_24 (image, bits, offset); break; case 32: pixel = READ (image, ((uint32_t *)bits + offset)); break; default: pixel = 0xffff00ff; /* As ugly as possible to detect the bug */ break; } return convert_pixel_to_a8r8g8b8 (image, format, pixel); } static force_inline void convert_and_store_pixel (bits_image_t * image, uint8_t * dest, int offset, pixman_format_code_t format, uint32_t pixel) { uint32_t converted = convert_pixel_from_a8r8g8b8 ( (pixman_image_t *)image, format, pixel); switch (PIXMAN_FORMAT_BPP (format)) { case 1: STORE_1 (image, dest, offset, converted & 0x01); break; case 4: STORE_4 (image, dest, offset, converted & 0xf); break; case 8: WRITE (image, (dest + offset), converted & 0xff); break; case 16: WRITE (image, ((uint16_t *)dest + offset), converted & 0xffff); break; case 24: STORE_24 (image, dest, offset, converted); break; case 32: WRITE (image, ((uint32_t *)dest + offset), converted); break; default: *dest = 0x0; break; } } #define MAKE_ACCESSORS(format) \ static void \ fetch_scanline_ ## format (bits_image_t *image, \ int x, \ int y, \ int width, \ uint32_t * buffer, \ const uint32_t *mask) \ { \ uint8_t *bits = \ (uint8_t *)(image->bits + y * image->rowstride); \ int i; \ \ for (i = 0; i < width; ++i) \ { \ *buffer++ = \ fetch_and_convert_pixel (image, bits, x + i, PIXMAN_ ## format); \ } \ } \ \ static void \ store_scanline_ ## format (bits_image_t * image, \ int x, \ int y, \ int width, \ const uint32_t *values) \ { \ uint8_t *dest = \ (uint8_t *)(image->bits + y * image->rowstride); \ int i; \ \ for (i = 0; i < width; ++i) \ { \ convert_and_store_pixel ( \ image, dest, i + x, PIXMAN_ ## format, values[i]); \ } \ } \ \ static uint32_t \ fetch_pixel_ ## format (bits_image_t *image, \ int offset, \ int line) \ { \ uint8_t *bits = \ (uint8_t *)(image->bits + line * image->rowstride); \ \ return fetch_and_convert_pixel ( \ image, bits, offset, PIXMAN_ ## format); \ } \ \ static const void *const __dummy__ ## format MAKE_ACCESSORS(a8r8g8b8); MAKE_ACCESSORS(x8r8g8b8); MAKE_ACCESSORS(a8b8g8r8); MAKE_ACCESSORS(x8b8g8r8); MAKE_ACCESSORS(x14r6g6b6); MAKE_ACCESSORS(b8g8r8a8); MAKE_ACCESSORS(b8g8r8x8); MAKE_ACCESSORS(r8g8b8x8); MAKE_ACCESSORS(r8g8b8a8); MAKE_ACCESSORS(r8g8b8); MAKE_ACCESSORS(b8g8r8); MAKE_ACCESSORS(r5g6b5); MAKE_ACCESSORS(b5g6r5); MAKE_ACCESSORS(a1r5g5b5); MAKE_ACCESSORS(x1r5g5b5); MAKE_ACCESSORS(a1b5g5r5); MAKE_ACCESSORS(x1b5g5r5); MAKE_ACCESSORS(a4r4g4b4); MAKE_ACCESSORS(x4r4g4b4); MAKE_ACCESSORS(a4b4g4r4); MAKE_ACCESSORS(x4b4g4r4); MAKE_ACCESSORS(a8); MAKE_ACCESSORS(c8); MAKE_ACCESSORS(g8); MAKE_ACCESSORS(r3g3b2); MAKE_ACCESSORS(b2g3r3); MAKE_ACCESSORS(a2r2g2b2); MAKE_ACCESSORS(a2b2g2r2); MAKE_ACCESSORS(x4a4); MAKE_ACCESSORS(a4); MAKE_ACCESSORS(g4); MAKE_ACCESSORS(c4); MAKE_ACCESSORS(r1g2b1); MAKE_ACCESSORS(b1g2r1); MAKE_ACCESSORS(a1r1g1b1); MAKE_ACCESSORS(a1b1g1r1); MAKE_ACCESSORS(a1); MAKE_ACCESSORS(g1); /********************************** Fetch ************************************/ /* Table mapping sRGB-encoded 8 bit numbers to linearly encoded * floating point numbers. We assume that single precision * floating point follows the IEEE 754 format. */ static const uint32_t to_linear_u[256] = { 0x00000000, 0x399f22b4, 0x3a1f22b4, 0x3a6eb40e, 0x3a9f22b4, 0x3ac6eb61, 0x3aeeb40e, 0x3b0b3e5d, 0x3b1f22b4, 0x3b33070b, 0x3b46eb61, 0x3b5b518a, 0x3b70f18a, 0x3b83e1c5, 0x3b8fe614, 0x3b9c87fb, 0x3ba9c9b5, 0x3bb7ad6d, 0x3bc63547, 0x3bd5635f, 0x3be539bd, 0x3bf5ba70, 0x3c0373b5, 0x3c0c6152, 0x3c15a703, 0x3c1f45bc, 0x3c293e68, 0x3c3391f4, 0x3c3e4149, 0x3c494d43, 0x3c54b6c7, 0x3c607eb1, 0x3c6ca5df, 0x3c792d22, 0x3c830aa8, 0x3c89af9e, 0x3c9085db, 0x3c978dc5, 0x3c9ec7c0, 0x3ca63432, 0x3cadd37d, 0x3cb5a601, 0x3cbdac20, 0x3cc5e639, 0x3cce54ab, 0x3cd6f7d2, 0x3cdfd00e, 0x3ce8ddb9, 0x3cf2212c, 0x3cfb9ac1, 0x3d02a569, 0x3d0798dc, 0x3d0ca7e4, 0x3d11d2ae, 0x3d171963, 0x3d1c7c2e, 0x3d21fb3a, 0x3d2796af, 0x3d2d4ebb, 0x3d332380, 0x3d39152b, 0x3d3f23e3, 0x3d454fd0, 0x3d4b991c, 0x3d51ffeb, 0x3d588466, 0x3d5f26b7, 0x3d65e6fe, 0x3d6cc564, 0x3d73c210, 0x3d7add25, 0x3d810b65, 0x3d84b793, 0x3d88732e, 0x3d8c3e48, 0x3d9018f4, 0x3d940343, 0x3d97fd48, 0x3d9c0714, 0x3da020b9, 0x3da44a48, 0x3da883d6, 0x3daccd70, 0x3db12728, 0x3db59110, 0x3dba0b38, 0x3dbe95b2, 0x3dc3308f, 0x3dc7dbe0, 0x3dcc97b4, 0x3dd1641c, 0x3dd6412a, 0x3ddb2eec, 0x3de02d75, 0x3de53cd3, 0x3dea5d16, 0x3def8e52, 0x3df4d091, 0x3dfa23e5, 0x3dff885e, 0x3e027f06, 0x3e05427f, 0x3e080ea2, 0x3e0ae376, 0x3e0dc104, 0x3e10a752, 0x3e139669, 0x3e168e50, 0x3e198f0e, 0x3e1c98ab, 0x3e1fab2e, 0x3e22c6a0, 0x3e25eb08, 0x3e29186a, 0x3e2c4ed0, 0x3e2f8e42, 0x3e32d6c4, 0x3e362861, 0x3e39831e, 0x3e3ce702, 0x3e405416, 0x3e43ca5e, 0x3e4749e4, 0x3e4ad2ae, 0x3e4e64c2, 0x3e520027, 0x3e55a4e6, 0x3e595303, 0x3e5d0a8a, 0x3e60cb7c, 0x3e6495e0, 0x3e6869bf, 0x3e6c4720, 0x3e702e08, 0x3e741e7f, 0x3e78188c, 0x3e7c1c34, 0x3e8014c0, 0x3e822039, 0x3e84308b, 0x3e8645b8, 0x3e885fc3, 0x3e8a7eb0, 0x3e8ca281, 0x3e8ecb3a, 0x3e90f8df, 0x3e932b72, 0x3e9562f6, 0x3e979f6f, 0x3e99e0e0, 0x3e9c274e, 0x3e9e72b8, 0x3ea0c322, 0x3ea31892, 0x3ea57308, 0x3ea7d28a, 0x3eaa3718, 0x3eaca0b7, 0x3eaf0f69, 0x3eb18332, 0x3eb3fc16, 0x3eb67a15, 0x3eb8fd34, 0x3ebb8576, 0x3ebe12de, 0x3ec0a56e, 0x3ec33d2a, 0x3ec5da14, 0x3ec87c30, 0x3ecb2380, 0x3ecdd008, 0x3ed081ca, 0x3ed338c9, 0x3ed5f508, 0x3ed8b68a, 0x3edb7d52, 0x3ede4962, 0x3ee11abe, 0x3ee3f168, 0x3ee6cd64, 0x3ee9aeb6, 0x3eec955d, 0x3eef815d, 0x3ef272ba, 0x3ef56976, 0x3ef86594, 0x3efb6717, 0x3efe6e02, 0x3f00bd2b, 0x3f02460c, 0x3f03d1a5, 0x3f055ff8, 0x3f06f105, 0x3f0884ce, 0x3f0a1b54, 0x3f0bb499, 0x3f0d509f, 0x3f0eef65, 0x3f1090ef, 0x3f12353c, 0x3f13dc50, 0x3f15862a, 0x3f1732cc, 0x3f18e237, 0x3f1a946d, 0x3f1c4970, 0x3f1e013f, 0x3f1fbbde, 0x3f21794c, 0x3f23398c, 0x3f24fca0, 0x3f26c286, 0x3f288b42, 0x3f2a56d3, 0x3f2c253d, 0x3f2df680, 0x3f2fca9d, 0x3f31a195, 0x3f337b6a, 0x3f35581e, 0x3f3737b1, 0x3f391a24, 0x3f3aff7a, 0x3f3ce7b2, 0x3f3ed2d0, 0x3f40c0d2, 0x3f42b1bc, 0x3f44a58e, 0x3f469c49, 0x3f4895ee, 0x3f4a9280, 0x3f4c91ff, 0x3f4e946c, 0x3f5099c8, 0x3f52a216, 0x3f54ad55, 0x3f56bb88, 0x3f58ccae, 0x3f5ae0cb, 0x3f5cf7de, 0x3f5f11ec, 0x3f612ef0, 0x3f634eef, 0x3f6571ea, 0x3f6797e1, 0x3f69c0d6, 0x3f6beccb, 0x3f6e1bc0, 0x3f704db6, 0x3f7282af, 0x3f74baac, 0x3f76f5ae, 0x3f7933b6, 0x3f7b74c6, 0x3f7db8de, 0x3f800000 }; static const float * const to_linear = (const float *)to_linear_u; static uint8_t to_srgb (float f) { uint8_t low = 0; uint8_t high = 255; while (high - low > 1) { uint8_t mid = (low + high) / 2; if (to_linear[mid] > f) high = mid; else low = mid; } if (to_linear[high] - f < f - to_linear[low]) return high; else return low; } static void fetch_scanline_a8r8g8b8_sRGB_float (bits_image_t * image, int x, int y, int width, uint32_t * b, const uint32_t *mask) { const uint32_t *bits = image->bits + y * image->rowstride; const uint32_t *pixel = bits + x; const uint32_t *end = pixel + width; argb_t *buffer = (argb_t *)b; while (pixel < end) { uint32_t p = READ (image, pixel++); argb_t *argb = buffer; argb->a = pixman_unorm_to_float ((p >> 24) & 0xff, 8); argb->r = to_linear [(p >> 16) & 0xff]; argb->g = to_linear [(p >> 8) & 0xff]; argb->b = to_linear [(p >> 0) & 0xff]; buffer++; } } /* Expects a float buffer */ static void fetch_scanline_a2r10g10b10_float (bits_image_t * image, int x, int y, int width, uint32_t * b, const uint32_t *mask) { const uint32_t *bits = image->bits + y * image->rowstride; const uint32_t *pixel = bits + x; const uint32_t *end = pixel + width; argb_t *buffer = (argb_t *)b; while (pixel < end) { uint32_t p = READ (image, pixel++); uint64_t a = p >> 30; uint64_t r = (p >> 20) & 0x3ff; uint64_t g = (p >> 10) & 0x3ff; uint64_t b = p & 0x3ff; buffer->a = pixman_unorm_to_float (a, 2); buffer->r = pixman_unorm_to_float (r, 10); buffer->g = pixman_unorm_to_float (g, 10); buffer->b = pixman_unorm_to_float (b, 10); buffer++; } } /* Expects a float buffer */ #ifndef PIXMAN_FB_ACCESSORS static void fetch_scanline_rgbf_float (bits_image_t *image, int x, int y, int width, uint32_t * b, const uint32_t *mask) { const float *bits = (float *)image->bits + y * image->rowstride; const float *pixel = bits + x * 3; argb_t *buffer = (argb_t *)b; for (; width--; buffer++) { buffer->r = *pixel++; buffer->g = *pixel++; buffer->b = *pixel++; buffer->a = 1.f; } } static void fetch_scanline_rgbaf_float (bits_image_t *image, int x, int y, int width, uint32_t * b, const uint32_t *mask) { const float *bits = (float *)image->bits + y * image->rowstride; const float *pixel = bits + x * 4; argb_t *buffer = (argb_t *)b; for (; width--; buffer++) { buffer->r = *pixel++; buffer->g = *pixel++; buffer->b = *pixel++; buffer->a = *pixel++; } } #endif static void fetch_scanline_x2r10g10b10_float (bits_image_t *image, int x, int y, int width, uint32_t * b, const uint32_t *mask) { const uint32_t *bits = image->bits + y * image->rowstride; const uint32_t *pixel = (uint32_t *)bits + x; const uint32_t *end = pixel + width; argb_t *buffer = (argb_t *)b; while (pixel < end) { uint32_t p = READ (image, pixel++); uint64_t r = (p >> 20) & 0x3ff; uint64_t g = (p >> 10) & 0x3ff; uint64_t b = p & 0x3ff; buffer->a = 1.0; buffer->r = pixman_unorm_to_float (r, 10); buffer->g = pixman_unorm_to_float (g, 10); buffer->b = pixman_unorm_to_float (b, 10); buffer++; } } /* Expects a float buffer */ static void fetch_scanline_a2b10g10r10_float (bits_image_t *image, int x, int y, int width, uint32_t * b, const uint32_t *mask) { const uint32_t *bits = image->bits + y * image->rowstride; const uint32_t *pixel = bits + x; const uint32_t *end = pixel + width; argb_t *buffer = (argb_t *)b; while (pixel < end) { uint32_t p = READ (image, pixel++); uint64_t a = p >> 30; uint64_t b = (p >> 20) & 0x3ff; uint64_t g = (p >> 10) & 0x3ff; uint64_t r = p & 0x3ff; buffer->a = pixman_unorm_to_float (a, 2); buffer->r = pixman_unorm_to_float (r, 10); buffer->g = pixman_unorm_to_float (g, 10); buffer->b = pixman_unorm_to_float (b, 10); buffer++; } } /* Expects a float buffer */ static void fetch_scanline_x2b10g10r10_float (bits_image_t *image, int x, int y, int width, uint32_t * b, const uint32_t *mask) { const uint32_t *bits = image->bits + y * image->rowstride; const uint32_t *pixel = (uint32_t *)bits + x; const uint32_t *end = pixel + width; argb_t *buffer = (argb_t *)b; while (pixel < end) { uint32_t p = READ (image, pixel++); uint64_t b = (p >> 20) & 0x3ff; uint64_t g = (p >> 10) & 0x3ff; uint64_t r = p & 0x3ff; buffer->a = 1.0; buffer->r = pixman_unorm_to_float (r, 10); buffer->g = pixman_unorm_to_float (g, 10); buffer->b = pixman_unorm_to_float (b, 10); buffer++; } } static void fetch_scanline_yuy2 (bits_image_t *image, int x, int line, int width, uint32_t * buffer, const uint32_t *mask) { const uint32_t *bits = image->bits + image->rowstride * line; int i; for (i = 0; i < width; i++) { int16_t y, u, v; int32_t r, g, b; y = ((uint8_t *) bits)[(x + i) << 1] - 16; u = ((uint8_t *) bits)[(((x + i) << 1) & - 4) + 1] - 128; v = ((uint8_t *) bits)[(((x + i) << 1) & - 4) + 3] - 128; /* R = 1.164(Y - 16) + 1.596(V - 128) */ r = 0x012b27 * y + 0x019a2e * v; /* G = 1.164(Y - 16) - 0.813(V - 128) - 0.391(U - 128) */ g = 0x012b27 * y - 0x00d0f2 * v - 0x00647e * u; /* B = 1.164(Y - 16) + 2.018(U - 128) */ b = 0x012b27 * y + 0x0206a2 * u; *buffer++ = 0xff000000 | (r >= 0 ? r < 0x1000000 ? r & 0xff0000 : 0xff0000 : 0) | (g >= 0 ? g < 0x1000000 ? (g >> 8) & 0x00ff00 : 0x00ff00 : 0) | (b >= 0 ? b < 0x1000000 ? (b >> 16) & 0x0000ff : 0x0000ff : 0); } } static void fetch_scanline_yv12 (bits_image_t *image, int x, int line, int width, uint32_t * buffer, const uint32_t *mask) { YV12_SETUP (image); uint8_t *y_line = YV12_Y (line); uint8_t *u_line = YV12_U (line); uint8_t *v_line = YV12_V (line); int i; for (i = 0; i < width; i++) { int16_t y, u, v; int32_t r, g, b; y = y_line[x + i] - 16; u = u_line[(x + i) >> 1] - 128; v = v_line[(x + i) >> 1] - 128; /* R = 1.164(Y - 16) + 1.596(V - 128) */ r = 0x012b27 * y + 0x019a2e * v; /* G = 1.164(Y - 16) - 0.813(V - 128) - 0.391(U - 128) */ g = 0x012b27 * y - 0x00d0f2 * v - 0x00647e * u; /* B = 1.164(Y - 16) + 2.018(U - 128) */ b = 0x012b27 * y + 0x0206a2 * u; *buffer++ = 0xff000000 | (r >= 0 ? r < 0x1000000 ? r & 0xff0000 : 0xff0000 : 0) | (g >= 0 ? g < 0x1000000 ? (g >> 8) & 0x00ff00 : 0x00ff00 : 0) | (b >= 0 ? b < 0x1000000 ? (b >> 16) & 0x0000ff : 0x0000ff : 0); } } /**************************** Pixel wise fetching *****************************/ #ifndef PIXMAN_FB_ACCESSORS static argb_t fetch_pixel_rgbf_float (bits_image_t *image, int offset, int line) { float *bits = (float *)image->bits + line * image->rowstride; argb_t argb; argb.r = bits[offset * 3]; argb.g = bits[offset * 3 + 1]; argb.b = bits[offset * 3 + 2]; argb.a = 1.f; return argb; } static argb_t fetch_pixel_rgbaf_float (bits_image_t *image, int offset, int line) { float *bits = (float *)image->bits + line * image->rowstride; argb_t argb; argb.r = bits[offset * 4]; argb.g = bits[offset * 4 + 1]; argb.b = bits[offset * 4 + 2]; argb.a = bits[offset * 4 + 3]; return argb; } #endif static argb_t fetch_pixel_x2r10g10b10_float (bits_image_t *image, int offset, int line) { uint32_t *bits = image->bits + line * image->rowstride; uint32_t p = READ (image, bits + offset); uint64_t r = (p >> 20) & 0x3ff; uint64_t g = (p >> 10) & 0x3ff; uint64_t b = p & 0x3ff; argb_t argb; argb.a = 1.0; argb.r = pixman_unorm_to_float (r, 10); argb.g = pixman_unorm_to_float (g, 10); argb.b = pixman_unorm_to_float (b, 10); return argb; } static argb_t fetch_pixel_a2r10g10b10_float (bits_image_t *image, int offset, int line) { uint32_t *bits = image->bits + line * image->rowstride; uint32_t p = READ (image, bits + offset); uint64_t a = p >> 30; uint64_t r = (p >> 20) & 0x3ff; uint64_t g = (p >> 10) & 0x3ff; uint64_t b = p & 0x3ff; argb_t argb; argb.a = pixman_unorm_to_float (a, 2); argb.r = pixman_unorm_to_float (r, 10); argb.g = pixman_unorm_to_float (g, 10); argb.b = pixman_unorm_to_float (b, 10); return argb; } static argb_t fetch_pixel_a2b10g10r10_float (bits_image_t *image, int offset, int line) { uint32_t *bits = image->bits + line * image->rowstride; uint32_t p = READ (image, bits + offset); uint64_t a = p >> 30; uint64_t b = (p >> 20) & 0x3ff; uint64_t g = (p >> 10) & 0x3ff; uint64_t r = p & 0x3ff; argb_t argb; argb.a = pixman_unorm_to_float (a, 2); argb.r = pixman_unorm_to_float (r, 10); argb.g = pixman_unorm_to_float (g, 10); argb.b = pixman_unorm_to_float (b, 10); return argb; } static argb_t fetch_pixel_x2b10g10r10_float (bits_image_t *image, int offset, int line) { uint32_t *bits = image->bits + line * image->rowstride; uint32_t p = READ (image, bits + offset); uint64_t b = (p >> 20) & 0x3ff; uint64_t g = (p >> 10) & 0x3ff; uint64_t r = p & 0x3ff; argb_t argb; argb.a = 1.0; argb.r = pixman_unorm_to_float (r, 10); argb.g = pixman_unorm_to_float (g, 10); argb.b = pixman_unorm_to_float (b, 10); return argb; } static argb_t fetch_pixel_a8r8g8b8_sRGB_float (bits_image_t *image, int offset, int line) { uint32_t *bits = image->bits + line * image->rowstride; uint32_t p = READ (image, bits + offset); argb_t argb; argb.a = pixman_unorm_to_float ((p >> 24) & 0xff, 8); argb.r = to_linear [(p >> 16) & 0xff]; argb.g = to_linear [(p >> 8) & 0xff]; argb.b = to_linear [(p >> 0) & 0xff]; return argb; } static uint32_t fetch_pixel_yuy2 (bits_image_t *image, int offset, int line) { const uint32_t *bits = image->bits + image->rowstride * line; int16_t y, u, v; int32_t r, g, b; y = ((uint8_t *) bits)[offset << 1] - 16; u = ((uint8_t *) bits)[((offset << 1) & - 4) + 1] - 128; v = ((uint8_t *) bits)[((offset << 1) & - 4) + 3] - 128; /* R = 1.164(Y - 16) + 1.596(V - 128) */ r = 0x012b27 * y + 0x019a2e * v; /* G = 1.164(Y - 16) - 0.813(V - 128) - 0.391(U - 128) */ g = 0x012b27 * y - 0x00d0f2 * v - 0x00647e * u; /* B = 1.164(Y - 16) + 2.018(U - 128) */ b = 0x012b27 * y + 0x0206a2 * u; return 0xff000000 | (r >= 0 ? r < 0x1000000 ? r & 0xff0000 : 0xff0000 : 0) | (g >= 0 ? g < 0x1000000 ? (g >> 8) & 0x00ff00 : 0x00ff00 : 0) | (b >= 0 ? b < 0x1000000 ? (b >> 16) & 0x0000ff : 0x0000ff : 0); } static uint32_t fetch_pixel_yv12 (bits_image_t *image, int offset, int line) { YV12_SETUP (image); int16_t y = YV12_Y (line)[offset] - 16; int16_t u = YV12_U (line)[offset >> 1] - 128; int16_t v = YV12_V (line)[offset >> 1] - 128; int32_t r, g, b; /* R = 1.164(Y - 16) + 1.596(V - 128) */ r = 0x012b27 * y + 0x019a2e * v; /* G = 1.164(Y - 16) - 0.813(V - 128) - 0.391(U - 128) */ g = 0x012b27 * y - 0x00d0f2 * v - 0x00647e * u; /* B = 1.164(Y - 16) + 2.018(U - 128) */ b = 0x012b27 * y + 0x0206a2 * u; return 0xff000000 | (r >= 0 ? r < 0x1000000 ? r & 0xff0000 : 0xff0000 : 0) | (g >= 0 ? g < 0x1000000 ? (g >> 8) & 0x00ff00 : 0x00ff00 : 0) | (b >= 0 ? b < 0x1000000 ? (b >> 16) & 0x0000ff : 0x0000ff : 0); } /*********************************** Store ************************************/ #ifndef PIXMAN_FB_ACCESSORS static void store_scanline_rgbaf_float (bits_image_t * image, int x, int y, int width, const uint32_t *v) { float *bits = (float *)image->bits + image->rowstride * y + 4 * x; const argb_t *values = (argb_t *)v; for (; width; width--, values++) { *bits++ = values->r; *bits++ = values->g; *bits++ = values->b; *bits++ = values->a; } } static void store_scanline_rgbf_float (bits_image_t * image, int x, int y, int width, const uint32_t *v) { float *bits = (float *)image->bits + image->rowstride * y + 3 * x; const argb_t *values = (argb_t *)v; for (; width; width--, values++) { *bits++ = values->r; *bits++ = values->g; *bits++ = values->b; } } #endif static void store_scanline_a2r10g10b10_float (bits_image_t * image, int x, int y, int width, const uint32_t *v) { uint32_t *bits = image->bits + image->rowstride * y; uint32_t *pixel = bits + x; argb_t *values = (argb_t *)v; int i; for (i = 0; i < width; ++i) { uint16_t a, r, g, b; a = pixman_float_to_unorm (values[i].a, 2); r = pixman_float_to_unorm (values[i].r, 10); g = pixman_float_to_unorm (values[i].g, 10); b = pixman_float_to_unorm (values[i].b, 10); WRITE (image, pixel++, (a << 30) | (r << 20) | (g << 10) | b); } } static void store_scanline_x2r10g10b10_float (bits_image_t * image, int x, int y, int width, const uint32_t *v) { uint32_t *bits = image->bits + image->rowstride * y; uint32_t *pixel = bits + x; argb_t *values = (argb_t *)v; int i; for (i = 0; i < width; ++i) { uint16_t r, g, b; r = pixman_float_to_unorm (values[i].r, 10); g = pixman_float_to_unorm (values[i].g, 10); b = pixman_float_to_unorm (values[i].b, 10); WRITE (image, pixel++, (r << 20) | (g << 10) | b); } } static void store_scanline_a2b10g10r10_float (bits_image_t * image, int x, int y, int width, const uint32_t *v) { uint32_t *bits = image->bits + image->rowstride * y; uint32_t *pixel = bits + x; argb_t *values = (argb_t *)v; int i; for (i = 0; i < width; ++i) { uint16_t a, r, g, b; a = pixman_float_to_unorm (values[i].a, 2); r = pixman_float_to_unorm (values[i].r, 10); g = pixman_float_to_unorm (values[i].g, 10); b = pixman_float_to_unorm (values[i].b, 10); WRITE (image, pixel++, (a << 30) | (b << 20) | (g << 10) | r); } } static void store_scanline_x2b10g10r10_float (bits_image_t * image, int x, int y, int width, const uint32_t *v) { uint32_t *bits = image->bits + image->rowstride * y; uint32_t *pixel = bits + x; argb_t *values = (argb_t *)v; int i; for (i = 0; i < width; ++i) { uint16_t r, g, b; r = pixman_float_to_unorm (values[i].r, 10); g = pixman_float_to_unorm (values[i].g, 10); b = pixman_float_to_unorm (values[i].b, 10); WRITE (image, pixel++, (b << 20) | (g << 10) | r); } } static void store_scanline_a8r8g8b8_sRGB_float (bits_image_t * image, int x, int y, int width, const uint32_t *v) { uint32_t *bits = image->bits + image->rowstride * y; uint32_t *pixel = bits + x; argb_t *values = (argb_t *)v; int i; for (i = 0; i < width; ++i) { uint8_t a, r, g, b; a = pixman_float_to_unorm (values[i].a, 8); r = to_srgb (values[i].r); g = to_srgb (values[i].g); b = to_srgb (values[i].b); WRITE (image, pixel++, (a << 24) | (r << 16) | (g << 8) | b); } } /* * Contracts a floating point image to 32bpp and then stores it using a * regular 32-bit store proc. Despite the type, this function expects an * argb_t buffer. */ static void store_scanline_generic_float (bits_image_t * image, int x, int y, int width, const uint32_t *values) { uint32_t *argb8_pixels; assert (image->common.type == BITS); argb8_pixels = pixman_malloc_ab (width, sizeof(uint32_t)); if (!argb8_pixels) return; /* Contract the scanline. We could do this in place if values weren't * const. */ pixman_contract_from_float (argb8_pixels, (argb_t *)values, width); image->store_scanline_32 (image, x, y, width, argb8_pixels); free (argb8_pixels); } static void fetch_scanline_generic_float (bits_image_t * image, int x, int y, int width, uint32_t * buffer, const uint32_t *mask) { image->fetch_scanline_32 (image, x, y, width, buffer, NULL); pixman_expand_to_float ((argb_t *)buffer, buffer, image->format, width); } /* The 32_sRGB paths should be deleted after narrow processing * is no longer invoked for formats that are considered wide. * (Also see fetch_pixel_generic_lossy_32) */ static void fetch_scanline_a8r8g8b8_32_sRGB (bits_image_t *image, int x, int y, int width, uint32_t *buffer, const uint32_t *mask) { const uint32_t *bits = image->bits + y * image->rowstride; const uint32_t *pixel = (uint32_t *)bits + x; const uint32_t *end = pixel + width; uint32_t tmp; while (pixel < end) { uint8_t a, r, g, b; tmp = READ (image, pixel++); a = (tmp >> 24) & 0xff; r = (tmp >> 16) & 0xff; g = (tmp >> 8) & 0xff; b = (tmp >> 0) & 0xff; r = to_linear[r] * 255.0f + 0.5f; g = to_linear[g] * 255.0f + 0.5f; b = to_linear[b] * 255.0f + 0.5f; *buffer++ = (a << 24) | (r << 16) | (g << 8) | (b << 0); } } static uint32_t fetch_pixel_a8r8g8b8_32_sRGB (bits_image_t *image, int offset, int line) { uint32_t *bits = image->bits + line * image->rowstride; uint32_t tmp = READ (image, bits + offset); uint8_t a, r, g, b; a = (tmp >> 24) & 0xff; r = (tmp >> 16) & 0xff; g = (tmp >> 8) & 0xff; b = (tmp >> 0) & 0xff; r = to_linear[r] * 255.0f + 0.5f; g = to_linear[g] * 255.0f + 0.5f; b = to_linear[b] * 255.0f + 0.5f; return (a << 24) | (r << 16) | (g << 8) | (b << 0); } static void store_scanline_a8r8g8b8_32_sRGB (bits_image_t *image, int x, int y, int width, const uint32_t *v) { uint32_t *bits = image->bits + image->rowstride * y; uint64_t *values = (uint64_t *)v; uint32_t *pixel = bits + x; uint64_t tmp; int i; for (i = 0; i < width; ++i) { uint8_t a, r, g, b; tmp = values[i]; a = (tmp >> 24) & 0xff; r = (tmp >> 16) & 0xff; g = (tmp >> 8) & 0xff; b = (tmp >> 0) & 0xff; r = to_srgb (r * (1/255.0f)); g = to_srgb (g * (1/255.0f)); b = to_srgb (b * (1/255.0f)); WRITE (image, pixel++, a | (r << 16) | (g << 8) | (b << 0)); } } static argb_t fetch_pixel_generic_float (bits_image_t *image, int offset, int line) { uint32_t pixel32 = image->fetch_pixel_32 (image, offset, line); argb_t f; pixman_expand_to_float (&f, &pixel32, image->format, 1); return f; } /* * XXX: The transformed fetch path only works at 32-bpp so far. When all * paths have wide versions, this can be removed. * * WARNING: This function loses precision! */ static uint32_t fetch_pixel_generic_lossy_32 (bits_image_t *image, int offset, int line) { argb_t pixel64 = image->fetch_pixel_float (image, offset, line); uint32_t result; pixman_contract_from_float (&result, &pixel64, 1); return result; } typedef struct { pixman_format_code_t format; fetch_scanline_t fetch_scanline_32; fetch_scanline_t fetch_scanline_float; fetch_pixel_32_t fetch_pixel_32; fetch_pixel_float_t fetch_pixel_float; store_scanline_t store_scanline_32; store_scanline_t store_scanline_float; } format_info_t; #define FORMAT_INFO(format) \ { \ PIXMAN_ ## format, \ fetch_scanline_ ## format, \ fetch_scanline_generic_float, \ fetch_pixel_ ## format, \ fetch_pixel_generic_float, \ store_scanline_ ## format, \ store_scanline_generic_float \ } static const format_info_t accessors[] = { /* 32 bpp formats */ FORMAT_INFO (a8r8g8b8), FORMAT_INFO (x8r8g8b8), FORMAT_INFO (a8b8g8r8), FORMAT_INFO (x8b8g8r8), FORMAT_INFO (b8g8r8a8), FORMAT_INFO (b8g8r8x8), FORMAT_INFO (r8g8b8a8), FORMAT_INFO (r8g8b8x8), FORMAT_INFO (x14r6g6b6), /* sRGB formats */ { PIXMAN_a8r8g8b8_sRGB, fetch_scanline_a8r8g8b8_32_sRGB, fetch_scanline_a8r8g8b8_sRGB_float, fetch_pixel_a8r8g8b8_32_sRGB, fetch_pixel_a8r8g8b8_sRGB_float, store_scanline_a8r8g8b8_32_sRGB, store_scanline_a8r8g8b8_sRGB_float, }, /* 24bpp formats */ FORMAT_INFO (r8g8b8), FORMAT_INFO (b8g8r8), /* 16bpp formats */ FORMAT_INFO (r5g6b5), FORMAT_INFO (b5g6r5), FORMAT_INFO (a1r5g5b5), FORMAT_INFO (x1r5g5b5), FORMAT_INFO (a1b5g5r5), FORMAT_INFO (x1b5g5r5), FORMAT_INFO (a4r4g4b4), FORMAT_INFO (x4r4g4b4), FORMAT_INFO (a4b4g4r4), FORMAT_INFO (x4b4g4r4), /* 8bpp formats */ FORMAT_INFO (a8), FORMAT_INFO (r3g3b2), FORMAT_INFO (b2g3r3), FORMAT_INFO (a2r2g2b2), FORMAT_INFO (a2b2g2r2), FORMAT_INFO (c8), FORMAT_INFO (g8), #define fetch_scanline_x4c4 fetch_scanline_c8 #define fetch_pixel_x4c4 fetch_pixel_c8 #define store_scanline_x4c4 store_scanline_c8 FORMAT_INFO (x4c4), #define fetch_scanline_x4g4 fetch_scanline_g8 #define fetch_pixel_x4g4 fetch_pixel_g8 #define store_scanline_x4g4 store_scanline_g8 FORMAT_INFO (x4g4), FORMAT_INFO (x4a4), /* 4bpp formats */ FORMAT_INFO (a4), FORMAT_INFO (r1g2b1), FORMAT_INFO (b1g2r1), FORMAT_INFO (a1r1g1b1), FORMAT_INFO (a1b1g1r1), FORMAT_INFO (c4), FORMAT_INFO (g4), /* 1bpp formats */ FORMAT_INFO (a1), FORMAT_INFO (g1), /* Wide formats */ #ifndef PIXMAN_FB_ACCESSORS { PIXMAN_rgba_float, NULL, fetch_scanline_rgbaf_float, fetch_pixel_generic_lossy_32, fetch_pixel_rgbaf_float, NULL, store_scanline_rgbaf_float }, { PIXMAN_rgb_float, NULL, fetch_scanline_rgbf_float, fetch_pixel_generic_lossy_32, fetch_pixel_rgbf_float, NULL, store_scanline_rgbf_float }, #endif { PIXMAN_a2r10g10b10, NULL, fetch_scanline_a2r10g10b10_float, fetch_pixel_generic_lossy_32, fetch_pixel_a2r10g10b10_float, NULL, store_scanline_a2r10g10b10_float }, { PIXMAN_x2r10g10b10, NULL, fetch_scanline_x2r10g10b10_float, fetch_pixel_generic_lossy_32, fetch_pixel_x2r10g10b10_float, NULL, store_scanline_x2r10g10b10_float }, { PIXMAN_a2b10g10r10, NULL, fetch_scanline_a2b10g10r10_float, fetch_pixel_generic_lossy_32, fetch_pixel_a2b10g10r10_float, NULL, store_scanline_a2b10g10r10_float }, { PIXMAN_x2b10g10r10, NULL, fetch_scanline_x2b10g10r10_float, fetch_pixel_generic_lossy_32, fetch_pixel_x2b10g10r10_float, NULL, store_scanline_x2b10g10r10_float }, /* YUV formats */ { PIXMAN_yuy2, fetch_scanline_yuy2, fetch_scanline_generic_float, fetch_pixel_yuy2, fetch_pixel_generic_float, NULL, NULL }, { PIXMAN_yv12, fetch_scanline_yv12, fetch_scanline_generic_float, fetch_pixel_yv12, fetch_pixel_generic_float, NULL, NULL }, { PIXMAN_null }, }; static void setup_accessors (bits_image_t *image) { const format_info_t *info = accessors; while (info->format != PIXMAN_null) { if (info->format == image->format) { image->fetch_scanline_32 = info->fetch_scanline_32; image->fetch_scanline_float = info->fetch_scanline_float; image->fetch_pixel_32 = info->fetch_pixel_32; image->fetch_pixel_float = info->fetch_pixel_float; image->store_scanline_32 = info->store_scanline_32; image->store_scanline_float = info->store_scanline_float; return; } info++; } } #ifndef PIXMAN_FB_ACCESSORS void _pixman_bits_image_setup_accessors_accessors (bits_image_t *image); void _pixman_bits_image_setup_accessors (bits_image_t *image) { if (image->read_func || image->write_func) _pixman_bits_image_setup_accessors_accessors (image); else setup_accessors (image); } #else void _pixman_bits_image_setup_accessors_accessors (bits_image_t *image) { setup_accessors (image); } #endif
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-accessor.h
#ifdef PIXMAN_FB_ACCESSORS #define READ(img, ptr) \ (((bits_image_t *)(img))->read_func ((ptr), sizeof(*(ptr)))) #define WRITE(img, ptr,val) \ (((bits_image_t *)(img))->write_func ((ptr), (val), sizeof (*(ptr)))) #define MEMSET_WRAPPED(img, dst, val, size) \ do { \ size_t _i; \ uint8_t *_dst = (uint8_t*)(dst); \ for(_i = 0; _i < (size_t) size; _i++) { \ WRITE((img), _dst +_i, (val)); \ } \ } while (0) #else #define READ(img, ptr) (*(ptr)) #define WRITE(img, ptr, val) (*(ptr) = (val)) #define MEMSET_WRAPPED(img, dst, val, size) \ memset(dst, val, size) #endif
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-arm-asm.h
/* * Copyright © 2008 Mozilla Corporation * Copyright © 2010 Nokia Corporation * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Mozilla Corporation not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Mozilla Corporation makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. * * Author: Jeff Muizelaar (jeff@infidigm.net) * */ /* Supplementary macro for setting function attributes */ .macro pixman_asm_function fname .func fname .global fname #ifdef __ELF__ .hidden fname .type fname, %function #endif fname: .endm
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-arm-common.h
/* * Copyright © 2010 Nokia Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Author: Siarhei Siamashka (siarhei.siamashka@nokia.com) */ #ifndef PIXMAN_ARM_COMMON_H #define PIXMAN_ARM_COMMON_H #include "pixman-inlines.h" /* Define some macros which can expand into proxy functions between * ARM assembly optimized functions and the rest of pixman fast path API. * * All the low level ARM assembly functions have to use ARM EABI * calling convention and take up to 8 arguments: * width, height, dst, dst_stride, src, src_stride, mask, mask_stride * * The arguments are ordered with the most important coming first (the * first 4 arguments are passed to function in registers, the rest are * on stack). The last arguments are optional, for example if the * function is not using mask, then 'mask' and 'mask_stride' can be * omitted when doing a function call. * * Arguments 'src' and 'mask' contain either a pointer to the top left * pixel of the composited rectangle or a pixel color value depending * on the function type. In the case of just a color value (solid source * or mask), the corresponding stride argument is unused. */ #define SKIP_ZERO_SRC 1 #define SKIP_ZERO_MASK 2 #define PIXMAN_ARM_BIND_FAST_PATH_SRC_DST(cputype, name, \ src_type, src_cnt, \ dst_type, dst_cnt) \ void \ pixman_composite_##name##_asm_##cputype (int32_t w, \ int32_t h, \ dst_type *dst, \ int32_t dst_stride, \ src_type *src, \ int32_t src_stride); \ \ static void \ cputype##_composite_##name (pixman_implementation_t *imp, \ pixman_composite_info_t *info) \ { \ PIXMAN_COMPOSITE_ARGS (info); \ dst_type *dst_line; \ src_type *src_line; \ int32_t dst_stride, src_stride; \ \ PIXMAN_IMAGE_GET_LINE (src_image, src_x, src_y, src_type, \ src_stride, src_line, src_cnt); \ PIXMAN_IMAGE_GET_LINE (dest_image, dest_x, dest_y, dst_type, \ dst_stride, dst_line, dst_cnt); \ \ pixman_composite_##name##_asm_##cputype (width, height, \ dst_line, dst_stride, \ src_line, src_stride); \ } #define PIXMAN_ARM_BIND_FAST_PATH_N_DST(flags, cputype, name, \ dst_type, dst_cnt) \ void \ pixman_composite_##name##_asm_##cputype (int32_t w, \ int32_t h, \ dst_type *dst, \ int32_t dst_stride, \ uint32_t src); \ \ static void \ cputype##_composite_##name (pixman_implementation_t *imp, \ pixman_composite_info_t *info) \ { \ PIXMAN_COMPOSITE_ARGS (info); \ dst_type *dst_line; \ int32_t dst_stride; \ uint32_t src; \ \ src = _pixman_image_get_solid ( \ imp, src_image, dest_image->bits.format); \ \ if ((flags & SKIP_ZERO_SRC) && src == 0) \ return; \ \ PIXMAN_IMAGE_GET_LINE (dest_image, dest_x, dest_y, dst_type, \ dst_stride, dst_line, dst_cnt); \ \ pixman_composite_##name##_asm_##cputype (width, height, \ dst_line, dst_stride, \ src); \ } #define PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST(flags, cputype, name, \ mask_type, mask_cnt, \ dst_type, dst_cnt) \ void \ pixman_composite_##name##_asm_##cputype (int32_t w, \ int32_t h, \ dst_type *dst, \ int32_t dst_stride, \ uint32_t src, \ int32_t unused, \ mask_type *mask, \ int32_t mask_stride); \ \ static void \ cputype##_composite_##name (pixman_implementation_t *imp, \ pixman_composite_info_t *info) \ { \ PIXMAN_COMPOSITE_ARGS (info); \ dst_type *dst_line; \ mask_type *mask_line; \ int32_t dst_stride, mask_stride; \ uint32_t src; \ \ src = _pixman_image_get_solid ( \ imp, src_image, dest_image->bits.format); \ \ if ((flags & SKIP_ZERO_SRC) && src == 0) \ return; \ \ PIXMAN_IMAGE_GET_LINE (dest_image, dest_x, dest_y, dst_type, \ dst_stride, dst_line, dst_cnt); \ PIXMAN_IMAGE_GET_LINE (mask_image, mask_x, mask_y, mask_type, \ mask_stride, mask_line, mask_cnt); \ \ pixman_composite_##name##_asm_##cputype (width, height, \ dst_line, dst_stride, \ src, 0, \ mask_line, mask_stride); \ } #define PIXMAN_ARM_BIND_FAST_PATH_SRC_N_DST(flags, cputype, name, \ src_type, src_cnt, \ dst_type, dst_cnt) \ void \ pixman_composite_##name##_asm_##cputype (int32_t w, \ int32_t h, \ dst_type *dst, \ int32_t dst_stride, \ src_type *src, \ int32_t src_stride, \ uint32_t mask); \ \ static void \ cputype##_composite_##name (pixman_implementation_t *imp, \ pixman_composite_info_t *info) \ { \ PIXMAN_COMPOSITE_ARGS (info); \ dst_type *dst_line; \ src_type *src_line; \ int32_t dst_stride, src_stride; \ uint32_t mask; \ \ mask = _pixman_image_get_solid ( \ imp, mask_image, dest_image->bits.format); \ \ if ((flags & SKIP_ZERO_MASK) && mask == 0) \ return; \ \ PIXMAN_IMAGE_GET_LINE (dest_image, dest_x, dest_y, dst_type, \ dst_stride, dst_line, dst_cnt); \ PIXMAN_IMAGE_GET_LINE (src_image, src_x, src_y, src_type, \ src_stride, src_line, src_cnt); \ \ pixman_composite_##name##_asm_##cputype (width, height, \ dst_line, dst_stride, \ src_line, src_stride, \ mask); \ } #define PIXMAN_ARM_BIND_FAST_PATH_SRC_MASK_DST(cputype, name, \ src_type, src_cnt, \ mask_type, mask_cnt, \ dst_type, dst_cnt) \ void \ pixman_composite_##name##_asm_##cputype (int32_t w, \ int32_t h, \ dst_type *dst, \ int32_t dst_stride, \ src_type *src, \ int32_t src_stride, \ mask_type *mask, \ int32_t mask_stride); \ \ static void \ cputype##_composite_##name (pixman_implementation_t *imp, \ pixman_composite_info_t *info) \ { \ PIXMAN_COMPOSITE_ARGS (info); \ dst_type *dst_line; \ src_type *src_line; \ mask_type *mask_line; \ int32_t dst_stride, src_stride, mask_stride; \ \ PIXMAN_IMAGE_GET_LINE (dest_image, dest_x, dest_y, dst_type, \ dst_stride, dst_line, dst_cnt); \ PIXMAN_IMAGE_GET_LINE (src_image, src_x, src_y, src_type, \ src_stride, src_line, src_cnt); \ PIXMAN_IMAGE_GET_LINE (mask_image, mask_x, mask_y, mask_type, \ mask_stride, mask_line, mask_cnt); \ \ pixman_composite_##name##_asm_##cputype (width, height, \ dst_line, dst_stride, \ src_line, src_stride, \ mask_line, mask_stride); \ } #define PIXMAN_ARM_BIND_SCALED_NEAREST_SRC_DST(cputype, name, op, \ src_type, dst_type) \ void \ pixman_scaled_nearest_scanline_##name##_##op##_asm_##cputype ( \ int32_t w, \ dst_type * dst, \ const src_type * src, \ pixman_fixed_t vx, \ pixman_fixed_t unit_x, \ pixman_fixed_t max_vx); \ \ static force_inline void \ scaled_nearest_scanline_##cputype##_##name##_##op (dst_type * pd, \ const src_type * ps, \ int32_t w, \ pixman_fixed_t vx, \ pixman_fixed_t unit_x, \ pixman_fixed_t max_vx, \ pixman_bool_t zero_src) \ { \ pixman_scaled_nearest_scanline_##name##_##op##_asm_##cputype (w, pd, ps, \ vx, unit_x, \ max_vx); \ } \ \ FAST_NEAREST_MAINLOOP (cputype##_##name##_cover_##op, \ scaled_nearest_scanline_##cputype##_##name##_##op, \ src_type, dst_type, COVER) \ FAST_NEAREST_MAINLOOP (cputype##_##name##_none_##op, \ scaled_nearest_scanline_##cputype##_##name##_##op, \ src_type, dst_type, NONE) \ FAST_NEAREST_MAINLOOP (cputype##_##name##_pad_##op, \ scaled_nearest_scanline_##cputype##_##name##_##op, \ src_type, dst_type, PAD) \ FAST_NEAREST_MAINLOOP (cputype##_##name##_normal_##op, \ scaled_nearest_scanline_##cputype##_##name##_##op, \ src_type, dst_type, NORMAL) #define PIXMAN_ARM_BIND_SCALED_NEAREST_SRC_A8_DST(flags, cputype, name, op, \ src_type, dst_type) \ void \ pixman_scaled_nearest_scanline_##name##_##op##_asm_##cputype ( \ int32_t w, \ dst_type * dst, \ const src_type * src, \ pixman_fixed_t vx, \ pixman_fixed_t unit_x, \ pixman_fixed_t max_vx, \ const uint8_t * mask); \ \ static force_inline void \ scaled_nearest_scanline_##cputype##_##name##_##op (const uint8_t * mask, \ dst_type * pd, \ const src_type * ps, \ int32_t w, \ pixman_fixed_t vx, \ pixman_fixed_t unit_x, \ pixman_fixed_t max_vx, \ pixman_bool_t zero_src) \ { \ if ((flags & SKIP_ZERO_SRC) && zero_src) \ return; \ pixman_scaled_nearest_scanline_##name##_##op##_asm_##cputype (w, pd, ps, \ vx, unit_x, \ max_vx, \ mask); \ } \ \ FAST_NEAREST_MAINLOOP_COMMON (cputype##_##name##_cover_##op, \ scaled_nearest_scanline_##cputype##_##name##_##op,\ src_type, uint8_t, dst_type, COVER, TRUE, FALSE)\ FAST_NEAREST_MAINLOOP_COMMON (cputype##_##name##_none_##op, \ scaled_nearest_scanline_##cputype##_##name##_##op,\ src_type, uint8_t, dst_type, NONE, TRUE, FALSE) \ FAST_NEAREST_MAINLOOP_COMMON (cputype##_##name##_pad_##op, \ scaled_nearest_scanline_##cputype##_##name##_##op,\ src_type, uint8_t, dst_type, PAD, TRUE, FALSE) \ FAST_NEAREST_MAINLOOP_COMMON (cputype##_##name##_normal_##op, \ scaled_nearest_scanline_##cputype##_##name##_##op,\ src_type, uint8_t, dst_type, NORMAL, TRUE, FALSE) /* Provide entries for the fast path table */ #define PIXMAN_ARM_SIMPLE_NEAREST_A8_MASK_FAST_PATH(op,s,d,func) \ SIMPLE_NEAREST_A8_MASK_FAST_PATH (op,s,d,func), \ SIMPLE_NEAREST_A8_MASK_FAST_PATH_NORMAL (op,s,d,func) /*****************************************************************************/ #define PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_DST(flags, cputype, name, op, \ src_type, dst_type) \ void \ pixman_scaled_bilinear_scanline_##name##_##op##_asm_##cputype ( \ dst_type * dst, \ const src_type * top, \ const src_type * bottom, \ int wt, \ int wb, \ pixman_fixed_t x, \ pixman_fixed_t ux, \ int width); \ \ static force_inline void \ scaled_bilinear_scanline_##cputype##_##name##_##op ( \ dst_type * dst, \ const uint32_t * mask, \ const src_type * src_top, \ const src_type * src_bottom, \ int32_t w, \ int wt, \ int wb, \ pixman_fixed_t vx, \ pixman_fixed_t unit_x, \ pixman_fixed_t max_vx, \ pixman_bool_t zero_src) \ { \ if ((flags & SKIP_ZERO_SRC) && zero_src) \ return; \ pixman_scaled_bilinear_scanline_##name##_##op##_asm_##cputype ( \ dst, src_top, src_bottom, wt, wb, vx, unit_x, w); \ } \ \ FAST_BILINEAR_MAINLOOP_COMMON (cputype##_##name##_cover_##op, \ scaled_bilinear_scanline_##cputype##_##name##_##op, \ src_type, uint32_t, dst_type, COVER, FLAG_NONE) \ FAST_BILINEAR_MAINLOOP_COMMON (cputype##_##name##_none_##op, \ scaled_bilinear_scanline_##cputype##_##name##_##op, \ src_type, uint32_t, dst_type, NONE, FLAG_NONE) \ FAST_BILINEAR_MAINLOOP_COMMON (cputype##_##name##_pad_##op, \ scaled_bilinear_scanline_##cputype##_##name##_##op, \ src_type, uint32_t, dst_type, PAD, FLAG_NONE) \ FAST_BILINEAR_MAINLOOP_COMMON (cputype##_##name##_normal_##op, \ scaled_bilinear_scanline_##cputype##_##name##_##op, \ src_type, uint32_t, dst_type, NORMAL, \ FLAG_NONE) #define PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_A8_DST(flags, cputype, name, op, \ src_type, dst_type) \ void \ pixman_scaled_bilinear_scanline_##name##_##op##_asm_##cputype ( \ dst_type * dst, \ const uint8_t * mask, \ const src_type * top, \ const src_type * bottom, \ int wt, \ int wb, \ pixman_fixed_t x, \ pixman_fixed_t ux, \ int width); \ \ static force_inline void \ scaled_bilinear_scanline_##cputype##_##name##_##op ( \ dst_type * dst, \ const uint8_t * mask, \ const src_type * src_top, \ const src_type * src_bottom, \ int32_t w, \ int wt, \ int wb, \ pixman_fixed_t vx, \ pixman_fixed_t unit_x, \ pixman_fixed_t max_vx, \ pixman_bool_t zero_src) \ { \ if ((flags & SKIP_ZERO_SRC) && zero_src) \ return; \ pixman_scaled_bilinear_scanline_##name##_##op##_asm_##cputype ( \ dst, mask, src_top, src_bottom, wt, wb, vx, unit_x, w); \ } \ \ FAST_BILINEAR_MAINLOOP_COMMON (cputype##_##name##_cover_##op, \ scaled_bilinear_scanline_##cputype##_##name##_##op, \ src_type, uint8_t, dst_type, COVER, \ FLAG_HAVE_NON_SOLID_MASK) \ FAST_BILINEAR_MAINLOOP_COMMON (cputype##_##name##_none_##op, \ scaled_bilinear_scanline_##cputype##_##name##_##op, \ src_type, uint8_t, dst_type, NONE, \ FLAG_HAVE_NON_SOLID_MASK) \ FAST_BILINEAR_MAINLOOP_COMMON (cputype##_##name##_pad_##op, \ scaled_bilinear_scanline_##cputype##_##name##_##op, \ src_type, uint8_t, dst_type, PAD, \ FLAG_HAVE_NON_SOLID_MASK) \ FAST_BILINEAR_MAINLOOP_COMMON (cputype##_##name##_normal_##op, \ scaled_bilinear_scanline_##cputype##_##name##_##op, \ src_type, uint8_t, dst_type, NORMAL, \ FLAG_HAVE_NON_SOLID_MASK) #endif
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-arm-neon-asm.h
/* * Copyright © 2009 Nokia Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Author: Siarhei Siamashka (siarhei.siamashka@nokia.com) */ /* * This file contains a macro ('generate_composite_function') which can * construct 2D image processing functions, based on a common template. * Any combinations of source, destination and mask images with 8bpp, * 16bpp, 24bpp, 32bpp color formats are supported. * * This macro takes care of: * - handling of leading and trailing unaligned pixels * - doing most of the work related to L2 cache preload * - encourages the use of software pipelining for better instructions * scheduling * * The user of this macro has to provide some configuration parameters * (bit depths for the images, prefetch distance, etc.) and a set of * macros, which should implement basic code chunks responsible for * pixels processing. See 'pixman-arm-neon-asm.S' file for the usage * examples. * * TODO: * - try overlapped pixel method (from Ian Rickards) when processing * exactly two blocks of pixels * - maybe add an option to do reverse scanline processing */ /* * Bit flags for 'generate_composite_function' macro which are used * to tune generated functions behavior. */ .set FLAG_DST_WRITEONLY, 0 .set FLAG_DST_READWRITE, 1 .set FLAG_DEINTERLEAVE_32BPP, 2 /* * Offset in stack where mask and source pointer/stride can be accessed * from 'init' macro. This is useful for doing special handling for solid mask. */ .set ARGS_STACK_OFFSET, 40 /* * Constants for selecting preferable prefetch type. */ .set PREFETCH_TYPE_NONE, 0 /* No prefetch at all */ .set PREFETCH_TYPE_SIMPLE, 1 /* A simple, fixed-distance-ahead prefetch */ .set PREFETCH_TYPE_ADVANCED, 2 /* Advanced fine-grained prefetch */ /* * Definitions of supplementary pixld/pixst macros (for partial load/store of * pixel data). */ .macro pixldst1 op, elem_size, reg1, mem_operand, abits .if abits > 0 op&.&elem_size {d&reg1}, [&mem_operand&, :&abits&]! .else op&.&elem_size {d&reg1}, [&mem_operand&]! .endif .endm .macro pixldst2 op, elem_size, reg1, reg2, mem_operand, abits .if abits > 0 op&.&elem_size {d&reg1, d&reg2}, [&mem_operand&, :&abits&]! .else op&.&elem_size {d&reg1, d&reg2}, [&mem_operand&]! .endif .endm .macro pixldst4 op, elem_size, reg1, reg2, reg3, reg4, mem_operand, abits .if abits > 0 op&.&elem_size {d&reg1, d&reg2, d&reg3, d&reg4}, [&mem_operand&, :&abits&]! .else op&.&elem_size {d&reg1, d&reg2, d&reg3, d&reg4}, [&mem_operand&]! .endif .endm .macro pixldst0 op, elem_size, reg1, idx, mem_operand, abits op&.&elem_size {d&reg1[idx]}, [&mem_operand&]! .endm .macro pixldst3 op, elem_size, reg1, reg2, reg3, mem_operand op&.&elem_size {d&reg1, d&reg2, d&reg3}, [&mem_operand&]! .endm .macro pixldst30 op, elem_size, reg1, reg2, reg3, idx, mem_operand op&.&elem_size {d&reg1[idx], d&reg2[idx], d&reg3[idx]}, [&mem_operand&]! .endm .macro pixldst numbytes, op, elem_size, basereg, mem_operand, abits .if numbytes == 32 pixldst4 op, elem_size, %(basereg+4), %(basereg+5), \ %(basereg+6), %(basereg+7), mem_operand, abits .elseif numbytes == 16 pixldst2 op, elem_size, %(basereg+2), %(basereg+3), mem_operand, abits .elseif numbytes == 8 pixldst1 op, elem_size, %(basereg+1), mem_operand, abits .elseif numbytes == 4 .if !RESPECT_STRICT_ALIGNMENT || (elem_size == 32) pixldst0 op, 32, %(basereg+0), 1, mem_operand, abits .elseif elem_size == 16 pixldst0 op, 16, %(basereg+0), 2, mem_operand, abits pixldst0 op, 16, %(basereg+0), 3, mem_operand, abits .else pixldst0 op, 8, %(basereg+0), 4, mem_operand, abits pixldst0 op, 8, %(basereg+0), 5, mem_operand, abits pixldst0 op, 8, %(basereg+0), 6, mem_operand, abits pixldst0 op, 8, %(basereg+0), 7, mem_operand, abits .endif .elseif numbytes == 2 .if !RESPECT_STRICT_ALIGNMENT || (elem_size == 16) pixldst0 op, 16, %(basereg+0), 1, mem_operand, abits .else pixldst0 op, 8, %(basereg+0), 2, mem_operand, abits pixldst0 op, 8, %(basereg+0), 3, mem_operand, abits .endif .elseif numbytes == 1 pixldst0 op, 8, %(basereg+0), 1, mem_operand, abits .else .error "unsupported size: numbytes" .endif .endm .macro pixld numpix, bpp, basereg, mem_operand, abits=0 .if bpp > 0 .if (bpp == 32) && (numpix == 8) && (DEINTERLEAVE_32BPP_ENABLED != 0) pixldst4 vld4, 8, %(basereg+4), %(basereg+5), \ %(basereg+6), %(basereg+7), mem_operand, abits .elseif (bpp == 24) && (numpix == 8) pixldst3 vld3, 8, %(basereg+3), %(basereg+4), %(basereg+5), mem_operand .elseif (bpp == 24) && (numpix == 4) pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 4, mem_operand pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 5, mem_operand pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 6, mem_operand pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 7, mem_operand .elseif (bpp == 24) && (numpix == 2) pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 2, mem_operand pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 3, mem_operand .elseif (bpp == 24) && (numpix == 1) pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 1, mem_operand .else pixldst %(numpix * bpp / 8), vld1, %(bpp), basereg, mem_operand, abits .endif .endif .endm .macro pixst numpix, bpp, basereg, mem_operand, abits=0 .if bpp > 0 .if (bpp == 32) && (numpix == 8) && (DEINTERLEAVE_32BPP_ENABLED != 0) pixldst4 vst4, 8, %(basereg+4), %(basereg+5), \ %(basereg+6), %(basereg+7), mem_operand, abits .elseif (bpp == 24) && (numpix == 8) pixldst3 vst3, 8, %(basereg+3), %(basereg+4), %(basereg+5), mem_operand .elseif (bpp == 24) && (numpix == 4) pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 4, mem_operand pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 5, mem_operand pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 6, mem_operand pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 7, mem_operand .elseif (bpp == 24) && (numpix == 2) pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 2, mem_operand pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 3, mem_operand .elseif (bpp == 24) && (numpix == 1) pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 1, mem_operand .else pixldst %(numpix * bpp / 8), vst1, %(bpp), basereg, mem_operand, abits .endif .endif .endm .macro pixld_a numpix, bpp, basereg, mem_operand .if (bpp * numpix) <= 128 pixld numpix, bpp, basereg, mem_operand, %(bpp * numpix) .else pixld numpix, bpp, basereg, mem_operand, 128 .endif .endm .macro pixst_a numpix, bpp, basereg, mem_operand .if (bpp * numpix) <= 128 pixst numpix, bpp, basereg, mem_operand, %(bpp * numpix) .else pixst numpix, bpp, basereg, mem_operand, 128 .endif .endm /* * Pixel fetcher for nearest scaling (needs TMP1, TMP2, VX, UNIT_X register * aliases to be defined) */ .macro pixld1_s elem_size, reg1, mem_operand .if elem_size == 16 mov TMP1, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP1, mem_operand, TMP1, asl #1 mov TMP2, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP2, mem_operand, TMP2, asl #1 vld1.16 {d&reg1&[0]}, [TMP1, :16] mov TMP1, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP1, mem_operand, TMP1, asl #1 vld1.16 {d&reg1&[1]}, [TMP2, :16] mov TMP2, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP2, mem_operand, TMP2, asl #1 vld1.16 {d&reg1&[2]}, [TMP1, :16] vld1.16 {d&reg1&[3]}, [TMP2, :16] .elseif elem_size == 32 mov TMP1, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP1, mem_operand, TMP1, asl #2 mov TMP2, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP2, mem_operand, TMP2, asl #2 vld1.32 {d&reg1&[0]}, [TMP1, :32] vld1.32 {d&reg1&[1]}, [TMP2, :32] .else .error "unsupported" .endif .endm .macro pixld2_s elem_size, reg1, reg2, mem_operand .if 0 /* elem_size == 32 */ mov TMP1, VX, asr #16 add VX, VX, UNIT_X, asl #1 add TMP1, mem_operand, TMP1, asl #2 mov TMP2, VX, asr #16 sub VX, VX, UNIT_X add TMP2, mem_operand, TMP2, asl #2 vld1.32 {d&reg1&[0]}, [TMP1, :32] mov TMP1, VX, asr #16 add VX, VX, UNIT_X, asl #1 add TMP1, mem_operand, TMP1, asl #2 vld1.32 {d&reg2&[0]}, [TMP2, :32] mov TMP2, VX, asr #16 add VX, VX, UNIT_X add TMP2, mem_operand, TMP2, asl #2 vld1.32 {d&reg1&[1]}, [TMP1, :32] vld1.32 {d&reg2&[1]}, [TMP2, :32] .else pixld1_s elem_size, reg1, mem_operand pixld1_s elem_size, reg2, mem_operand .endif .endm .macro pixld0_s elem_size, reg1, idx, mem_operand .if elem_size == 16 mov TMP1, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP1, mem_operand, TMP1, asl #1 vld1.16 {d&reg1&[idx]}, [TMP1, :16] .elseif elem_size == 32 mov TMP1, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP1, mem_operand, TMP1, asl #2 vld1.32 {d&reg1&[idx]}, [TMP1, :32] .endif .endm .macro pixld_s_internal numbytes, elem_size, basereg, mem_operand .if numbytes == 32 pixld2_s elem_size, %(basereg+4), %(basereg+5), mem_operand pixld2_s elem_size, %(basereg+6), %(basereg+7), mem_operand pixdeinterleave elem_size, %(basereg+4) .elseif numbytes == 16 pixld2_s elem_size, %(basereg+2), %(basereg+3), mem_operand .elseif numbytes == 8 pixld1_s elem_size, %(basereg+1), mem_operand .elseif numbytes == 4 .if elem_size == 32 pixld0_s elem_size, %(basereg+0), 1, mem_operand .elseif elem_size == 16 pixld0_s elem_size, %(basereg+0), 2, mem_operand pixld0_s elem_size, %(basereg+0), 3, mem_operand .else pixld0_s elem_size, %(basereg+0), 4, mem_operand pixld0_s elem_size, %(basereg+0), 5, mem_operand pixld0_s elem_size, %(basereg+0), 6, mem_operand pixld0_s elem_size, %(basereg+0), 7, mem_operand .endif .elseif numbytes == 2 .if elem_size == 16 pixld0_s elem_size, %(basereg+0), 1, mem_operand .else pixld0_s elem_size, %(basereg+0), 2, mem_operand pixld0_s elem_size, %(basereg+0), 3, mem_operand .endif .elseif numbytes == 1 pixld0_s elem_size, %(basereg+0), 1, mem_operand .else .error "unsupported size: numbytes" .endif .endm .macro pixld_s numpix, bpp, basereg, mem_operand .if bpp > 0 pixld_s_internal %(numpix * bpp / 8), %(bpp), basereg, mem_operand .endif .endm .macro vuzp8 reg1, reg2 vuzp.8 d&reg1, d&reg2 .endm .macro vzip8 reg1, reg2 vzip.8 d&reg1, d&reg2 .endm /* deinterleave B, G, R, A channels for eight 32bpp pixels in 4 registers */ .macro pixdeinterleave bpp, basereg .if (bpp == 32) && (DEINTERLEAVE_32BPP_ENABLED != 0) vuzp8 %(basereg+0), %(basereg+1) vuzp8 %(basereg+2), %(basereg+3) vuzp8 %(basereg+1), %(basereg+3) vuzp8 %(basereg+0), %(basereg+2) .endif .endm /* interleave B, G, R, A channels for eight 32bpp pixels in 4 registers */ .macro pixinterleave bpp, basereg .if (bpp == 32) && (DEINTERLEAVE_32BPP_ENABLED != 0) vzip8 %(basereg+0), %(basereg+2) vzip8 %(basereg+1), %(basereg+3) vzip8 %(basereg+2), %(basereg+3) vzip8 %(basereg+0), %(basereg+1) .endif .endm /* * This is a macro for implementing cache preload. The main idea is that * cache preload logic is mostly independent from the rest of pixels * processing code. It starts at the top left pixel and moves forward * across pixels and can jump across scanlines. Prefetch distance is * handled in an 'incremental' way: it starts from 0 and advances to the * optimal distance over time. After reaching optimal prefetch distance, * it is kept constant. There are some checks which prevent prefetching * unneeded pixel lines below the image (but it still can prefetch a bit * more data on the right side of the image - not a big issue and may * be actually helpful when rendering text glyphs). Additional trick is * the use of LDR instruction for prefetch instead of PLD when moving to * the next line, the point is that we have a high chance of getting TLB * miss in this case, and PLD would be useless. * * This sounds like it may introduce a noticeable overhead (when working with * fully cached data). But in reality, due to having a separate pipeline and * instruction queue for NEON unit in ARM Cortex-A8, normal ARM code can * execute simultaneously with NEON and be completely shadowed by it. Thus * we get no performance overhead at all (*). This looks like a very nice * feature of Cortex-A8, if used wisely. We don't have a hardware prefetcher, * but still can implement some rather advanced prefetch logic in software * for almost zero cost! * * (*) The overhead of the prefetcher is visible when running some trivial * pixels processing like simple copy. Anyway, having prefetch is a must * when working with the graphics data. */ .macro PF a, x:vararg .if (PREFETCH_TYPE_CURRENT == PREFETCH_TYPE_ADVANCED) a x .endif .endm .macro cache_preload std_increment, boost_increment .if (src_bpp_shift >= 0) || (dst_r_bpp != 0) || (mask_bpp_shift >= 0) .if regs_shortage PF ldr ORIG_W, [sp] /* If we are short on regs, ORIG_W is kept on stack */ .endif .if std_increment != 0 PF add PF_X, PF_X, #std_increment .endif PF tst PF_CTL, #0xF PF addne PF_X, PF_X, #boost_increment PF subne PF_CTL, PF_CTL, #1 PF cmp PF_X, ORIG_W .if src_bpp_shift >= 0 PF pld, [PF_SRC, PF_X, lsl #src_bpp_shift] .endif .if dst_r_bpp != 0 PF pld, [PF_DST, PF_X, lsl #dst_bpp_shift] .endif .if mask_bpp_shift >= 0 PF pld, [PF_MASK, PF_X, lsl #mask_bpp_shift] .endif PF subge PF_X, PF_X, ORIG_W PF subges PF_CTL, PF_CTL, #0x10 .if src_bpp_shift >= 0 PF ldrgeb DUMMY, [PF_SRC, SRC_STRIDE, lsl #src_bpp_shift]! .endif .if dst_r_bpp != 0 PF ldrgeb DUMMY, [PF_DST, DST_STRIDE, lsl #dst_bpp_shift]! .endif .if mask_bpp_shift >= 0 PF ldrgeb DUMMY, [PF_MASK, MASK_STRIDE, lsl #mask_bpp_shift]! .endif .endif .endm .macro cache_preload_simple .if (PREFETCH_TYPE_CURRENT == PREFETCH_TYPE_SIMPLE) .if src_bpp > 0 pld [SRC, #(PREFETCH_DISTANCE_SIMPLE * src_bpp / 8)] .endif .if dst_r_bpp > 0 pld [DST_R, #(PREFETCH_DISTANCE_SIMPLE * dst_r_bpp / 8)] .endif .if mask_bpp > 0 pld [MASK, #(PREFETCH_DISTANCE_SIMPLE * mask_bpp / 8)] .endif .endif .endm .macro fetch_mask_pixblock pixld pixblock_size, mask_bpp, \ (mask_basereg - pixblock_size * mask_bpp / 64), MASK .endm /* * Macro which is used to process leading pixels until destination * pointer is properly aligned (at 16 bytes boundary). When destination * buffer uses 16bpp format, this is unnecessary, or even pointless. */ .macro ensure_destination_ptr_alignment process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head .if dst_w_bpp != 24 tst DST_R, #0xF beq 2f .irp lowbit, 1, 2, 4, 8, 16 local skip1 .if (dst_w_bpp <= (lowbit * 8)) && ((lowbit * 8) < (pixblock_size * dst_w_bpp)) .if lowbit < 16 /* we don't need more than 16-byte alignment */ tst DST_R, #lowbit beq 1f .endif pixld_src (lowbit * 8 / dst_w_bpp), src_bpp, src_basereg, SRC pixld (lowbit * 8 / dst_w_bpp), mask_bpp, mask_basereg, MASK .if dst_r_bpp > 0 pixld_a (lowbit * 8 / dst_r_bpp), dst_r_bpp, dst_r_basereg, DST_R .else add DST_R, DST_R, #lowbit .endif PF add PF_X, PF_X, #(lowbit * 8 / dst_w_bpp) sub W, W, #(lowbit * 8 / dst_w_bpp) 1: .endif .endr pixdeinterleave src_bpp, src_basereg pixdeinterleave mask_bpp, mask_basereg pixdeinterleave dst_r_bpp, dst_r_basereg process_pixblock_head cache_preload 0, pixblock_size cache_preload_simple process_pixblock_tail pixinterleave dst_w_bpp, dst_w_basereg .irp lowbit, 1, 2, 4, 8, 16 .if (dst_w_bpp <= (lowbit * 8)) && ((lowbit * 8) < (pixblock_size * dst_w_bpp)) .if lowbit < 16 /* we don't need more than 16-byte alignment */ tst DST_W, #lowbit beq 1f .endif pixst_a (lowbit * 8 / dst_w_bpp), dst_w_bpp, dst_w_basereg, DST_W 1: .endif .endr .endif 2: .endm /* * Special code for processing up to (pixblock_size - 1) remaining * trailing pixels. As SIMD processing performs operation on * pixblock_size pixels, anything smaller than this has to be loaded * and stored in a special way. Loading and storing of pixel data is * performed in such a way that we fill some 'slots' in the NEON * registers (some slots naturally are unused), then perform compositing * operation as usual. In the end, the data is taken from these 'slots' * and saved to memory. * * cache_preload_flag - allows to suppress prefetch if * set to 0 * dst_aligned_flag - selects whether destination buffer * is aligned */ .macro process_trailing_pixels cache_preload_flag, \ dst_aligned_flag, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head tst W, #(pixblock_size - 1) beq 2f .irp chunk_size, 16, 8, 4, 2, 1 .if pixblock_size > chunk_size tst W, #chunk_size beq 1f pixld_src chunk_size, src_bpp, src_basereg, SRC pixld chunk_size, mask_bpp, mask_basereg, MASK .if dst_aligned_flag != 0 pixld_a chunk_size, dst_r_bpp, dst_r_basereg, DST_R .else pixld chunk_size, dst_r_bpp, dst_r_basereg, DST_R .endif .if cache_preload_flag != 0 PF add PF_X, PF_X, #chunk_size .endif 1: .endif .endr pixdeinterleave src_bpp, src_basereg pixdeinterleave mask_bpp, mask_basereg pixdeinterleave dst_r_bpp, dst_r_basereg process_pixblock_head .if cache_preload_flag != 0 cache_preload 0, pixblock_size cache_preload_simple .endif process_pixblock_tail pixinterleave dst_w_bpp, dst_w_basereg .irp chunk_size, 16, 8, 4, 2, 1 .if pixblock_size > chunk_size tst W, #chunk_size beq 1f .if dst_aligned_flag != 0 pixst_a chunk_size, dst_w_bpp, dst_w_basereg, DST_W .else pixst chunk_size, dst_w_bpp, dst_w_basereg, DST_W .endif 1: .endif .endr 2: .endm /* * Macro, which performs all the needed operations to switch to the next * scanline and start the next loop iteration unless all the scanlines * are already processed. */ .macro advance_to_next_scanline start_of_loop_label .if regs_shortage ldrd W, [sp] /* load W and H (width and height) from stack */ .else mov W, ORIG_W .endif add DST_W, DST_W, DST_STRIDE, lsl #dst_bpp_shift .if src_bpp != 0 add SRC, SRC, SRC_STRIDE, lsl #src_bpp_shift .endif .if mask_bpp != 0 add MASK, MASK, MASK_STRIDE, lsl #mask_bpp_shift .endif .if (dst_w_bpp != 24) sub DST_W, DST_W, W, lsl #dst_bpp_shift .endif .if (src_bpp != 24) && (src_bpp != 0) sub SRC, SRC, W, lsl #src_bpp_shift .endif .if (mask_bpp != 24) && (mask_bpp != 0) sub MASK, MASK, W, lsl #mask_bpp_shift .endif subs H, H, #1 mov DST_R, DST_W .if regs_shortage str H, [sp, #4] /* save updated height to stack */ .endif bge start_of_loop_label .endm /* * Registers are allocated in the following way by default: * d0, d1, d2, d3 - reserved for loading source pixel data * d4, d5, d6, d7 - reserved for loading destination pixel data * d24, d25, d26, d27 - reserved for loading mask pixel data * d28, d29, d30, d31 - final destination pixel data for writeback to memory */ .macro generate_composite_function fname, \ src_bpp_, \ mask_bpp_, \ dst_w_bpp_, \ flags, \ pixblock_size_, \ prefetch_distance, \ init, \ cleanup, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head, \ dst_w_basereg_ = 28, \ dst_r_basereg_ = 4, \ src_basereg_ = 0, \ mask_basereg_ = 24 pixman_asm_function fname push {r4-r12, lr} /* save all registers */ /* * Select prefetch type for this function. If prefetch distance is * set to 0 or one of the color formats is 24bpp, SIMPLE prefetch * has to be used instead of ADVANCED. */ .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_DEFAULT .if prefetch_distance == 0 .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_NONE .elseif (PREFETCH_TYPE_CURRENT > PREFETCH_TYPE_SIMPLE) && \ ((src_bpp_ == 24) || (mask_bpp_ == 24) || (dst_w_bpp_ == 24)) .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_SIMPLE .endif /* * Make some macro arguments globally visible and accessible * from other macros */ .set src_bpp, src_bpp_ .set mask_bpp, mask_bpp_ .set dst_w_bpp, dst_w_bpp_ .set pixblock_size, pixblock_size_ .set dst_w_basereg, dst_w_basereg_ .set dst_r_basereg, dst_r_basereg_ .set src_basereg, src_basereg_ .set mask_basereg, mask_basereg_ .macro pixld_src x:vararg pixld x .endm .macro fetch_src_pixblock pixld_src pixblock_size, src_bpp, \ (src_basereg - pixblock_size * src_bpp / 64), SRC .endm /* * Assign symbolic names to registers */ W .req r0 /* width (is updated during processing) */ H .req r1 /* height (is updated during processing) */ DST_W .req r2 /* destination buffer pointer for writes */ DST_STRIDE .req r3 /* destination image stride */ SRC .req r4 /* source buffer pointer */ SRC_STRIDE .req r5 /* source image stride */ DST_R .req r6 /* destination buffer pointer for reads */ MASK .req r7 /* mask pointer */ MASK_STRIDE .req r8 /* mask stride */ PF_CTL .req r9 /* combined lines counter and prefetch */ /* distance increment counter */ PF_X .req r10 /* pixel index in a scanline for current */ /* pretetch position */ PF_SRC .req r11 /* pointer to source scanline start */ /* for prefetch purposes */ PF_DST .req r12 /* pointer to destination scanline start */ /* for prefetch purposes */ PF_MASK .req r14 /* pointer to mask scanline start */ /* for prefetch purposes */ /* * Check whether we have enough registers for all the local variables. * If we don't have enough registers, original width and height are * kept on top of stack (and 'regs_shortage' variable is set to indicate * this for the rest of code). Even if there are enough registers, the * allocation scheme may be a bit different depending on whether source * or mask is not used. */ .if (PREFETCH_TYPE_CURRENT < PREFETCH_TYPE_ADVANCED) ORIG_W .req r10 /* saved original width */ DUMMY .req r12 /* temporary register */ .set regs_shortage, 0 .elseif mask_bpp == 0 ORIG_W .req r7 /* saved original width */ DUMMY .req r8 /* temporary register */ .set regs_shortage, 0 .elseif src_bpp == 0 ORIG_W .req r4 /* saved original width */ DUMMY .req r5 /* temporary register */ .set regs_shortage, 0 .else ORIG_W .req r1 /* saved original width */ DUMMY .req r1 /* temporary register */ .set regs_shortage, 1 .endif .set mask_bpp_shift, -1 .if src_bpp == 32 .set src_bpp_shift, 2 .elseif src_bpp == 24 .set src_bpp_shift, 0 .elseif src_bpp == 16 .set src_bpp_shift, 1 .elseif src_bpp == 8 .set src_bpp_shift, 0 .elseif src_bpp == 0 .set src_bpp_shift, -1 .else .error "requested src bpp (src_bpp) is not supported" .endif .if mask_bpp == 32 .set mask_bpp_shift, 2 .elseif mask_bpp == 24 .set mask_bpp_shift, 0 .elseif mask_bpp == 8 .set mask_bpp_shift, 0 .elseif mask_bpp == 0 .set mask_bpp_shift, -1 .else .error "requested mask bpp (mask_bpp) is not supported" .endif .if dst_w_bpp == 32 .set dst_bpp_shift, 2 .elseif dst_w_bpp == 24 .set dst_bpp_shift, 0 .elseif dst_w_bpp == 16 .set dst_bpp_shift, 1 .elseif dst_w_bpp == 8 .set dst_bpp_shift, 0 .else .error "requested dst bpp (dst_w_bpp) is not supported" .endif .if (((flags) & FLAG_DST_READWRITE) != 0) .set dst_r_bpp, dst_w_bpp .else .set dst_r_bpp, 0 .endif .if (((flags) & FLAG_DEINTERLEAVE_32BPP) != 0) .set DEINTERLEAVE_32BPP_ENABLED, 1 .else .set DEINTERLEAVE_32BPP_ENABLED, 0 .endif .if prefetch_distance < 0 || prefetch_distance > 15 .error "invalid prefetch distance (prefetch_distance)" .endif .if src_bpp > 0 ldr SRC, [sp, #40] .endif .if mask_bpp > 0 ldr MASK, [sp, #48] .endif PF mov PF_X, #0 .if src_bpp > 0 ldr SRC_STRIDE, [sp, #44] .endif .if mask_bpp > 0 ldr MASK_STRIDE, [sp, #52] .endif mov DST_R, DST_W .if src_bpp == 24 sub SRC_STRIDE, SRC_STRIDE, W sub SRC_STRIDE, SRC_STRIDE, W, lsl #1 .endif .if mask_bpp == 24 sub MASK_STRIDE, MASK_STRIDE, W sub MASK_STRIDE, MASK_STRIDE, W, lsl #1 .endif .if dst_w_bpp == 24 sub DST_STRIDE, DST_STRIDE, W sub DST_STRIDE, DST_STRIDE, W, lsl #1 .endif /* * Setup advanced prefetcher initial state */ PF mov PF_SRC, SRC PF mov PF_DST, DST_R PF mov PF_MASK, MASK /* PF_CTL = prefetch_distance | ((h - 1) << 4) */ PF mov PF_CTL, H, lsl #4 PF add PF_CTL, #(prefetch_distance - 0x10) init .if regs_shortage push {r0, r1} .endif subs H, H, #1 .if regs_shortage str H, [sp, #4] /* save updated height to stack */ .else mov ORIG_W, W .endif blt 9f cmp W, #(pixblock_size * 2) blt 8f /* * This is the start of the pipelined loop, which if optimized for * long scanlines */ 0: ensure_destination_ptr_alignment process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head /* Implement "head (tail_head) ... (tail_head) tail" loop pattern */ pixld_a pixblock_size, dst_r_bpp, \ (dst_r_basereg - pixblock_size * dst_r_bpp / 64), DST_R fetch_src_pixblock pixld pixblock_size, mask_bpp, \ (mask_basereg - pixblock_size * mask_bpp / 64), MASK PF add PF_X, PF_X, #pixblock_size process_pixblock_head cache_preload 0, pixblock_size cache_preload_simple subs W, W, #(pixblock_size * 2) blt 2f 1: process_pixblock_tail_head cache_preload_simple subs W, W, #pixblock_size bge 1b 2: process_pixblock_tail pixst_a pixblock_size, dst_w_bpp, \ (dst_w_basereg - pixblock_size * dst_w_bpp / 64), DST_W /* Process the remaining trailing pixels in the scanline */ process_trailing_pixels 1, 1, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head advance_to_next_scanline 0b .if regs_shortage pop {r0, r1} .endif cleanup pop {r4-r12, pc} /* exit */ /* * This is the start of the loop, designed to process images with small width * (less than pixblock_size * 2 pixels). In this case neither pipelining * nor prefetch are used. */ 8: /* Process exactly pixblock_size pixels if needed */ tst W, #pixblock_size beq 1f pixld pixblock_size, dst_r_bpp, \ (dst_r_basereg - pixblock_size * dst_r_bpp / 64), DST_R fetch_src_pixblock pixld pixblock_size, mask_bpp, \ (mask_basereg - pixblock_size * mask_bpp / 64), MASK process_pixblock_head process_pixblock_tail pixst pixblock_size, dst_w_bpp, \ (dst_w_basereg - pixblock_size * dst_w_bpp / 64), DST_W 1: /* Process the remaining trailing pixels in the scanline */ process_trailing_pixels 0, 0, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head advance_to_next_scanline 8b 9: .if regs_shortage pop {r0, r1} .endif cleanup pop {r4-r12, pc} /* exit */ .purgem fetch_src_pixblock .purgem pixld_src .unreq SRC .unreq MASK .unreq DST_R .unreq DST_W .unreq ORIG_W .unreq W .unreq H .unreq SRC_STRIDE .unreq DST_STRIDE .unreq MASK_STRIDE .unreq PF_CTL .unreq PF_X .unreq PF_SRC .unreq PF_DST .unreq PF_MASK .unreq DUMMY .endfunc .endm /* * A simplified variant of function generation template for a single * scanline processing (for implementing pixman combine functions) */ .macro generate_composite_function_scanline use_nearest_scaling, \ fname, \ src_bpp_, \ mask_bpp_, \ dst_w_bpp_, \ flags, \ pixblock_size_, \ init, \ cleanup, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head, \ dst_w_basereg_ = 28, \ dst_r_basereg_ = 4, \ src_basereg_ = 0, \ mask_basereg_ = 24 pixman_asm_function fname .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_NONE /* * Make some macro arguments globally visible and accessible * from other macros */ .set src_bpp, src_bpp_ .set mask_bpp, mask_bpp_ .set dst_w_bpp, dst_w_bpp_ .set pixblock_size, pixblock_size_ .set dst_w_basereg, dst_w_basereg_ .set dst_r_basereg, dst_r_basereg_ .set src_basereg, src_basereg_ .set mask_basereg, mask_basereg_ .if use_nearest_scaling != 0 /* * Assign symbolic names to registers for nearest scaling */ W .req r0 DST_W .req r1 SRC .req r2 VX .req r3 UNIT_X .req ip MASK .req lr TMP1 .req r4 TMP2 .req r5 DST_R .req r6 SRC_WIDTH_FIXED .req r7 .macro pixld_src x:vararg pixld_s x .endm ldr UNIT_X, [sp] push {r4-r8, lr} ldr SRC_WIDTH_FIXED, [sp, #(24 + 4)] .if mask_bpp != 0 ldr MASK, [sp, #(24 + 8)] .endif .else /* * Assign symbolic names to registers */ W .req r0 /* width (is updated during processing) */ DST_W .req r1 /* destination buffer pointer for writes */ SRC .req r2 /* source buffer pointer */ DST_R .req ip /* destination buffer pointer for reads */ MASK .req r3 /* mask pointer */ .macro pixld_src x:vararg pixld x .endm .endif .if (((flags) & FLAG_DST_READWRITE) != 0) .set dst_r_bpp, dst_w_bpp .else .set dst_r_bpp, 0 .endif .if (((flags) & FLAG_DEINTERLEAVE_32BPP) != 0) .set DEINTERLEAVE_32BPP_ENABLED, 1 .else .set DEINTERLEAVE_32BPP_ENABLED, 0 .endif .macro fetch_src_pixblock pixld_src pixblock_size, src_bpp, \ (src_basereg - pixblock_size * src_bpp / 64), SRC .endm init mov DST_R, DST_W cmp W, #pixblock_size blt 8f ensure_destination_ptr_alignment process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head subs W, W, #pixblock_size blt 7f /* Implement "head (tail_head) ... (tail_head) tail" loop pattern */ pixld_a pixblock_size, dst_r_bpp, \ (dst_r_basereg - pixblock_size * dst_r_bpp / 64), DST_R fetch_src_pixblock pixld pixblock_size, mask_bpp, \ (mask_basereg - pixblock_size * mask_bpp / 64), MASK process_pixblock_head subs W, W, #pixblock_size blt 2f 1: process_pixblock_tail_head subs W, W, #pixblock_size bge 1b 2: process_pixblock_tail pixst_a pixblock_size, dst_w_bpp, \ (dst_w_basereg - pixblock_size * dst_w_bpp / 64), DST_W 7: /* Process the remaining trailing pixels in the scanline (dst aligned) */ process_trailing_pixels 0, 1, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head cleanup .if use_nearest_scaling != 0 pop {r4-r8, pc} /* exit */ .else bx lr /* exit */ .endif 8: /* Process the remaining trailing pixels in the scanline (dst unaligned) */ process_trailing_pixels 0, 0, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head cleanup .if use_nearest_scaling != 0 pop {r4-r8, pc} /* exit */ .unreq DST_R .unreq SRC .unreq W .unreq VX .unreq UNIT_X .unreq TMP1 .unreq TMP2 .unreq DST_W .unreq MASK .unreq SRC_WIDTH_FIXED .else bx lr /* exit */ .unreq SRC .unreq MASK .unreq DST_R .unreq DST_W .unreq W .endif .purgem fetch_src_pixblock .purgem pixld_src .endfunc .endm .macro generate_composite_function_single_scanline x:vararg generate_composite_function_scanline 0, x .endm .macro generate_composite_function_nearest_scanline x:vararg generate_composite_function_scanline 1, x .endm /* Default prologue/epilogue, nothing special needs to be done */ .macro default_init .endm .macro default_cleanup .endm /* * Prologue/epilogue variant which additionally saves/restores d8-d15 * registers (they need to be saved/restored by callee according to ABI). * This is required if the code needs to use all the NEON registers. */ .macro default_init_need_all_regs vpush {d8-d15} .endm .macro default_cleanup_need_all_regs vpop {d8-d15} .endm /******************************************************************************/ /* * Conversion of 8 r5g6b6 pixels packed in 128-bit register (in) * into a planar a8r8g8b8 format (with a, r, g, b color components * stored into 64-bit registers out_a, out_r, out_g, out_b respectively). * * Warning: the conversion is destructive and the original * value (in) is lost. */ .macro convert_0565_to_8888 in, out_a, out_r, out_g, out_b vshrn.u16 out_r, in, #8 vshrn.u16 out_g, in, #3 vsli.u16 in, in, #5 vmov.u8 out_a, #255 vsri.u8 out_r, out_r, #5 vsri.u8 out_g, out_g, #6 vshrn.u16 out_b, in, #2 .endm .macro convert_0565_to_x888 in, out_r, out_g, out_b vshrn.u16 out_r, in, #8 vshrn.u16 out_g, in, #3 vsli.u16 in, in, #5 vsri.u8 out_r, out_r, #5 vsri.u8 out_g, out_g, #6 vshrn.u16 out_b, in, #2 .endm /* * Conversion from planar a8r8g8b8 format (with a, r, g, b color components * in 64-bit registers in_a, in_r, in_g, in_b respectively) into 8 r5g6b6 * pixels packed in 128-bit register (out). Requires two temporary 128-bit * registers (tmp1, tmp2) */ .macro convert_8888_to_0565 in_r, in_g, in_b, out, tmp1, tmp2 vshll.u8 tmp1, in_g, #8 vshll.u8 out, in_r, #8 vshll.u8 tmp2, in_b, #8 vsri.u16 out, tmp1, #5 vsri.u16 out, tmp2, #11 .endm /* * Conversion of four r5g6b5 pixels (in) to four x8r8g8b8 pixels * returned in (out0, out1) registers pair. Requires one temporary * 64-bit register (tmp). 'out1' and 'in' may overlap, the original * value from 'in' is lost */ .macro convert_four_0565_to_x888_packed in, out0, out1, tmp vshl.u16 out0, in, #5 /* G top 6 bits */ vshl.u16 tmp, in, #11 /* B top 5 bits */ vsri.u16 in, in, #5 /* R is ready in top bits */ vsri.u16 out0, out0, #6 /* G is ready in top bits */ vsri.u16 tmp, tmp, #5 /* B is ready in top bits */ vshr.u16 out1, in, #8 /* R is in place */ vsri.u16 out0, tmp, #8 /* G & B is in place */ vzip.u16 out0, out1 /* everything is in place */ .endm
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-arm-neon.c
/* * Copyright © 2009 ARM Ltd, Movial Creative Technologies Oy * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of ARM Ltd not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. ARM Ltd makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. * * Author: Ian Rickards (ian.rickards@arm.com) * Author: Jonathan Morton (jonathan.morton@movial.com) * Author: Markku Vire (markku.vire@movial.com) * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include "pixman-private.h" #include "pixman-arm-common.h" PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, src_8888_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, src_x888_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, src_0565_0565, uint16_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, src_0888_0888, uint8_t, 3, uint8_t, 3) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, src_8888_0565, uint32_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, src_0565_8888, uint16_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, src_0888_8888_rev, uint8_t, 3, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, src_0888_0565_rev, uint8_t, 3, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, src_pixbuf_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, src_rpixbuf_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, add_8_8, uint8_t, 1, uint8_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, add_8888_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, over_8888_0565, uint32_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, over_8888_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, out_reverse_8_0565, uint8_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (neon, out_reverse_8_8888, uint8_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_DST (SKIP_ZERO_SRC, neon, over_n_0565, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_DST (SKIP_ZERO_SRC, neon, over_n_8888, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_DST (SKIP_ZERO_SRC, neon, over_reverse_n_8888, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_DST (0, neon, in_n_8, uint8_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (SKIP_ZERO_SRC, neon, over_n_8_0565, uint8_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (SKIP_ZERO_SRC, neon, over_n_8_8888, uint8_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (SKIP_ZERO_SRC, neon, over_n_8888_8888_ca, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (SKIP_ZERO_SRC, neon, over_n_8888_0565_ca, uint32_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (SKIP_ZERO_SRC, neon, over_n_8_8, uint8_t, 1, uint8_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (SKIP_ZERO_SRC, neon, add_n_8_8, uint8_t, 1, uint8_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (SKIP_ZERO_SRC, neon, add_n_8_8888, uint8_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (0, neon, src_n_8_8888, uint8_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (0, neon, src_n_8_8, uint8_t, 1, uint8_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_N_DST (SKIP_ZERO_MASK, neon, over_8888_n_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_N_DST (SKIP_ZERO_MASK, neon, over_8888_n_0565, uint32_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_N_DST (SKIP_ZERO_MASK, neon, over_0565_n_0565, uint16_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_N_DST (SKIP_ZERO_MASK, neon, add_8888_n_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_MASK_DST (neon, add_8_8_8, uint8_t, 1, uint8_t, 1, uint8_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_MASK_DST (neon, add_0565_8_0565, uint16_t, 1, uint8_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_MASK_DST (neon, add_8888_8_8888, uint32_t, 1, uint8_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_MASK_DST (neon, add_8888_8888_8888, uint32_t, 1, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_MASK_DST (neon, over_8888_8_8888, uint32_t, 1, uint8_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_MASK_DST (neon, over_8888_8888_8888, uint32_t, 1, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_MASK_DST (neon, over_8888_8_0565, uint32_t, 1, uint8_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_MASK_DST (neon, over_0565_8_0565, uint16_t, 1, uint8_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_SCALED_NEAREST_SRC_DST (neon, 8888_8888, OVER, uint32_t, uint32_t) PIXMAN_ARM_BIND_SCALED_NEAREST_SRC_DST (neon, 8888_0565, OVER, uint32_t, uint16_t) PIXMAN_ARM_BIND_SCALED_NEAREST_SRC_DST (neon, 8888_0565, SRC, uint32_t, uint16_t) PIXMAN_ARM_BIND_SCALED_NEAREST_SRC_DST (neon, 0565_8888, SRC, uint16_t, uint32_t) PIXMAN_ARM_BIND_SCALED_NEAREST_SRC_A8_DST (SKIP_ZERO_SRC, neon, 8888_8_0565, OVER, uint32_t, uint16_t) PIXMAN_ARM_BIND_SCALED_NEAREST_SRC_A8_DST (SKIP_ZERO_SRC, neon, 0565_8_0565, OVER, uint16_t, uint16_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_DST (0, neon, 8888_8888, SRC, uint32_t, uint32_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_DST (0, neon, 8888_0565, SRC, uint32_t, uint16_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_DST (0, neon, 0565_x888, SRC, uint16_t, uint32_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_DST (0, neon, 0565_0565, SRC, uint16_t, uint16_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_DST (SKIP_ZERO_SRC, neon, 8888_8888, OVER, uint32_t, uint32_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_DST (SKIP_ZERO_SRC, neon, 8888_8888, ADD, uint32_t, uint32_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_A8_DST (0, neon, 8888_8_8888, SRC, uint32_t, uint32_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_A8_DST (0, neon, 8888_8_0565, SRC, uint32_t, uint16_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_A8_DST (0, neon, 0565_8_x888, SRC, uint16_t, uint32_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_A8_DST (0, neon, 0565_8_0565, SRC, uint16_t, uint16_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_A8_DST (SKIP_ZERO_SRC, neon, 8888_8_8888, OVER, uint32_t, uint32_t) PIXMAN_ARM_BIND_SCALED_BILINEAR_SRC_A8_DST (SKIP_ZERO_SRC, neon, 8888_8_8888, ADD, uint32_t, uint32_t) void pixman_composite_src_n_8_asm_neon (int32_t w, int32_t h, uint8_t *dst, int32_t dst_stride, uint8_t src); void pixman_composite_src_n_0565_asm_neon (int32_t w, int32_t h, uint16_t *dst, int32_t dst_stride, uint16_t src); void pixman_composite_src_n_8888_asm_neon (int32_t w, int32_t h, uint32_t *dst, int32_t dst_stride, uint32_t src); static pixman_bool_t arm_neon_fill (pixman_implementation_t *imp, uint32_t * bits, int stride, int bpp, int x, int y, int width, int height, uint32_t _xor) { /* stride is always multiple of 32bit units in pixman */ uint32_t byte_stride = stride * sizeof(uint32_t); switch (bpp) { case 8: pixman_composite_src_n_8_asm_neon ( width, height, (uint8_t *)(((char *) bits) + y * byte_stride + x), byte_stride, _xor & 0xff); return TRUE; case 16: pixman_composite_src_n_0565_asm_neon ( width, height, (uint16_t *)(((char *) bits) + y * byte_stride + x * 2), byte_stride / 2, _xor & 0xffff); return TRUE; case 32: pixman_composite_src_n_8888_asm_neon ( width, height, (uint32_t *)(((char *) bits) + y * byte_stride + x * 4), byte_stride / 4, _xor); return TRUE; default: return FALSE; } } static pixman_bool_t arm_neon_blt (pixman_implementation_t *imp, uint32_t * src_bits, uint32_t * dst_bits, int src_stride, int dst_stride, int src_bpp, int dst_bpp, int src_x, int src_y, int dest_x, int dest_y, int width, int height) { if (src_bpp != dst_bpp) return FALSE; switch (src_bpp) { case 16: pixman_composite_src_0565_0565_asm_neon ( width, height, (uint16_t *)(((char *) dst_bits) + dest_y * dst_stride * 4 + dest_x * 2), dst_stride * 2, (uint16_t *)(((char *) src_bits) + src_y * src_stride * 4 + src_x * 2), src_stride * 2); return TRUE; case 32: pixman_composite_src_8888_8888_asm_neon ( width, height, (uint32_t *)(((char *) dst_bits) + dest_y * dst_stride * 4 + dest_x * 4), dst_stride, (uint32_t *)(((char *) src_bits) + src_y * src_stride * 4 + src_x * 4), src_stride); return TRUE; default: return FALSE; } } static const pixman_fast_path_t arm_neon_fast_paths[] = { PIXMAN_STD_FAST_PATH (SRC, r5g6b5, null, r5g6b5, neon_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, b5g6r5, null, b5g6r5, neon_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, a8r8g8b8, null, r5g6b5, neon_composite_src_8888_0565), PIXMAN_STD_FAST_PATH (SRC, x8r8g8b8, null, r5g6b5, neon_composite_src_8888_0565), PIXMAN_STD_FAST_PATH (SRC, a8b8g8r8, null, b5g6r5, neon_composite_src_8888_0565), PIXMAN_STD_FAST_PATH (SRC, x8b8g8r8, null, b5g6r5, neon_composite_src_8888_0565), PIXMAN_STD_FAST_PATH (SRC, r5g6b5, null, a8r8g8b8, neon_composite_src_0565_8888), PIXMAN_STD_FAST_PATH (SRC, r5g6b5, null, x8r8g8b8, neon_composite_src_0565_8888), PIXMAN_STD_FAST_PATH (SRC, b5g6r5, null, a8b8g8r8, neon_composite_src_0565_8888), PIXMAN_STD_FAST_PATH (SRC, b5g6r5, null, x8b8g8r8, neon_composite_src_0565_8888), PIXMAN_STD_FAST_PATH (SRC, a8r8g8b8, null, x8r8g8b8, neon_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, x8r8g8b8, null, x8r8g8b8, neon_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, a8b8g8r8, null, x8b8g8r8, neon_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, x8b8g8r8, null, x8b8g8r8, neon_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, a8r8g8b8, null, a8r8g8b8, neon_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, a8b8g8r8, null, a8b8g8r8, neon_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, x8r8g8b8, null, a8r8g8b8, neon_composite_src_x888_8888), PIXMAN_STD_FAST_PATH (SRC, x8b8g8r8, null, a8b8g8r8, neon_composite_src_x888_8888), PIXMAN_STD_FAST_PATH (SRC, r8g8b8, null, r8g8b8, neon_composite_src_0888_0888), PIXMAN_STD_FAST_PATH (SRC, b8g8r8, null, x8r8g8b8, neon_composite_src_0888_8888_rev), PIXMAN_STD_FAST_PATH (SRC, b8g8r8, null, r5g6b5, neon_composite_src_0888_0565_rev), PIXMAN_STD_FAST_PATH (SRC, pixbuf, pixbuf, a8r8g8b8, neon_composite_src_pixbuf_8888), PIXMAN_STD_FAST_PATH (SRC, pixbuf, pixbuf, a8b8g8r8, neon_composite_src_rpixbuf_8888), PIXMAN_STD_FAST_PATH (SRC, rpixbuf, rpixbuf, a8r8g8b8, neon_composite_src_rpixbuf_8888), PIXMAN_STD_FAST_PATH (SRC, rpixbuf, rpixbuf, a8b8g8r8, neon_composite_src_pixbuf_8888), PIXMAN_STD_FAST_PATH (SRC, solid, a8, a8r8g8b8, neon_composite_src_n_8_8888), PIXMAN_STD_FAST_PATH (SRC, solid, a8, x8r8g8b8, neon_composite_src_n_8_8888), PIXMAN_STD_FAST_PATH (SRC, solid, a8, a8b8g8r8, neon_composite_src_n_8_8888), PIXMAN_STD_FAST_PATH (SRC, solid, a8, x8b8g8r8, neon_composite_src_n_8_8888), PIXMAN_STD_FAST_PATH (SRC, solid, a8, a8, neon_composite_src_n_8_8), PIXMAN_STD_FAST_PATH (OVER, solid, a8, a8, neon_composite_over_n_8_8), PIXMAN_STD_FAST_PATH (OVER, solid, a8, r5g6b5, neon_composite_over_n_8_0565), PIXMAN_STD_FAST_PATH (OVER, solid, a8, b5g6r5, neon_composite_over_n_8_0565), PIXMAN_STD_FAST_PATH (OVER, solid, a8, a8r8g8b8, neon_composite_over_n_8_8888), PIXMAN_STD_FAST_PATH (OVER, solid, a8, x8r8g8b8, neon_composite_over_n_8_8888), PIXMAN_STD_FAST_PATH (OVER, solid, a8, a8b8g8r8, neon_composite_over_n_8_8888), PIXMAN_STD_FAST_PATH (OVER, solid, a8, x8b8g8r8, neon_composite_over_n_8_8888), PIXMAN_STD_FAST_PATH (OVER, solid, null, r5g6b5, neon_composite_over_n_0565), PIXMAN_STD_FAST_PATH (OVER, solid, null, a8r8g8b8, neon_composite_over_n_8888), PIXMAN_STD_FAST_PATH (OVER, solid, null, x8r8g8b8, neon_composite_over_n_8888), PIXMAN_STD_FAST_PATH_CA (OVER, solid, a8r8g8b8, a8r8g8b8, neon_composite_over_n_8888_8888_ca), PIXMAN_STD_FAST_PATH_CA (OVER, solid, a8r8g8b8, x8r8g8b8, neon_composite_over_n_8888_8888_ca), PIXMAN_STD_FAST_PATH_CA (OVER, solid, a8b8g8r8, a8b8g8r8, neon_composite_over_n_8888_8888_ca), PIXMAN_STD_FAST_PATH_CA (OVER, solid, a8b8g8r8, x8b8g8r8, neon_composite_over_n_8888_8888_ca), PIXMAN_STD_FAST_PATH_CA (OVER, solid, a8r8g8b8, r5g6b5, neon_composite_over_n_8888_0565_ca), PIXMAN_STD_FAST_PATH_CA (OVER, solid, a8b8g8r8, b5g6r5, neon_composite_over_n_8888_0565_ca), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, solid, a8r8g8b8, neon_composite_over_8888_n_8888), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, solid, x8r8g8b8, neon_composite_over_8888_n_8888), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, solid, r5g6b5, neon_composite_over_8888_n_0565), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, solid, b5g6r5, neon_composite_over_8888_n_0565), PIXMAN_STD_FAST_PATH (OVER, r5g6b5, solid, r5g6b5, neon_composite_over_0565_n_0565), PIXMAN_STD_FAST_PATH (OVER, b5g6r5, solid, b5g6r5, neon_composite_over_0565_n_0565), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, a8, a8r8g8b8, neon_composite_over_8888_8_8888), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, a8, x8r8g8b8, neon_composite_over_8888_8_8888), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, a8, a8b8g8r8, neon_composite_over_8888_8_8888), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, a8, x8b8g8r8, neon_composite_over_8888_8_8888), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, a8, r5g6b5, neon_composite_over_8888_8_0565), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, a8, b5g6r5, neon_composite_over_8888_8_0565), PIXMAN_STD_FAST_PATH (OVER, r5g6b5, a8, r5g6b5, neon_composite_over_0565_8_0565), PIXMAN_STD_FAST_PATH (OVER, b5g6r5, a8, b5g6r5, neon_composite_over_0565_8_0565), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, a8r8g8b8, a8r8g8b8, neon_composite_over_8888_8888_8888), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, null, r5g6b5, neon_composite_over_8888_0565), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, null, b5g6r5, neon_composite_over_8888_0565), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, null, a8r8g8b8, neon_composite_over_8888_8888), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, null, x8r8g8b8, neon_composite_over_8888_8888), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, null, a8b8g8r8, neon_composite_over_8888_8888), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, null, x8b8g8r8, neon_composite_over_8888_8888), PIXMAN_STD_FAST_PATH (OVER, x8r8g8b8, null, a8r8g8b8, neon_composite_src_x888_8888), PIXMAN_STD_FAST_PATH (OVER, x8b8g8r8, null, a8b8g8r8, neon_composite_src_x888_8888), PIXMAN_STD_FAST_PATH (ADD, solid, a8, a8, neon_composite_add_n_8_8), PIXMAN_STD_FAST_PATH (ADD, solid, a8, a8r8g8b8, neon_composite_add_n_8_8888), PIXMAN_STD_FAST_PATH (ADD, solid, a8, a8b8g8r8, neon_composite_add_n_8_8888), PIXMAN_STD_FAST_PATH (ADD, a8, a8, a8, neon_composite_add_8_8_8), PIXMAN_STD_FAST_PATH (ADD, r5g6b5, a8, r5g6b5, neon_composite_add_0565_8_0565), PIXMAN_STD_FAST_PATH (ADD, b5g6r5, a8, b5g6r5, neon_composite_add_0565_8_0565), PIXMAN_STD_FAST_PATH (ADD, a8r8g8b8, a8, a8r8g8b8, neon_composite_add_8888_8_8888), PIXMAN_STD_FAST_PATH (ADD, a8b8g8r8, a8, a8b8g8r8, neon_composite_add_8888_8_8888), PIXMAN_STD_FAST_PATH (ADD, a8r8g8b8, a8r8g8b8, a8r8g8b8, neon_composite_add_8888_8888_8888), PIXMAN_STD_FAST_PATH (ADD, a8r8g8b8, solid, a8r8g8b8, neon_composite_add_8888_n_8888), PIXMAN_STD_FAST_PATH (ADD, a8b8g8r8, solid, a8b8g8r8, neon_composite_add_8888_n_8888), PIXMAN_STD_FAST_PATH (ADD, a8, null, a8, neon_composite_add_8_8), PIXMAN_STD_FAST_PATH (ADD, a8r8g8b8, null, a8r8g8b8, neon_composite_add_8888_8888), PIXMAN_STD_FAST_PATH (ADD, a8b8g8r8, null, a8b8g8r8, neon_composite_add_8888_8888), PIXMAN_STD_FAST_PATH (IN, solid, null, a8, neon_composite_in_n_8), PIXMAN_STD_FAST_PATH (OVER_REVERSE, solid, null, a8r8g8b8, neon_composite_over_reverse_n_8888), PIXMAN_STD_FAST_PATH (OVER_REVERSE, solid, null, a8b8g8r8, neon_composite_over_reverse_n_8888), PIXMAN_STD_FAST_PATH (OUT_REVERSE, a8, null, r5g6b5, neon_composite_out_reverse_8_0565), PIXMAN_STD_FAST_PATH (OUT_REVERSE, a8, null, b5g6r5, neon_composite_out_reverse_8_0565), PIXMAN_STD_FAST_PATH (OUT_REVERSE, a8, null, a8r8g8b8, neon_composite_out_reverse_8_8888), PIXMAN_STD_FAST_PATH (OUT_REVERSE, a8, null, a8b8g8r8, neon_composite_out_reverse_8_8888), SIMPLE_NEAREST_FAST_PATH (OVER, a8r8g8b8, a8r8g8b8, neon_8888_8888), SIMPLE_NEAREST_FAST_PATH (OVER, a8b8g8r8, a8b8g8r8, neon_8888_8888), SIMPLE_NEAREST_FAST_PATH (OVER, a8r8g8b8, x8r8g8b8, neon_8888_8888), SIMPLE_NEAREST_FAST_PATH (OVER, a8b8g8r8, x8b8g8r8, neon_8888_8888), SIMPLE_NEAREST_FAST_PATH (OVER, a8r8g8b8, r5g6b5, neon_8888_0565), SIMPLE_NEAREST_FAST_PATH (OVER, a8b8g8r8, b5g6r5, neon_8888_0565), SIMPLE_NEAREST_FAST_PATH (SRC, a8r8g8b8, r5g6b5, neon_8888_0565), SIMPLE_NEAREST_FAST_PATH (SRC, x8r8g8b8, r5g6b5, neon_8888_0565), SIMPLE_NEAREST_FAST_PATH (SRC, a8b8g8r8, b5g6r5, neon_8888_0565), SIMPLE_NEAREST_FAST_PATH (SRC, x8b8g8r8, b5g6r5, neon_8888_0565), SIMPLE_NEAREST_FAST_PATH (SRC, b5g6r5, x8b8g8r8, neon_0565_8888), SIMPLE_NEAREST_FAST_PATH (SRC, r5g6b5, x8r8g8b8, neon_0565_8888), /* Note: NONE repeat is not supported yet */ SIMPLE_NEAREST_FAST_PATH_COVER (SRC, r5g6b5, a8r8g8b8, neon_0565_8888), SIMPLE_NEAREST_FAST_PATH_COVER (SRC, b5g6r5, a8b8g8r8, neon_0565_8888), SIMPLE_NEAREST_FAST_PATH_PAD (SRC, r5g6b5, a8r8g8b8, neon_0565_8888), SIMPLE_NEAREST_FAST_PATH_PAD (SRC, b5g6r5, a8b8g8r8, neon_0565_8888), PIXMAN_ARM_SIMPLE_NEAREST_A8_MASK_FAST_PATH (OVER, a8r8g8b8, r5g6b5, neon_8888_8_0565), PIXMAN_ARM_SIMPLE_NEAREST_A8_MASK_FAST_PATH (OVER, a8b8g8r8, b5g6r5, neon_8888_8_0565), PIXMAN_ARM_SIMPLE_NEAREST_A8_MASK_FAST_PATH (OVER, r5g6b5, r5g6b5, neon_0565_8_0565), PIXMAN_ARM_SIMPLE_NEAREST_A8_MASK_FAST_PATH (OVER, b5g6r5, b5g6r5, neon_0565_8_0565), SIMPLE_BILINEAR_FAST_PATH (SRC, a8r8g8b8, a8r8g8b8, neon_8888_8888), SIMPLE_BILINEAR_FAST_PATH (SRC, a8r8g8b8, x8r8g8b8, neon_8888_8888), SIMPLE_BILINEAR_FAST_PATH (SRC, x8r8g8b8, x8r8g8b8, neon_8888_8888), SIMPLE_BILINEAR_FAST_PATH (SRC, a8r8g8b8, r5g6b5, neon_8888_0565), SIMPLE_BILINEAR_FAST_PATH (SRC, x8r8g8b8, r5g6b5, neon_8888_0565), SIMPLE_BILINEAR_FAST_PATH (SRC, r5g6b5, x8r8g8b8, neon_0565_x888), SIMPLE_BILINEAR_FAST_PATH (SRC, r5g6b5, r5g6b5, neon_0565_0565), SIMPLE_BILINEAR_FAST_PATH (OVER, a8r8g8b8, a8r8g8b8, neon_8888_8888), SIMPLE_BILINEAR_FAST_PATH (OVER, a8r8g8b8, x8r8g8b8, neon_8888_8888), SIMPLE_BILINEAR_FAST_PATH (ADD, a8r8g8b8, a8r8g8b8, neon_8888_8888), SIMPLE_BILINEAR_FAST_PATH (ADD, a8r8g8b8, x8r8g8b8, neon_8888_8888), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (SRC, a8r8g8b8, a8r8g8b8, neon_8888_8_8888), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (SRC, a8r8g8b8, x8r8g8b8, neon_8888_8_8888), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (SRC, x8r8g8b8, x8r8g8b8, neon_8888_8_8888), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (SRC, a8r8g8b8, r5g6b5, neon_8888_8_0565), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (SRC, x8r8g8b8, r5g6b5, neon_8888_8_0565), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (SRC, r5g6b5, x8r8g8b8, neon_0565_8_x888), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (SRC, r5g6b5, r5g6b5, neon_0565_8_0565), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (OVER, a8r8g8b8, a8r8g8b8, neon_8888_8_8888), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (OVER, a8r8g8b8, x8r8g8b8, neon_8888_8_8888), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (ADD, a8r8g8b8, a8r8g8b8, neon_8888_8_8888), SIMPLE_BILINEAR_A8_MASK_FAST_PATH (ADD, a8r8g8b8, x8r8g8b8, neon_8888_8_8888), { PIXMAN_OP_NONE }, }; #define BIND_COMBINE_U(name) \ void \ pixman_composite_scanline_##name##_mask_asm_neon (int32_t w, \ const uint32_t *dst, \ const uint32_t *src, \ const uint32_t *mask); \ \ void \ pixman_composite_scanline_##name##_asm_neon (int32_t w, \ const uint32_t *dst, \ const uint32_t *src); \ \ static void \ neon_combine_##name##_u (pixman_implementation_t *imp, \ pixman_op_t op, \ uint32_t * dest, \ const uint32_t * src, \ const uint32_t * mask, \ int width) \ { \ if (mask) \ pixman_composite_scanline_##name##_mask_asm_neon (width, dest, \ src, mask); \ else \ pixman_composite_scanline_##name##_asm_neon (width, dest, src); \ } BIND_COMBINE_U (over) BIND_COMBINE_U (add) BIND_COMBINE_U (out_reverse) pixman_implementation_t * _pixman_implementation_create_arm_neon (pixman_implementation_t *fallback) { pixman_implementation_t *imp = _pixman_implementation_create (fallback, arm_neon_fast_paths); imp->combine_32[PIXMAN_OP_OVER] = neon_combine_over_u; imp->combine_32[PIXMAN_OP_ADD] = neon_combine_add_u; imp->combine_32[PIXMAN_OP_OUT_REVERSE] = neon_combine_out_reverse_u; imp->blt = arm_neon_blt; imp->fill = arm_neon_fill; return imp; }
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-arm-simd-asm.h
/* * Copyright © 2012 Raspberry Pi Foundation * Copyright © 2012 RISC OS Open Ltd * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of the copyright holders not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. The copyright holders make no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. * * Author: Ben Avison (bavison@riscosopen.org) * */ /* * Because the alignment of pixel data to cachelines, and even the number of * cachelines per row can vary from row to row, and because of the need to * preload each scanline once and only once, this prefetch strategy treats * each row of pixels independently. When a pixel row is long enough, there * are three distinct phases of prefetch: * * an inner loop section, where each time a cacheline of data is * processed, another cacheline is preloaded (the exact distance ahead is * determined empirically using profiling results from lowlevel-blt-bench) * * a leading section, where enough cachelines are preloaded to ensure no * cachelines escape being preloaded when the inner loop starts * * a trailing section, where a limited number (0 or more) of cachelines * are preloaded to deal with data (if any) that hangs off the end of the * last iteration of the inner loop, plus any trailing bytes that were not * enough to make up one whole iteration of the inner loop * * There are (in general) three distinct code paths, selected between * depending upon how long the pixel row is. If it is long enough that there * is at least one iteration of the inner loop (as described above) then * this is described as the "wide" case. If it is shorter than that, but * there are still enough bytes output that there is at least one 16-byte- * long, 16-byte-aligned write to the destination (the optimum type of * write), then this is the "medium" case. If it is not even this long, then * this is the "narrow" case, and there is no attempt to align writes to * 16-byte boundaries. In the "medium" and "narrow" cases, all the * cachelines containing data from the pixel row are prefetched up-front. */ /* * Determine whether we put the arguments on the stack for debugging. */ #undef DEBUG_PARAMS /* * Bit flags for 'generate_composite_function' macro which are used * to tune generated functions behavior. */ .set FLAG_DST_WRITEONLY, 0 .set FLAG_DST_READWRITE, 1 .set FLAG_COND_EXEC, 0 .set FLAG_BRANCH_OVER, 2 .set FLAG_PROCESS_PRESERVES_PSR, 0 .set FLAG_PROCESS_CORRUPTS_PSR, 4 .set FLAG_PROCESS_DOESNT_STORE, 0 .set FLAG_PROCESS_DOES_STORE, 8 /* usually because it needs to conditionally skip it */ .set FLAG_NO_SPILL_LINE_VARS, 0 .set FLAG_SPILL_LINE_VARS_WIDE, 16 .set FLAG_SPILL_LINE_VARS_NON_WIDE, 32 .set FLAG_SPILL_LINE_VARS, 48 .set FLAG_PROCESS_CORRUPTS_SCRATCH, 0 .set FLAG_PROCESS_PRESERVES_SCRATCH, 64 .set FLAG_PROCESS_PRESERVES_WK0, 0 .set FLAG_PROCESS_CORRUPTS_WK0, 128 /* if possible, use the specified register(s) instead so WK0 can hold number of leading pixels */ .set FLAG_PRELOAD_DST, 0 .set FLAG_NO_PRELOAD_DST, 256 /* * Number of bytes by which to adjust preload offset of destination * buffer (allows preload instruction to be moved before the load(s)) */ .set DST_PRELOAD_BIAS, 0 /* * Offset into stack where mask and source pointer/stride can be accessed. */ #ifdef DEBUG_PARAMS .set ARGS_STACK_OFFSET, (9*4+9*4) #else .set ARGS_STACK_OFFSET, (9*4) #endif /* * Offset into stack where space allocated during init macro can be accessed. */ .set LOCALS_STACK_OFFSET, 0 /* * Constants for selecting preferable prefetch type. */ .set PREFETCH_TYPE_NONE, 0 .set PREFETCH_TYPE_STANDARD, 1 /* * Definitions of macros for load/store of pixel data. */ .macro pixldst op, cond=al, numbytes, reg0, reg1, reg2, reg3, base, unaligned=0 .if numbytes == 16 .if unaligned == 1 op&r&cond WK&reg0, [base], #4 op&r&cond WK&reg1, [base], #4 op&r&cond WK&reg2, [base], #4 op&r&cond WK&reg3, [base], #4 .else op&m&cond&ia base!, {WK&reg0,WK&reg1,WK&reg2,WK&reg3} .endif .elseif numbytes == 8 .if unaligned == 1 op&r&cond WK&reg0, [base], #4 op&r&cond WK&reg1, [base], #4 .else op&m&cond&ia base!, {WK&reg0,WK&reg1} .endif .elseif numbytes == 4 op&r&cond WK&reg0, [base], #4 .elseif numbytes == 2 op&r&cond&h WK&reg0, [base], #2 .elseif numbytes == 1 op&r&cond&b WK&reg0, [base], #1 .else .error "unsupported size: numbytes" .endif .endm .macro pixst_baseupdated cond, numbytes, reg0, reg1, reg2, reg3, base .if numbytes == 16 stm&cond&db base, {WK&reg0,WK&reg1,WK&reg2,WK&reg3} .elseif numbytes == 8 stm&cond&db base, {WK&reg0,WK&reg1} .elseif numbytes == 4 str&cond WK&reg0, [base, #-4] .elseif numbytes == 2 str&cond&h WK&reg0, [base, #-2] .elseif numbytes == 1 str&cond&b WK&reg0, [base, #-1] .else .error "unsupported size: numbytes" .endif .endm .macro pixld cond, numbytes, firstreg, base, unaligned pixldst ld, cond, numbytes, %(firstreg+0), %(firstreg+1), %(firstreg+2), %(firstreg+3), base, unaligned .endm .macro pixst cond, numbytes, firstreg, base .if (flags) & FLAG_DST_READWRITE pixst_baseupdated cond, numbytes, %(firstreg+0), %(firstreg+1), %(firstreg+2), %(firstreg+3), base .else pixldst st, cond, numbytes, %(firstreg+0), %(firstreg+1), %(firstreg+2), %(firstreg+3), base .endif .endm .macro PF a, x:vararg .if (PREFETCH_TYPE_CURRENT == PREFETCH_TYPE_STANDARD) a x .endif .endm .macro preload_leading_step1 bpp, ptr, base /* If the destination is already 16-byte aligned, then we need to preload * between 0 and prefetch_distance (inclusive) cache lines ahead so there * are no gaps when the inner loop starts. */ .if bpp > 0 PF bic, ptr, base, #31 .set OFFSET, 0 .rept prefetch_distance+1 PF pld, [ptr, #OFFSET] .set OFFSET, OFFSET+32 .endr .endif .endm .macro preload_leading_step2 bpp, bpp_shift, ptr, base /* However, if the destination is not 16-byte aligned, we may need to * preload more cache lines than that. The question we need to ask is: * are the bytes corresponding to the leading pixels more than the amount * by which the source pointer will be rounded down for preloading, and if * so, by how many cache lines? Effectively, we want to calculate * leading_bytes = ((-dst)&15)*src_bpp/dst_bpp * inner_loop_offset = (src+leading_bytes)&31 * extra_needed = leading_bytes - inner_loop_offset * and test if extra_needed is <= 0, <= 32, or > 32 (where > 32 is only * possible when there are 4 src bytes for every 1 dst byte). */ .if bpp > 0 .ifc base,DST /* The test can be simplified further when preloading the destination */ PF tst, base, #16 PF beq, 61f .else .if bpp/dst_w_bpp == 4 PF add, SCRATCH, base, WK0, lsl #bpp_shift-dst_bpp_shift PF and, SCRATCH, SCRATCH, #31 PF rsb, SCRATCH, SCRATCH, WK0, lsl #bpp_shift-dst_bpp_shift PF sub, SCRATCH, SCRATCH, #1 /* so now ranges are -16..-1 / 0..31 / 32..63 */ PF movs, SCRATCH, SCRATCH, lsl #32-6 /* so this sets NC / nc / Nc */ PF bcs, 61f PF bpl, 60f PF pld, [ptr, #32*(prefetch_distance+2)] .else PF mov, SCRATCH, base, lsl #32-5 PF add, SCRATCH, SCRATCH, WK0, lsl #32-5+bpp_shift-dst_bpp_shift PF rsbs, SCRATCH, SCRATCH, WK0, lsl #32-5+bpp_shift-dst_bpp_shift PF bls, 61f .endif .endif 60: PF pld, [ptr, #32*(prefetch_distance+1)] 61: .endif .endm #define IS_END_OF_GROUP(INDEX,SIZE) ((SIZE) < 2 || ((INDEX) & ~((INDEX)+1)) & ((SIZE)/2)) .macro preload_middle bpp, base, scratch_holds_offset .if bpp > 0 /* prefetch distance = 256/bpp, stm distance = 128/dst_w_bpp */ .if IS_END_OF_GROUP(SUBBLOCK,256/128*dst_w_bpp/bpp) .if scratch_holds_offset PF pld, [base, SCRATCH] .else PF bic, SCRATCH, base, #31 PF pld, [SCRATCH, #32*prefetch_distance] .endif .endif .endif .endm .macro preload_trailing bpp, bpp_shift, base .if bpp > 0 .if bpp*pix_per_block > 256 /* Calculations are more complex if more than one fetch per block */ PF and, WK1, base, #31 PF add, WK1, WK1, WK0, lsl #bpp_shift PF add, WK1, WK1, #32*(bpp*pix_per_block/256-1)*(prefetch_distance+1) PF bic, SCRATCH, base, #31 80: PF pld, [SCRATCH, #32*(prefetch_distance+1)] PF add, SCRATCH, SCRATCH, #32 PF subs, WK1, WK1, #32 PF bhi, 80b .else /* If exactly one fetch per block, then we need either 0, 1 or 2 extra preloads */ PF mov, SCRATCH, base, lsl #32-5 PF adds, SCRATCH, SCRATCH, X, lsl #32-5+bpp_shift PF adceqs, SCRATCH, SCRATCH, #0 /* The instruction above has two effects: ensures Z is only * set if C was clear (so Z indicates that both shifted quantities * were 0), and clears C if Z was set (so C indicates that the sum * of the shifted quantities was greater and not equal to 32) */ PF beq, 82f PF bic, SCRATCH, base, #31 PF bcc, 81f PF pld, [SCRATCH, #32*(prefetch_distance+2)] 81: PF pld, [SCRATCH, #32*(prefetch_distance+1)] 82: .endif .endif .endm .macro preload_line narrow_case, bpp, bpp_shift, base /* "narrow_case" - just means that the macro was invoked from the "narrow" * code path rather than the "medium" one - because in the narrow case, * the row of pixels is known to output no more than 30 bytes, then * (assuming the source pixels are no wider than the the destination * pixels) they cannot possibly straddle more than 2 32-byte cachelines, * meaning there's no need for a loop. * "bpp" - number of bits per pixel in the channel (source, mask or * destination) that's being preloaded, or 0 if this channel is not used * for reading * "bpp_shift" - log2 of ("bpp"/8) (except if "bpp"=0 of course) * "base" - base address register of channel to preload (SRC, MASK or DST) */ .if bpp > 0 .if narrow_case && (bpp <= dst_w_bpp) /* In these cases, each line for each channel is in either 1 or 2 cache lines */ PF bic, WK0, base, #31 PF pld, [WK0] PF add, WK1, base, X, LSL #bpp_shift PF sub, WK1, WK1, #1 PF bic, WK1, WK1, #31 PF cmp, WK1, WK0 PF beq, 90f PF pld, [WK1] 90: .else PF bic, WK0, base, #31 PF pld, [WK0] PF add, WK1, base, X, lsl #bpp_shift PF sub, WK1, WK1, #1 PF bic, WK1, WK1, #31 PF cmp, WK1, WK0 PF beq, 92f 91: PF add, WK0, WK0, #32 PF cmp, WK0, WK1 PF pld, [WK0] PF bne, 91b 92: .endif .endif .endm .macro conditional_process1_helper cond, process_head, process_tail, numbytes, firstreg, unaligned_src, unaligned_mask, decrementx process_head cond, numbytes, firstreg, unaligned_src, unaligned_mask, 0 .if decrementx sub&cond X, X, #8*numbytes/dst_w_bpp .endif process_tail cond, numbytes, firstreg .if !((flags) & FLAG_PROCESS_DOES_STORE) pixst cond, numbytes, firstreg, DST .endif .endm .macro conditional_process1 cond, process_head, process_tail, numbytes, firstreg, unaligned_src, unaligned_mask, decrementx .if (flags) & FLAG_BRANCH_OVER .ifc cond,mi bpl 100f .endif .ifc cond,cs bcc 100f .endif .ifc cond,ne beq 100f .endif conditional_process1_helper , process_head, process_tail, numbytes, firstreg, unaligned_src, unaligned_mask, decrementx 100: .else conditional_process1_helper cond, process_head, process_tail, numbytes, firstreg, unaligned_src, unaligned_mask, decrementx .endif .endm .macro conditional_process2 test, cond1, cond2, process_head, process_tail, numbytes1, numbytes2, firstreg1, firstreg2, unaligned_src, unaligned_mask, decrementx .if (flags) & (FLAG_DST_READWRITE | FLAG_BRANCH_OVER | FLAG_PROCESS_CORRUPTS_PSR | FLAG_PROCESS_DOES_STORE) /* Can't interleave reads and writes */ test conditional_process1 cond1, process_head, process_tail, numbytes1, firstreg1, unaligned_src, unaligned_mask, decrementx .if (flags) & FLAG_PROCESS_CORRUPTS_PSR test .endif conditional_process1 cond2, process_head, process_tail, numbytes2, firstreg2, unaligned_src, unaligned_mask, decrementx .else /* Can interleave reads and writes for better scheduling */ test process_head cond1, numbytes1, firstreg1, unaligned_src, unaligned_mask, 0 process_head cond2, numbytes2, firstreg2, unaligned_src, unaligned_mask, 0 .if decrementx sub&cond1 X, X, #8*numbytes1/dst_w_bpp sub&cond2 X, X, #8*numbytes2/dst_w_bpp .endif process_tail cond1, numbytes1, firstreg1 process_tail cond2, numbytes2, firstreg2 pixst cond1, numbytes1, firstreg1, DST pixst cond2, numbytes2, firstreg2, DST .endif .endm .macro test_bits_1_0_ptr .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 movs SCRATCH, X, lsl #32-1 /* C,N = bits 1,0 of DST */ .else movs SCRATCH, WK0, lsl #32-1 /* C,N = bits 1,0 of DST */ .endif .endm .macro test_bits_3_2_ptr .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 movs SCRATCH, X, lsl #32-3 /* C,N = bits 3, 2 of DST */ .else movs SCRATCH, WK0, lsl #32-3 /* C,N = bits 3, 2 of DST */ .endif .endm .macro leading_15bytes process_head, process_tail /* On entry, WK0 bits 0-3 = number of bytes until destination is 16-byte aligned */ .set DECREMENT_X, 1 .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 .set DECREMENT_X, 0 sub X, X, WK0, lsr #dst_bpp_shift str X, [sp, #LINE_SAVED_REG_COUNT*4] mov X, WK0 .endif /* Use unaligned loads in all cases for simplicity */ .if dst_w_bpp == 8 conditional_process2 test_bits_1_0_ptr, mi, cs, process_head, process_tail, 1, 2, 1, 2, 1, 1, DECREMENT_X .elseif dst_w_bpp == 16 test_bits_1_0_ptr conditional_process1 cs, process_head, process_tail, 2, 2, 1, 1, DECREMENT_X .endif conditional_process2 test_bits_3_2_ptr, mi, cs, process_head, process_tail, 4, 8, 1, 2, 1, 1, DECREMENT_X .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 ldr X, [sp, #LINE_SAVED_REG_COUNT*4] .endif .endm .macro test_bits_3_2_pix movs SCRATCH, X, lsl #dst_bpp_shift+32-3 .endm .macro test_bits_1_0_pix .if dst_w_bpp == 8 movs SCRATCH, X, lsl #dst_bpp_shift+32-1 .else movs SCRATCH, X, lsr #1 .endif .endm .macro trailing_15bytes process_head, process_tail, unaligned_src, unaligned_mask conditional_process2 test_bits_3_2_pix, cs, mi, process_head, process_tail, 8, 4, 0, 2, unaligned_src, unaligned_mask, 0 .if dst_w_bpp == 16 test_bits_1_0_pix conditional_process1 cs, process_head, process_tail, 2, 0, unaligned_src, unaligned_mask, 0 .elseif dst_w_bpp == 8 conditional_process2 test_bits_1_0_pix, cs, mi, process_head, process_tail, 2, 1, 0, 1, unaligned_src, unaligned_mask, 0 .endif .endm .macro wide_case_inner_loop process_head, process_tail, unaligned_src, unaligned_mask, dst_alignment 110: .set SUBBLOCK, 0 /* this is a count of STMs; there can be up to 8 STMs per block */ .rept pix_per_block*dst_w_bpp/128 process_head , 16, 0, unaligned_src, unaligned_mask, 1 .if (src_bpp > 0) && (mask_bpp == 0) && ((flags) & FLAG_PROCESS_PRESERVES_SCRATCH) preload_middle src_bpp, SRC, 1 .elseif (src_bpp == 0) && (mask_bpp > 0) && ((flags) & FLAG_PROCESS_PRESERVES_SCRATCH) preload_middle mask_bpp, MASK, 1 .else preload_middle src_bpp, SRC, 0 preload_middle mask_bpp, MASK, 0 .endif .if (dst_r_bpp > 0) && ((SUBBLOCK % 2) == 0) && (((flags) & FLAG_NO_PRELOAD_DST) == 0) /* Because we know that writes are 16-byte aligned, it's relatively easy to ensure that * destination prefetches are 32-byte aligned. It's also the easiest channel to offset * preloads for, to achieve staggered prefetches for multiple channels, because there are * always two STMs per prefetch, so there is always an opposite STM on which to put the * preload. Note, no need to BIC the base register here */ PF pld, [DST, #32*prefetch_distance - dst_alignment] .endif process_tail , 16, 0 .if !((flags) & FLAG_PROCESS_DOES_STORE) pixst , 16, 0, DST .endif .set SUBBLOCK, SUBBLOCK+1 .endr subs X, X, #pix_per_block bhs 110b .endm .macro wide_case_inner_loop_and_trailing_pixels process_head, process_tail, process_inner_loop, exit_label, unaligned_src, unaligned_mask /* Destination now 16-byte aligned; we have at least one block before we have to stop preloading */ .if dst_r_bpp > 0 tst DST, #16 bne 111f process_inner_loop process_head, process_tail, unaligned_src, unaligned_mask, 16 + DST_PRELOAD_BIAS b 112f 111: .endif process_inner_loop process_head, process_tail, unaligned_src, unaligned_mask, 0 + DST_PRELOAD_BIAS 112: /* Just before the final (prefetch_distance+1) 32-byte blocks, deal with final preloads */ .if (src_bpp*pix_per_block > 256) || (mask_bpp*pix_per_block > 256) || (dst_r_bpp*pix_per_block > 256) PF and, WK0, X, #pix_per_block-1 .endif preload_trailing src_bpp, src_bpp_shift, SRC preload_trailing mask_bpp, mask_bpp_shift, MASK .if ((flags) & FLAG_NO_PRELOAD_DST) == 0 preload_trailing dst_r_bpp, dst_bpp_shift, DST .endif add X, X, #(prefetch_distance+2)*pix_per_block - 128/dst_w_bpp /* The remainder of the line is handled identically to the medium case */ medium_case_inner_loop_and_trailing_pixels process_head, process_tail,, exit_label, unaligned_src, unaligned_mask .endm .macro medium_case_inner_loop_and_trailing_pixels process_head, process_tail, unused, exit_label, unaligned_src, unaligned_mask 120: process_head , 16, 0, unaligned_src, unaligned_mask, 0 process_tail , 16, 0 .if !((flags) & FLAG_PROCESS_DOES_STORE) pixst , 16, 0, DST .endif subs X, X, #128/dst_w_bpp bhs 120b /* Trailing pixels */ tst X, #128/dst_w_bpp - 1 beq exit_label trailing_15bytes process_head, process_tail, unaligned_src, unaligned_mask .endm .macro narrow_case_inner_loop_and_trailing_pixels process_head, process_tail, unused, exit_label, unaligned_src, unaligned_mask tst X, #16*8/dst_w_bpp conditional_process1 ne, process_head, process_tail, 16, 0, unaligned_src, unaligned_mask, 0 /* Trailing pixels */ /* In narrow case, it's relatively unlikely to be aligned, so let's do without a branch here */ trailing_15bytes process_head, process_tail, unaligned_src, unaligned_mask .endm .macro switch_on_alignment action, process_head, process_tail, process_inner_loop, exit_label /* Note that if we're reading the destination, it's already guaranteed to be aligned at this point */ .if mask_bpp == 8 || mask_bpp == 16 tst MASK, #3 bne 141f .endif .if src_bpp == 8 || src_bpp == 16 tst SRC, #3 bne 140f .endif action process_head, process_tail, process_inner_loop, exit_label, 0, 0 .if src_bpp == 8 || src_bpp == 16 b exit_label 140: action process_head, process_tail, process_inner_loop, exit_label, 1, 0 .endif .if mask_bpp == 8 || mask_bpp == 16 b exit_label 141: .if src_bpp == 8 || src_bpp == 16 tst SRC, #3 bne 142f .endif action process_head, process_tail, process_inner_loop, exit_label, 0, 1 .if src_bpp == 8 || src_bpp == 16 b exit_label 142: action process_head, process_tail, process_inner_loop, exit_label, 1, 1 .endif .endif .endm .macro end_of_line restore_x, vars_spilled, loop_label, last_one .if vars_spilled /* Sadly, GAS doesn't seem have an equivalent of the DCI directive? */ /* This is ldmia sp,{} */ .word 0xE89D0000 | LINE_SAVED_REGS .endif subs Y, Y, #1 .if vars_spilled .if (LINE_SAVED_REGS) & (1<<1) str Y, [sp] .endif .endif add DST, DST, STRIDE_D .if src_bpp > 0 add SRC, SRC, STRIDE_S .endif .if mask_bpp > 0 add MASK, MASK, STRIDE_M .endif .if restore_x mov X, ORIG_W .endif bhs loop_label .ifc "last_one","" .if vars_spilled b 197f .else b 198f .endif .else .if (!vars_spilled) && ((flags) & FLAG_SPILL_LINE_VARS) b 198f .endif .endif .endm .macro generate_composite_function fname, \ src_bpp_, \ mask_bpp_, \ dst_w_bpp_, \ flags_, \ prefetch_distance_, \ init, \ newline, \ cleanup, \ process_head, \ process_tail, \ process_inner_loop pixman_asm_function fname /* * Make some macro arguments globally visible and accessible * from other macros */ .set src_bpp, src_bpp_ .set mask_bpp, mask_bpp_ .set dst_w_bpp, dst_w_bpp_ .set flags, flags_ .set prefetch_distance, prefetch_distance_ /* * Select prefetch type for this function. */ .if prefetch_distance == 0 .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_NONE .else .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_STANDARD .endif .if src_bpp == 32 .set src_bpp_shift, 2 .elseif src_bpp == 24 .set src_bpp_shift, 0 .elseif src_bpp == 16 .set src_bpp_shift, 1 .elseif src_bpp == 8 .set src_bpp_shift, 0 .elseif src_bpp == 0 .set src_bpp_shift, -1 .else .error "requested src bpp (src_bpp) is not supported" .endif .if mask_bpp == 32 .set mask_bpp_shift, 2 .elseif mask_bpp == 24 .set mask_bpp_shift, 0 .elseif mask_bpp == 8 .set mask_bpp_shift, 0 .elseif mask_bpp == 0 .set mask_bpp_shift, -1 .else .error "requested mask bpp (mask_bpp) is not supported" .endif .if dst_w_bpp == 32 .set dst_bpp_shift, 2 .elseif dst_w_bpp == 24 .set dst_bpp_shift, 0 .elseif dst_w_bpp == 16 .set dst_bpp_shift, 1 .elseif dst_w_bpp == 8 .set dst_bpp_shift, 0 .else .error "requested dst bpp (dst_w_bpp) is not supported" .endif .if (((flags) & FLAG_DST_READWRITE) != 0) .set dst_r_bpp, dst_w_bpp .else .set dst_r_bpp, 0 .endif .set pix_per_block, 16*8/dst_w_bpp .if src_bpp != 0 .if 32*8/src_bpp > pix_per_block .set pix_per_block, 32*8/src_bpp .endif .endif .if mask_bpp != 0 .if 32*8/mask_bpp > pix_per_block .set pix_per_block, 32*8/mask_bpp .endif .endif .if dst_r_bpp != 0 .if 32*8/dst_r_bpp > pix_per_block .set pix_per_block, 32*8/dst_r_bpp .endif .endif /* The standard entry conditions set up by pixman-arm-common.h are: * r0 = width (pixels) * r1 = height (rows) * r2 = pointer to top-left pixel of destination * r3 = destination stride (pixels) * [sp] = source pixel value, or pointer to top-left pixel of source * [sp,#4] = 0 or source stride (pixels) * The following arguments are unused for non-mask operations * [sp,#8] = mask pixel value, or pointer to top-left pixel of mask * [sp,#12] = 0 or mask stride (pixels) */ /* * Assign symbolic names to registers */ X .req r0 /* pixels to go on this line */ Y .req r1 /* lines to go */ DST .req r2 /* destination pixel pointer */ STRIDE_D .req r3 /* destination stride (bytes, minus width) */ SRC .req r4 /* source pixel pointer */ STRIDE_S .req r5 /* source stride (bytes, minus width) */ MASK .req r6 /* mask pixel pointer (if applicable) */ STRIDE_M .req r7 /* mask stride (bytes, minus width) */ WK0 .req r8 /* pixel data registers */ WK1 .req r9 WK2 .req r10 WK3 .req r11 SCRATCH .req r12 ORIG_W .req r14 /* width (pixels) */ push {r4-r11, lr} /* save all registers */ subs Y, Y, #1 blo 199f #ifdef DEBUG_PARAMS sub sp, sp, #9*4 #endif .if src_bpp > 0 ldr SRC, [sp, #ARGS_STACK_OFFSET] ldr STRIDE_S, [sp, #ARGS_STACK_OFFSET+4] .endif .if mask_bpp > 0 ldr MASK, [sp, #ARGS_STACK_OFFSET+8] ldr STRIDE_M, [sp, #ARGS_STACK_OFFSET+12] .endif #ifdef DEBUG_PARAMS add Y, Y, #1 stmia sp, {r0-r7,pc} sub Y, Y, #1 #endif init .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 /* Reserve a word in which to store X during leading pixels */ sub sp, sp, #4 .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET+4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET+4 .endif lsl STRIDE_D, #dst_bpp_shift /* stride in bytes */ sub STRIDE_D, STRIDE_D, X, lsl #dst_bpp_shift .if src_bpp > 0 lsl STRIDE_S, #src_bpp_shift sub STRIDE_S, STRIDE_S, X, lsl #src_bpp_shift .endif .if mask_bpp > 0 lsl STRIDE_M, #mask_bpp_shift sub STRIDE_M, STRIDE_M, X, lsl #mask_bpp_shift .endif /* Are we not even wide enough to have one 16-byte aligned 16-byte block write? */ cmp X, #2*16*8/dst_w_bpp - 1 blo 170f .if src_bpp || mask_bpp || dst_r_bpp /* Wide and medium cases are the same for fill */ /* To preload ahead on the current line, we need at least (prefetch_distance+2) 32-byte blocks on all prefetch channels */ cmp X, #(prefetch_distance+3)*pix_per_block - 1 blo 160f /* Wide case */ /* Adjust X so that the decrement instruction can also test for * inner loop termination. We want it to stop when there are * (prefetch_distance+1) complete blocks to go. */ sub X, X, #(prefetch_distance+2)*pix_per_block mov ORIG_W, X .if (flags) & FLAG_SPILL_LINE_VARS_WIDE /* This is stmdb sp!,{} */ .word 0xE92D0000 | LINE_SAVED_REGS .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET + LINE_SAVED_REG_COUNT*4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET + LINE_SAVED_REG_COUNT*4 .endif 151: /* New line */ newline preload_leading_step1 src_bpp, WK1, SRC preload_leading_step1 mask_bpp, WK2, MASK .if ((flags) & FLAG_NO_PRELOAD_DST) == 0 preload_leading_step1 dst_r_bpp, WK3, DST .endif ands WK0, DST, #15 beq 154f rsb WK0, WK0, #16 /* number of leading bytes until destination aligned */ preload_leading_step2 src_bpp, src_bpp_shift, WK1, SRC preload_leading_step2 mask_bpp, mask_bpp_shift, WK2, MASK .if ((flags) & FLAG_NO_PRELOAD_DST) == 0 preload_leading_step2 dst_r_bpp, dst_bpp_shift, WK3, DST .endif leading_15bytes process_head, process_tail 154: /* Destination now 16-byte aligned; we have at least one prefetch on each channel as well as at least one 16-byte output block */ .if (src_bpp > 0) && (mask_bpp == 0) && ((flags) & FLAG_PROCESS_PRESERVES_SCRATCH) and SCRATCH, SRC, #31 rsb SCRATCH, SCRATCH, #32*prefetch_distance .elseif (src_bpp == 0) && (mask_bpp > 0) && ((flags) & FLAG_PROCESS_PRESERVES_SCRATCH) and SCRATCH, MASK, #31 rsb SCRATCH, SCRATCH, #32*prefetch_distance .endif .ifc "process_inner_loop","" switch_on_alignment wide_case_inner_loop_and_trailing_pixels, process_head, process_tail, wide_case_inner_loop, 157f .else switch_on_alignment wide_case_inner_loop_and_trailing_pixels, process_head, process_tail, process_inner_loop, 157f .endif 157: /* Check for another line */ end_of_line 1, %((flags) & FLAG_SPILL_LINE_VARS_WIDE), 151b .if (flags) & FLAG_SPILL_LINE_VARS_WIDE .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET - LINE_SAVED_REG_COUNT*4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET - LINE_SAVED_REG_COUNT*4 .endif .endif .ltorg 160: /* Medium case */ mov ORIG_W, X .if (flags) & FLAG_SPILL_LINE_VARS_NON_WIDE /* This is stmdb sp!,{} */ .word 0xE92D0000 | LINE_SAVED_REGS .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET + LINE_SAVED_REG_COUNT*4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET + LINE_SAVED_REG_COUNT*4 .endif 161: /* New line */ newline preload_line 0, src_bpp, src_bpp_shift, SRC /* in: X, corrupts: WK0-WK1 */ preload_line 0, mask_bpp, mask_bpp_shift, MASK .if ((flags) & FLAG_NO_PRELOAD_DST) == 0 preload_line 0, dst_r_bpp, dst_bpp_shift, DST .endif sub X, X, #128/dst_w_bpp /* simplifies inner loop termination */ ands WK0, DST, #15 beq 164f rsb WK0, WK0, #16 /* number of leading bytes until destination aligned */ leading_15bytes process_head, process_tail 164: /* Destination now 16-byte aligned; we have at least one 16-byte output block */ switch_on_alignment medium_case_inner_loop_and_trailing_pixels, process_head, process_tail,, 167f 167: /* Check for another line */ end_of_line 1, %((flags) & FLAG_SPILL_LINE_VARS_NON_WIDE), 161b .ltorg 170: /* Narrow case, less than 31 bytes, so no guarantee of at least one 16-byte block */ .if dst_w_bpp < 32 mov ORIG_W, X .endif .if (flags) & FLAG_SPILL_LINE_VARS_NON_WIDE /* This is stmdb sp!,{} */ .word 0xE92D0000 | LINE_SAVED_REGS .endif 171: /* New line */ newline preload_line 1, src_bpp, src_bpp_shift, SRC /* in: X, corrupts: WK0-WK1 */ preload_line 1, mask_bpp, mask_bpp_shift, MASK .if ((flags) & FLAG_NO_PRELOAD_DST) == 0 preload_line 1, dst_r_bpp, dst_bpp_shift, DST .endif .if dst_w_bpp == 8 tst DST, #3 beq 174f 172: subs X, X, #1 blo 177f process_head , 1, 0, 1, 1, 0 process_tail , 1, 0 .if !((flags) & FLAG_PROCESS_DOES_STORE) pixst , 1, 0, DST .endif tst DST, #3 bne 172b .elseif dst_w_bpp == 16 tst DST, #2 beq 174f subs X, X, #1 blo 177f process_head , 2, 0, 1, 1, 0 process_tail , 2, 0 .if !((flags) & FLAG_PROCESS_DOES_STORE) pixst , 2, 0, DST .endif .endif 174: /* Destination now 4-byte aligned; we have 0 or more output bytes to go */ switch_on_alignment narrow_case_inner_loop_and_trailing_pixels, process_head, process_tail,, 177f 177: /* Check for another line */ end_of_line %(dst_w_bpp < 32), %((flags) & FLAG_SPILL_LINE_VARS_NON_WIDE), 171b, last_one .if (flags) & FLAG_SPILL_LINE_VARS_NON_WIDE .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET - LINE_SAVED_REG_COUNT*4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET - LINE_SAVED_REG_COUNT*4 .endif 197: .if (flags) & FLAG_SPILL_LINE_VARS add sp, sp, #LINE_SAVED_REG_COUNT*4 .endif 198: .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET-4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET-4 add sp, sp, #4 .endif cleanup #ifdef DEBUG_PARAMS add sp, sp, #9*4 /* junk the debug copy of arguments */ #endif 199: pop {r4-r11, pc} /* exit */ .ltorg .unreq X .unreq Y .unreq DST .unreq STRIDE_D .unreq SRC .unreq STRIDE_S .unreq MASK .unreq STRIDE_M .unreq WK0 .unreq WK1 .unreq WK2 .unreq WK3 .unreq SCRATCH .unreq ORIG_W .endfunc .endm .macro line_saved_regs x:vararg .set LINE_SAVED_REGS, 0 .set LINE_SAVED_REG_COUNT, 0 .irp SAVED_REG,x .ifc "SAVED_REG","Y" .set LINE_SAVED_REGS, LINE_SAVED_REGS | (1<<1) .set LINE_SAVED_REG_COUNT, LINE_SAVED_REG_COUNT + 1 .endif .ifc "SAVED_REG","STRIDE_D" .set LINE_SAVED_REGS, LINE_SAVED_REGS | (1<<3) .set LINE_SAVED_REG_COUNT, LINE_SAVED_REG_COUNT + 1 .endif .ifc "SAVED_REG","STRIDE_S" .set LINE_SAVED_REGS, LINE_SAVED_REGS | (1<<5) .set LINE_SAVED_REG_COUNT, LINE_SAVED_REG_COUNT + 1 .endif .ifc "SAVED_REG","STRIDE_M" .set LINE_SAVED_REGS, LINE_SAVED_REGS | (1<<7) .set LINE_SAVED_REG_COUNT, LINE_SAVED_REG_COUNT + 1 .endif .ifc "SAVED_REG","ORIG_W" .set LINE_SAVED_REGS, LINE_SAVED_REGS | (1<<14) .set LINE_SAVED_REG_COUNT, LINE_SAVED_REG_COUNT + 1 .endif .endr .endm .macro nop_macro x:vararg .endm
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-arm-simd.c
/* * Copyright © 2008 Mozilla Corporation * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Mozilla Corporation not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Mozilla Corporation makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. * * Author: Jeff Muizelaar (jeff@infidigm.net) * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pixman-private.h" #include "pixman-arm-common.h" #include "pixman-inlines.h" PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (armv6, src_8888_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (armv6, src_x888_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (armv6, src_0565_0565, uint16_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (armv6, src_8_8, uint8_t, 1, uint8_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (armv6, src_0565_8888, uint16_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (armv6, src_x888_0565, uint32_t, 1, uint16_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (armv6, add_8_8, uint8_t, 1, uint8_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (armv6, over_8888_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_DST (armv6, in_reverse_8888_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_DST (SKIP_ZERO_SRC, armv6, over_n_8888, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_DST (0, armv6, over_reverse_n_8888, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_SRC_N_DST (SKIP_ZERO_MASK, armv6, over_8888_n_8888, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (SKIP_ZERO_SRC, armv6, over_n_8_8888, uint8_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_FAST_PATH_N_MASK_DST (SKIP_ZERO_SRC, armv6, over_n_8888_8888_ca, uint32_t, 1, uint32_t, 1) PIXMAN_ARM_BIND_SCALED_NEAREST_SRC_DST (armv6, 0565_0565, SRC, uint16_t, uint16_t) PIXMAN_ARM_BIND_SCALED_NEAREST_SRC_DST (armv6, 8888_8888, SRC, uint32_t, uint32_t) void pixman_composite_src_n_8888_asm_armv6 (int32_t w, int32_t h, uint32_t *dst, int32_t dst_stride, uint32_t src); void pixman_composite_src_n_0565_asm_armv6 (int32_t w, int32_t h, uint16_t *dst, int32_t dst_stride, uint16_t src); void pixman_composite_src_n_8_asm_armv6 (int32_t w, int32_t h, uint8_t *dst, int32_t dst_stride, uint8_t src); static pixman_bool_t arm_simd_fill (pixman_implementation_t *imp, uint32_t * bits, int stride, /* in 32-bit words */ int bpp, int x, int y, int width, int height, uint32_t _xor) { /* stride is always multiple of 32bit units in pixman */ uint32_t byte_stride = stride * sizeof(uint32_t); switch (bpp) { case 8: pixman_composite_src_n_8_asm_armv6 ( width, height, (uint8_t *)(((char *) bits) + y * byte_stride + x), byte_stride, _xor & 0xff); return TRUE; case 16: pixman_composite_src_n_0565_asm_armv6 ( width, height, (uint16_t *)(((char *) bits) + y * byte_stride + x * 2), byte_stride / 2, _xor & 0xffff); return TRUE; case 32: pixman_composite_src_n_8888_asm_armv6 ( width, height, (uint32_t *)(((char *) bits) + y * byte_stride + x * 4), byte_stride / 4, _xor); return TRUE; default: return FALSE; } } static pixman_bool_t arm_simd_blt (pixman_implementation_t *imp, uint32_t * src_bits, uint32_t * dst_bits, int src_stride, /* in 32-bit words */ int dst_stride, /* in 32-bit words */ int src_bpp, int dst_bpp, int src_x, int src_y, int dest_x, int dest_y, int width, int height) { if (src_bpp != dst_bpp) return FALSE; switch (src_bpp) { case 8: pixman_composite_src_8_8_asm_armv6 ( width, height, (uint8_t *)(((char *) dst_bits) + dest_y * dst_stride * 4 + dest_x * 1), dst_stride * 4, (uint8_t *)(((char *) src_bits) + src_y * src_stride * 4 + src_x * 1), src_stride * 4); return TRUE; case 16: pixman_composite_src_0565_0565_asm_armv6 ( width, height, (uint16_t *)(((char *) dst_bits) + dest_y * dst_stride * 4 + dest_x * 2), dst_stride * 2, (uint16_t *)(((char *) src_bits) + src_y * src_stride * 4 + src_x * 2), src_stride * 2); return TRUE; case 32: pixman_composite_src_8888_8888_asm_armv6 ( width, height, (uint32_t *)(((char *) dst_bits) + dest_y * dst_stride * 4 + dest_x * 4), dst_stride, (uint32_t *)(((char *) src_bits) + src_y * src_stride * 4 + src_x * 4), src_stride); return TRUE; default: return FALSE; } } static const pixman_fast_path_t arm_simd_fast_paths[] = { PIXMAN_STD_FAST_PATH (SRC, a8r8g8b8, null, a8r8g8b8, armv6_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, a8b8g8r8, null, a8b8g8r8, armv6_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, a8r8g8b8, null, x8r8g8b8, armv6_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, a8b8g8r8, null, x8b8g8r8, armv6_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, x8r8g8b8, null, x8r8g8b8, armv6_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, x8b8g8r8, null, x8b8g8r8, armv6_composite_src_8888_8888), PIXMAN_STD_FAST_PATH (SRC, x8b8g8r8, null, a8b8g8r8, armv6_composite_src_x888_8888), PIXMAN_STD_FAST_PATH (SRC, x8r8g8b8, null, a8r8g8b8, armv6_composite_src_x888_8888), PIXMAN_STD_FAST_PATH (SRC, r5g6b5, null, r5g6b5, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, b5g6r5, null, b5g6r5, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, a1r5g5b5, null, a1r5g5b5, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, a1b5g5r5, null, a1b5g5r5, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, a1r5g5b5, null, x1r5g5b5, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, a1b5g5r5, null, x1b5g5r5, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, x1r5g5b5, null, x1r5g5b5, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, x1b5g5r5, null, x1b5g5r5, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, a4r4g4b4, null, a4r4g4b4, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, a4b4g4r4, null, a4b4g4r4, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, a4r4g4b4, null, x4r4g4b4, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, a4b4g4r4, null, x4b4g4r4, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, x4r4g4b4, null, x4r4g4b4, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, x4b4g4r4, null, x4b4g4r4, armv6_composite_src_0565_0565), PIXMAN_STD_FAST_PATH (SRC, a8, null, a8, armv6_composite_src_8_8), PIXMAN_STD_FAST_PATH (SRC, r3g3b2, null, r3g3b2, armv6_composite_src_8_8), PIXMAN_STD_FAST_PATH (SRC, b2g3r3, null, b2g3r3, armv6_composite_src_8_8), PIXMAN_STD_FAST_PATH (SRC, a2r2g2b2, null, a2r2g2b2, armv6_composite_src_8_8), PIXMAN_STD_FAST_PATH (SRC, a2b2g2r2, null, a2b2g2r2, armv6_composite_src_8_8), PIXMAN_STD_FAST_PATH (SRC, c8, null, c8, armv6_composite_src_8_8), PIXMAN_STD_FAST_PATH (SRC, g8, null, g8, armv6_composite_src_8_8), PIXMAN_STD_FAST_PATH (SRC, x4a4, null, x4a4, armv6_composite_src_8_8), PIXMAN_STD_FAST_PATH (SRC, x4c4, null, x4c4, armv6_composite_src_8_8), PIXMAN_STD_FAST_PATH (SRC, x4g4, null, x4g4, armv6_composite_src_8_8), PIXMAN_STD_FAST_PATH (SRC, r5g6b5, null, a8r8g8b8, armv6_composite_src_0565_8888), PIXMAN_STD_FAST_PATH (SRC, r5g6b5, null, x8r8g8b8, armv6_composite_src_0565_8888), PIXMAN_STD_FAST_PATH (SRC, b5g6r5, null, a8b8g8r8, armv6_composite_src_0565_8888), PIXMAN_STD_FAST_PATH (SRC, b5g6r5, null, x8b8g8r8, armv6_composite_src_0565_8888), PIXMAN_STD_FAST_PATH (SRC, a8r8g8b8, null, r5g6b5, armv6_composite_src_x888_0565), PIXMAN_STD_FAST_PATH (SRC, x8r8g8b8, null, r5g6b5, armv6_composite_src_x888_0565), PIXMAN_STD_FAST_PATH (SRC, a8b8g8r8, null, b5g6r5, armv6_composite_src_x888_0565), PIXMAN_STD_FAST_PATH (SRC, x8b8g8r8, null, b5g6r5, armv6_composite_src_x888_0565), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, null, a8r8g8b8, armv6_composite_over_8888_8888), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, null, x8r8g8b8, armv6_composite_over_8888_8888), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, null, a8b8g8r8, armv6_composite_over_8888_8888), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, null, x8b8g8r8, armv6_composite_over_8888_8888), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, solid, a8r8g8b8, armv6_composite_over_8888_n_8888), PIXMAN_STD_FAST_PATH (OVER, a8r8g8b8, solid, x8r8g8b8, armv6_composite_over_8888_n_8888), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, solid, a8b8g8r8, armv6_composite_over_8888_n_8888), PIXMAN_STD_FAST_PATH (OVER, a8b8g8r8, solid, x8b8g8r8, armv6_composite_over_8888_n_8888), PIXMAN_STD_FAST_PATH (OVER, solid, null, a8r8g8b8, armv6_composite_over_n_8888), PIXMAN_STD_FAST_PATH (OVER, solid, null, x8r8g8b8, armv6_composite_over_n_8888), PIXMAN_STD_FAST_PATH (OVER, solid, null, a8b8g8r8, armv6_composite_over_n_8888), PIXMAN_STD_FAST_PATH (OVER, solid, null, x8b8g8r8, armv6_composite_over_n_8888), PIXMAN_STD_FAST_PATH (OVER_REVERSE, solid, null, a8r8g8b8, armv6_composite_over_reverse_n_8888), PIXMAN_STD_FAST_PATH (OVER_REVERSE, solid, null, a8b8g8r8, armv6_composite_over_reverse_n_8888), PIXMAN_STD_FAST_PATH (ADD, a8, null, a8, armv6_composite_add_8_8), PIXMAN_STD_FAST_PATH (OVER, solid, a8, a8r8g8b8, armv6_composite_over_n_8_8888), PIXMAN_STD_FAST_PATH (OVER, solid, a8, x8r8g8b8, armv6_composite_over_n_8_8888), PIXMAN_STD_FAST_PATH (OVER, solid, a8, a8b8g8r8, armv6_composite_over_n_8_8888), PIXMAN_STD_FAST_PATH (OVER, solid, a8, x8b8g8r8, armv6_composite_over_n_8_8888), PIXMAN_STD_FAST_PATH (IN_REVERSE, a8r8g8b8, null, a8r8g8b8, armv6_composite_in_reverse_8888_8888), PIXMAN_STD_FAST_PATH (IN_REVERSE, a8r8g8b8, null, x8r8g8b8, armv6_composite_in_reverse_8888_8888), PIXMAN_STD_FAST_PATH (IN_REVERSE, a8b8g8r8, null, a8b8g8r8, armv6_composite_in_reverse_8888_8888), PIXMAN_STD_FAST_PATH (IN_REVERSE, a8b8g8r8, null, x8b8g8r8, armv6_composite_in_reverse_8888_8888), PIXMAN_STD_FAST_PATH_CA (OVER, solid, a8r8g8b8, a8r8g8b8, armv6_composite_over_n_8888_8888_ca), PIXMAN_STD_FAST_PATH_CA (OVER, solid, a8r8g8b8, x8r8g8b8, armv6_composite_over_n_8888_8888_ca), PIXMAN_STD_FAST_PATH_CA (OVER, solid, a8b8g8r8, a8b8g8r8, armv6_composite_over_n_8888_8888_ca), PIXMAN_STD_FAST_PATH_CA (OVER, solid, a8b8g8r8, x8b8g8r8, armv6_composite_over_n_8888_8888_ca), SIMPLE_NEAREST_FAST_PATH (SRC, r5g6b5, r5g6b5, armv6_0565_0565), SIMPLE_NEAREST_FAST_PATH (SRC, b5g6r5, b5g6r5, armv6_0565_0565), SIMPLE_NEAREST_FAST_PATH (SRC, a8r8g8b8, a8r8g8b8, armv6_8888_8888), SIMPLE_NEAREST_FAST_PATH (SRC, a8r8g8b8, x8r8g8b8, armv6_8888_8888), SIMPLE_NEAREST_FAST_PATH (SRC, x8r8g8b8, x8r8g8b8, armv6_8888_8888), SIMPLE_NEAREST_FAST_PATH (SRC, a8b8g8r8, a8b8g8r8, armv6_8888_8888), SIMPLE_NEAREST_FAST_PATH (SRC, a8b8g8r8, x8b8g8r8, armv6_8888_8888), SIMPLE_NEAREST_FAST_PATH (SRC, x8b8g8r8, x8b8g8r8, armv6_8888_8888), { PIXMAN_OP_NONE }, }; pixman_implementation_t * _pixman_implementation_create_arm_simd (pixman_implementation_t *fallback) { pixman_implementation_t *imp = _pixman_implementation_create (fallback, arm_simd_fast_paths); imp->blt = arm_simd_blt; imp->fill = arm_simd_fill; return imp; }
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-arm.c
/* * Copyright © 2000 SuSE, Inc. * Copyright © 2007 Red Hat, Inc. * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of SuSE not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. SuSE makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * SuSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SuSE * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pixman-private.h" typedef enum { ARM_V7 = (1 << 0), ARM_V6 = (1 << 1), ARM_VFP = (1 << 2), ARM_NEON = (1 << 3), ARM_IWMMXT = (1 << 4) } arm_cpu_features_t; #if defined(USE_ARM_SIMD) || defined(USE_ARM_NEON) || defined(USE_ARM_IWMMXT) #if defined(_MSC_VER) /* Needed for EXCEPTION_ILLEGAL_INSTRUCTION */ #include <windows.h> extern int pixman_msvc_try_arm_neon_op (); extern int pixman_msvc_try_arm_simd_op (); static arm_cpu_features_t detect_cpu_features (void) { arm_cpu_features_t features = 0; __try { pixman_msvc_try_arm_simd_op (); features |= ARM_V6; } __except (GetExceptionCode () == EXCEPTION_ILLEGAL_INSTRUCTION) { } __try { pixman_msvc_try_arm_neon_op (); features |= ARM_NEON; } __except (GetExceptionCode () == EXCEPTION_ILLEGAL_INSTRUCTION) { } return features; } #elif defined(__APPLE__) && defined(TARGET_OS_IPHONE) /* iOS */ #include "TargetConditionals.h" static arm_cpu_features_t detect_cpu_features (void) { arm_cpu_features_t features = 0; features |= ARM_V6; /* Detection of ARM NEON on iOS is fairly simple because iOS binaries * contain separate executable images for each processor architecture. * So all we have to do is detect the armv7 architecture build. The * operating system automatically runs the armv7 binary for armv7 devices * and the armv6 binary for armv6 devices. */ #if defined(__ARM_NEON__) features |= ARM_NEON; #endif return features; } #elif defined(__ANDROID__) || defined(ANDROID) /* Android */ #include <cpu-features.h> static arm_cpu_features_t detect_cpu_features (void) { arm_cpu_features_t features = 0; AndroidCpuFamily cpu_family; uint64_t cpu_features; cpu_family = android_getCpuFamily(); cpu_features = android_getCpuFeatures(); if (cpu_family == ANDROID_CPU_FAMILY_ARM) { if (cpu_features & ANDROID_CPU_ARM_FEATURE_ARMv7) features |= ARM_V7; if (cpu_features & ANDROID_CPU_ARM_FEATURE_VFPv3) features |= ARM_VFP; if (cpu_features & ANDROID_CPU_ARM_FEATURE_NEON) features |= ARM_NEON; } return features; } #elif defined (__linux__) /* linux ELF */ #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> #include <elf.h> static arm_cpu_features_t detect_cpu_features (void) { arm_cpu_features_t features = 0; Elf32_auxv_t aux; int fd; fd = open ("/proc/self/auxv", O_RDONLY); if (fd >= 0) { while (read (fd, &aux, sizeof(Elf32_auxv_t)) == sizeof(Elf32_auxv_t)) { if (aux.a_type == AT_HWCAP) { uint32_t hwcap = aux.a_un.a_val; /* hardcode these values to avoid depending on specific * versions of the hwcap header, e.g. HWCAP_NEON */ if ((hwcap & 64) != 0) features |= ARM_VFP; if ((hwcap & 512) != 0) features |= ARM_IWMMXT; /* this flag is only present on kernel 2.6.29 */ if ((hwcap & 4096) != 0) features |= ARM_NEON; } else if (aux.a_type == AT_PLATFORM) { const char *plat = (const char*) aux.a_un.a_val; if (strncmp (plat, "v7l", 3) == 0) features |= (ARM_V7 | ARM_V6); else if (strncmp (plat, "v6l", 3) == 0) features |= ARM_V6; } } close (fd); } return features; } #else /* Unknown */ static arm_cpu_features_t detect_cpu_features (void) { return 0; } #endif /* Linux elf */ static pixman_bool_t have_feature (arm_cpu_features_t feature) { static pixman_bool_t initialized; static arm_cpu_features_t features; if (!initialized) { features = detect_cpu_features(); initialized = TRUE; } return (features & feature) == feature; } #endif /* USE_ARM_SIMD || USE_ARM_NEON || USE_ARM_IWMMXT */ pixman_implementation_t * _pixman_arm_get_implementations (pixman_implementation_t *imp) { #ifdef USE_ARM_SIMD if (!_pixman_disabled ("arm-simd") && have_feature (ARM_V6)) imp = _pixman_implementation_create_arm_simd (imp); #endif #ifdef USE_ARM_IWMMXT if (!_pixman_disabled ("arm-iwmmxt") && have_feature (ARM_IWMMXT)) imp = _pixman_implementation_create_mmx (imp); #endif #ifdef USE_ARM_NEON if (!_pixman_disabled ("arm-neon") && have_feature (ARM_NEON)) imp = _pixman_implementation_create_arm_neon (imp); #endif return imp; }
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-bits-image.c
/* * Copyright © 2000 Keith Packard, member of The XFree86 Project, Inc. * 2005 Lars Knoll & Zack Rusin, Trolltech * 2008 Aaron Plattner, NVIDIA Corporation * Copyright © 2000 SuSE, Inc. * Copyright © 2007, 2009 Red Hat, Inc. * Copyright © 2008 André Tupinambá <andrelrt@gmail.com> * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "pixman-private.h" #include "pixman-combine32.h" #include "pixman-inlines.h" /* Fetch functions */ static force_inline void fetch_pixel_no_alpha_32 (bits_image_t *image, int x, int y, pixman_bool_t check_bounds, void *out) { uint32_t *ret = out; if (check_bounds && (x < 0 || x >= image->width || y < 0 || y >= image->height)) *ret = 0; else *ret = image->fetch_pixel_32 (image, x, y); } static force_inline void fetch_pixel_no_alpha_float (bits_image_t *image, int x, int y, pixman_bool_t check_bounds, void *out) { argb_t *ret = out; if (check_bounds && (x < 0 || x >= image->width || y < 0 || y >= image->height)) ret->a = ret->r = ret->g = ret->b = 0.f; else *ret = image->fetch_pixel_float (image, x, y); } typedef void (* get_pixel_t) (bits_image_t *image, int x, int y, pixman_bool_t check_bounds, void *out); static force_inline void bits_image_fetch_pixel_nearest (bits_image_t *image, pixman_fixed_t x, pixman_fixed_t y, get_pixel_t get_pixel, void *out) { int x0 = pixman_fixed_to_int (x - pixman_fixed_e); int y0 = pixman_fixed_to_int (y - pixman_fixed_e); if (image->common.repeat != PIXMAN_REPEAT_NONE) { repeat (image->common.repeat, &x0, image->width); repeat (image->common.repeat, &y0, image->height); get_pixel (image, x0, y0, FALSE, out); } else { get_pixel (image, x0, y0, TRUE, out); } } static force_inline void bits_image_fetch_pixel_bilinear_32 (bits_image_t *image, pixman_fixed_t x, pixman_fixed_t y, get_pixel_t get_pixel, void *out) { pixman_repeat_t repeat_mode = image->common.repeat; int width = image->width; int height = image->height; int x1, y1, x2, y2; uint32_t tl, tr, bl, br; int32_t distx, disty; uint32_t *ret = out; x1 = x - pixman_fixed_1 / 2; y1 = y - pixman_fixed_1 / 2; distx = pixman_fixed_to_bilinear_weight (x1); disty = pixman_fixed_to_bilinear_weight (y1); x1 = pixman_fixed_to_int (x1); y1 = pixman_fixed_to_int (y1); x2 = x1 + 1; y2 = y1 + 1; if (repeat_mode != PIXMAN_REPEAT_NONE) { repeat (repeat_mode, &x1, width); repeat (repeat_mode, &y1, height); repeat (repeat_mode, &x2, width); repeat (repeat_mode, &y2, height); get_pixel (image, x1, y1, FALSE, &tl); get_pixel (image, x2, y1, FALSE, &tr); get_pixel (image, x1, y2, FALSE, &bl); get_pixel (image, x2, y2, FALSE, &br); } else { get_pixel (image, x1, y1, TRUE, &tl); get_pixel (image, x2, y1, TRUE, &tr); get_pixel (image, x1, y2, TRUE, &bl); get_pixel (image, x2, y2, TRUE, &br); } *ret = bilinear_interpolation (tl, tr, bl, br, distx, disty); } static force_inline void bits_image_fetch_pixel_bilinear_float (bits_image_t *image, pixman_fixed_t x, pixman_fixed_t y, get_pixel_t get_pixel, void *out) { pixman_repeat_t repeat_mode = image->common.repeat; int width = image->width; int height = image->height; int x1, y1, x2, y2; argb_t tl, tr, bl, br; float distx, disty; argb_t *ret = out; x1 = x - pixman_fixed_1 / 2; y1 = y - pixman_fixed_1 / 2; distx = ((float)pixman_fixed_fraction(x1)) / 65536.f; disty = ((float)pixman_fixed_fraction(y1)) / 65536.f; x1 = pixman_fixed_to_int (x1); y1 = pixman_fixed_to_int (y1); x2 = x1 + 1; y2 = y1 + 1; if (repeat_mode != PIXMAN_REPEAT_NONE) { repeat (repeat_mode, &x1, width); repeat (repeat_mode, &y1, height); repeat (repeat_mode, &x2, width); repeat (repeat_mode, &y2, height); get_pixel (image, x1, y1, FALSE, &tl); get_pixel (image, x2, y1, FALSE, &tr); get_pixel (image, x1, y2, FALSE, &bl); get_pixel (image, x2, y2, FALSE, &br); } else { get_pixel (image, x1, y1, TRUE, &tl); get_pixel (image, x2, y1, TRUE, &tr); get_pixel (image, x1, y2, TRUE, &bl); get_pixel (image, x2, y2, TRUE, &br); } *ret = bilinear_interpolation_float (tl, tr, bl, br, distx, disty); } static force_inline void accum_32(int *satot, int *srtot, int *sgtot, int *sbtot, const void *p, pixman_fixed_t f) { uint32_t pixel = *(uint32_t *)p; *srtot += (int)RED_8 (pixel) * f; *sgtot += (int)GREEN_8 (pixel) * f; *sbtot += (int)BLUE_8 (pixel) * f; *satot += (int)ALPHA_8 (pixel) * f; } static force_inline void reduce_32(int satot, int srtot, int sgtot, int sbtot, void *p) { uint32_t *ret = p; satot = (satot + 0x8000) >> 16; srtot = (srtot + 0x8000) >> 16; sgtot = (sgtot + 0x8000) >> 16; sbtot = (sbtot + 0x8000) >> 16; satot = CLIP (satot, 0, 0xff); srtot = CLIP (srtot, 0, 0xff); sgtot = CLIP (sgtot, 0, 0xff); sbtot = CLIP (sbtot, 0, 0xff); *ret = ((satot << 24) | (srtot << 16) | (sgtot << 8) | (sbtot)); } static force_inline void accum_float(int *satot, int *srtot, int *sgtot, int *sbtot, const void *p, pixman_fixed_t f) { const argb_t *pixel = p; *satot += pixel->a * f; *srtot += pixel->r * f; *sgtot += pixel->g * f; *sbtot += pixel->b * f; } static force_inline void reduce_float(int satot, int srtot, int sgtot, int sbtot, void *p) { argb_t *ret = p; ret->a = CLIP (satot / 65536.f, 0.f, 1.f); ret->r = CLIP (srtot / 65536.f, 0.f, 1.f); ret->g = CLIP (sgtot / 65536.f, 0.f, 1.f); ret->b = CLIP (sbtot / 65536.f, 0.f, 1.f); } typedef void (* accumulate_pixel_t) (int *satot, int *srtot, int *sgtot, int *sbtot, const void *pixel, pixman_fixed_t f); typedef void (* reduce_pixel_t) (int satot, int srtot, int sgtot, int sbtot, void *out); static force_inline void bits_image_fetch_pixel_convolution (bits_image_t *image, pixman_fixed_t x, pixman_fixed_t y, get_pixel_t get_pixel, void *out, accumulate_pixel_t accum, reduce_pixel_t reduce) { pixman_fixed_t *params = image->common.filter_params; int x_off = (params[0] - pixman_fixed_1) >> 1; int y_off = (params[1] - pixman_fixed_1) >> 1; int32_t cwidth = pixman_fixed_to_int (params[0]); int32_t cheight = pixman_fixed_to_int (params[1]); int32_t i, j, x1, x2, y1, y2; pixman_repeat_t repeat_mode = image->common.repeat; int width = image->width; int height = image->height; int srtot, sgtot, sbtot, satot; params += 2; x1 = pixman_fixed_to_int (x - pixman_fixed_e - x_off); y1 = pixman_fixed_to_int (y - pixman_fixed_e - y_off); x2 = x1 + cwidth; y2 = y1 + cheight; srtot = sgtot = sbtot = satot = 0; for (i = y1; i < y2; ++i) { for (j = x1; j < x2; ++j) { int rx = j; int ry = i; pixman_fixed_t f = *params; if (f) { /* Must be big enough to hold a argb_t */ argb_t pixel; if (repeat_mode != PIXMAN_REPEAT_NONE) { repeat (repeat_mode, &rx, width); repeat (repeat_mode, &ry, height); get_pixel (image, rx, ry, FALSE, &pixel); } else { get_pixel (image, rx, ry, TRUE, &pixel); } accum (&satot, &srtot, &sgtot, &sbtot, &pixel, f); } params++; } } reduce (satot, srtot, sgtot, sbtot, out); } static void bits_image_fetch_pixel_separable_convolution (bits_image_t *image, pixman_fixed_t x, pixman_fixed_t y, get_pixel_t get_pixel, void *out, accumulate_pixel_t accum, reduce_pixel_t reduce) { pixman_fixed_t *params = image->common.filter_params; pixman_repeat_t repeat_mode = image->common.repeat; int width = image->width; int height = image->height; int cwidth = pixman_fixed_to_int (params[0]); int cheight = pixman_fixed_to_int (params[1]); int x_phase_bits = pixman_fixed_to_int (params[2]); int y_phase_bits = pixman_fixed_to_int (params[3]); int x_phase_shift = 16 - x_phase_bits; int y_phase_shift = 16 - y_phase_bits; int x_off = ((cwidth << 16) - pixman_fixed_1) >> 1; int y_off = ((cheight << 16) - pixman_fixed_1) >> 1; pixman_fixed_t *y_params; int srtot, sgtot, sbtot, satot; int32_t x1, x2, y1, y2; int32_t px, py; int i, j; /* Round x and y to the middle of the closest phase before continuing. This * ensures that the convolution matrix is aligned right, since it was * positioned relative to a particular phase (and not relative to whatever * exact fraction we happen to get here). */ x = ((x >> x_phase_shift) << x_phase_shift) + ((1 << x_phase_shift) >> 1); y = ((y >> y_phase_shift) << y_phase_shift) + ((1 << y_phase_shift) >> 1); px = (x & 0xffff) >> x_phase_shift; py = (y & 0xffff) >> y_phase_shift; y_params = params + 4 + (1 << x_phase_bits) * cwidth + py * cheight; x1 = pixman_fixed_to_int (x - pixman_fixed_e - x_off); y1 = pixman_fixed_to_int (y - pixman_fixed_e - y_off); x2 = x1 + cwidth; y2 = y1 + cheight; srtot = sgtot = sbtot = satot = 0; for (i = y1; i < y2; ++i) { pixman_fixed_48_16_t fy = *y_params++; pixman_fixed_t *x_params = params + 4 + px * cwidth; if (fy) { for (j = x1; j < x2; ++j) { pixman_fixed_t fx = *x_params++; int rx = j; int ry = i; if (fx) { /* Must be big enough to hold a argb_t */ argb_t pixel; pixman_fixed_t f; if (repeat_mode != PIXMAN_REPEAT_NONE) { repeat (repeat_mode, &rx, width); repeat (repeat_mode, &ry, height); get_pixel (image, rx, ry, FALSE, &pixel); } else { get_pixel (image, rx, ry, TRUE, &pixel); } f = (fy * fx + 0x8000) >> 16; accum(&satot, &srtot, &sgtot, &sbtot, &pixel, f); } } } } reduce(satot, srtot, sgtot, sbtot, out); } static force_inline void bits_image_fetch_pixel_filtered (bits_image_t *image, pixman_bool_t wide, pixman_fixed_t x, pixman_fixed_t y, get_pixel_t get_pixel, void *out) { switch (image->common.filter) { case PIXMAN_FILTER_NEAREST: case PIXMAN_FILTER_FAST: bits_image_fetch_pixel_nearest (image, x, y, get_pixel, out); break; case PIXMAN_FILTER_BILINEAR: case PIXMAN_FILTER_GOOD: case PIXMAN_FILTER_BEST: if (wide) bits_image_fetch_pixel_bilinear_float (image, x, y, get_pixel, out); else bits_image_fetch_pixel_bilinear_32 (image, x, y, get_pixel, out); break; case PIXMAN_FILTER_CONVOLUTION: if (wide) { bits_image_fetch_pixel_convolution (image, x, y, get_pixel, out, accum_float, reduce_float); } else { bits_image_fetch_pixel_convolution (image, x, y, get_pixel, out, accum_32, reduce_32); } break; case PIXMAN_FILTER_SEPARABLE_CONVOLUTION: if (wide) { bits_image_fetch_pixel_separable_convolution (image, x, y, get_pixel, out, accum_float, reduce_float); } else { bits_image_fetch_pixel_separable_convolution (image, x, y, get_pixel, out, accum_32, reduce_32); } break; default: assert (0); break; } } static uint32_t * __bits_image_fetch_affine_no_alpha (pixman_iter_t * iter, pixman_bool_t wide, const uint32_t * mask) { pixman_image_t *image = iter->image; int offset = iter->x; int line = iter->y++; int width = iter->width; uint32_t * buffer = iter->buffer; pixman_fixed_t x, y; pixman_fixed_t ux, uy; pixman_vector_t v; int i; get_pixel_t get_pixel = wide ? fetch_pixel_no_alpha_float : fetch_pixel_no_alpha_32; /* reference point is the center of the pixel */ v.vector[0] = pixman_int_to_fixed (offset) + pixman_fixed_1 / 2; v.vector[1] = pixman_int_to_fixed (line) + pixman_fixed_1 / 2; v.vector[2] = pixman_fixed_1; if (image->common.transform) { if (!pixman_transform_point_3d (image->common.transform, &v)) return iter->buffer; ux = image->common.transform->matrix[0][0]; uy = image->common.transform->matrix[1][0]; } else { ux = pixman_fixed_1; uy = 0; } x = v.vector[0]; y = v.vector[1]; for (i = 0; i < width; ++i) { if (!mask || mask[i]) { bits_image_fetch_pixel_filtered ( &image->bits, wide, x, y, get_pixel, buffer); } x += ux; y += uy; buffer += wide ? 4 : 1; } return iter->buffer; } static uint32_t * bits_image_fetch_affine_no_alpha_32 (pixman_iter_t *iter, const uint32_t *mask) { return __bits_image_fetch_affine_no_alpha(iter, FALSE, mask); } static uint32_t * bits_image_fetch_affine_no_alpha_float (pixman_iter_t *iter, const uint32_t *mask) { return __bits_image_fetch_affine_no_alpha(iter, TRUE, mask); } /* General fetcher */ static force_inline void fetch_pixel_general_32 (bits_image_t *image, int x, int y, pixman_bool_t check_bounds, void *out) { uint32_t pixel, *ret = out; if (check_bounds && (x < 0 || x >= image->width || y < 0 || y >= image->height)) { *ret = 0; return; } pixel = image->fetch_pixel_32 (image, x, y); if (image->common.alpha_map) { uint32_t pixel_a; x -= image->common.alpha_origin_x; y -= image->common.alpha_origin_y; if (x < 0 || x >= image->common.alpha_map->width || y < 0 || y >= image->common.alpha_map->height) { pixel_a = 0; } else { pixel_a = image->common.alpha_map->fetch_pixel_32 ( image->common.alpha_map, x, y); pixel_a = ALPHA_8 (pixel_a); } pixel &= 0x00ffffff; pixel |= (pixel_a << 24); } *ret = pixel; } static force_inline void fetch_pixel_general_float (bits_image_t *image, int x, int y, pixman_bool_t check_bounds, void *out) { argb_t *ret = out; if (check_bounds && (x < 0 || x >= image->width || y < 0 || y >= image->height)) { ret->a = ret->r = ret->g = ret->b = 0; return; } *ret = image->fetch_pixel_float (image, x, y); if (image->common.alpha_map) { x -= image->common.alpha_origin_x; y -= image->common.alpha_origin_y; if (x < 0 || x >= image->common.alpha_map->width || y < 0 || y >= image->common.alpha_map->height) { ret->a = 0.f; } else { argb_t alpha; alpha = image->common.alpha_map->fetch_pixel_float ( image->common.alpha_map, x, y); ret->a = alpha.a; } } } static uint32_t * __bits_image_fetch_general (pixman_iter_t *iter, pixman_bool_t wide, const uint32_t *mask) { pixman_image_t *image = iter->image; int offset = iter->x; int line = iter->y++; int width = iter->width; uint32_t * buffer = iter->buffer; get_pixel_t get_pixel = wide ? fetch_pixel_general_float : fetch_pixel_general_32; pixman_fixed_t x, y, w; pixman_fixed_t ux, uy, uw; pixman_vector_t v; int i; /* reference point is the center of the pixel */ v.vector[0] = pixman_int_to_fixed (offset) + pixman_fixed_1 / 2; v.vector[1] = pixman_int_to_fixed (line) + pixman_fixed_1 / 2; v.vector[2] = pixman_fixed_1; if (image->common.transform) { if (!pixman_transform_point_3d (image->common.transform, &v)) return buffer; ux = image->common.transform->matrix[0][0]; uy = image->common.transform->matrix[1][0]; uw = image->common.transform->matrix[2][0]; } else { ux = pixman_fixed_1; uy = 0; uw = 0; } x = v.vector[0]; y = v.vector[1]; w = v.vector[2]; for (i = 0; i < width; ++i) { pixman_fixed_t x0, y0; if (!mask || mask[i]) { if (w != 0) { x0 = ((pixman_fixed_48_16_t)x << 16) / w; y0 = ((pixman_fixed_48_16_t)y << 16) / w; } else { x0 = 0; y0 = 0; } bits_image_fetch_pixel_filtered ( &image->bits, wide, x0, y0, get_pixel, buffer); } x += ux; y += uy; w += uw; buffer += wide ? 4 : 1; } return iter->buffer; } static uint32_t * bits_image_fetch_general_32 (pixman_iter_t *iter, const uint32_t *mask) { return __bits_image_fetch_general(iter, FALSE, mask); } static uint32_t * bits_image_fetch_general_float (pixman_iter_t *iter, const uint32_t *mask) { return __bits_image_fetch_general(iter, TRUE, mask); } static void replicate_pixel_32 (bits_image_t * bits, int x, int y, int width, uint32_t * buffer) { uint32_t color; uint32_t *end; color = bits->fetch_pixel_32 (bits, x, y); end = buffer + width; while (buffer < end) *(buffer++) = color; } static void replicate_pixel_float (bits_image_t * bits, int x, int y, int width, uint32_t * b) { argb_t color; argb_t *buffer = (argb_t *)b; argb_t *end; color = bits->fetch_pixel_float (bits, x, y); end = buffer + width; while (buffer < end) *(buffer++) = color; } static void bits_image_fetch_untransformed_repeat_none (bits_image_t *image, pixman_bool_t wide, int x, int y, int width, uint32_t * buffer) { uint32_t w; if (y < 0 || y >= image->height) { memset (buffer, 0, width * (wide? sizeof (argb_t) : 4)); return; } if (x < 0) { w = MIN (width, -x); memset (buffer, 0, w * (wide ? sizeof (argb_t) : 4)); width -= w; buffer += w * (wide? 4 : 1); x += w; } if (x < image->width) { w = MIN (width, image->width - x); if (wide) image->fetch_scanline_float (image, x, y, w, buffer, NULL); else image->fetch_scanline_32 (image, x, y, w, buffer, NULL); width -= w; buffer += w * (wide? 4 : 1); x += w; } memset (buffer, 0, width * (wide ? sizeof (argb_t) : 4)); } static void bits_image_fetch_untransformed_repeat_normal (bits_image_t *image, pixman_bool_t wide, int x, int y, int width, uint32_t * buffer) { uint32_t w; while (y < 0) y += image->height; while (y >= image->height) y -= image->height; if (image->width == 1) { if (wide) replicate_pixel_float (image, 0, y, width, buffer); else replicate_pixel_32 (image, 0, y, width, buffer); return; } while (width) { while (x < 0) x += image->width; while (x >= image->width) x -= image->width; w = MIN (width, image->width - x); if (wide) image->fetch_scanline_float (image, x, y, w, buffer, NULL); else image->fetch_scanline_32 (image, x, y, w, buffer, NULL); buffer += w * (wide? 4 : 1); x += w; width -= w; } } static uint32_t * bits_image_fetch_untransformed_32 (pixman_iter_t * iter, const uint32_t *mask) { pixman_image_t *image = iter->image; int x = iter->x; int y = iter->y; int width = iter->width; uint32_t * buffer = iter->buffer; if (image->common.repeat == PIXMAN_REPEAT_NONE) { bits_image_fetch_untransformed_repeat_none ( &image->bits, FALSE, x, y, width, buffer); } else { bits_image_fetch_untransformed_repeat_normal ( &image->bits, FALSE, x, y, width, buffer); } iter->y++; return buffer; } static uint32_t * bits_image_fetch_untransformed_float (pixman_iter_t * iter, const uint32_t *mask) { pixman_image_t *image = iter->image; int x = iter->x; int y = iter->y; int width = iter->width; uint32_t * buffer = iter->buffer; if (image->common.repeat == PIXMAN_REPEAT_NONE) { bits_image_fetch_untransformed_repeat_none ( &image->bits, TRUE, x, y, width, buffer); } else { bits_image_fetch_untransformed_repeat_normal ( &image->bits, TRUE, x, y, width, buffer); } iter->y++; return buffer; } typedef struct { pixman_format_code_t format; uint32_t flags; pixman_iter_get_scanline_t get_scanline_32; pixman_iter_get_scanline_t get_scanline_float; } fetcher_info_t; static const fetcher_info_t fetcher_info[] = { { PIXMAN_any, (FAST_PATH_NO_ALPHA_MAP | FAST_PATH_ID_TRANSFORM | FAST_PATH_NO_CONVOLUTION_FILTER | FAST_PATH_NO_PAD_REPEAT | FAST_PATH_NO_REFLECT_REPEAT), bits_image_fetch_untransformed_32, bits_image_fetch_untransformed_float }, /* Affine, no alpha */ { PIXMAN_any, (FAST_PATH_NO_ALPHA_MAP | FAST_PATH_HAS_TRANSFORM | FAST_PATH_AFFINE_TRANSFORM), bits_image_fetch_affine_no_alpha_32, bits_image_fetch_affine_no_alpha_float, }, /* General */ { PIXMAN_any, 0, bits_image_fetch_general_32, bits_image_fetch_general_float, }, { PIXMAN_null }, }; static void bits_image_property_changed (pixman_image_t *image) { _pixman_bits_image_setup_accessors (&image->bits); } void _pixman_bits_image_src_iter_init (pixman_image_t *image, pixman_iter_t *iter) { pixman_format_code_t format = image->common.extended_format_code; uint32_t flags = image->common.flags; const fetcher_info_t *info; for (info = fetcher_info; info->format != PIXMAN_null; ++info) { if ((info->format == format || info->format == PIXMAN_any) && (info->flags & flags) == info->flags) { if (iter->iter_flags & ITER_NARROW) { iter->get_scanline = info->get_scanline_32; } else { iter->get_scanline = info->get_scanline_float; } return; } } /* Just in case we somehow didn't find a scanline function */ iter->get_scanline = _pixman_iter_get_scanline_noop; } static uint32_t * dest_get_scanline_narrow (pixman_iter_t *iter, const uint32_t *mask) { pixman_image_t *image = iter->image; int x = iter->x; int y = iter->y; int width = iter->width; uint32_t * buffer = iter->buffer; image->bits.fetch_scanline_32 (&image->bits, x, y, width, buffer, mask); if (image->common.alpha_map) { uint32_t *alpha; if ((alpha = malloc (width * sizeof (uint32_t)))) { int i; x -= image->common.alpha_origin_x; y -= image->common.alpha_origin_y; image->common.alpha_map->fetch_scanline_32 ( image->common.alpha_map, x, y, width, alpha, mask); for (i = 0; i < width; ++i) { buffer[i] &= ~0xff000000; buffer[i] |= (alpha[i] & 0xff000000); } free (alpha); } } return iter->buffer; } static uint32_t * dest_get_scanline_wide (pixman_iter_t *iter, const uint32_t *mask) { bits_image_t * image = &iter->image->bits; int x = iter->x; int y = iter->y; int width = iter->width; argb_t * buffer = (argb_t *)iter->buffer; image->fetch_scanline_float ( image, x, y, width, (uint32_t *)buffer, mask); if (image->common.alpha_map) { argb_t *alpha; if ((alpha = malloc (width * sizeof (argb_t)))) { int i; x -= image->common.alpha_origin_x; y -= image->common.alpha_origin_y; image->common.alpha_map->fetch_scanline_float ( image->common.alpha_map, x, y, width, (uint32_t *)alpha, mask); for (i = 0; i < width; ++i) buffer[i].a = alpha[i].a; free (alpha); } } return iter->buffer; } static void dest_write_back_narrow (pixman_iter_t *iter) { bits_image_t * image = &iter->image->bits; int x = iter->x; int y = iter->y; int width = iter->width; const uint32_t *buffer = iter->buffer; image->store_scanline_32 (image, x, y, width, buffer); if (image->common.alpha_map) { x -= image->common.alpha_origin_x; y -= image->common.alpha_origin_y; image->common.alpha_map->store_scanline_32 ( image->common.alpha_map, x, y, width, buffer); } iter->y++; } static void dest_write_back_wide (pixman_iter_t *iter) { bits_image_t * image = &iter->image->bits; int x = iter->x; int y = iter->y; int width = iter->width; const uint32_t *buffer = iter->buffer; image->store_scanline_float (image, x, y, width, buffer); if (image->common.alpha_map) { x -= image->common.alpha_origin_x; y -= image->common.alpha_origin_y; image->common.alpha_map->store_scanline_float ( image->common.alpha_map, x, y, width, buffer); } iter->y++; } void _pixman_bits_image_dest_iter_init (pixman_image_t *image, pixman_iter_t *iter) { if (iter->iter_flags & ITER_NARROW) { if ((iter->iter_flags & (ITER_IGNORE_RGB | ITER_IGNORE_ALPHA)) == (ITER_IGNORE_RGB | ITER_IGNORE_ALPHA)) { iter->get_scanline = _pixman_iter_get_scanline_noop; } else { iter->get_scanline = dest_get_scanline_narrow; } iter->write_back = dest_write_back_narrow; } else { iter->get_scanline = dest_get_scanline_wide; iter->write_back = dest_write_back_wide; } } static uint32_t * create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = (size_t)height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); } pixman_bool_t _pixman_bits_image_init (pixman_image_t * image, pixman_format_code_t format, int width, int height, uint32_t * bits, int rowstride, pixman_bool_t clear) { uint32_t *free_me = NULL; if (PIXMAN_FORMAT_BPP (format) == 128) return_val_if_fail(!(rowstride % 4), FALSE); if (!bits && width && height) { int rowstride_bytes; free_me = bits = create_bits (format, width, height, &rowstride_bytes, clear); if (!bits) return FALSE; rowstride = rowstride_bytes / (int) sizeof (uint32_t); } _pixman_image_init (image); image->type = BITS; image->bits.format = format; image->bits.width = width; image->bits.height = height; image->bits.bits = bits; image->bits.free_me = free_me; image->bits.read_func = NULL; image->bits.write_func = NULL; image->bits.rowstride = rowstride; image->bits.indexed = NULL; image->common.property_changed = bits_image_property_changed; _pixman_image_reset_clip_region (image); return TRUE; } static pixman_image_t * create_bits_image_internal (pixman_format_code_t format, int width, int height, uint32_t * bits, int rowstride_bytes, pixman_bool_t clear) { pixman_image_t *image; /* must be a whole number of uint32_t's */ return_val_if_fail ( bits == NULL || (rowstride_bytes % sizeof (uint32_t)) == 0, NULL); return_val_if_fail (PIXMAN_FORMAT_BPP (format) >= PIXMAN_FORMAT_DEPTH (format), NULL); image = _pixman_image_allocate (); if (!image) return NULL; if (!_pixman_bits_image_init (image, format, width, height, bits, rowstride_bytes / (int) sizeof (uint32_t), clear)) { free (image); return NULL; } return image; } /* If bits is NULL, a buffer will be allocated and initialized to 0 */ PIXMAN_EXPORT pixman_image_t * pixman_image_create_bits (pixman_format_code_t format, int width, int height, uint32_t * bits, int rowstride_bytes) { return create_bits_image_internal ( format, width, height, bits, rowstride_bytes, TRUE); } /* If bits is NULL, a buffer will be allocated and _not_ initialized */ PIXMAN_EXPORT pixman_image_t * pixman_image_create_bits_no_clear (pixman_format_code_t format, int width, int height, uint32_t * bits, int rowstride_bytes) { return create_bits_image_internal ( format, width, height, bits, rowstride_bytes, FALSE); }
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-combine-float.c
/* -*- Mode: c; c-basic-offset: 4; tab-width: 8; indent-tabs-mode: t; -*- */ /* * Copyright © 2010, 2012 Soren Sandmann Pedersen * Copyright © 2010, 2012 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Author: Soren Sandmann Pedersen (sandmann@cs.au.dk) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <math.h> #include <string.h> #include <float.h> #include "pixman-private.h" /* Workaround for http://gcc.gnu.org/PR54965 */ /* GCC 4.6 has problems with force_inline, so just use normal inline instead */ #if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 6) #undef force_inline #define force_inline __inline__ #endif typedef float (* combine_channel_t) (float sa, float s, float da, float d); static force_inline void combine_inner (pixman_bool_t component, float *dest, const float *src, const float *mask, int n_pixels, combine_channel_t combine_a, combine_channel_t combine_c) { int i; if (!mask) { for (i = 0; i < 4 * n_pixels; i += 4) { float sa = src[i + 0]; float sr = src[i + 1]; float sg = src[i + 2]; float sb = src[i + 3]; float da = dest[i + 0]; float dr = dest[i + 1]; float dg = dest[i + 2]; float db = dest[i + 3]; dest[i + 0] = combine_a (sa, sa, da, da); dest[i + 1] = combine_c (sa, sr, da, dr); dest[i + 2] = combine_c (sa, sg, da, dg); dest[i + 3] = combine_c (sa, sb, da, db); } } else { for (i = 0; i < 4 * n_pixels; i += 4) { float sa, sr, sg, sb; float ma, mr, mg, mb; float da, dr, dg, db; sa = src[i + 0]; sr = src[i + 1]; sg = src[i + 2]; sb = src[i + 3]; if (component) { ma = mask[i + 0]; mr = mask[i + 1]; mg = mask[i + 2]; mb = mask[i + 3]; sr *= mr; sg *= mg; sb *= mb; ma *= sa; mr *= sa; mg *= sa; mb *= sa; sa = ma; } else { ma = mask[i + 0]; sa *= ma; sr *= ma; sg *= ma; sb *= ma; ma = mr = mg = mb = sa; } da = dest[i + 0]; dr = dest[i + 1]; dg = dest[i + 2]; db = dest[i + 3]; dest[i + 0] = combine_a (ma, sa, da, da); dest[i + 1] = combine_c (mr, sr, da, dr); dest[i + 2] = combine_c (mg, sg, da, dg); dest[i + 3] = combine_c (mb, sb, da, db); } } } #define MAKE_COMBINER(name, component, combine_a, combine_c) \ static void \ combine_ ## name ## _float (pixman_implementation_t *imp, \ pixman_op_t op, \ float *dest, \ const float *src, \ const float *mask, \ int n_pixels) \ { \ combine_inner (component, dest, src, mask, n_pixels, \ combine_a, combine_c); \ } #define MAKE_COMBINERS(name, combine_a, combine_c) \ MAKE_COMBINER(name ## _ca, TRUE, combine_a, combine_c) \ MAKE_COMBINER(name ## _u, FALSE, combine_a, combine_c) /* * Porter/Duff operators */ typedef enum { ZERO, ONE, SRC_ALPHA, DEST_ALPHA, INV_SA, INV_DA, SA_OVER_DA, DA_OVER_SA, INV_SA_OVER_DA, INV_DA_OVER_SA, ONE_MINUS_SA_OVER_DA, ONE_MINUS_DA_OVER_SA, ONE_MINUS_INV_DA_OVER_SA, ONE_MINUS_INV_SA_OVER_DA } combine_factor_t; #define CLAMP(f) \ (((f) < 0)? 0 : (((f) > 1.0) ? 1.0 : (f))) static force_inline float get_factor (combine_factor_t factor, float sa, float da) { float f = -1; switch (factor) { case ZERO: f = 0.0f; break; case ONE: f = 1.0f; break; case SRC_ALPHA: f = sa; break; case DEST_ALPHA: f = da; break; case INV_SA: f = 1 - sa; break; case INV_DA: f = 1 - da; break; case SA_OVER_DA: if (FLOAT_IS_ZERO (da)) f = 1.0f; else f = CLAMP (sa / da); break; case DA_OVER_SA: if (FLOAT_IS_ZERO (sa)) f = 1.0f; else f = CLAMP (da / sa); break; case INV_SA_OVER_DA: if (FLOAT_IS_ZERO (da)) f = 1.0f; else f = CLAMP ((1.0f - sa) / da); break; case INV_DA_OVER_SA: if (FLOAT_IS_ZERO (sa)) f = 1.0f; else f = CLAMP ((1.0f - da) / sa); break; case ONE_MINUS_SA_OVER_DA: if (FLOAT_IS_ZERO (da)) f = 0.0f; else f = CLAMP (1.0f - sa / da); break; case ONE_MINUS_DA_OVER_SA: if (FLOAT_IS_ZERO (sa)) f = 0.0f; else f = CLAMP (1.0f - da / sa); break; case ONE_MINUS_INV_DA_OVER_SA: if (FLOAT_IS_ZERO (sa)) f = 0.0f; else f = CLAMP (1.0f - (1.0f - da) / sa); break; case ONE_MINUS_INV_SA_OVER_DA: if (FLOAT_IS_ZERO (da)) f = 0.0f; else f = CLAMP (1.0f - (1.0f - sa) / da); break; } return f; } #define MAKE_PD_COMBINERS(name, a, b) \ static float force_inline \ pd_combine_ ## name (float sa, float s, float da, float d) \ { \ const float fa = get_factor (a, sa, da); \ const float fb = get_factor (b, sa, da); \ \ return MIN (1.0f, s * fa + d * fb); \ } \ \ MAKE_COMBINERS(name, pd_combine_ ## name, pd_combine_ ## name) MAKE_PD_COMBINERS (clear, ZERO, ZERO) MAKE_PD_COMBINERS (src, ONE, ZERO) MAKE_PD_COMBINERS (dst, ZERO, ONE) MAKE_PD_COMBINERS (over, ONE, INV_SA) MAKE_PD_COMBINERS (over_reverse, INV_DA, ONE) MAKE_PD_COMBINERS (in, DEST_ALPHA, ZERO) MAKE_PD_COMBINERS (in_reverse, ZERO, SRC_ALPHA) MAKE_PD_COMBINERS (out, INV_DA, ZERO) MAKE_PD_COMBINERS (out_reverse, ZERO, INV_SA) MAKE_PD_COMBINERS (atop, DEST_ALPHA, INV_SA) MAKE_PD_COMBINERS (atop_reverse, INV_DA, SRC_ALPHA) MAKE_PD_COMBINERS (xor, INV_DA, INV_SA) MAKE_PD_COMBINERS (add, ONE, ONE) MAKE_PD_COMBINERS (saturate, INV_DA_OVER_SA, ONE) MAKE_PD_COMBINERS (disjoint_clear, ZERO, ZERO) MAKE_PD_COMBINERS (disjoint_src, ONE, ZERO) MAKE_PD_COMBINERS (disjoint_dst, ZERO, ONE) MAKE_PD_COMBINERS (disjoint_over, ONE, INV_SA_OVER_DA) MAKE_PD_COMBINERS (disjoint_over_reverse, INV_DA_OVER_SA, ONE) MAKE_PD_COMBINERS (disjoint_in, ONE_MINUS_INV_DA_OVER_SA, ZERO) MAKE_PD_COMBINERS (disjoint_in_reverse, ZERO, ONE_MINUS_INV_SA_OVER_DA) MAKE_PD_COMBINERS (disjoint_out, INV_DA_OVER_SA, ZERO) MAKE_PD_COMBINERS (disjoint_out_reverse, ZERO, INV_SA_OVER_DA) MAKE_PD_COMBINERS (disjoint_atop, ONE_MINUS_INV_DA_OVER_SA, INV_SA_OVER_DA) MAKE_PD_COMBINERS (disjoint_atop_reverse, INV_DA_OVER_SA, ONE_MINUS_INV_SA_OVER_DA) MAKE_PD_COMBINERS (disjoint_xor, INV_DA_OVER_SA, INV_SA_OVER_DA) MAKE_PD_COMBINERS (conjoint_clear, ZERO, ZERO) MAKE_PD_COMBINERS (conjoint_src, ONE, ZERO) MAKE_PD_COMBINERS (conjoint_dst, ZERO, ONE) MAKE_PD_COMBINERS (conjoint_over, ONE, ONE_MINUS_SA_OVER_DA) MAKE_PD_COMBINERS (conjoint_over_reverse, ONE_MINUS_DA_OVER_SA, ONE) MAKE_PD_COMBINERS (conjoint_in, DA_OVER_SA, ZERO) MAKE_PD_COMBINERS (conjoint_in_reverse, ZERO, SA_OVER_DA) MAKE_PD_COMBINERS (conjoint_out, ONE_MINUS_DA_OVER_SA, ZERO) MAKE_PD_COMBINERS (conjoint_out_reverse, ZERO, ONE_MINUS_SA_OVER_DA) MAKE_PD_COMBINERS (conjoint_atop, DA_OVER_SA, ONE_MINUS_SA_OVER_DA) MAKE_PD_COMBINERS (conjoint_atop_reverse, ONE_MINUS_DA_OVER_SA, SA_OVER_DA) MAKE_PD_COMBINERS (conjoint_xor, ONE_MINUS_DA_OVER_SA, ONE_MINUS_SA_OVER_DA) /* * PDF blend modes: * * The following blend modes have been taken from the PDF ISO 32000 * specification, which at this point in time is available from * * http://www.adobe.com/devnet/pdf/pdf_reference.html * * The specific documents of interest are the PDF spec itself: * * http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/PDF32000_2008.pdf * * chapters 11.3.5 and 11.3.6 and a later supplement for Adobe Acrobat * 9.1 and Reader 9.1: * * http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/adobe_supplement_iso32000_1.pdf * * that clarifies the specifications for blend modes ColorDodge and * ColorBurn. * * The formula for computing the final pixel color given in 11.3.6 is: * * αr × Cr = (1 – αs) × αb × Cb + (1 – αb) × αs × Cs + αb × αs × B(Cb, Cs) * * with B() is the blend function. When B(Cb, Cs) = Cs, this formula * reduces to the regular OVER operator. * * Cs and Cb are not premultiplied, so in our implementation we instead * use: * * cr = (1 – αs) × cb + (1 – αb) × cs + αb × αs × B (cb/αb, cs/αs) * * where cr, cs, and cb are premultiplied colors, and where the * * αb × αs × B(cb/αb, cs/αs) * * part is first arithmetically simplified under the assumption that αb * and αs are not 0, and then updated to produce a meaningful result when * they are. * * For all the blend mode operators, the alpha channel is given by * * αr = αs + αb + αb × αs */ #define MAKE_SEPARABLE_PDF_COMBINERS(name) \ static force_inline float \ combine_ ## name ## _a (float sa, float s, float da, float d) \ { \ return da + sa - da * sa; \ } \ \ static force_inline float \ combine_ ## name ## _c (float sa, float s, float da, float d) \ { \ float f = (1 - sa) * d + (1 - da) * s; \ \ return f + blend_ ## name (sa, s, da, d); \ } \ \ MAKE_COMBINERS (name, combine_ ## name ## _a, combine_ ## name ## _c) /* * Multiply * * ad * as * B(d / ad, s / as) * = ad * as * d/ad * s/as * = d * s * */ static force_inline float blend_multiply (float sa, float s, float da, float d) { return d * s; } /* * Screen * * ad * as * B(d/ad, s/as) * = ad * as * (d/ad + s/as - s/as * d/ad) * = ad * s + as * d - s * d */ static force_inline float blend_screen (float sa, float s, float da, float d) { return d * sa + s * da - s * d; } /* * Overlay * * ad * as * B(d/ad, s/as) * = ad * as * Hardlight (s, d) * = if (d / ad < 0.5) * as * ad * Multiply (s/as, 2 * d/ad) * else * as * ad * Screen (s/as, 2 * d / ad - 1) * = if (d < 0.5 * ad) * as * ad * s/as * 2 * d /ad * else * as * ad * (s/as + 2 * d / ad - 1 - s / as * (2 * d / ad - 1)) * = if (2 * d < ad) * 2 * s * d * else * ad * s + 2 * as * d - as * ad - ad * s * (2 * d / ad - 1) * = if (2 * d < ad) * 2 * s * d * else * as * ad - 2 * (ad - d) * (as - s) */ static force_inline float blend_overlay (float sa, float s, float da, float d) { if (2 * d < da) return 2 * s * d; else return sa * da - 2 * (da - d) * (sa - s); } /* * Darken * * ad * as * B(d/ad, s/as) * = ad * as * MIN(d/ad, s/as) * = MIN (as * d, ad * s) */ static force_inline float blend_darken (float sa, float s, float da, float d) { s = s * da; d = d * sa; if (s > d) return d; else return s; } /* * Lighten * * ad * as * B(d/ad, s/as) * = ad * as * MAX(d/ad, s/as) * = MAX (as * d, ad * s) */ static force_inline float blend_lighten (float sa, float s, float da, float d) { s = s * da; d = d * sa; if (s > d) return s; else return d; } /* * Color dodge * * ad * as * B(d/ad, s/as) * = if d/ad = 0 * ad * as * 0 * else if (d/ad >= (1 - s/as) * ad * as * 1 * else * ad * as * ((d/ad) / (1 - s/as)) * = if d = 0 * 0 * elif as * d >= ad * (as - s) * ad * as * else * as * (as * d / (as - s)) * */ static force_inline float blend_color_dodge (float sa, float s, float da, float d) { if (FLOAT_IS_ZERO (d)) return 0.0f; else if (d * sa >= sa * da - s * da) return sa * da; else if (FLOAT_IS_ZERO (sa - s)) return sa * da; else return sa * sa * d / (sa - s); } /* * Color burn * * We modify the first clause "if d = 1" to "if d >= 1" since with * premultiplied colors d > 1 can actually happen. * * ad * as * B(d/ad, s/as) * = if d/ad >= 1 * ad * as * 1 * elif (1 - d/ad) >= s/as * ad * as * 0 * else * ad * as * (1 - ((1 - d/ad) / (s/as))) * = if d >= ad * ad * as * elif as * ad - as * d >= ad * s * 0 * else * ad * as - as * as * (ad - d) / s */ static force_inline float blend_color_burn (float sa, float s, float da, float d) { if (d >= da) return sa * da; else if (sa * (da - d) >= s * da) return 0.0f; else if (FLOAT_IS_ZERO (s)) return 0.0f; else return sa * (da - sa * (da - d) / s); } /* * Hard light * * ad * as * B(d/ad, s/as) * = if (s/as <= 0.5) * ad * as * Multiply (d/ad, 2 * s/as) * else * ad * as * Screen (d/ad, 2 * s/as - 1) * = if 2 * s <= as * ad * as * d/ad * 2 * s / as * else * ad * as * (d/ad + (2 * s/as - 1) + d/ad * (2 * s/as - 1)) * = if 2 * s <= as * 2 * s * d * else * as * ad - 2 * (ad - d) * (as - s) */ static force_inline float blend_hard_light (float sa, float s, float da, float d) { if (2 * s < sa) return 2 * s * d; else return sa * da - 2 * (da - d) * (sa - s); } /* * Soft light * * ad * as * B(d/ad, s/as) * = if (s/as <= 0.5) * ad * as * (d/ad - (1 - 2 * s/as) * d/ad * (1 - d/ad)) * else if (d/ad <= 0.25) * ad * as * (d/ad + (2 * s/as - 1) * ((((16 * d/ad - 12) * d/ad + 4) * d/ad) - d/ad)) * else * ad * as * (d/ad + (2 * s/as - 1) * sqrt (d/ad)) * = if (2 * s <= as) * d * as - d * (ad - d) * (as - 2 * s) / ad; * else if (4 * d <= ad) * (2 * s - as) * d * ((16 * d / ad - 12) * d / ad + 3); * else * d * as + (sqrt (d * ad) - d) * (2 * s - as); */ static force_inline float blend_soft_light (float sa, float s, float da, float d) { if (2 * s <= sa) { if (FLOAT_IS_ZERO (da)) return d * sa; else return d * sa - d * (da - d) * (sa - 2 * s) / da; } else { if (FLOAT_IS_ZERO (da)) { return d * sa; } else { if (4 * d <= da) return d * sa + (2 * s - sa) * d * ((16 * d / da - 12) * d / da + 3); else return d * sa + (sqrtf (d * da) - d) * (2 * s - sa); } } } /* * Difference * * ad * as * B(s/as, d/ad) * = ad * as * abs (s/as - d/ad) * = if (s/as <= d/ad) * ad * as * (d/ad - s/as) * else * ad * as * (s/as - d/ad) * = if (ad * s <= as * d) * as * d - ad * s * else * ad * s - as * d */ static force_inline float blend_difference (float sa, float s, float da, float d) { float dsa = d * sa; float sda = s * da; if (sda < dsa) return dsa - sda; else return sda - dsa; } /* * Exclusion * * ad * as * B(s/as, d/ad) * = ad * as * (d/ad + s/as - 2 * d/ad * s/as) * = as * d + ad * s - 2 * s * d */ static force_inline float blend_exclusion (float sa, float s, float da, float d) { return s * da + d * sa - 2 * d * s; } MAKE_SEPARABLE_PDF_COMBINERS (multiply) MAKE_SEPARABLE_PDF_COMBINERS (screen) MAKE_SEPARABLE_PDF_COMBINERS (overlay) MAKE_SEPARABLE_PDF_COMBINERS (darken) MAKE_SEPARABLE_PDF_COMBINERS (lighten) MAKE_SEPARABLE_PDF_COMBINERS (color_dodge) MAKE_SEPARABLE_PDF_COMBINERS (color_burn) MAKE_SEPARABLE_PDF_COMBINERS (hard_light) MAKE_SEPARABLE_PDF_COMBINERS (soft_light) MAKE_SEPARABLE_PDF_COMBINERS (difference) MAKE_SEPARABLE_PDF_COMBINERS (exclusion) /* * PDF nonseperable blend modes are implemented using the following functions * to operate in Hsl space, with Cmax, Cmid, Cmin referring to the max, mid * and min value of the red, green and blue components. * * LUM (C) = 0.3 × Cred + 0.59 × Cgreen + 0.11 × Cblue * * clip_color (C): * l = LUM (C) * min = Cmin * max = Cmax * if n < 0.0 * C = l + (((C – l) × l) ⁄ (l – min)) * if x > 1.0 * C = l + (((C – l) × (1 – l) ) ⁄ (max – l)) * return C * * set_lum (C, l): * d = l – LUM (C) * C += d * return clip_color (C) * * SAT (C) = CH_MAX (C) - CH_MIN (C) * * set_sat (C, s): * if Cmax > Cmin * Cmid = ( ( ( Cmid – Cmin ) × s ) ⁄ ( Cmax – Cmin ) ) * Cmax = s * else * Cmid = Cmax = 0.0 * Cmin = 0.0 * return C */ /* For premultiplied colors, we need to know what happens when C is * multiplied by a real number. LUM and SAT are linear: * * LUM (r × C) = r × LUM (C) SAT (r * C) = r * SAT (C) * * If we extend clip_color with an extra argument a and change * * if x >= 1.0 * * into * * if x >= a * * then clip_color is also linear: * * r * clip_color (C, a) = clip_color (r * C, r * a); * * for positive r. * * Similarly, we can extend set_lum with an extra argument that is just passed * on to clip_color: * * r * set_lum (C, l, a) * * = r × clip_color (C + l - LUM (C), a) * * = clip_color (r * C + r × l - r * LUM (C), r * a) * * = set_lum (r * C, r * l, r * a) * * Finally, set_sat: * * r * set_sat (C, s) = set_sat (x * C, r * s) * * The above holds for all non-zero x, because the x'es in the fraction for * C_mid cancel out. Specifically, it holds for x = r: * * r * set_sat (C, s) = set_sat (r * C, r * s) * */ typedef struct { float r; float g; float b; } rgb_t; static force_inline float minf (float a, float b) { return a < b? a : b; } static force_inline float maxf (float a, float b) { return a > b? a : b; } static force_inline float channel_min (const rgb_t *c) { return minf (minf (c->r, c->g), c->b); } static force_inline float channel_max (const rgb_t *c) { return maxf (maxf (c->r, c->g), c->b); } static force_inline float get_lum (const rgb_t *c) { return c->r * 0.3f + c->g * 0.59f + c->b * 0.11f; } static force_inline float get_sat (const rgb_t *c) { return channel_max (c) - channel_min (c); } static void clip_color (rgb_t *color, float a) { float l = get_lum (color); float n = channel_min (color); float x = channel_max (color); float t; if (n < 0.0f) { t = l - n; if (FLOAT_IS_ZERO (t)) { color->r = 0.0f; color->g = 0.0f; color->b = 0.0f; } else { color->r = l + (((color->r - l) * l) / t); color->g = l + (((color->g - l) * l) / t); color->b = l + (((color->b - l) * l) / t); } } if (x > a) { t = x - l; if (FLOAT_IS_ZERO (t)) { color->r = a; color->g = a; color->b = a; } else { color->r = l + (((color->r - l) * (a - l) / t)); color->g = l + (((color->g - l) * (a - l) / t)); color->b = l + (((color->b - l) * (a - l) / t)); } } } static void set_lum (rgb_t *color, float sa, float l) { float d = l - get_lum (color); color->r = color->r + d; color->g = color->g + d; color->b = color->b + d; clip_color (color, sa); } static void set_sat (rgb_t *src, float sat) { float *max, *mid, *min; float t; if (src->r > src->g) { if (src->r > src->b) { max = &(src->r); if (src->g > src->b) { mid = &(src->g); min = &(src->b); } else { mid = &(src->b); min = &(src->g); } } else { max = &(src->b); mid = &(src->r); min = &(src->g); } } else { if (src->r > src->b) { max = &(src->g); mid = &(src->r); min = &(src->b); } else { min = &(src->r); if (src->g > src->b) { max = &(src->g); mid = &(src->b); } else { max = &(src->b); mid = &(src->g); } } } t = *max - *min; if (FLOAT_IS_ZERO (t)) { *mid = *max = 0.0f; } else { *mid = ((*mid - *min) * sat) / t; *max = sat; } *min = 0.0f; } /* Hue: * * as * ad * B(s/as, d/as) * = as * ad * set_lum (set_sat (s/as, SAT (d/ad)), LUM (d/ad), 1) * = set_lum (set_sat (ad * s, as * SAT (d)), as * LUM (d), as * ad) * */ static force_inline void blend_hsl_hue (rgb_t *res, const rgb_t *dest, float da, const rgb_t *src, float sa) { res->r = src->r * da; res->g = src->g * da; res->b = src->b * da; set_sat (res, get_sat (dest) * sa); set_lum (res, sa * da, get_lum (dest) * sa); } /* * Saturation * * as * ad * B(s/as, d/ad) * = as * ad * set_lum (set_sat (d/ad, SAT (s/as)), LUM (d/ad), 1) * = set_lum (as * ad * set_sat (d/ad, SAT (s/as)), * as * LUM (d), as * ad) * = set_lum (set_sat (as * d, ad * SAT (s), as * LUM (d), as * ad)) */ static force_inline void blend_hsl_saturation (rgb_t *res, const rgb_t *dest, float da, const rgb_t *src, float sa) { res->r = dest->r * sa; res->g = dest->g * sa; res->b = dest->b * sa; set_sat (res, get_sat (src) * da); set_lum (res, sa * da, get_lum (dest) * sa); } /* * Color * * as * ad * B(s/as, d/as) * = as * ad * set_lum (s/as, LUM (d/ad), 1) * = set_lum (s * ad, as * LUM (d), as * ad) */ static force_inline void blend_hsl_color (rgb_t *res, const rgb_t *dest, float da, const rgb_t *src, float sa) { res->r = src->r * da; res->g = src->g * da; res->b = src->b * da; set_lum (res, sa * da, get_lum (dest) * sa); } /* * Luminosity * * as * ad * B(s/as, d/ad) * = as * ad * set_lum (d/ad, LUM (s/as), 1) * = set_lum (as * d, ad * LUM (s), as * ad) */ static force_inline void blend_hsl_luminosity (rgb_t *res, const rgb_t *dest, float da, const rgb_t *src, float sa) { res->r = dest->r * sa; res->g = dest->g * sa; res->b = dest->b * sa; set_lum (res, sa * da, get_lum (src) * da); } #define MAKE_NON_SEPARABLE_PDF_COMBINERS(name) \ static void \ combine_ ## name ## _u_float (pixman_implementation_t *imp, \ pixman_op_t op, \ float *dest, \ const float *src, \ const float *mask, \ int n_pixels) \ { \ int i; \ \ for (i = 0; i < 4 * n_pixels; i += 4) \ { \ float sa, da; \ rgb_t sc, dc, rc; \ \ sa = src[i + 0]; \ sc.r = src[i + 1]; \ sc.g = src[i + 2]; \ sc.b = src[i + 3]; \ \ da = dest[i + 0]; \ dc.r = dest[i + 1]; \ dc.g = dest[i + 2]; \ dc.b = dest[i + 3]; \ \ if (mask) \ { \ float ma = mask[i + 0]; \ \ /* Component alpha is not supported for HSL modes */ \ sa *= ma; \ sc.r *= ma; \ sc.g *= ma; \ sc.g *= ma; \ } \ \ blend_ ## name (&rc, &dc, da, &sc, sa); \ \ dest[i + 0] = sa + da - sa * da; \ dest[i + 1] = (1 - sa) * dc.r + (1 - da) * sc.r + rc.r; \ dest[i + 2] = (1 - sa) * dc.g + (1 - da) * sc.g + rc.g; \ dest[i + 3] = (1 - sa) * dc.b + (1 - da) * sc.b + rc.b; \ } \ } MAKE_NON_SEPARABLE_PDF_COMBINERS(hsl_hue) MAKE_NON_SEPARABLE_PDF_COMBINERS(hsl_saturation) MAKE_NON_SEPARABLE_PDF_COMBINERS(hsl_color) MAKE_NON_SEPARABLE_PDF_COMBINERS(hsl_luminosity) void _pixman_setup_combiner_functions_float (pixman_implementation_t *imp) { /* Unified alpha */ imp->combine_float[PIXMAN_OP_CLEAR] = combine_clear_u_float; imp->combine_float[PIXMAN_OP_SRC] = combine_src_u_float; imp->combine_float[PIXMAN_OP_DST] = combine_dst_u_float; imp->combine_float[PIXMAN_OP_OVER] = combine_over_u_float; imp->combine_float[PIXMAN_OP_OVER_REVERSE] = combine_over_reverse_u_float; imp->combine_float[PIXMAN_OP_IN] = combine_in_u_float; imp->combine_float[PIXMAN_OP_IN_REVERSE] = combine_in_reverse_u_float; imp->combine_float[PIXMAN_OP_OUT] = combine_out_u_float; imp->combine_float[PIXMAN_OP_OUT_REVERSE] = combine_out_reverse_u_float; imp->combine_float[PIXMAN_OP_ATOP] = combine_atop_u_float; imp->combine_float[PIXMAN_OP_ATOP_REVERSE] = combine_atop_reverse_u_float; imp->combine_float[PIXMAN_OP_XOR] = combine_xor_u_float; imp->combine_float[PIXMAN_OP_ADD] = combine_add_u_float; imp->combine_float[PIXMAN_OP_SATURATE] = combine_saturate_u_float; /* Disjoint, unified */ imp->combine_float[PIXMAN_OP_DISJOINT_CLEAR] = combine_disjoint_clear_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_SRC] = combine_disjoint_src_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_DST] = combine_disjoint_dst_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_OVER] = combine_disjoint_over_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_OVER_REVERSE] = combine_disjoint_over_reverse_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_IN] = combine_disjoint_in_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_IN_REVERSE] = combine_disjoint_in_reverse_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_OUT] = combine_disjoint_out_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_OUT_REVERSE] = combine_disjoint_out_reverse_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_ATOP] = combine_disjoint_atop_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_ATOP_REVERSE] = combine_disjoint_atop_reverse_u_float; imp->combine_float[PIXMAN_OP_DISJOINT_XOR] = combine_disjoint_xor_u_float; /* Conjoint, unified */ imp->combine_float[PIXMAN_OP_CONJOINT_CLEAR] = combine_conjoint_clear_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_SRC] = combine_conjoint_src_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_DST] = combine_conjoint_dst_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_OVER] = combine_conjoint_over_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_OVER_REVERSE] = combine_conjoint_over_reverse_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_IN] = combine_conjoint_in_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_IN_REVERSE] = combine_conjoint_in_reverse_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_OUT] = combine_conjoint_out_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_OUT_REVERSE] = combine_conjoint_out_reverse_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_ATOP] = combine_conjoint_atop_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_ATOP_REVERSE] = combine_conjoint_atop_reverse_u_float; imp->combine_float[PIXMAN_OP_CONJOINT_XOR] = combine_conjoint_xor_u_float; /* PDF operators, unified */ imp->combine_float[PIXMAN_OP_MULTIPLY] = combine_multiply_u_float; imp->combine_float[PIXMAN_OP_SCREEN] = combine_screen_u_float; imp->combine_float[PIXMAN_OP_OVERLAY] = combine_overlay_u_float; imp->combine_float[PIXMAN_OP_DARKEN] = combine_darken_u_float; imp->combine_float[PIXMAN_OP_LIGHTEN] = combine_lighten_u_float; imp->combine_float[PIXMAN_OP_COLOR_DODGE] = combine_color_dodge_u_float; imp->combine_float[PIXMAN_OP_COLOR_BURN] = combine_color_burn_u_float; imp->combine_float[PIXMAN_OP_HARD_LIGHT] = combine_hard_light_u_float; imp->combine_float[PIXMAN_OP_SOFT_LIGHT] = combine_soft_light_u_float; imp->combine_float[PIXMAN_OP_DIFFERENCE] = combine_difference_u_float; imp->combine_float[PIXMAN_OP_EXCLUSION] = combine_exclusion_u_float; imp->combine_float[PIXMAN_OP_HSL_HUE] = combine_hsl_hue_u_float; imp->combine_float[PIXMAN_OP_HSL_SATURATION] = combine_hsl_saturation_u_float; imp->combine_float[PIXMAN_OP_HSL_COLOR] = combine_hsl_color_u_float; imp->combine_float[PIXMAN_OP_HSL_LUMINOSITY] = combine_hsl_luminosity_u_float; /* Component alpha combiners */ imp->combine_float_ca[PIXMAN_OP_CLEAR] = combine_clear_ca_float; imp->combine_float_ca[PIXMAN_OP_SRC] = combine_src_ca_float; imp->combine_float_ca[PIXMAN_OP_DST] = combine_dst_ca_float; imp->combine_float_ca[PIXMAN_OP_OVER] = combine_over_ca_float; imp->combine_float_ca[PIXMAN_OP_OVER_REVERSE] = combine_over_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_IN] = combine_in_ca_float; imp->combine_float_ca[PIXMAN_OP_IN_REVERSE] = combine_in_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_OUT] = combine_out_ca_float; imp->combine_float_ca[PIXMAN_OP_OUT_REVERSE] = combine_out_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_ATOP] = combine_atop_ca_float; imp->combine_float_ca[PIXMAN_OP_ATOP_REVERSE] = combine_atop_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_XOR] = combine_xor_ca_float; imp->combine_float_ca[PIXMAN_OP_ADD] = combine_add_ca_float; imp->combine_float_ca[PIXMAN_OP_SATURATE] = combine_saturate_ca_float; /* Disjoint CA */ imp->combine_float_ca[PIXMAN_OP_DISJOINT_CLEAR] = combine_disjoint_clear_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_SRC] = combine_disjoint_src_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_DST] = combine_disjoint_dst_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_OVER] = combine_disjoint_over_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_OVER_REVERSE] = combine_disjoint_over_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_IN] = combine_disjoint_in_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_IN_REVERSE] = combine_disjoint_in_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_OUT] = combine_disjoint_out_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_OUT_REVERSE] = combine_disjoint_out_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_ATOP] = combine_disjoint_atop_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_ATOP_REVERSE] = combine_disjoint_atop_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_DISJOINT_XOR] = combine_disjoint_xor_ca_float; /* Conjoint CA */ imp->combine_float_ca[PIXMAN_OP_CONJOINT_CLEAR] = combine_conjoint_clear_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_SRC] = combine_conjoint_src_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_DST] = combine_conjoint_dst_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_OVER] = combine_conjoint_over_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_OVER_REVERSE] = combine_conjoint_over_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_IN] = combine_conjoint_in_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_IN_REVERSE] = combine_conjoint_in_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_OUT] = combine_conjoint_out_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_OUT_REVERSE] = combine_conjoint_out_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_ATOP] = combine_conjoint_atop_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_ATOP_REVERSE] = combine_conjoint_atop_reverse_ca_float; imp->combine_float_ca[PIXMAN_OP_CONJOINT_XOR] = combine_conjoint_xor_ca_float; /* PDF operators CA */ imp->combine_float_ca[PIXMAN_OP_MULTIPLY] = combine_multiply_ca_float; imp->combine_float_ca[PIXMAN_OP_SCREEN] = combine_screen_ca_float; imp->combine_float_ca[PIXMAN_OP_OVERLAY] = combine_overlay_ca_float; imp->combine_float_ca[PIXMAN_OP_DARKEN] = combine_darken_ca_float; imp->combine_float_ca[PIXMAN_OP_LIGHTEN] = combine_lighten_ca_float; imp->combine_float_ca[PIXMAN_OP_COLOR_DODGE] = combine_color_dodge_ca_float; imp->combine_float_ca[PIXMAN_OP_COLOR_BURN] = combine_color_burn_ca_float; imp->combine_float_ca[PIXMAN_OP_HARD_LIGHT] = combine_hard_light_ca_float; imp->combine_float_ca[PIXMAN_OP_SOFT_LIGHT] = combine_soft_light_ca_float; imp->combine_float_ca[PIXMAN_OP_DIFFERENCE] = combine_difference_ca_float; imp->combine_float_ca[PIXMAN_OP_EXCLUSION] = combine_exclusion_ca_float; /* It is not clear that these make sense, so make them noops for now */ imp->combine_float_ca[PIXMAN_OP_HSL_HUE] = combine_dst_u_float; imp->combine_float_ca[PIXMAN_OP_HSL_SATURATION] = combine_dst_u_float; imp->combine_float_ca[PIXMAN_OP_HSL_COLOR] = combine_dst_u_float; imp->combine_float_ca[PIXMAN_OP_HSL_LUMINOSITY] = combine_dst_u_float; }
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-combine32.c
/* * Copyright © 2000 Keith Packard, member of The XFree86 Project, Inc. * 2005 Lars Knoll & Zack Rusin, Trolltech * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <math.h> #include <string.h> #include "pixman-private.h" #include "pixman-combine32.h" /* component alpha helper functions */ static void combine_mask_ca (uint32_t *src, uint32_t *mask) { uint32_t a = *mask; uint32_t x; uint16_t xa; if (!a) { *(src) = 0; return; } x = *(src); if (a == ~0) { x = x >> A_SHIFT; x |= x << G_SHIFT; x |= x << R_SHIFT; *(mask) = x; return; } xa = x >> A_SHIFT; UN8x4_MUL_UN8x4 (x, a); *(src) = x; UN8x4_MUL_UN8 (a, xa); *(mask) = a; } static void combine_mask_value_ca (uint32_t *src, const uint32_t *mask) { uint32_t a = *mask; uint32_t x; if (!a) { *(src) = 0; return; } if (a == ~0) return; x = *(src); UN8x4_MUL_UN8x4 (x, a); *(src) = x; } static void combine_mask_alpha_ca (const uint32_t *src, uint32_t *mask) { uint32_t a = *(mask); uint32_t x; if (!a) return; x = *(src) >> A_SHIFT; if (x == MASK) return; if (a == ~0) { x |= x << G_SHIFT; x |= x << R_SHIFT; *(mask) = x; return; } UN8x4_MUL_UN8 (a, x); *(mask) = a; } /* * There are two ways of handling alpha -- either as a single unified value or * a separate value for each component, hence each macro must have two * versions. The unified alpha version has a 'u' at the end of the name, * the component version has a 'ca'. Similarly, functions which deal with * this difference will have two versions using the same convention. */ static force_inline uint32_t combine_mask (const uint32_t *src, const uint32_t *mask, int i) { uint32_t s, m; if (mask) { m = *(mask + i) >> A_SHIFT; if (!m) return 0; } s = *(src + i); if (mask) UN8x4_MUL_UN8 (s, m); return s; } static void combine_clear (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { memset (dest, 0, width * sizeof (uint32_t)); } static void combine_dst (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { return; } static void combine_src_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; if (!mask) { memcpy (dest, src, width * sizeof (uint32_t)); } else { for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); *(dest + i) = s; } } } static void combine_over_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; if (!mask) { for (i = 0; i < width; ++i) { uint32_t s = *(src + i); uint32_t a = ALPHA_8 (s); if (a == 0xFF) { *(dest + i) = s; } else if (s) { uint32_t d = *(dest + i); uint32_t ia = a ^ 0xFF; UN8x4_MUL_UN8_ADD_UN8x4 (d, ia, s); *(dest + i) = d; } } } else { for (i = 0; i < width; ++i) { uint32_t m = ALPHA_8 (*(mask + i)); if (m == 0xFF) { uint32_t s = *(src + i); uint32_t a = ALPHA_8 (s); if (a == 0xFF) { *(dest + i) = s; } else if (s) { uint32_t d = *(dest + i); uint32_t ia = a ^ 0xFF; UN8x4_MUL_UN8_ADD_UN8x4 (d, ia, s); *(dest + i) = d; } } else if (m) { uint32_t s = *(src + i); if (s) { uint32_t d = *(dest + i); UN8x4_MUL_UN8 (s, m); UN8x4_MUL_UN8_ADD_UN8x4 (d, ALPHA_8 (~s), s); *(dest + i) = d; } } } } } static void combine_over_reverse_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); uint32_t d = *(dest + i); uint32_t ia = ALPHA_8 (~*(dest + i)); UN8x4_MUL_UN8_ADD_UN8x4 (s, ia, d); *(dest + i) = s; } } static void combine_in_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); uint32_t a = ALPHA_8 (*(dest + i)); UN8x4_MUL_UN8 (s, a); *(dest + i) = s; } } static void combine_in_reverse_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); uint32_t d = *(dest + i); uint32_t a = ALPHA_8 (s); UN8x4_MUL_UN8 (d, a); *(dest + i) = d; } } static void combine_out_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); uint32_t a = ALPHA_8 (~*(dest + i)); UN8x4_MUL_UN8 (s, a); *(dest + i) = s; } } static void combine_out_reverse_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); uint32_t d = *(dest + i); uint32_t a = ALPHA_8 (~s); UN8x4_MUL_UN8 (d, a); *(dest + i) = d; } } static void combine_atop_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); uint32_t d = *(dest + i); uint32_t dest_a = ALPHA_8 (d); uint32_t src_ia = ALPHA_8 (~s); UN8x4_MUL_UN8_ADD_UN8x4_MUL_UN8 (s, dest_a, d, src_ia); *(dest + i) = s; } } static void combine_atop_reverse_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); uint32_t d = *(dest + i); uint32_t src_a = ALPHA_8 (s); uint32_t dest_ia = ALPHA_8 (~d); UN8x4_MUL_UN8_ADD_UN8x4_MUL_UN8 (s, dest_ia, d, src_a); *(dest + i) = s; } } static void combine_xor_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); uint32_t d = *(dest + i); uint32_t src_ia = ALPHA_8 (~s); uint32_t dest_ia = ALPHA_8 (~d); UN8x4_MUL_UN8_ADD_UN8x4_MUL_UN8 (s, dest_ia, d, src_ia); *(dest + i) = s; } } static void combine_add_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); uint32_t d = *(dest + i); UN8x4_ADD_UN8x4 (d, s); *(dest + i) = d; } } /* * PDF blend modes: * * The following blend modes have been taken from the PDF ISO 32000 * specification, which at this point in time is available from * * http://www.adobe.com/devnet/pdf/pdf_reference.html * * The specific documents of interest are the PDF spec itself: * * http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/PDF32000_2008.pdf * * chapters 11.3.5 and 11.3.6 and a later supplement for Adobe Acrobat * 9.1 and Reader 9.1: * * http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/adobe_supplement_iso32000_1.pdf * * that clarifies the specifications for blend modes ColorDodge and * ColorBurn. * * The formula for computing the final pixel color given in 11.3.6 is: * * αr × Cr = (1 – αs) × αb × Cb + (1 – αb) × αs × Cs + αb × αs × B(Cb, Cs) * * with B() is the blend function. When B(Cb, Cs) = Cs, this formula * reduces to the regular OVER operator. * * Cs and Cb are not premultiplied, so in our implementation we instead * use: * * cr = (1 – αs) × cb + (1 – αb) × cs + αb × αs × B (cb/αb, cs/αs) * * where cr, cs, and cb are premultiplied colors, and where the * * αb × αs × B(cb/αb, cs/αs) * * part is first arithmetically simplified under the assumption that αb * and αs are not 0, and then updated to produce a meaningful result when * they are. * * For all the blend mode operators, the alpha channel is given by * * αr = αs + αb + αb × αs */ /* * Multiply * * ad * as * B(d / ad, s / as) * = ad * as * d/ad * s/as * = d * s * */ static void combine_multiply_u (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = combine_mask (src, mask, i); uint32_t d = *(dest + i); uint32_t ss = s; uint32_t src_ia = ALPHA_8 (~s); uint32_t dest_ia = ALPHA_8 (~d); UN8x4_MUL_UN8_ADD_UN8x4_MUL_UN8 (ss, dest_ia, d, src_ia); UN8x4_MUL_UN8x4 (d, s); UN8x4_ADD_UN8x4 (d, ss); *(dest + i) = d; } } static void combine_multiply_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t m = *(mask + i); uint32_t s = *(src + i); uint32_t d = *(dest + i); uint32_t r = d; uint32_t dest_ia = ALPHA_8 (~d); combine_mask_ca (&s, &m); UN8x4_MUL_UN8x4_ADD_UN8x4_MUL_UN8 (r, ~m, s, dest_ia); UN8x4_MUL_UN8x4 (d, s); UN8x4_ADD_UN8x4 (r, d); *(dest + i) = r; } } #define CLAMP(v, low, high) \ do \ { \ if (v < (low)) \ v = (low); \ if (v > (high)) \ v = (high); \ } while (0) #define PDF_SEPARABLE_BLEND_MODE(name) \ static void \ combine_ ## name ## _u (pixman_implementation_t *imp, \ pixman_op_t op, \ uint32_t * dest, \ const uint32_t * src, \ const uint32_t * mask, \ int width) \ { \ int i; \ for (i = 0; i < width; ++i) \ { \ uint32_t s = combine_mask (src, mask, i); \ uint32_t d = *(dest + i); \ uint8_t sa = ALPHA_8 (s); \ uint8_t isa = ~sa; \ uint8_t da = ALPHA_8 (d); \ uint8_t ida = ~da; \ int32_t ra, rr, rg, rb; \ \ ra = da * 0xff + sa * 0xff - sa * da; \ rr = isa * RED_8 (d) + ida * RED_8 (s); \ rg = isa * GREEN_8 (d) + ida * GREEN_8 (s); \ rb = isa * BLUE_8 (d) + ida * BLUE_8 (s); \ \ rr += blend_ ## name (RED_8 (d), da, RED_8 (s), sa); \ rg += blend_ ## name (GREEN_8 (d), da, GREEN_8 (s), sa); \ rb += blend_ ## name (BLUE_8 (d), da, BLUE_8 (s), sa); \ \ CLAMP (ra, 0, 255 * 255); \ CLAMP (rr, 0, 255 * 255); \ CLAMP (rg, 0, 255 * 255); \ CLAMP (rb, 0, 255 * 255); \ \ ra = DIV_ONE_UN8 (ra); \ rr = DIV_ONE_UN8 (rr); \ rg = DIV_ONE_UN8 (rg); \ rb = DIV_ONE_UN8 (rb); \ \ *(dest + i) = ra << 24 | rr << 16 | rg << 8 | rb; \ } \ } \ \ static void \ combine_ ## name ## _ca (pixman_implementation_t *imp, \ pixman_op_t op, \ uint32_t * dest, \ const uint32_t * src, \ const uint32_t * mask, \ int width) \ { \ int i; \ for (i = 0; i < width; ++i) \ { \ uint32_t m = *(mask + i); \ uint32_t s = *(src + i); \ uint32_t d = *(dest + i); \ uint8_t da = ALPHA_8 (d); \ uint8_t ida = ~da; \ int32_t ra, rr, rg, rb; \ uint8_t ira, iga, iba; \ \ combine_mask_ca (&s, &m); \ \ ira = ~RED_8 (m); \ iga = ~GREEN_8 (m); \ iba = ~BLUE_8 (m); \ \ ra = da * 0xff + ALPHA_8 (s) * 0xff - ALPHA_8 (s) * da; \ rr = ira * RED_8 (d) + ida * RED_8 (s); \ rg = iga * GREEN_8 (d) + ida * GREEN_8 (s); \ rb = iba * BLUE_8 (d) + ida * BLUE_8 (s); \ \ rr += blend_ ## name (RED_8 (d), da, RED_8 (s), RED_8 (m)); \ rg += blend_ ## name (GREEN_8 (d), da, GREEN_8 (s), GREEN_8 (m)); \ rb += blend_ ## name (BLUE_8 (d), da, BLUE_8 (s), BLUE_8 (m)); \ \ CLAMP (ra, 0, 255 * 255); \ CLAMP (rr, 0, 255 * 255); \ CLAMP (rg, 0, 255 * 255); \ CLAMP (rb, 0, 255 * 255); \ \ ra = DIV_ONE_UN8 (ra); \ rr = DIV_ONE_UN8 (rr); \ rg = DIV_ONE_UN8 (rg); \ rb = DIV_ONE_UN8 (rb); \ \ *(dest + i) = ra << 24 | rr << 16 | rg << 8 | rb; \ } \ } /* * Screen * * ad * as * B(d/ad, s/as) * = ad * as * (d/ad + s/as - s/as * d/ad) * = ad * s + as * d - s * d */ static inline int32_t blend_screen (int32_t d, int32_t ad, int32_t s, int32_t as) { return s * ad + d * as - s * d; } PDF_SEPARABLE_BLEND_MODE (screen) /* * Overlay * * ad * as * B(d/ad, s/as) * = ad * as * Hardlight (s, d) * = if (d / ad < 0.5) * as * ad * Multiply (s/as, 2 * d/ad) * else * as * ad * Screen (s/as, 2 * d / ad - 1) * = if (d < 0.5 * ad) * as * ad * s/as * 2 * d /ad * else * as * ad * (s/as + 2 * d / ad - 1 - s / as * (2 * d / ad - 1)) * = if (2 * d < ad) * 2 * s * d * else * ad * s + 2 * as * d - as * ad - ad * s * (2 * d / ad - 1) * = if (2 * d < ad) * 2 * s * d * else * as * ad - 2 * (ad - d) * (as - s) */ static inline int32_t blend_overlay (int32_t d, int32_t ad, int32_t s, int32_t as) { uint32_t r; if (2 * d < ad) r = 2 * s * d; else r = as * ad - 2 * (ad - d) * (as - s); return r; } PDF_SEPARABLE_BLEND_MODE (overlay) /* * Darken * * ad * as * B(d/ad, s/as) * = ad * as * MIN(d/ad, s/as) * = MIN (as * d, ad * s) */ static inline int32_t blend_darken (int32_t d, int32_t ad, int32_t s, int32_t as) { s = ad * s; d = as * d; return s > d ? d : s; } PDF_SEPARABLE_BLEND_MODE (darken) /* * Lighten * * ad * as * B(d/ad, s/as) * = ad * as * MAX(d/ad, s/as) * = MAX (as * d, ad * s) */ static inline int32_t blend_lighten (int32_t d, int32_t ad, int32_t s, int32_t as) { s = ad * s; d = as * d; return s > d ? s : d; } PDF_SEPARABLE_BLEND_MODE (lighten) /* * Hard light * * ad * as * B(d/ad, s/as) * = if (s/as <= 0.5) * ad * as * Multiply (d/ad, 2 * s/as) * else * ad * as * Screen (d/ad, 2 * s/as - 1) * = if 2 * s <= as * ad * as * d/ad * 2 * s / as * else * ad * as * (d/ad + (2 * s/as - 1) + d/ad * (2 * s/as - 1)) * = if 2 * s <= as * 2 * s * d * else * as * ad - 2 * (ad - d) * (as - s) */ static inline int32_t blend_hard_light (int32_t d, int32_t ad, int32_t s, int32_t as) { if (2 * s < as) return 2 * s * d; else return as * ad - 2 * (ad - d) * (as - s); } PDF_SEPARABLE_BLEND_MODE (hard_light) /* * Difference * * ad * as * B(s/as, d/ad) * = ad * as * abs (s/as - d/ad) * = if (s/as <= d/ad) * ad * as * (d/ad - s/as) * else * ad * as * (s/as - d/ad) * = if (ad * s <= as * d) * as * d - ad * s * else * ad * s - as * d */ static inline int32_t blend_difference (int32_t d, int32_t ad, int32_t s, int32_t as) { int32_t das = d * as; int32_t sad = s * ad; if (sad < das) return das - sad; else return sad - das; } PDF_SEPARABLE_BLEND_MODE (difference) /* * Exclusion * * ad * as * B(s/as, d/ad) * = ad * as * (d/ad + s/as - 2 * d/ad * s/as) * = as * d + ad * s - 2 * s * d */ /* This can be made faster by writing it directly and not using * PDF_SEPARABLE_BLEND_MODE, but that's a performance optimization */ static inline int32_t blend_exclusion (int32_t d, int32_t ad, int32_t s, int32_t as) { return s * ad + d * as - 2 * d * s; } PDF_SEPARABLE_BLEND_MODE (exclusion) #undef PDF_SEPARABLE_BLEND_MODE /* Component alpha combiners */ static void combine_clear_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { memset (dest, 0, width * sizeof(uint32_t)); } static void combine_src_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = *(src + i); uint32_t m = *(mask + i); combine_mask_value_ca (&s, &m); *(dest + i) = s; } } static void combine_over_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = *(src + i); uint32_t m = *(mask + i); uint32_t a; combine_mask_ca (&s, &m); a = ~m; if (a) { uint32_t d = *(dest + i); UN8x4_MUL_UN8x4_ADD_UN8x4 (d, a, s); s = d; } *(dest + i) = s; } } static void combine_over_reverse_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t d = *(dest + i); uint32_t a = ~d >> A_SHIFT; if (a) { uint32_t s = *(src + i); uint32_t m = *(mask + i); UN8x4_MUL_UN8x4 (s, m); UN8x4_MUL_UN8_ADD_UN8x4 (s, a, d); *(dest + i) = s; } } } static void combine_in_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t d = *(dest + i); uint16_t a = d >> A_SHIFT; uint32_t s = 0; if (a) { uint32_t m = *(mask + i); s = *(src + i); combine_mask_value_ca (&s, &m); if (a != MASK) UN8x4_MUL_UN8 (s, a); } *(dest + i) = s; } } static void combine_in_reverse_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = *(src + i); uint32_t m = *(mask + i); uint32_t a; combine_mask_alpha_ca (&s, &m); a = m; if (a != ~0) { uint32_t d = 0; if (a) { d = *(dest + i); UN8x4_MUL_UN8x4 (d, a); } *(dest + i) = d; } } } static void combine_out_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t d = *(dest + i); uint16_t a = ~d >> A_SHIFT; uint32_t s = 0; if (a) { uint32_t m = *(mask + i); s = *(src + i); combine_mask_value_ca (&s, &m); if (a != MASK) UN8x4_MUL_UN8 (s, a); } *(dest + i) = s; } } static void combine_out_reverse_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = *(src + i); uint32_t m = *(mask + i); uint32_t a; combine_mask_alpha_ca (&s, &m); a = ~m; if (a != ~0) { uint32_t d = 0; if (a) { d = *(dest + i); UN8x4_MUL_UN8x4 (d, a); } *(dest + i) = d; } } } static void combine_atop_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t d = *(dest + i); uint32_t s = *(src + i); uint32_t m = *(mask + i); uint32_t ad; uint16_t as = d >> A_SHIFT; combine_mask_ca (&s, &m); ad = ~m; UN8x4_MUL_UN8x4_ADD_UN8x4_MUL_UN8 (d, ad, s, as); *(dest + i) = d; } } static void combine_atop_reverse_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t d = *(dest + i); uint32_t s = *(src + i); uint32_t m = *(mask + i); uint32_t ad; uint16_t as = ~d >> A_SHIFT; combine_mask_ca (&s, &m); ad = m; UN8x4_MUL_UN8x4_ADD_UN8x4_MUL_UN8 (d, ad, s, as); *(dest + i) = d; } } static void combine_xor_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t d = *(dest + i); uint32_t s = *(src + i); uint32_t m = *(mask + i); uint32_t ad; uint16_t as = ~d >> A_SHIFT; combine_mask_ca (&s, &m); ad = ~m; UN8x4_MUL_UN8x4_ADD_UN8x4_MUL_UN8 (d, ad, s, as); *(dest + i) = d; } } static void combine_add_ca (pixman_implementation_t *imp, pixman_op_t op, uint32_t * dest, const uint32_t * src, const uint32_t * mask, int width) { int i; for (i = 0; i < width; ++i) { uint32_t s = *(src + i); uint32_t m = *(mask + i); uint32_t d = *(dest + i); combine_mask_value_ca (&s, &m); UN8x4_ADD_UN8x4 (d, s); *(dest + i) = d; } } void _pixman_setup_combiner_functions_32 (pixman_implementation_t *imp) { /* Unified alpha */ imp->combine_32[PIXMAN_OP_CLEAR] = combine_clear; imp->combine_32[PIXMAN_OP_SRC] = combine_src_u; imp->combine_32[PIXMAN_OP_DST] = combine_dst; imp->combine_32[PIXMAN_OP_OVER] = combine_over_u; imp->combine_32[PIXMAN_OP_OVER_REVERSE] = combine_over_reverse_u; imp->combine_32[PIXMAN_OP_IN] = combine_in_u; imp->combine_32[PIXMAN_OP_IN_REVERSE] = combine_in_reverse_u; imp->combine_32[PIXMAN_OP_OUT] = combine_out_u; imp->combine_32[PIXMAN_OP_OUT_REVERSE] = combine_out_reverse_u; imp->combine_32[PIXMAN_OP_ATOP] = combine_atop_u; imp->combine_32[PIXMAN_OP_ATOP_REVERSE] = combine_atop_reverse_u; imp->combine_32[PIXMAN_OP_XOR] = combine_xor_u; imp->combine_32[PIXMAN_OP_ADD] = combine_add_u; imp->combine_32[PIXMAN_OP_MULTIPLY] = combine_multiply_u; imp->combine_32[PIXMAN_OP_SCREEN] = combine_screen_u; imp->combine_32[PIXMAN_OP_OVERLAY] = combine_overlay_u; imp->combine_32[PIXMAN_OP_DARKEN] = combine_darken_u; imp->combine_32[PIXMAN_OP_LIGHTEN] = combine_lighten_u; imp->combine_32[PIXMAN_OP_HARD_LIGHT] = combine_hard_light_u; imp->combine_32[PIXMAN_OP_DIFFERENCE] = combine_difference_u; imp->combine_32[PIXMAN_OP_EXCLUSION] = combine_exclusion_u; /* Component alpha combiners */ imp->combine_32_ca[PIXMAN_OP_CLEAR] = combine_clear_ca; imp->combine_32_ca[PIXMAN_OP_SRC] = combine_src_ca; /* dest */ imp->combine_32_ca[PIXMAN_OP_OVER] = combine_over_ca; imp->combine_32_ca[PIXMAN_OP_OVER_REVERSE] = combine_over_reverse_ca; imp->combine_32_ca[PIXMAN_OP_IN] = combine_in_ca; imp->combine_32_ca[PIXMAN_OP_IN_REVERSE] = combine_in_reverse_ca; imp->combine_32_ca[PIXMAN_OP_OUT] = combine_out_ca; imp->combine_32_ca[PIXMAN_OP_OUT_REVERSE] = combine_out_reverse_ca; imp->combine_32_ca[PIXMAN_OP_ATOP] = combine_atop_ca; imp->combine_32_ca[PIXMAN_OP_ATOP_REVERSE] = combine_atop_reverse_ca; imp->combine_32_ca[PIXMAN_OP_XOR] = combine_xor_ca; imp->combine_32_ca[PIXMAN_OP_ADD] = combine_add_ca; imp->combine_32_ca[PIXMAN_OP_MULTIPLY] = combine_multiply_ca; imp->combine_32_ca[PIXMAN_OP_SCREEN] = combine_screen_ca; imp->combine_32_ca[PIXMAN_OP_OVERLAY] = combine_overlay_ca; imp->combine_32_ca[PIXMAN_OP_DARKEN] = combine_darken_ca; imp->combine_32_ca[PIXMAN_OP_LIGHTEN] = combine_lighten_ca; imp->combine_32_ca[PIXMAN_OP_HARD_LIGHT] = combine_hard_light_ca; imp->combine_32_ca[PIXMAN_OP_DIFFERENCE] = combine_difference_ca; imp->combine_32_ca[PIXMAN_OP_EXCLUSION] = combine_exclusion_ca; }
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-combine32.h
#define COMPONENT_SIZE 8 #define MASK 0xff #define ONE_HALF 0x80 #define A_SHIFT 8 * 3 #define R_SHIFT 8 * 2 #define G_SHIFT 8 #define A_MASK 0xff000000 #define R_MASK 0xff0000 #define G_MASK 0xff00 #define RB_MASK 0xff00ff #define AG_MASK 0xff00ff00 #define RB_ONE_HALF 0x800080 #define RB_MASK_PLUS_ONE 0x10000100 #define ALPHA_8(x) ((x) >> A_SHIFT) #define RED_8(x) (((x) >> R_SHIFT) & MASK) #define GREEN_8(x) (((x) >> G_SHIFT) & MASK) #define BLUE_8(x) ((x) & MASK) /* * ARMv6 has UQADD8 instruction, which implements unsigned saturated * addition for 8-bit values packed in 32-bit registers. It is very useful * for UN8x4_ADD_UN8x4, UN8_rb_ADD_UN8_rb and ADD_UN8 macros (which would * otherwise need a lot of arithmetic operations to simulate this operation). * Since most of the major ARM linux distros are built for ARMv7, we are * much less dependent on runtime CPU detection and can get practical * benefits from conditional compilation here for a lot of users. */ #if defined(USE_GCC_INLINE_ASM) && defined(__arm__) && \ !defined(__aarch64__) && (!defined(__thumb__) || defined(__thumb2__)) #if defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || \ defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || \ defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) || \ defined(__ARM_ARCH_6M__) || defined(__ARM_ARCH_7__) || \ defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || \ defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__) static force_inline uint32_t un8x4_add_un8x4 (uint32_t x, uint32_t y) { uint32_t t; asm ("uqadd8 %0, %1, %2" : "=r" (t) : "%r" (x), "r" (y)); return t; } #define UN8x4_ADD_UN8x4(x, y) \ ((x) = un8x4_add_un8x4 ((x), (y))) #define UN8_rb_ADD_UN8_rb(x, y, t) \ ((t) = un8x4_add_un8x4 ((x), (y)), (x) = (t)) #define ADD_UN8(x, y, t) \ ((t) = (x), un8x4_add_un8x4 ((t), (y))) #endif #endif /*****************************************************************************/ /* * Helper macros. */ #define MUL_UN8(a, b, t) \ ((t) = (a) * (uint16_t)(b) + ONE_HALF, ((((t) >> G_SHIFT ) + (t) ) >> G_SHIFT )) #define DIV_UN8(a, b) \ (((uint16_t) (a) * MASK + ((b) / 2)) / (b)) #ifndef ADD_UN8 #define ADD_UN8(x, y, t) \ ((t) = (x) + (y), \ (uint32_t) (uint8_t) ((t) | (0 - ((t) >> G_SHIFT)))) #endif #define DIV_ONE_UN8(x) \ (((x) + ONE_HALF + (((x) + ONE_HALF) >> G_SHIFT)) >> G_SHIFT) /* * The methods below use some tricks to be able to do two color * components at the same time. */ /* * x_rb = (x_rb * a) / 255 */ #define UN8_rb_MUL_UN8(x, a, t) \ do \ { \ t = ((x) & RB_MASK) * (a); \ t += RB_ONE_HALF; \ x = (t + ((t >> G_SHIFT) & RB_MASK)) >> G_SHIFT; \ x &= RB_MASK; \ } while (0) /* * x_rb = min (x_rb + y_rb, 255) */ #ifndef UN8_rb_ADD_UN8_rb #define UN8_rb_ADD_UN8_rb(x, y, t) \ do \ { \ t = ((x) + (y)); \ t |= RB_MASK_PLUS_ONE - ((t >> G_SHIFT) & RB_MASK); \ x = (t & RB_MASK); \ } while (0) #endif /* * x_rb = (x_rb * a_rb) / 255 */ #define UN8_rb_MUL_UN8_rb(x, a, t) \ do \ { \ t = (x & MASK) * (a & MASK); \ t |= (x & R_MASK) * ((a >> R_SHIFT) & MASK); \ t += RB_ONE_HALF; \ t = (t + ((t >> G_SHIFT) & RB_MASK)) >> G_SHIFT; \ x = t & RB_MASK; \ } while (0) /* * x_c = (x_c * a) / 255 */ #define UN8x4_MUL_UN8(x, a) \ do \ { \ uint32_t r1__, r2__, t__; \ \ r1__ = (x); \ UN8_rb_MUL_UN8 (r1__, (a), t__); \ \ r2__ = (x) >> G_SHIFT; \ UN8_rb_MUL_UN8 (r2__, (a), t__); \ \ (x) = r1__ | (r2__ << G_SHIFT); \ } while (0) /* * x_c = (x_c * a) / 255 + y_c */ #define UN8x4_MUL_UN8_ADD_UN8x4(x, a, y) \ do \ { \ uint32_t r1__, r2__, r3__, t__; \ \ r1__ = (x); \ r2__ = (y) & RB_MASK; \ UN8_rb_MUL_UN8 (r1__, (a), t__); \ UN8_rb_ADD_UN8_rb (r1__, r2__, t__); \ \ r2__ = (x) >> G_SHIFT; \ r3__ = ((y) >> G_SHIFT) & RB_MASK; \ UN8_rb_MUL_UN8 (r2__, (a), t__); \ UN8_rb_ADD_UN8_rb (r2__, r3__, t__); \ \ (x) = r1__ | (r2__ << G_SHIFT); \ } while (0) /* * x_c = (x_c * a + y_c * b) / 255 */ #define UN8x4_MUL_UN8_ADD_UN8x4_MUL_UN8(x, a, y, b) \ do \ { \ uint32_t r1__, r2__, r3__, t__; \ \ r1__ = (x); \ r2__ = (y); \ UN8_rb_MUL_UN8 (r1__, (a), t__); \ UN8_rb_MUL_UN8 (r2__, (b), t__); \ UN8_rb_ADD_UN8_rb (r1__, r2__, t__); \ \ r2__ = ((x) >> G_SHIFT); \ r3__ = ((y) >> G_SHIFT); \ UN8_rb_MUL_UN8 (r2__, (a), t__); \ UN8_rb_MUL_UN8 (r3__, (b), t__); \ UN8_rb_ADD_UN8_rb (r2__, r3__, t__); \ \ (x) = r1__ | (r2__ << G_SHIFT); \ } while (0) /* * x_c = (x_c * a_c) / 255 */ #define UN8x4_MUL_UN8x4(x, a) \ do \ { \ uint32_t r1__, r2__, r3__, t__; \ \ r1__ = (x); \ r2__ = (a); \ UN8_rb_MUL_UN8_rb (r1__, r2__, t__); \ \ r2__ = (x) >> G_SHIFT; \ r3__ = (a) >> G_SHIFT; \ UN8_rb_MUL_UN8_rb (r2__, r3__, t__); \ \ (x) = r1__ | (r2__ << G_SHIFT); \ } while (0) /* * x_c = (x_c * a_c) / 255 + y_c */ #define UN8x4_MUL_UN8x4_ADD_UN8x4(x, a, y) \ do \ { \ uint32_t r1__, r2__, r3__, t__; \ \ r1__ = (x); \ r2__ = (a); \ UN8_rb_MUL_UN8_rb (r1__, r2__, t__); \ r2__ = (y) & RB_MASK; \ UN8_rb_ADD_UN8_rb (r1__, r2__, t__); \ \ r2__ = ((x) >> G_SHIFT); \ r3__ = ((a) >> G_SHIFT); \ UN8_rb_MUL_UN8_rb (r2__, r3__, t__); \ r3__ = ((y) >> G_SHIFT) & RB_MASK; \ UN8_rb_ADD_UN8_rb (r2__, r3__, t__); \ \ (x) = r1__ | (r2__ << G_SHIFT); \ } while (0) /* * x_c = (x_c * a_c + y_c * b) / 255 */ #define UN8x4_MUL_UN8x4_ADD_UN8x4_MUL_UN8(x, a, y, b) \ do \ { \ uint32_t r1__, r2__, r3__, t__; \ \ r1__ = (x); \ r2__ = (a); \ UN8_rb_MUL_UN8_rb (r1__, r2__, t__); \ r2__ = (y); \ UN8_rb_MUL_UN8 (r2__, (b), t__); \ UN8_rb_ADD_UN8_rb (r1__, r2__, t__); \ \ r2__ = (x) >> G_SHIFT; \ r3__ = (a) >> G_SHIFT; \ UN8_rb_MUL_UN8_rb (r2__, r3__, t__); \ r3__ = (y) >> G_SHIFT; \ UN8_rb_MUL_UN8 (r3__, (b), t__); \ UN8_rb_ADD_UN8_rb (r2__, r3__, t__); \ \ x = r1__ | (r2__ << G_SHIFT); \ } while (0) /* x_c = min(x_c + y_c, 255) */ #ifndef UN8x4_ADD_UN8x4 #define UN8x4_ADD_UN8x4(x, y) \ do \ { \ uint32_t r1__, r2__, r3__, t__; \ \ r1__ = (x) & RB_MASK; \ r2__ = (y) & RB_MASK; \ UN8_rb_ADD_UN8_rb (r1__, r2__, t__); \ \ r2__ = ((x) >> G_SHIFT) & RB_MASK; \ r3__ = ((y) >> G_SHIFT) & RB_MASK; \ UN8_rb_ADD_UN8_rb (r2__, r3__, t__); \ \ x = r1__ | (r2__ << G_SHIFT); \ } while (0) #endif
0
D://workCode//uploadProject\awtk\3rd\pixman
D://workCode//uploadProject\awtk\3rd\pixman\pixman\pixman-compiler.h
/* Pixman uses some non-standard compiler features. This file ensures * they exist * * The features are: * * FUNC must be defined to expand to the current function * PIXMAN_EXPORT should be defined to whatever is required to * export functions from a shared library * limits limits for various types must be defined * inline must be defined * force_inline must be defined */ #define PIXMAN_NO_TLS 1 #if defined (__GNUC__) # define FUNC ((const char*) (__PRETTY_FUNCTION__)) #elif defined (__sun) || (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) # define FUNC ((const char*) (__func__)) #else # define FUNC ((const char*) ("???")) #endif #if defined (__GNUC__) # define unlikely(expr) __builtin_expect ((expr), 0) #else # define unlikely(expr) (expr) #endif #if defined (__GNUC__) # define MAYBE_UNUSED __attribute__((unused)) #else # define MAYBE_UNUSED #endif #ifndef INT16_MIN # define INT16_MIN (-32767-1) #endif #ifndef INT16_MAX # define INT16_MAX (32767) #endif #ifndef INT32_MIN # define INT32_MIN (-2147483647-1) #endif #ifndef INT32_MAX # define INT32_MAX (2147483647) #endif #ifndef UINT32_MIN # define UINT32_MIN (0) #endif #ifndef UINT32_MAX # define UINT32_MAX (4294967295U) #endif #ifndef INT64_MIN # define INT64_MIN (-9223372036854775807-1) #endif #ifndef INT64_MAX # define INT64_MAX (9223372036854775807) #endif #ifndef SIZE_MAX # define SIZE_MAX ((size_t)-1) #endif #ifndef M_PI # define M_PI 3.14159265358979323846 #endif #ifdef _MSC_VER /* 'inline' is available only in C++ in MSVC */ # define inline __inline # define force_inline __forceinline # define noinline __declspec(noinline) #elif defined __GNUC__ || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590)) # define inline __inline__ # define force_inline __inline__ __attribute__ ((__always_inline__)) # define noinline __attribute__((noinline)) #else # ifndef force_inline # define force_inline inline # endif # ifndef noinline # define noinline # endif #endif /* GCC visibility */ #if defined(__GNUC__) && __GNUC__ >= 4 && !defined(_WIN32) # define PIXMAN_EXPORT __attribute__ ((visibility("default"))) /* Sun Studio 8 visibility */ #elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550) # define PIXMAN_EXPORT __global #else # define PIXMAN_EXPORT #endif /* member offsets */ #define CONTAINER_OF(type, member, data) \ ((type *)(((uint8_t *)data) - offsetof (type, member))) /* TLS */ #if defined(PIXMAN_NO_TLS) # define PIXMAN_DEFINE_THREAD_LOCAL(type, name) \ static type name # define PIXMAN_GET_THREAD_LOCAL(name) \ (&name) #elif defined(TLS) # define PIXMAN_DEFINE_THREAD_LOCAL(type, name) \ static TLS type name # define PIXMAN_GET_THREAD_LOCAL(name) \ (&name) #elif defined(__MINGW32__) # define _NO_W32_PSEUDO_MODIFIERS # include <windows.h> # define PIXMAN_DEFINE_THREAD_LOCAL(type, name) \ static volatile int tls_ ## name ## _initialized = 0; \ static void *tls_ ## name ## _mutex = NULL; \ static unsigned tls_ ## name ## _index; \ \ static type * \ tls_ ## name ## _alloc (void) \ { \ type *value = calloc (1, sizeof (type)); \ if (value) \ TlsSetValue (tls_ ## name ## _index, value); \ return value; \ } \ \ static force_inline type * \ tls_ ## name ## _get (void) \ { \ type *value; \ if (!tls_ ## name ## _initialized) \ { \ if (!tls_ ## name ## _mutex) \ { \ void *mutex = CreateMutexA (NULL, 0, NULL); \ if (InterlockedCompareExchangePointer ( \ &tls_ ## name ## _mutex, mutex, NULL) != NULL) \ { \ CloseHandle (mutex); \ } \ } \ WaitForSingleObject (tls_ ## name ## _mutex, 0xFFFFFFFF); \ if (!tls_ ## name ## _initialized) \ { \ tls_ ## name ## _index = TlsAlloc (); \ tls_ ## name ## _initialized = 1; \ } \ ReleaseMutex (tls_ ## name ## _mutex); \ } \ if (tls_ ## name ## _index == 0xFFFFFFFF) \ return NULL; \ value = TlsGetValue (tls_ ## name ## _index); \ if (!value) \ value = tls_ ## name ## _alloc (); \ return value; \ } # define PIXMAN_GET_THREAD_LOCAL(name) \ tls_ ## name ## _get () #elif defined(_MSC_VER) # define PIXMAN_DEFINE_THREAD_LOCAL(type, name) \ static __declspec(thread) type name # define PIXMAN_GET_THREAD_LOCAL(name) \ (&name) #elif defined(HAVE_PTHREADS) #include <pthread.h> # define PIXMAN_DEFINE_THREAD_LOCAL(type, name) \ static pthread_once_t tls_ ## name ## _once_control = PTHREAD_ONCE_INIT; \ static pthread_key_t tls_ ## name ## _key; \ \ static void \ tls_ ## name ## _destroy_value (void *value) \ { \ free (value); \ } \ \ static void \ tls_ ## name ## _make_key (void) \ { \ pthread_key_create (&tls_ ## name ## _key, \ tls_ ## name ## _destroy_value); \ } \ \ static type * \ tls_ ## name ## _alloc (void) \ { \ type *value = calloc (1, sizeof (type)); \ if (value) \ pthread_setspecific (tls_ ## name ## _key, value); \ return value; \ } \ \ static force_inline type * \ tls_ ## name ## _get (void) \ { \ type *value = NULL; \ if (pthread_once (&tls_ ## name ## _once_control, \ tls_ ## name ## _make_key) == 0) \ { \ value = pthread_getspecific (tls_ ## name ## _key); \ if (!value) \ value = tls_ ## name ## _alloc (); \ } \ return value; \ } # define PIXMAN_GET_THREAD_LOCAL(name) \ tls_ ## name ## _get () #else # error "Unknown thread local support for this system. Pixman will not work with multiple threads. Define PIXMAN_NO_TLS to acknowledge and accept this limitation and compile pixman without thread-safety support." #endif
0