Merge branch 'development' into dtls

* development: (100 commits)
  Update Changelog for the mem-measure branch
  Fix issues introduced when rebasing
  Fix compile error in memory_buffer_alloc_selftest
  Code cosmetics
  Add curve25519 to ecc-heap.sh
  Add curve25519 to the benchmark program
  Fix compile issue when buffer_alloc not available
  New script ecc-heap.sh
  Fix unused variable issue in some configs
  Rm usunused member in private struct
  Add heap usage for PK in benchmark
  Use memory_buffer_alloc() in benchmark if available
  Only define mode_func if mode is enabled (CBC etc)
  PKCS8 encrypted key depend on PKCS5 or PKCS12
  Disable SRV_C for client measurement
  Output stack+heap usage with massif
  Enable NIST_OPTIM by default for config-suite-b
  Refactor memory.sh
  Adapt memory.sh to config-suite-b
  Adapt mini-client for config-suite-b.h
  ...

Conflicts:
	ChangeLog
	include/polarssl/net.h
	library/Makefile
	library/error.c
	library/ssl_tls.c
	programs/Makefile
	programs/ssl/ssl_client2.c
	programs/ssl/ssl_server2.c
	tests/Makefile
diff --git a/library/Makefile b/library/Makefile
index 6b1136b..2c4a93e 100644
--- a/library/Makefile
+++ b/library/Makefile
@@ -19,17 +19,28 @@
 
 # To compile as a shared library:
 ifdef SHARED
+# all code is position-indep with mingw, avoid warning about useless flag
+ifndef WINDOWS
 CFLAGS += -fPIC
 endif
+endif
 
-SONAME=libmbedtls.so.8
+SOEXT=so.8
 
-DLEXT=so.8
+DLEXT=so
 # OSX shared library extension:
 # DLEXT=dylib
 
-# Windows shared library extension:
+#
+# if we running on Windows build
+# for Windows
+#
 ifdef WINDOWS
+WINDOWS_BUILD=1
+endif
+
+# Windows shared library extension:
+ifdef WINDOWS_BUILD
 DLEXT=dll
 LDFLAGS += -lws2_32
 endif
@@ -74,7 +85,7 @@
 
 static: libpolarssl.a
 
-shared: libpolarssl.so
+shared: libpolarssl.$(DLEXT)
 
 libpolarssl.a: libmbedtls.a
 	echo "  LN    $@ -> $?"
@@ -86,25 +97,32 @@
 
 libmbedtls.a: $(OBJS)
 	echo "  AR    $@"
-	$(AR) r $@ $(OBJS)
+	$(AR) rc $@ $(OBJS)
 	echo "  RL    $@"
 	$(AR) s $@
 
-libpolarssl.so: libmbedtls.so
+libpolarssl.$(DLEXT): libmbedtls.$(DLEXT)
 	echo "  LN    $@ -> $?"
 ifndef WINDOWS
 	ln -sf $? $@
 else
 	copy /y /b $? $@
 endif
+ifdef WINDOWS_BUILD
+ifndef WINDOWS
+	ln -sf $?.a $@.a
+else
+	copy /y /b $?.a $@.a
+endif
+endif
 
-libmbedtls.${DLEXT}: $(OBJS)
+libmbedtls.$(SOEXT): $(OBJS)
 	echo "  LD    $@"
-	$(CC) ${LDFLAGS} -shared -Wl,-soname,$(SONAME) -o $@ $(OBJS)
+	$(CC) ${LDFLAGS} -shared -Wl,-soname,$@ -o $@ $(OBJS)
 
-libmbedtls.so: libmbedtls.${DLEXT}
-	echo "  LN    $@ -> libmbedtls.${DLEXT}"
-	ln -sf libmbedtls.${DLEXT} $@
+libmbedtls.so: libmbedtls.$(SOEXT)
+	echo "  LN    $@ -> libmbedtls.$(SOEXT)"
+	ln -sf libmbedtls.$(SOEXT) $@
 
 libmbedtls.dylib: $(OBJS)
 	echo "  LD    $@"
@@ -112,7 +130,7 @@
 
 libmbedtls.dll: $(OBJS)
 	echo "  LD    $@"
-	$(CC) -shared -Wl,-soname,$@ -o $@ $(OBJS) -lws2_32 -lwinmm -lgdi32
+	$(CC) -shared -Wl,-soname,$@ -Wl,--out-implib,$@.a -o $@ $(OBJS) -lws2_32 -lwinmm -lgdi32
 
 .c.o:
 	echo "  CC    $<"
diff --git a/library/aes.c b/library/aes.c
index c579d78..69505ef 100644
--- a/library/aes.c
+++ b/library/aes.c
@@ -34,6 +34,8 @@
 
 #if defined(POLARSSL_AES_C)
 
+#include <string.h>
+
 #include "polarssl/aes.h"
 #if defined(POLARSSL_PADLOCK_C)
 #include "polarssl/padlock.h"
@@ -42,11 +44,14 @@
 #include "polarssl/aesni.h"
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 #if !defined(POLARSSL_AES_ALT)
 
@@ -926,7 +931,6 @@
 /*
  * AES-CFB8 buffer encryption/decryption
  */
-#include <stdio.h>
 int aes_crypt_cfb8( aes_context *ctx,
                        int mode,
                        size_t length,
@@ -996,9 +1000,6 @@
 #endif /* !POLARSSL_AES_ALT */
 
 #if defined(POLARSSL_SELF_TEST)
-
-#include <stdio.h>
-
 /*
  * AES test vectors from:
  *
diff --git a/library/aesni.c b/library/aesni.c
index d4ec9ec..a235904 100644
--- a/library/aesni.c
+++ b/library/aesni.c
@@ -34,7 +34,8 @@
 #if defined(POLARSSL_AESNI_C)
 
 #include "polarssl/aesni.h"
-#include <stdio.h>
+
+#include <string.h>
 
 #if defined(POLARSSL_HAVE_X86_64)
 
diff --git a/library/arc4.c b/library/arc4.c
index ef0e7f8..90970ef 100644
--- a/library/arc4.c
+++ b/library/arc4.c
@@ -35,11 +35,16 @@
 
 #include "polarssl/arc4.h"
 
+#include <string.h>
+
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 #if !defined(POLARSSL_ARC4_ALT)
 
@@ -126,10 +131,6 @@
 #endif /* !POLARSSL_ARC4_ALT */
 
 #if defined(POLARSSL_SELF_TEST)
-
-#include <string.h>
-#include <stdio.h>
-
 /*
  * ARC4 tests vectors as posted by Eric Rescorla in sep. 1994:
  *
diff --git a/library/asn1parse.c b/library/asn1parse.c
index 7e8fc32..2cfd129 100644
--- a/library/asn1parse.c
+++ b/library/asn1parse.c
@@ -30,6 +30,8 @@
 
 #include "polarssl/asn1.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_BIGNUM_C)
 #include "polarssl/bignum.h"
 #endif
@@ -37,13 +39,11 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdlib.h>
 #define polarssl_malloc     malloc
 #define polarssl_free       free
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
@@ -77,7 +77,7 @@
             if( ( end - *p ) < 3 )
                 return( POLARSSL_ERR_ASN1_OUT_OF_DATA );
 
-            *len = ( (*p)[1] << 8 ) | (*p)[2];
+            *len = ( (size_t)(*p)[1] << 8 ) | (*p)[2];
             (*p) += 3;
             break;
 
@@ -85,7 +85,8 @@
             if( ( end - *p ) < 4 )
                 return( POLARSSL_ERR_ASN1_OUT_OF_DATA );
 
-            *len = ( (*p)[1] << 16 ) | ( (*p)[2] << 8 ) | (*p)[3];
+            *len = ( (size_t)(*p)[1] << 16 ) |
+                   ( (size_t)(*p)[2] << 8  ) | (*p)[3];
             (*p) += 4;
             break;
 
@@ -93,8 +94,8 @@
             if( ( end - *p ) < 5 )
                 return( POLARSSL_ERR_ASN1_OUT_OF_DATA );
 
-            *len = ( (*p)[1] << 24 ) | ( (*p)[2] << 16 ) | ( (*p)[3] << 8 ) |
-                   (*p)[4];
+            *len = ( (size_t)(*p)[1] << 24 ) | ( (size_t)(*p)[2] << 16 ) |
+                   ( (size_t)(*p)[3] << 8  ) |           (*p)[4];
             (*p) += 5;
             break;
 
@@ -269,8 +270,7 @@
         /* Allocate and assign next pointer */
         if( *p < end )
         {
-            cur->next = (asn1_sequence *) polarssl_malloc(
-                 sizeof( asn1_sequence ) );
+            cur->next = polarssl_malloc( sizeof( asn1_sequence ) );
 
             if( cur->next == NULL )
                 return( POLARSSL_ERR_ASN1_MALLOC_FAILED );
diff --git a/library/asn1write.c b/library/asn1write.c
index 8d92888..efdd648 100644
--- a/library/asn1write.c
+++ b/library/asn1write.c
@@ -30,6 +30,8 @@
 
 #include "polarssl/asn1write.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
diff --git a/library/base64.c b/library/base64.c
index 21cd3a6..684c537 100644
--- a/library/base64.c
+++ b/library/base64.c
@@ -37,11 +37,15 @@
 #include <inttypes.h>
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
+#include <string.h>
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 static const unsigned char base64_enc_map[64] =
 {
@@ -221,9 +225,6 @@
 
 #if defined(POLARSSL_SELF_TEST)
 
-#include <string.h>
-#include <stdio.h>
-
 static const unsigned char base64_test_dec[64] =
 {
     0x24, 0x48, 0x6E, 0x56, 0x87, 0x62, 0x5A, 0xBD,
diff --git a/library/bignum.c b/library/bignum.c
index 0eb95ee..91c7963 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -38,16 +38,18 @@
 #include "polarssl/bignum.h"
 #include "polarssl/bn_mul.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#include <stdlib.h>
 #define polarssl_printf     printf
 #define polarssl_malloc     malloc
 #define polarssl_free       free
 #endif
 
-#include <stdlib.h>
-
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
@@ -107,7 +109,7 @@
 
     if( X->n < nblimbs )
     {
-        if( ( p = (t_uint *) polarssl_malloc( nblimbs * ciL ) ) == NULL )
+        if( ( p = polarssl_malloc( nblimbs * ciL ) ) == NULL )
             return( POLARSSL_ERR_MPI_MALLOC_FAILED );
 
         memset( p, 0, nblimbs * ciL );
@@ -147,7 +149,7 @@
     if( i < nblimbs )
         i = nblimbs;
 
-    if( ( p = (t_uint *) polarssl_malloc( i * ciL ) ) == NULL )
+    if( ( p = polarssl_malloc( i * ciL ) ) == NULL )
         return( POLARSSL_ERR_MPI_MALLOC_FAILED );
 
     memset( p, 0, i * ciL );
@@ -1238,17 +1240,7 @@
             Z.p[i - t - 1] = ~0;
         else
         {
-            /*
-             * The version of Clang shipped by Apple with Mavericks around
-             * 2014-03 can't handle 128-bit division properly. Disable
-             * 128-bits division for this version. Let's be optimistic and
-             * assume it'll be fixed in the next minor version (next
-             * patchlevel is probably a bit too optimistic).
-             */
-#if defined(POLARSSL_HAVE_UDBL) &&                          \
-    ! ( defined(__x86_64__) && defined(__APPLE__) &&        \
-        defined(__clang_major__) && __clang_major__ == 5 && \
-        defined(__clang_minor__) && __clang_minor__ == 0 )
+#if defined(POLARSSL_HAVE_UDBL)
             t_udbl r;
 
             r  = (t_udbl) X.p[i] << biL;
diff --git a/library/blowfish.c b/library/blowfish.c
index 4bbaaf2..07cd060 100644
--- a/library/blowfish.c
+++ b/library/blowfish.c
@@ -36,6 +36,8 @@
 
 #include "polarssl/blowfish.h"
 
+#include <string.h>
+
 #if !defined(POLARSSL_BLOWFISH_ALT)
 
 /* Implementation that should never be optimized out by the compiler */
diff --git a/library/camellia.c b/library/camellia.c
index 92f74fa..72d902b 100644
--- a/library/camellia.c
+++ b/library/camellia.c
@@ -36,11 +36,15 @@
 
 #include "polarssl/camellia.h"
 
+#if defined(POLARSSL_SELF_TEST)
+#include <string.h>
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 #if !defined(POLARSSL_CAMELLIA_ALT)
 
@@ -452,7 +456,7 @@
     camellia_init( &cty );
 
     /* Also checks keysize */
-    if( ( ret = camellia_setkey_enc( &cty, key, keysize ) ) )
+    if( ( ret = camellia_setkey_enc( &cty, key, keysize ) ) != 0 )
         goto exit;
 
     ctx->nr = cty.nr;
@@ -689,8 +693,6 @@
 
 #if defined(POLARSSL_SELF_TEST)
 
-#include <stdio.h>
-
 /*
  * Camellia test vectors from:
  *
diff --git a/library/ccm.c b/library/ccm.c
index 8590c29..bfa9ed9 100644
--- a/library/ccm.c
+++ b/library/ccm.c
@@ -39,6 +39,17 @@
 
 #include "polarssl/ccm.h"
 
+#include <string.h>
+
+#if defined(POLARSSL_SELF_TEST) && defined(POLARSSL_AES_C)
+#if defined(POLARSSL_PLATFORM_C)
+#include "polarssl/platform.h"
+#else
+#include <stdio.h>
+#define polarssl_printf printf
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST && POLARSSL_AES_C */
+
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
@@ -333,14 +344,6 @@
 
 
 #if defined(POLARSSL_SELF_TEST) && defined(POLARSSL_AES_C)
-
-#if defined(POLARSSL_PLATFORM_C)
-#include "polarssl/platform.h"
-#else
-#include <stdio.h>
-#define polarssl_printf printf
-#endif
-
 /*
  * Examples 1 to 3 from SP800-38C Appendix C
  */
diff --git a/library/cipher.c b/library/cipher.c
index 2f886d9..b98b4a2 100644
--- a/library/cipher.c
+++ b/library/cipher.c
@@ -35,6 +35,9 @@
 #include "polarssl/cipher.h"
 #include "polarssl/cipher_wrap.h"
 
+#include <stdlib.h>
+#include <string.h>
+
 #if defined(POLARSSL_GCM_C)
 #include "polarssl/gcm.h"
 #endif
@@ -43,8 +46,6 @@
 #include "polarssl/ccm.h"
 #endif
 
-#include <stdlib.h>
-
 #if defined(POLARSSL_ARC4_C) || defined(POLARSSL_CIPHER_NULL_CIPHER)
 #define POLARSSL_CIPHER_MODE_STREAM
 #endif
diff --git a/library/cipher_wrap.c b/library/cipher_wrap.c
index e289aa2..12fc5c6 100644
--- a/library/cipher_wrap.c
+++ b/library/cipher_wrap.c
@@ -62,15 +62,18 @@
 #include "polarssl/ccm.h"
 #endif
 
+#if defined(POLARSSL_CIPHER_NULL_CIPHER)
+#include <string.h>
+#endif
+
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdlib.h>
 #define polarssl_malloc     malloc
 #define polarssl_free       free
 #endif
 
-#include <stdlib.h>
-
 #if defined(POLARSSL_GCM_C)
 /* shared by all GCM ciphers */
 static void *gcm_ctx_alloc( void )
@@ -107,63 +110,34 @@
     return aes_crypt_ecb( (aes_context *) ctx, operation, input, output );
 }
 
+#if defined(POLARSSL_CIPHER_MODE_CBC)
 static int aes_crypt_cbc_wrap( void *ctx, operation_t operation, size_t length,
         unsigned char *iv, const unsigned char *input, unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CBC)
     return aes_crypt_cbc( (aes_context *) ctx, operation, length, iv, input,
                           output );
-#else
-    ((void) ctx);
-    ((void) operation);
-    ((void) length);
-    ((void) iv);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CBC */
 }
+#endif /* POLARSSL_CIPHER_MODE_CBC */
 
+#if defined(POLARSSL_CIPHER_MODE_CFB)
 static int aes_crypt_cfb128_wrap( void *ctx, operation_t operation,
         size_t length, size_t *iv_off, unsigned char *iv,
         const unsigned char *input, unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CFB)
     return aes_crypt_cfb128( (aes_context *) ctx, operation, length, iv_off, iv,
                              input, output );
-#else
-    ((void) ctx);
-    ((void) operation);
-    ((void) length);
-    ((void) iv_off);
-    ((void) iv);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CFB */
 }
+#endif /* POLARSSL_CIPHER_MODE_CFB */
 
+#if defined(POLARSSL_CIPHER_MODE_CTR)
 static int aes_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,
         unsigned char *nonce_counter, unsigned char *stream_block,
         const unsigned char *input, unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CTR)
     return aes_crypt_ctr( (aes_context *) ctx, length, nc_off, nonce_counter,
                           stream_block, input, output );
-#else
-    ((void) ctx);
-    ((void) length);
-    ((void) nc_off);
-    ((void) nonce_counter);
-    ((void) stream_block);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CTR */
 }
+#endif /* POLARSSL_CIPHER_MODE_CTR */
 
 static int aes_setkey_dec_wrap( void *ctx, const unsigned char *key,
                                 unsigned int key_length )
@@ -179,7 +153,7 @@
 
 static void * aes_ctx_alloc( void )
 {
-    aes_context *aes = (aes_context *) polarssl_malloc( sizeof( aes_context ) );
+    aes_context *aes = polarssl_malloc( sizeof( aes_context ) );
 
     if( aes == NULL )
         return( NULL );
@@ -198,10 +172,18 @@
 const cipher_base_t aes_info = {
     POLARSSL_CIPHER_ID_AES,
     aes_crypt_ecb_wrap,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     aes_crypt_cbc_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     aes_crypt_cfb128_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     aes_crypt_ctr_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     NULL,
+#endif
     aes_setkey_enc_wrap,
     aes_setkey_dec_wrap,
     aes_ctx_alloc,
@@ -357,10 +339,18 @@
 const cipher_base_t gcm_aes_info = {
     POLARSSL_CIPHER_ID_AES,
     NULL,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     NULL,
+#endif
     gcm_aes_setkey_wrap,
     gcm_aes_setkey_wrap,
     gcm_ctx_alloc,
@@ -412,10 +402,18 @@
 const cipher_base_t ccm_aes_info = {
     POLARSSL_CIPHER_ID_AES,
     NULL,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     NULL,
+#endif
     ccm_aes_setkey_wrap,
     ccm_aes_setkey_wrap,
     ccm_ctx_alloc,
@@ -467,64 +465,35 @@
                                output );
 }
 
+#if defined(POLARSSL_CIPHER_MODE_CBC)
 static int camellia_crypt_cbc_wrap( void *ctx, operation_t operation,
         size_t length, unsigned char *iv,
         const unsigned char *input, unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CBC)
     return camellia_crypt_cbc( (camellia_context *) ctx, operation, length, iv,
                                input, output );
-#else
-    ((void) ctx);
-    ((void) operation);
-    ((void) length);
-    ((void) iv);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CBC */
 }
+#endif /* POLARSSL_CIPHER_MODE_CBC */
 
+#if defined(POLARSSL_CIPHER_MODE_CFB)
 static int camellia_crypt_cfb128_wrap( void *ctx, operation_t operation,
         size_t length, size_t *iv_off, unsigned char *iv,
         const unsigned char *input, unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CFB)
     return camellia_crypt_cfb128( (camellia_context *) ctx, operation, length,
                                   iv_off, iv, input, output );
-#else
-    ((void) ctx);
-    ((void) operation);
-    ((void) length);
-    ((void) iv_off);
-    ((void) iv);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CFB */
 }
+#endif /* POLARSSL_CIPHER_MODE_CFB */
 
+#if defined(POLARSSL_CIPHER_MODE_CTR)
 static int camellia_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,
         unsigned char *nonce_counter, unsigned char *stream_block,
         const unsigned char *input, unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CTR)
     return camellia_crypt_ctr( (camellia_context *) ctx, length, nc_off,
                                nonce_counter, stream_block, input, output );
-#else
-    ((void) ctx);
-    ((void) length);
-    ((void) nc_off);
-    ((void) nonce_counter);
-    ((void) stream_block);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CTR */
 }
+#endif /* POLARSSL_CIPHER_MODE_CTR */
 
 static int camellia_setkey_dec_wrap( void *ctx, const unsigned char *key,
                                      unsigned int key_length )
@@ -541,7 +510,7 @@
 static void * camellia_ctx_alloc( void )
 {
     camellia_context *ctx;
-    ctx = (camellia_context *) polarssl_malloc( sizeof( camellia_context ) );
+    ctx = polarssl_malloc( sizeof( camellia_context ) );
 
     if( ctx == NULL )
         return( NULL );
@@ -560,10 +529,18 @@
 const cipher_base_t camellia_info = {
     POLARSSL_CIPHER_ID_CAMELLIA,
     camellia_crypt_ecb_wrap,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     camellia_crypt_cbc_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     camellia_crypt_cfb128_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     camellia_crypt_ctr_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     NULL,
+#endif
     camellia_setkey_enc_wrap,
     camellia_setkey_dec_wrap,
     camellia_ctx_alloc,
@@ -719,10 +696,18 @@
 const cipher_base_t gcm_camellia_info = {
     POLARSSL_CIPHER_ID_CAMELLIA,
     NULL,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     NULL,
+#endif
     gcm_camellia_setkey_wrap,
     gcm_camellia_setkey_wrap,
     gcm_ctx_alloc,
@@ -774,10 +759,18 @@
 const cipher_base_t ccm_camellia_info = {
     POLARSSL_CIPHER_ID_CAMELLIA,
     NULL,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     NULL,
+#endif
     ccm_camellia_setkey_wrap,
     ccm_camellia_setkey_wrap,
     ccm_ctx_alloc,
@@ -836,41 +829,23 @@
     return des3_crypt_ecb( (des3_context *) ctx, input, output );
 }
 
+#if defined(POLARSSL_CIPHER_MODE_CBC)
 static int des_crypt_cbc_wrap( void *ctx, operation_t operation, size_t length,
         unsigned char *iv, const unsigned char *input, unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CBC)
     return des_crypt_cbc( (des_context *) ctx, operation, length, iv, input,
                           output );
-#else
-    ((void) ctx);
-    ((void) operation);
-    ((void) length);
-    ((void) iv);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CBC */
 }
+#endif /* POLARSSL_CIPHER_MODE_CBC */
 
+#if defined(POLARSSL_CIPHER_MODE_CBC)
 static int des3_crypt_cbc_wrap( void *ctx, operation_t operation, size_t length,
         unsigned char *iv, const unsigned char *input, unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CBC)
     return des3_crypt_cbc( (des3_context *) ctx, operation, length, iv, input,
                            output );
-#else
-    ((void) ctx);
-    ((void) operation);
-    ((void) length);
-    ((void) iv);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CBC */
 }
+#endif /* POLARSSL_CIPHER_MODE_CBC */
 
 static int des_setkey_dec_wrap( void *ctx, const unsigned char *key,
                                 unsigned int key_length )
@@ -922,7 +897,7 @@
 
 static void * des_ctx_alloc( void )
 {
-    des_context *des = (des_context *) polarssl_malloc( sizeof( des_context ) );
+    des_context *des = polarssl_malloc( sizeof( des_context ) );
 
     if( des == NULL )
         return( NULL );
@@ -941,7 +916,7 @@
 static void * des3_ctx_alloc( void )
 {
     des3_context *des3;
-    des3 = (des3_context *) polarssl_malloc( sizeof( des3_context ) );
+    des3 = polarssl_malloc( sizeof( des3_context ) );
 
     if( des3 == NULL )
         return( NULL );
@@ -960,10 +935,18 @@
 const cipher_base_t des_info = {
     POLARSSL_CIPHER_ID_DES,
     des_crypt_ecb_wrap,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     des_crypt_cbc_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     NULL,
+#endif
     des_setkey_enc_wrap,
     des_setkey_dec_wrap,
     des_ctx_alloc,
@@ -997,10 +980,18 @@
 const cipher_base_t des_ede_info = {
     POLARSSL_CIPHER_ID_DES,
     des3_crypt_ecb_wrap,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     des3_crypt_cbc_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     NULL,
+#endif
     des3_set2key_enc_wrap,
     des3_set2key_dec_wrap,
     des3_ctx_alloc,
@@ -1034,10 +1025,18 @@
 const cipher_base_t des_ede3_info = {
     POLARSSL_CIPHER_ID_DES,
     des3_crypt_ecb_wrap,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     des3_crypt_cbc_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     NULL,
+#endif
     des3_set3key_enc_wrap,
     des3_set3key_dec_wrap,
     des3_ctx_alloc,
@@ -1077,64 +1076,35 @@
                                output );
 }
 
+#if defined(POLARSSL_CIPHER_MODE_CBC)
 static int blowfish_crypt_cbc_wrap( void *ctx, operation_t operation,
         size_t length, unsigned char *iv, const unsigned char *input,
         unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CBC)
     return blowfish_crypt_cbc( (blowfish_context *) ctx, operation, length, iv,
                                input, output );
-#else
-    ((void) ctx);
-    ((void) operation);
-    ((void) length);
-    ((void) iv);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CBC */
 }
+#endif /* POLARSSL_CIPHER_MODE_CBC */
 
+#if defined(POLARSSL_CIPHER_MODE_CFB)
 static int blowfish_crypt_cfb64_wrap( void *ctx, operation_t operation,
         size_t length, size_t *iv_off, unsigned char *iv,
         const unsigned char *input, unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CFB)
     return blowfish_crypt_cfb64( (blowfish_context *) ctx, operation, length,
                                  iv_off, iv, input, output );
-#else
-    ((void) ctx);
-    ((void) operation);
-    ((void) length);
-    ((void) iv_off);
-    ((void) iv);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CFB */
 }
+#endif /* POLARSSL_CIPHER_MODE_CFB */
 
+#if defined(POLARSSL_CIPHER_MODE_CTR)
 static int blowfish_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,
         unsigned char *nonce_counter, unsigned char *stream_block,
         const unsigned char *input, unsigned char *output )
 {
-#if defined(POLARSSL_CIPHER_MODE_CTR)
     return blowfish_crypt_ctr( (blowfish_context *) ctx, length, nc_off,
                                nonce_counter, stream_block, input, output );
-#else
-    ((void) ctx);
-    ((void) length);
-    ((void) nc_off);
-    ((void) nonce_counter);
-    ((void) stream_block);
-    ((void) input);
-    ((void) output);
-
-    return( POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE );
-#endif /* POLARSSL_CIPHER_MODE_CTR */
 }
+#endif /* POLARSSL_CIPHER_MODE_CTR */
 
 static int blowfish_setkey_wrap( void *ctx, const unsigned char *key,
                                  unsigned int key_length )
@@ -1145,7 +1115,7 @@
 static void * blowfish_ctx_alloc( void )
 {
     blowfish_context *ctx;
-    ctx = (blowfish_context *) polarssl_malloc( sizeof( blowfish_context ) );
+    ctx = polarssl_malloc( sizeof( blowfish_context ) );
 
     if( ctx == NULL )
         return( NULL );
@@ -1164,10 +1134,18 @@
 const cipher_base_t blowfish_info = {
     POLARSSL_CIPHER_ID_BLOWFISH,
     blowfish_crypt_ecb_wrap,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     blowfish_crypt_cbc_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     blowfish_crypt_cfb64_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     blowfish_crypt_ctr_wrap,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     NULL,
+#endif
     blowfish_setkey_wrap,
     blowfish_setkey_wrap,
     blowfish_ctx_alloc,
@@ -1247,7 +1225,7 @@
 static void * arc4_ctx_alloc( void )
 {
     arc4_context *ctx;
-    ctx = (arc4_context *) polarssl_malloc( sizeof( arc4_context ) );
+    ctx = polarssl_malloc( sizeof( arc4_context ) );
 
     if( ctx == NULL )
         return( NULL );
@@ -1266,10 +1244,18 @@
 const cipher_base_t arc4_base_info = {
     POLARSSL_CIPHER_ID_ARC4,
     NULL,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     arc4_crypt_stream_wrap,
+#endif
     arc4_setkey_wrap,
     arc4_setkey_wrap,
     arc4_ctx_alloc,
@@ -1321,10 +1307,18 @@
 const cipher_base_t null_base_info = {
     POLARSSL_CIPHER_ID_NULL,
     NULL,
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     NULL,
+#endif
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     null_crypt_stream,
+#endif
     null_setkey,
     null_setkey,
     null_ctx_alloc,
@@ -1439,7 +1433,7 @@
     { POLARSSL_CIPHER_NULL,                 &null_cipher_info },
 #endif /* POLARSSL_CIPHER_NULL_CIPHER */
 
-    { 0, NULL }
+    { POLARSSL_CIPHER_NONE, NULL }
 };
 
 #define NUM_CIPHERS sizeof cipher_definitions / sizeof cipher_definitions[0]
diff --git a/library/ctr_drbg.c b/library/ctr_drbg.c
index 5e63848..4fc1deb 100644
--- a/library/ctr_drbg.c
+++ b/library/ctr_drbg.c
@@ -35,15 +35,20 @@
 
 #include "polarssl/ctr_drbg.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
@@ -443,8 +448,6 @@
 
 #if defined(POLARSSL_SELF_TEST)
 
-#include <stdio.h>
-
 static unsigned char entropy_source_pr[96] =
     { 0xc1, 0x80, 0x81, 0xa6, 0x5d, 0x44, 0x02, 0x16,
       0x19, 0xb3, 0xf1, 0x80, 0xb1, 0xc9, 0x20, 0x02,
diff --git a/library/debug.c b/library/debug.c
index 24c5e70..88a9dac 100644
--- a/library/debug.c
+++ b/library/debug.c
@@ -31,8 +31,8 @@
 #include "polarssl/debug.h"
 
 #include <stdarg.h>
-#include <stdlib.h>
 #include <stdio.h>
+#include <string.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #if !defined  snprintf
@@ -44,6 +44,12 @@
 #endif
 #endif /* _MSC_VER */
 
+#if defined(POLARSSL_PLATFORM_C)
+#include "polarssl/platform.h"
+#else
+#define polarssl_snprintf snprintf
+#endif
+
 static int debug_log_mode = POLARSSL_DEBUG_DFL_MODE;
 static int debug_threshold = 0;
 
@@ -86,7 +92,7 @@
         return;
     }
 
-    snprintf( str, maxlen, "%s(%04d): %s\n", file, line, text );
+    polarssl_snprintf( str, maxlen, "%s(%04d): %s\n", file, line, text );
     str[maxlen] = '\0';
     ssl->f_dbg( ssl->p_dbg, level, str );
 }
@@ -103,9 +109,9 @@
         return;
 
     if( debug_log_mode == POLARSSL_DEBUG_LOG_FULL )
-        idx = snprintf( str, maxlen, "%s(%04d): ", file, line );
+        idx = polarssl_snprintf( str, maxlen, "%s(%04d): ", file, line );
 
-    snprintf( str + idx, maxlen - idx, "%s() returned %d (-0x%04x)\n",
+    polarssl_snprintf( str + idx, maxlen - idx, "%s() returned %d (-0x%04x)\n",
               text, ret, -ret );
 
     str[maxlen] = '\0';
@@ -124,9 +130,9 @@
         return;
 
     if( debug_log_mode == POLARSSL_DEBUG_LOG_FULL )
-        idx = snprintf( str, maxlen, "%s(%04d): ", file, line );
+        idx = polarssl_snprintf( str, maxlen, "%s(%04d): ", file, line );
 
-    snprintf( str + idx, maxlen - idx, "dumping '%s' (%u bytes)\n",
+    polarssl_snprintf( str + idx, maxlen - idx, "dumping '%s' (%u bytes)\n",
               text, (unsigned int) len );
 
     str[maxlen] = '\0';
@@ -143,7 +149,7 @@
         {
             if( i > 0 )
             {
-                snprintf( str + idx, maxlen - idx, "  %s\n", txt );
+                polarssl_snprintf( str + idx, maxlen - idx, "  %s\n", txt );
                 ssl->f_dbg( ssl->p_dbg, level, str );
 
                 idx = 0;
@@ -151,14 +157,14 @@
             }
 
             if( debug_log_mode == POLARSSL_DEBUG_LOG_FULL )
-                idx = snprintf( str, maxlen, "%s(%04d): ", file, line );
+                idx = polarssl_snprintf( str, maxlen, "%s(%04d): ", file, line );
 
-            idx += snprintf( str + idx, maxlen - idx, "%04x: ",
+            idx += polarssl_snprintf( str + idx, maxlen - idx, "%04x: ",
                              (unsigned int) i );
 
         }
 
-        idx += snprintf( str + idx, maxlen - idx, " %02x",
+        idx += polarssl_snprintf( str + idx, maxlen - idx, " %02x",
                          (unsigned int) buf[i] );
         txt[i % 16] = ( buf[i] > 31 && buf[i] < 127 ) ? buf[i] : '.' ;
     }
@@ -166,9 +172,9 @@
     if( len > 0 )
     {
         for( /* i = i */; i % 16 != 0; i++ )
-            idx += snprintf( str + idx, maxlen - idx, "   " );
+            idx += polarssl_snprintf( str + idx, maxlen - idx, "   " );
 
-        snprintf( str + idx, maxlen - idx, "  %s\n", txt );
+        polarssl_snprintf( str + idx, maxlen - idx, "  %s\n", txt );
         ssl->f_dbg( ssl->p_dbg, level, str );
     }
 }
@@ -184,11 +190,11 @@
     if( ssl->f_dbg == NULL || level > debug_threshold )
         return;
 
-    snprintf( str, maxlen, "%s(X)", text );
+    polarssl_snprintf( str, maxlen, "%s(X)", text );
     str[maxlen] = '\0';
     debug_print_mpi( ssl, level, file, line, str, &X->X );
 
-    snprintf( str, maxlen, "%s(Y)", text );
+    polarssl_snprintf( str, maxlen, "%s(Y)", text );
     str[maxlen] = '\0';
     debug_print_mpi( ssl, level, file, line, str, &X->Y );
 }
@@ -215,9 +221,9 @@
             break;
 
     if( debug_log_mode == POLARSSL_DEBUG_LOG_FULL )
-        idx = snprintf( str, maxlen, "%s(%04d): ", file, line );
+        idx = polarssl_snprintf( str, maxlen, "%s(%04d): ", file, line );
 
-    snprintf( str + idx, maxlen - idx, "value of '%s' (%d bits) is:\n",
+    polarssl_snprintf( str + idx, maxlen - idx, "value of '%s' (%d bits) is:\n",
               text, (int) ( ( n * ( sizeof(t_uint) << 3 ) ) + j + 1 ) );
 
     str[maxlen] = '\0';
@@ -240,16 +246,16 @@
             {
                 if( j > 0 )
                 {
-                    snprintf( str + idx, maxlen - idx, "\n" );
+                    polarssl_snprintf( str + idx, maxlen - idx, "\n" );
                     ssl->f_dbg( ssl->p_dbg, level, str );
                     idx = 0;
                 }
 
                 if( debug_log_mode == POLARSSL_DEBUG_LOG_FULL )
-                    idx = snprintf( str, maxlen, "%s(%04d): ", file, line );
+                    idx = polarssl_snprintf( str, maxlen, "%s(%04d): ", file, line );
             }
 
-            idx += snprintf( str + idx, maxlen - idx, " %02x", (unsigned int)
+            idx += polarssl_snprintf( str + idx, maxlen - idx, " %02x", (unsigned int)
                              ( X->p[i - 1] >> ( k << 3 ) ) & 0xFF );
 
             j++;
@@ -261,13 +267,13 @@
     {
         if( debug_log_mode == POLARSSL_DEBUG_LOG_FULL )
         {
-            idx = snprintf( str, maxlen, "%s(%04d): ", file, line );
+            idx = polarssl_snprintf( str, maxlen, "%s(%04d): ", file, line );
 
         }
-        idx += snprintf( str + idx, maxlen - idx, " 00" );
+        idx += polarssl_snprintf( str + idx, maxlen - idx, " 00" );
     }
 
-    snprintf( str + idx, maxlen - idx, "\n" );
+    polarssl_snprintf( str + idx, maxlen - idx, "\n" );
     ssl->f_dbg( ssl->p_dbg, level, str );
 }
 #endif /* POLARSSL_BIGNUM_C */
@@ -294,7 +300,7 @@
         if( items[i].type == POLARSSL_PK_DEBUG_NONE )
             return;
 
-        snprintf( name, sizeof( name ), "%s%s", text, items[i].name );
+        polarssl_snprintf( name, sizeof( name ), "%s%s", text, items[i].name );
         name[sizeof( name ) - 1] = '\0';
 
         if( items[i].type == POLARSSL_PK_DEBUG_MPI )
@@ -321,7 +327,7 @@
 
     if( debug_log_mode == POLARSSL_DEBUG_LOG_FULL )
     {
-        snprintf( prefix, maxlen, "%s(%04d): ", file, line );
+        polarssl_snprintf( prefix, maxlen, "%s(%04d): ", file, line );
         prefix[maxlen] = '\0';
     }
     else
@@ -335,9 +341,9 @@
         x509_crt_info( buf, sizeof( buf ) - 1, prefix, crt );
 
         if( debug_log_mode == POLARSSL_DEBUG_LOG_FULL )
-            idx = snprintf( str, maxlen, "%s(%04d): ", file, line );
+            idx = polarssl_snprintf( str, maxlen, "%s(%04d): ", file, line );
 
-        snprintf( str + idx, maxlen - idx, "%s #%d:\n%s",
+        polarssl_snprintf( str + idx, maxlen - idx, "%s #%d:\n%s",
                   text, ++i, buf );
 
         str[maxlen] = '\0';
diff --git a/library/des.c b/library/des.c
index 6e08cf2..16a2e74 100644
--- a/library/des.c
+++ b/library/des.c
@@ -36,11 +36,16 @@
 
 #include "polarssl/des.h"
 
+#include <string.h>
+
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 #if !defined(POLARSSL_DES_ALT)
 
@@ -802,9 +807,6 @@
 #endif /* !POLARSSL_DES_ALT */
 
 #if defined(POLARSSL_SELF_TEST)
-
-#include <stdio.h>
-
 /*
  * DES and 3DES test vectors from:
  *
diff --git a/library/dhm.c b/library/dhm.c
index fb7826a..a7b275f 100644
--- a/library/dhm.c
+++ b/library/dhm.c
@@ -35,6 +35,8 @@
 
 #include "polarssl/dhm.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_PEM_PARSE_C)
 #include "polarssl/pem.h"
 #endif
@@ -505,7 +507,7 @@
     *n = (size_t) size;
 
     if( *n + 1 == 0 ||
-        ( *buf = (unsigned char *) polarssl_malloc( *n + 1 ) ) == NULL )
+        ( *buf = polarssl_malloc( *n + 1 ) ) == NULL )
     {
         fclose( f );
         return( POLARSSL_ERR_DHM_MALLOC_FAILED );
diff --git a/library/ecdh.c b/library/ecdh.c
index 21823c6..d287948 100644
--- a/library/ecdh.c
+++ b/library/ecdh.c
@@ -37,6 +37,8 @@
 
 #include "polarssl/ecdh.h"
 
+#include <string.h>
+
 /*
  * Generate public key: simple wrapper around ecp_gen_keypair
  */
diff --git a/library/ecdsa.c b/library/ecdsa.c
index 5b62939..0585748 100644
--- a/library/ecdsa.c
+++ b/library/ecdsa.c
@@ -37,6 +37,8 @@
 #include "polarssl/ecdsa.h"
 #include "polarssl/asn1write.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_ECDSA_DETERMINISTIC)
 #include "polarssl/hmac_drbg.h"
 #endif
@@ -57,7 +59,7 @@
 
     for( md_alg = md_list(); *md_alg != 0; md_alg++ )
     {
-        if( ( md_cur = md_info_from_type( *md_alg ) ) == NULL ||
+        if( ( md_cur = md_info_from_type( (md_type_t) *md_alg ) ) == NULL ||
             (size_t) md_cur->size < min_size ||
             ( md_picked != NULL && md_cur->size > md_picked->size ) )
             continue;
diff --git a/library/ecp.c b/library/ecp.c
index aca3a2d..298c964 100644
--- a/library/ecp.c
+++ b/library/ecp.c
@@ -51,16 +51,17 @@
 
 #include "polarssl/ecp.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdlib.h>
 #define polarssl_printf     printf
 #define polarssl_malloc     malloc
 #define polarssl_free       free
 #endif
 
-#include <stdlib.h>
-
 #if defined(_MSC_VER) && !defined strcasecmp && !defined(EFIX64) && \
     !defined(EFI32)
 #define strcasecmp _stricmp
@@ -812,7 +813,7 @@
     if( t_len < 2 )
         return( ecp_normalize_jac( grp, *T ) );
 
-    if( ( c = (mpi *) polarssl_malloc( t_len * sizeof( mpi ) ) ) == NULL )
+    if( ( c = polarssl_malloc( t_len * sizeof( mpi ) ) ) == NULL )
         return( POLARSSL_ERR_ECP_MALLOC_FAILED );
 
     mpi_init( &u ); mpi_init( &Zi ); mpi_init( &ZZi );
@@ -1415,7 +1416,7 @@
 
     if( T == NULL )
     {
-        T = (ecp_point *) polarssl_malloc( pre_len * sizeof( ecp_point ) );
+        T = polarssl_malloc( pre_len * sizeof( ecp_point ) );
         if( T == NULL )
         {
             ret = POLARSSL_ERR_ECP_MALLOC_FAILED;
diff --git a/library/ecp_curves.c b/library/ecp_curves.c
index 0464e7d..0659111 100644
--- a/library/ecp_curves.c
+++ b/library/ecp_curves.c
@@ -30,6 +30,8 @@
 
 #include "polarssl/ecp.h"
 
+#include <string.h>
+
 #if defined(_MSC_VER) && !defined(inline)
 #define inline _inline
 #else
diff --git a/library/entropy.c b/library/entropy.c
index 7604e0f..846d5ee 100644
--- a/library/entropy.c
+++ b/library/entropy.c
@@ -31,10 +31,21 @@
 #include "polarssl/entropy.h"
 #include "polarssl/entropy_poll.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
+#if defined(POLARSSL_PLATFORM_C)
+#include "polarssl/platform.h"
+#else
+#include <stdio.h>
+#define polarssl_printf     printf
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
+
 #if defined(POLARSSL_HAVEGE_C)
 #include "polarssl/havege.h"
 #endif
@@ -378,14 +389,6 @@
 #endif /* POLARSSL_FS_IO */
 
 #if defined(POLARSSL_SELF_TEST)
-
-#if defined(POLARSSL_PLATFORM_C)
-#include "polarssl/platform.h"
-#else
-#include <stdio.h>
-#define polarssl_printf     printf
-#endif
-
 /*
  * Dummy source function
  */
diff --git a/library/entropy_poll.c b/library/entropy_poll.c
index 467268c..8d98d89 100644
--- a/library/entropy_poll.c
+++ b/library/entropy_poll.c
@@ -32,6 +32,7 @@
 #include "polarssl/entropy_poll.h"
 
 #if defined(POLARSSL_TIMING_C)
+#include <string.h>
 #include "polarssl/timing.h"
 #endif
 #if defined(POLARSSL_HAVEGE_C)
diff --git a/library/error.c b/library/error.c
index a25b32c..6c00e1a 100644
--- a/library/error.c
+++ b/library/error.c
@@ -28,10 +28,19 @@
 
 #if defined(POLARSSL_ERROR_C) || defined(POLARSSL_ERROR_STRERROR_DUMMY)
 #include "polarssl/error.h"
+#include <string.h>
+#endif
+
+#if defined(POLARSSL_PLATFORM_C)
+#include "polarssl/platform.h"
+#else
+#define polarssl_snprintf snprintf
 #endif
 
 #if defined(POLARSSL_ERROR_C)
 
+#include <stdio.h>
+
 #if defined(POLARSSL_AES_C)
 #include "polarssl/aes.h"
 #endif
@@ -172,9 +181,6 @@
 #include "polarssl/xtea.h"
 #endif
 
-#include <stdio.h>
-#include <string.h>
-
 #if defined(_MSC_VER) && !defined  snprintf && !defined(EFIX64) && \
     !defined(EFI32)
 #define  snprintf  _snprintf
@@ -204,301 +210,301 @@
         // BEGIN generated code
 #if defined(POLARSSL_CIPHER_C)
         if( use_ret == -(POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE) )
-            snprintf( buf, buflen, "CIPHER - The selected feature is not available" );
+            polarssl_snprintf( buf, buflen, "CIPHER - The selected feature is not available" );
         if( use_ret == -(POLARSSL_ERR_CIPHER_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "CIPHER - Bad input parameters to function" );
+            polarssl_snprintf( buf, buflen, "CIPHER - Bad input parameters to function" );
         if( use_ret == -(POLARSSL_ERR_CIPHER_ALLOC_FAILED) )
-            snprintf( buf, buflen, "CIPHER - Failed to allocate memory" );
+            polarssl_snprintf( buf, buflen, "CIPHER - Failed to allocate memory" );
         if( use_ret == -(POLARSSL_ERR_CIPHER_INVALID_PADDING) )
-            snprintf( buf, buflen, "CIPHER - Input data contains invalid padding and is rejected" );
+            polarssl_snprintf( buf, buflen, "CIPHER - Input data contains invalid padding and is rejected" );
         if( use_ret == -(POLARSSL_ERR_CIPHER_FULL_BLOCK_EXPECTED) )
-            snprintf( buf, buflen, "CIPHER - Decryption of block requires a full block" );
+            polarssl_snprintf( buf, buflen, "CIPHER - Decryption of block requires a full block" );
         if( use_ret == -(POLARSSL_ERR_CIPHER_AUTH_FAILED) )
-            snprintf( buf, buflen, "CIPHER - Authentication failed (for AEAD modes)" );
+            polarssl_snprintf( buf, buflen, "CIPHER - Authentication failed (for AEAD modes)" );
 #endif /* POLARSSL_CIPHER_C */
 
 #if defined(POLARSSL_DHM_C)
         if( use_ret == -(POLARSSL_ERR_DHM_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "DHM - Bad input parameters to function" );
+            polarssl_snprintf( buf, buflen, "DHM - Bad input parameters to function" );
         if( use_ret == -(POLARSSL_ERR_DHM_READ_PARAMS_FAILED) )
-            snprintf( buf, buflen, "DHM - Reading of the DHM parameters failed" );
+            polarssl_snprintf( buf, buflen, "DHM - Reading of the DHM parameters failed" );
         if( use_ret == -(POLARSSL_ERR_DHM_MAKE_PARAMS_FAILED) )
-            snprintf( buf, buflen, "DHM - Making of the DHM parameters failed" );
+            polarssl_snprintf( buf, buflen, "DHM - Making of the DHM parameters failed" );
         if( use_ret == -(POLARSSL_ERR_DHM_READ_PUBLIC_FAILED) )
-            snprintf( buf, buflen, "DHM - Reading of the public values failed" );
+            polarssl_snprintf( buf, buflen, "DHM - Reading of the public values failed" );
         if( use_ret == -(POLARSSL_ERR_DHM_MAKE_PUBLIC_FAILED) )
-            snprintf( buf, buflen, "DHM - Making of the public value failed" );
+            polarssl_snprintf( buf, buflen, "DHM - Making of the public value failed" );
         if( use_ret == -(POLARSSL_ERR_DHM_CALC_SECRET_FAILED) )
-            snprintf( buf, buflen, "DHM - Calculation of the DHM secret failed" );
+            polarssl_snprintf( buf, buflen, "DHM - Calculation of the DHM secret failed" );
         if( use_ret == -(POLARSSL_ERR_DHM_INVALID_FORMAT) )
-            snprintf( buf, buflen, "DHM - The ASN.1 data is not formatted correctly" );
+            polarssl_snprintf( buf, buflen, "DHM - The ASN.1 data is not formatted correctly" );
         if( use_ret == -(POLARSSL_ERR_DHM_MALLOC_FAILED) )
-            snprintf( buf, buflen, "DHM - Allocation of memory failed" );
+            polarssl_snprintf( buf, buflen, "DHM - Allocation of memory failed" );
         if( use_ret == -(POLARSSL_ERR_DHM_FILE_IO_ERROR) )
-            snprintf( buf, buflen, "DHM - Read/write of file failed" );
+            polarssl_snprintf( buf, buflen, "DHM - Read/write of file failed" );
 #endif /* POLARSSL_DHM_C */
 
 #if defined(POLARSSL_ECP_C)
         if( use_ret == -(POLARSSL_ERR_ECP_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "ECP - Bad input parameters to function" );
+            polarssl_snprintf( buf, buflen, "ECP - Bad input parameters to function" );
         if( use_ret == -(POLARSSL_ERR_ECP_BUFFER_TOO_SMALL) )
-            snprintf( buf, buflen, "ECP - The buffer is too small to write to" );
+            polarssl_snprintf( buf, buflen, "ECP - The buffer is too small to write to" );
         if( use_ret == -(POLARSSL_ERR_ECP_FEATURE_UNAVAILABLE) )
-            snprintf( buf, buflen, "ECP - Requested curve not available" );
+            polarssl_snprintf( buf, buflen, "ECP - Requested curve not available" );
         if( use_ret == -(POLARSSL_ERR_ECP_VERIFY_FAILED) )
-            snprintf( buf, buflen, "ECP - The signature is not valid" );
+            polarssl_snprintf( buf, buflen, "ECP - The signature is not valid" );
         if( use_ret == -(POLARSSL_ERR_ECP_MALLOC_FAILED) )
-            snprintf( buf, buflen, "ECP - Memory allocation failed" );
+            polarssl_snprintf( buf, buflen, "ECP - Memory allocation failed" );
         if( use_ret == -(POLARSSL_ERR_ECP_RANDOM_FAILED) )
-            snprintf( buf, buflen, "ECP - Generation of random value, such as (ephemeral) key, failed" );
+            polarssl_snprintf( buf, buflen, "ECP - Generation of random value, such as (ephemeral) key, failed" );
         if( use_ret == -(POLARSSL_ERR_ECP_INVALID_KEY) )
-            snprintf( buf, buflen, "ECP - Invalid private or public key" );
+            polarssl_snprintf( buf, buflen, "ECP - Invalid private or public key" );
         if( use_ret == -(POLARSSL_ERR_ECP_SIG_LEN_MISMATCH) )
-            snprintf( buf, buflen, "ECP - Signature is valid but shorter than the user-supplied length" );
+            polarssl_snprintf( buf, buflen, "ECP - Signature is valid but shorter than the user-supplied length" );
 #endif /* POLARSSL_ECP_C */
 
 #if defined(POLARSSL_MD_C)
         if( use_ret == -(POLARSSL_ERR_MD_FEATURE_UNAVAILABLE) )
-            snprintf( buf, buflen, "MD - The selected feature is not available" );
+            polarssl_snprintf( buf, buflen, "MD - The selected feature is not available" );
         if( use_ret == -(POLARSSL_ERR_MD_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "MD - Bad input parameters to function" );
+            polarssl_snprintf( buf, buflen, "MD - Bad input parameters to function" );
         if( use_ret == -(POLARSSL_ERR_MD_ALLOC_FAILED) )
-            snprintf( buf, buflen, "MD - Failed to allocate memory" );
+            polarssl_snprintf( buf, buflen, "MD - Failed to allocate memory" );
         if( use_ret == -(POLARSSL_ERR_MD_FILE_IO_ERROR) )
-            snprintf( buf, buflen, "MD - Opening or reading of file failed" );
+            polarssl_snprintf( buf, buflen, "MD - Opening or reading of file failed" );
 #endif /* POLARSSL_MD_C */
 
 #if defined(POLARSSL_PEM_PARSE_C) || defined(POLARSSL_PEM_WRITE_C)
         if( use_ret == -(POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT) )
-            snprintf( buf, buflen, "PEM - No PEM header or footer found" );
+            polarssl_snprintf( buf, buflen, "PEM - No PEM header or footer found" );
         if( use_ret == -(POLARSSL_ERR_PEM_INVALID_DATA) )
-            snprintf( buf, buflen, "PEM - PEM string is not as expected" );
+            polarssl_snprintf( buf, buflen, "PEM - PEM string is not as expected" );
         if( use_ret == -(POLARSSL_ERR_PEM_MALLOC_FAILED) )
-            snprintf( buf, buflen, "PEM - Failed to allocate memory" );
+            polarssl_snprintf( buf, buflen, "PEM - Failed to allocate memory" );
         if( use_ret == -(POLARSSL_ERR_PEM_INVALID_ENC_IV) )
-            snprintf( buf, buflen, "PEM - RSA IV is not in hex-format" );
+            polarssl_snprintf( buf, buflen, "PEM - RSA IV is not in hex-format" );
         if( use_ret == -(POLARSSL_ERR_PEM_UNKNOWN_ENC_ALG) )
-            snprintf( buf, buflen, "PEM - Unsupported key encryption algorithm" );
+            polarssl_snprintf( buf, buflen, "PEM - Unsupported key encryption algorithm" );
         if( use_ret == -(POLARSSL_ERR_PEM_PASSWORD_REQUIRED) )
-            snprintf( buf, buflen, "PEM - Private key password can't be empty" );
+            polarssl_snprintf( buf, buflen, "PEM - Private key password can't be empty" );
         if( use_ret == -(POLARSSL_ERR_PEM_PASSWORD_MISMATCH) )
-            snprintf( buf, buflen, "PEM - Given private key password does not allow for correct decryption" );
+            polarssl_snprintf( buf, buflen, "PEM - Given private key password does not allow for correct decryption" );
         if( use_ret == -(POLARSSL_ERR_PEM_FEATURE_UNAVAILABLE) )
-            snprintf( buf, buflen, "PEM - Unavailable feature, e.g. hashing/encryption combination" );
+            polarssl_snprintf( buf, buflen, "PEM - Unavailable feature, e.g. hashing/encryption combination" );
         if( use_ret == -(POLARSSL_ERR_PEM_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "PEM - Bad input parameters to function" );
+            polarssl_snprintf( buf, buflen, "PEM - Bad input parameters to function" );
 #endif /* POLARSSL_PEM_PARSE_C || POLARSSL_PEM_WRITE_C */
 
 #if defined(POLARSSL_PK_C)
         if( use_ret == -(POLARSSL_ERR_PK_MALLOC_FAILED) )
-            snprintf( buf, buflen, "PK - Memory alloation failed" );
+            polarssl_snprintf( buf, buflen, "PK - Memory alloation failed" );
         if( use_ret == -(POLARSSL_ERR_PK_TYPE_MISMATCH) )
-            snprintf( buf, buflen, "PK - Type mismatch, eg attempt to encrypt with an ECDSA key" );
+            polarssl_snprintf( buf, buflen, "PK - Type mismatch, eg attempt to encrypt with an ECDSA key" );
         if( use_ret == -(POLARSSL_ERR_PK_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "PK - Bad input parameters to function" );
+            polarssl_snprintf( buf, buflen, "PK - Bad input parameters to function" );
         if( use_ret == -(POLARSSL_ERR_PK_FILE_IO_ERROR) )
-            snprintf( buf, buflen, "PK - Read/write of file failed" );
+            polarssl_snprintf( buf, buflen, "PK - Read/write of file failed" );
         if( use_ret == -(POLARSSL_ERR_PK_KEY_INVALID_VERSION) )
-            snprintf( buf, buflen, "PK - Unsupported key version" );
+            polarssl_snprintf( buf, buflen, "PK - Unsupported key version" );
         if( use_ret == -(POLARSSL_ERR_PK_KEY_INVALID_FORMAT) )
-            snprintf( buf, buflen, "PK - Invalid key tag or value" );
+            polarssl_snprintf( buf, buflen, "PK - Invalid key tag or value" );
         if( use_ret == -(POLARSSL_ERR_PK_UNKNOWN_PK_ALG) )
-            snprintf( buf, buflen, "PK - Key algorithm is unsupported (only RSA and EC are supported)" );
+            polarssl_snprintf( buf, buflen, "PK - Key algorithm is unsupported (only RSA and EC are supported)" );
         if( use_ret == -(POLARSSL_ERR_PK_PASSWORD_REQUIRED) )
-            snprintf( buf, buflen, "PK - Private key password can't be empty" );
+            polarssl_snprintf( buf, buflen, "PK - Private key password can't be empty" );
         if( use_ret == -(POLARSSL_ERR_PK_PASSWORD_MISMATCH) )
-            snprintf( buf, buflen, "PK - Given private key password does not allow for correct decryption" );
+            polarssl_snprintf( buf, buflen, "PK - Given private key password does not allow for correct decryption" );
         if( use_ret == -(POLARSSL_ERR_PK_INVALID_PUBKEY) )
-            snprintf( buf, buflen, "PK - The pubkey tag or value is invalid (only RSA and EC are supported)" );
+            polarssl_snprintf( buf, buflen, "PK - The pubkey tag or value is invalid (only RSA and EC are supported)" );
         if( use_ret == -(POLARSSL_ERR_PK_INVALID_ALG) )
-            snprintf( buf, buflen, "PK - The algorithm tag or value is invalid" );
+            polarssl_snprintf( buf, buflen, "PK - The algorithm tag or value is invalid" );
         if( use_ret == -(POLARSSL_ERR_PK_UNKNOWN_NAMED_CURVE) )
-            snprintf( buf, buflen, "PK - Elliptic curve is unsupported (only NIST curves are supported)" );
+            polarssl_snprintf( buf, buflen, "PK - Elliptic curve is unsupported (only NIST curves are supported)" );
         if( use_ret == -(POLARSSL_ERR_PK_FEATURE_UNAVAILABLE) )
-            snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" );
+            polarssl_snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" );
         if( use_ret == -(POLARSSL_ERR_PK_SIG_LEN_MISMATCH) )
-            snprintf( buf, buflen, "PK - The signature is valid but its length is less than expected" );
+            polarssl_snprintf( buf, buflen, "PK - The signature is valid but its length is less than expected" );
 #endif /* POLARSSL_PK_C */
 
 #if defined(POLARSSL_PKCS12_C)
         if( use_ret == -(POLARSSL_ERR_PKCS12_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "PKCS12 - Bad input parameters to function" );
+            polarssl_snprintf( buf, buflen, "PKCS12 - Bad input parameters to function" );
         if( use_ret == -(POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE) )
-            snprintf( buf, buflen, "PKCS12 - Feature not available, e.g. unsupported encryption scheme" );
+            polarssl_snprintf( buf, buflen, "PKCS12 - Feature not available, e.g. unsupported encryption scheme" );
         if( use_ret == -(POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT) )
-            snprintf( buf, buflen, "PKCS12 - PBE ASN.1 data not as expected" );
+            polarssl_snprintf( buf, buflen, "PKCS12 - PBE ASN.1 data not as expected" );
         if( use_ret == -(POLARSSL_ERR_PKCS12_PASSWORD_MISMATCH) )
-            snprintf( buf, buflen, "PKCS12 - Given private key password does not allow for correct decryption" );
+            polarssl_snprintf( buf, buflen, "PKCS12 - Given private key password does not allow for correct decryption" );
 #endif /* POLARSSL_PKCS12_C */
 
 #if defined(POLARSSL_PKCS5_C)
         if( use_ret == -(POLARSSL_ERR_PKCS5_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "PKCS5 - Bad input parameters to function" );
+            polarssl_snprintf( buf, buflen, "PKCS5 - Bad input parameters to function" );
         if( use_ret == -(POLARSSL_ERR_PKCS5_INVALID_FORMAT) )
-            snprintf( buf, buflen, "PKCS5 - Unexpected ASN.1 data" );
+            polarssl_snprintf( buf, buflen, "PKCS5 - Unexpected ASN.1 data" );
         if( use_ret == -(POLARSSL_ERR_PKCS5_FEATURE_UNAVAILABLE) )
-            snprintf( buf, buflen, "PKCS5 - Requested encryption or digest alg not available" );
+            polarssl_snprintf( buf, buflen, "PKCS5 - Requested encryption or digest alg not available" );
         if( use_ret == -(POLARSSL_ERR_PKCS5_PASSWORD_MISMATCH) )
-            snprintf( buf, buflen, "PKCS5 - Given private key password does not allow for correct decryption" );
+            polarssl_snprintf( buf, buflen, "PKCS5 - Given private key password does not allow for correct decryption" );
 #endif /* POLARSSL_PKCS5_C */
 
 #if defined(POLARSSL_RSA_C)
         if( use_ret == -(POLARSSL_ERR_RSA_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "RSA - Bad input parameters to function" );
+            polarssl_snprintf( buf, buflen, "RSA - Bad input parameters to function" );
         if( use_ret == -(POLARSSL_ERR_RSA_INVALID_PADDING) )
-            snprintf( buf, buflen, "RSA - Input data contains invalid padding and is rejected" );
+            polarssl_snprintf( buf, buflen, "RSA - Input data contains invalid padding and is rejected" );
         if( use_ret == -(POLARSSL_ERR_RSA_KEY_GEN_FAILED) )
-            snprintf( buf, buflen, "RSA - Something failed during generation of a key" );
+            polarssl_snprintf( buf, buflen, "RSA - Something failed during generation of a key" );
         if( use_ret == -(POLARSSL_ERR_RSA_KEY_CHECK_FAILED) )
-            snprintf( buf, buflen, "RSA - Key failed to pass the libraries validity check" );
+            polarssl_snprintf( buf, buflen, "RSA - Key failed to pass the libraries validity check" );
         if( use_ret == -(POLARSSL_ERR_RSA_PUBLIC_FAILED) )
-            snprintf( buf, buflen, "RSA - The public key operation failed" );
+            polarssl_snprintf( buf, buflen, "RSA - The public key operation failed" );
         if( use_ret == -(POLARSSL_ERR_RSA_PRIVATE_FAILED) )
-            snprintf( buf, buflen, "RSA - The private key operation failed" );
+            polarssl_snprintf( buf, buflen, "RSA - The private key operation failed" );
         if( use_ret == -(POLARSSL_ERR_RSA_VERIFY_FAILED) )
-            snprintf( buf, buflen, "RSA - The PKCS#1 verification failed" );
+            polarssl_snprintf( buf, buflen, "RSA - The PKCS#1 verification failed" );
         if( use_ret == -(POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE) )
-            snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" );
+            polarssl_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" );
         if( use_ret == -(POLARSSL_ERR_RSA_RNG_FAILED) )
-            snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" );
+            polarssl_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" );
 #endif /* POLARSSL_RSA_C */
 
 #if defined(POLARSSL_SSL_TLS_C)
         if( use_ret == -(POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE) )
-            snprintf( buf, buflen, "SSL - The requested feature is not available" );
+            polarssl_snprintf( buf, buflen, "SSL - The requested feature is not available" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "SSL - Bad input parameters to function" );
+            polarssl_snprintf( buf, buflen, "SSL - Bad input parameters to function" );
         if( use_ret == -(POLARSSL_ERR_SSL_INVALID_MAC) )
-            snprintf( buf, buflen, "SSL - Verification of the message MAC failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Verification of the message MAC failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_INVALID_RECORD) )
-            snprintf( buf, buflen, "SSL - An invalid SSL record was received" );
+            polarssl_snprintf( buf, buflen, "SSL - An invalid SSL record was received" );
         if( use_ret == -(POLARSSL_ERR_SSL_CONN_EOF) )
-            snprintf( buf, buflen, "SSL - The connection indicated an EOF" );
+            polarssl_snprintf( buf, buflen, "SSL - The connection indicated an EOF" );
         if( use_ret == -(POLARSSL_ERR_SSL_UNKNOWN_CIPHER) )
-            snprintf( buf, buflen, "SSL - An unknown cipher was received" );
+            polarssl_snprintf( buf, buflen, "SSL - An unknown cipher was received" );
         if( use_ret == -(POLARSSL_ERR_SSL_NO_CIPHER_CHOSEN) )
-            snprintf( buf, buflen, "SSL - The server has no ciphersuites in common with the client" );
+            polarssl_snprintf( buf, buflen, "SSL - The server has no ciphersuites in common with the client" );
         if( use_ret == -(POLARSSL_ERR_SSL_NO_RNG) )
-            snprintf( buf, buflen, "SSL - No RNG was provided to the SSL module" );
+            polarssl_snprintf( buf, buflen, "SSL - No RNG was provided to the SSL module" );
         if( use_ret == -(POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE) )
-            snprintf( buf, buflen, "SSL - No client certification received from the client, but required by the authentication mode" );
+            polarssl_snprintf( buf, buflen, "SSL - No client certification received from the client, but required by the authentication mode" );
         if( use_ret == -(POLARSSL_ERR_SSL_CERTIFICATE_TOO_LARGE) )
-            snprintf( buf, buflen, "SSL - Our own certificate(s) is/are too large to send in an SSL message" );
+            polarssl_snprintf( buf, buflen, "SSL - Our own certificate(s) is/are too large to send in an SSL message" );
         if( use_ret == -(POLARSSL_ERR_SSL_CERTIFICATE_REQUIRED) )
-            snprintf( buf, buflen, "SSL - The own certificate is not set, but needed by the server" );
+            polarssl_snprintf( buf, buflen, "SSL - The own certificate is not set, but needed by the server" );
         if( use_ret == -(POLARSSL_ERR_SSL_PRIVATE_KEY_REQUIRED) )
-            snprintf( buf, buflen, "SSL - The own private key or pre-shared key is not set, but needed" );
+            polarssl_snprintf( buf, buflen, "SSL - The own private key or pre-shared key is not set, but needed" );
         if( use_ret == -(POLARSSL_ERR_SSL_CA_CHAIN_REQUIRED) )
-            snprintf( buf, buflen, "SSL - No CA Chain is set, but required to operate" );
+            polarssl_snprintf( buf, buflen, "SSL - No CA Chain is set, but required to operate" );
         if( use_ret == -(POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE) )
-            snprintf( buf, buflen, "SSL - An unexpected message was received from our peer" );
+            polarssl_snprintf( buf, buflen, "SSL - An unexpected message was received from our peer" );
         if( use_ret == -(POLARSSL_ERR_SSL_FATAL_ALERT_MESSAGE) )
         {
-            snprintf( buf, buflen, "SSL - A fatal alert message was received from our peer" );
+            polarssl_snprintf( buf, buflen, "SSL - A fatal alert message was received from our peer" );
             return;
         }
         if( use_ret == -(POLARSSL_ERR_SSL_PEER_VERIFY_FAILED) )
-            snprintf( buf, buflen, "SSL - Verification of our peer failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Verification of our peer failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY) )
-            snprintf( buf, buflen, "SSL - The peer notified us that the connection is going to be closed" );
+            polarssl_snprintf( buf, buflen, "SSL - The peer notified us that the connection is going to be closed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO) )
-            snprintf( buf, buflen, "SSL - Processing of the ClientHello handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the ClientHello handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_SERVER_HELLO) )
-            snprintf( buf, buflen, "SSL - Processing of the ServerHello handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the ServerHello handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE) )
-            snprintf( buf, buflen, "SSL - Processing of the Certificate handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the Certificate handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST) )
-            snprintf( buf, buflen, "SSL - Processing of the CertificateRequest handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the CertificateRequest handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE) )
-            snprintf( buf, buflen, "SSL - Processing of the ServerKeyExchange handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the ServerKeyExchange handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_SERVER_HELLO_DONE) )
-            snprintf( buf, buflen, "SSL - Processing of the ServerHelloDone handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the ServerHelloDone handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) )
-            snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP) )
-            snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS) )
-            snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY) )
-            snprintf( buf, buflen, "SSL - Processing of the CertificateVerify handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the CertificateVerify handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC) )
-            snprintf( buf, buflen, "SSL - Processing of the ChangeCipherSpec handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the ChangeCipherSpec handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_FINISHED) )
-            snprintf( buf, buflen, "SSL - Processing of the Finished handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the Finished handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_MALLOC_FAILED) )
-            snprintf( buf, buflen, "SSL - Memory allocation failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Memory allocation failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_HW_ACCEL_FAILED) )
-            snprintf( buf, buflen, "SSL - Hardware acceleration function returned with error" );
+            polarssl_snprintf( buf, buflen, "SSL - Hardware acceleration function returned with error" );
         if( use_ret == -(POLARSSL_ERR_SSL_HW_ACCEL_FALLTHROUGH) )
-            snprintf( buf, buflen, "SSL - Hardware acceleration function skipped / left alone data" );
+            polarssl_snprintf( buf, buflen, "SSL - Hardware acceleration function skipped / left alone data" );
         if( use_ret == -(POLARSSL_ERR_SSL_COMPRESSION_FAILED) )
-            snprintf( buf, buflen, "SSL - Processing of the compression / decompression failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the compression / decompression failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_PROTOCOL_VERSION) )
-            snprintf( buf, buflen, "SSL - Handshake protocol not within min/max boundaries" );
+            polarssl_snprintf( buf, buflen, "SSL - Handshake protocol not within min/max boundaries" );
         if( use_ret == -(POLARSSL_ERR_SSL_BAD_HS_NEW_SESSION_TICKET) )
-            snprintf( buf, buflen, "SSL - Processing of the NewSessionTicket handshake message failed" );
+            polarssl_snprintf( buf, buflen, "SSL - Processing of the NewSessionTicket handshake message failed" );
         if( use_ret == -(POLARSSL_ERR_SSL_SESSION_TICKET_EXPIRED) )
-            snprintf( buf, buflen, "SSL - Session ticket has expired" );
+            polarssl_snprintf( buf, buflen, "SSL - Session ticket has expired" );
         if( use_ret == -(POLARSSL_ERR_SSL_PK_TYPE_MISMATCH) )
-            snprintf( buf, buflen, "SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)" );
+            polarssl_snprintf( buf, buflen, "SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)" );
         if( use_ret == -(POLARSSL_ERR_SSL_UNKNOWN_IDENTITY) )
-            snprintf( buf, buflen, "SSL - Unknown identity received (eg, PSK identity)" );
+            polarssl_snprintf( buf, buflen, "SSL - Unknown identity received (eg, PSK identity)" );
         if( use_ret == -(POLARSSL_ERR_SSL_INTERNAL_ERROR) )
-            snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" );
+            polarssl_snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" );
         if( use_ret == -(POLARSSL_ERR_SSL_COUNTER_WRAPPING) )
-            snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" );
+            polarssl_snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" );
         if( use_ret == -(POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) )
-            snprintf( buf, buflen, "SSL - Unexpected message at ServerHello in renegotiation" );
+            polarssl_snprintf( buf, buflen, "SSL - Unexpected message at ServerHello in renegotiation" );
         if( use_ret == -(POLARSSL_ERR_SSL_HELLO_VERIFY_REQUIRED) )
-            snprintf( buf, buflen, "SSL - DTLS client must retry for hello verification" );
+            polarssl_snprintf( buf, buflen, "SSL - DTLS client must retry for hello verification" );
         if( use_ret == -(POLARSSL_ERR_SSL_BUFFER_TOO_SMALL) )
-            snprintf( buf, buflen, "SSL - A buffer is too small to receive or write a message" );
+            polarssl_snprintf( buf, buflen, "SSL - A buffer is too small to receive or write a message" );
         if( use_ret == -(POLARSSL_ERR_SSL_NO_USABLE_CIPHERSUITE) )
-            snprintf( buf, buflen, "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" );
+            polarssl_snprintf( buf, buflen, "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" );
 #endif /* POLARSSL_SSL_TLS_C */
 
 #if defined(POLARSSL_X509_USE_C) || defined(POLARSSL_X509_CREATE_C)
         if( use_ret == -(POLARSSL_ERR_X509_FEATURE_UNAVAILABLE) )
-            snprintf( buf, buflen, "X509 - Unavailable feature, e.g. RSA hashing/encryption combination" );
+            polarssl_snprintf( buf, buflen, "X509 - Unavailable feature, e.g. RSA hashing/encryption combination" );
         if( use_ret == -(POLARSSL_ERR_X509_UNKNOWN_OID) )
-            snprintf( buf, buflen, "X509 - Requested OID is unknown" );
+            polarssl_snprintf( buf, buflen, "X509 - Requested OID is unknown" );
         if( use_ret == -(POLARSSL_ERR_X509_INVALID_FORMAT) )
-            snprintf( buf, buflen, "X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected" );
+            polarssl_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected" );
         if( use_ret == -(POLARSSL_ERR_X509_INVALID_VERSION) )
-            snprintf( buf, buflen, "X509 - The CRT/CRL/CSR version element is invalid" );
+            polarssl_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR version element is invalid" );
         if( use_ret == -(POLARSSL_ERR_X509_INVALID_SERIAL) )
-            snprintf( buf, buflen, "X509 - The serial tag or value is invalid" );
+            polarssl_snprintf( buf, buflen, "X509 - The serial tag or value is invalid" );
         if( use_ret == -(POLARSSL_ERR_X509_INVALID_ALG) )
-            snprintf( buf, buflen, "X509 - The algorithm tag or value is invalid" );
+            polarssl_snprintf( buf, buflen, "X509 - The algorithm tag or value is invalid" );
         if( use_ret == -(POLARSSL_ERR_X509_INVALID_NAME) )
-            snprintf( buf, buflen, "X509 - The name tag or value is invalid" );
+            polarssl_snprintf( buf, buflen, "X509 - The name tag or value is invalid" );
         if( use_ret == -(POLARSSL_ERR_X509_INVALID_DATE) )
-            snprintf( buf, buflen, "X509 - The date tag or value is invalid" );
+            polarssl_snprintf( buf, buflen, "X509 - The date tag or value is invalid" );
         if( use_ret == -(POLARSSL_ERR_X509_INVALID_SIGNATURE) )
-            snprintf( buf, buflen, "X509 - The signature tag or value invalid" );
+            polarssl_snprintf( buf, buflen, "X509 - The signature tag or value invalid" );
         if( use_ret == -(POLARSSL_ERR_X509_INVALID_EXTENSIONS) )
-            snprintf( buf, buflen, "X509 - The extension tag or value is invalid" );
+            polarssl_snprintf( buf, buflen, "X509 - The extension tag or value is invalid" );
         if( use_ret == -(POLARSSL_ERR_X509_UNKNOWN_VERSION) )
-            snprintf( buf, buflen, "X509 - CRT/CRL/CSR has an unsupported version number" );
+            polarssl_snprintf( buf, buflen, "X509 - CRT/CRL/CSR has an unsupported version number" );
         if( use_ret == -(POLARSSL_ERR_X509_UNKNOWN_SIG_ALG) )
-            snprintf( buf, buflen, "X509 - Signature algorithm (oid) is unsupported" );
+            polarssl_snprintf( buf, buflen, "X509 - Signature algorithm (oid) is unsupported" );
         if( use_ret == -(POLARSSL_ERR_X509_SIG_MISMATCH) )
-            snprintf( buf, buflen, "X509 - Signature algorithms do not match. (see \\c ::x509_crt sig_oid)" );
+            polarssl_snprintf( buf, buflen, "X509 - Signature algorithms do not match. (see \\c ::x509_crt sig_oid)" );
         if( use_ret == -(POLARSSL_ERR_X509_CERT_VERIFY_FAILED) )
-            snprintf( buf, buflen, "X509 - Certificate verification failed, e.g. CRL, CA or signature check failed" );
+            polarssl_snprintf( buf, buflen, "X509 - Certificate verification failed, e.g. CRL, CA or signature check failed" );
         if( use_ret == -(POLARSSL_ERR_X509_CERT_UNKNOWN_FORMAT) )
-            snprintf( buf, buflen, "X509 - Format not recognized as DER or PEM" );
+            polarssl_snprintf( buf, buflen, "X509 - Format not recognized as DER or PEM" );
         if( use_ret == -(POLARSSL_ERR_X509_BAD_INPUT_DATA) )
-            snprintf( buf, buflen, "X509 - Input invalid" );
+            polarssl_snprintf( buf, buflen, "X509 - Input invalid" );
         if( use_ret == -(POLARSSL_ERR_X509_MALLOC_FAILED) )
-            snprintf( buf, buflen, "X509 - Allocation of memory failed" );
+            polarssl_snprintf( buf, buflen, "X509 - Allocation of memory failed" );
         if( use_ret == -(POLARSSL_ERR_X509_FILE_IO_ERROR) )
-            snprintf( buf, buflen, "X509 - Read/write of file failed" );
+            polarssl_snprintf( buf, buflen, "X509 - Read/write of file failed" );
 #endif /* POLARSSL_X509_USE,X509_CREATE_C */
         // END generated code
 
         if( strlen( buf ) == 0 )
-            snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret );
+            polarssl_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret );
     }
 
     use_ret = ret & ~0xFF80;
@@ -516,7 +522,7 @@
         if( buflen - len < 5 )
             return;
 
-        snprintf( buf + len, buflen - len, " : " );
+        polarssl_snprintf( buf + len, buflen - len, " : " );
 
         buf += len + 3;
         buflen -= len + 3;
@@ -527,218 +533,218 @@
     // BEGIN generated code
 #if defined(POLARSSL_AES_C)
     if( use_ret == -(POLARSSL_ERR_AES_INVALID_KEY_LENGTH) )
-        snprintf( buf, buflen, "AES - Invalid key length" );
+        polarssl_snprintf( buf, buflen, "AES - Invalid key length" );
     if( use_ret == -(POLARSSL_ERR_AES_INVALID_INPUT_LENGTH) )
-        snprintf( buf, buflen, "AES - Invalid data input length" );
+        polarssl_snprintf( buf, buflen, "AES - Invalid data input length" );
 #endif /* POLARSSL_AES_C */
 
 #if defined(POLARSSL_ASN1_PARSE_C)
     if( use_ret == -(POLARSSL_ERR_ASN1_OUT_OF_DATA) )
-        snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" );
+        polarssl_snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" );
     if( use_ret == -(POLARSSL_ERR_ASN1_UNEXPECTED_TAG) )
-        snprintf( buf, buflen, "ASN1 - ASN1 tag was of an unexpected value" );
+        polarssl_snprintf( buf, buflen, "ASN1 - ASN1 tag was of an unexpected value" );
     if( use_ret == -(POLARSSL_ERR_ASN1_INVALID_LENGTH) )
-        snprintf( buf, buflen, "ASN1 - Error when trying to determine the length or invalid length" );
+        polarssl_snprintf( buf, buflen, "ASN1 - Error when trying to determine the length or invalid length" );
     if( use_ret == -(POLARSSL_ERR_ASN1_LENGTH_MISMATCH) )
-        snprintf( buf, buflen, "ASN1 - Actual length differs from expected length" );
+        polarssl_snprintf( buf, buflen, "ASN1 - Actual length differs from expected length" );
     if( use_ret == -(POLARSSL_ERR_ASN1_INVALID_DATA) )
-        snprintf( buf, buflen, "ASN1 - Data is invalid. (not used)" );
+        polarssl_snprintf( buf, buflen, "ASN1 - Data is invalid. (not used)" );
     if( use_ret == -(POLARSSL_ERR_ASN1_MALLOC_FAILED) )
-        snprintf( buf, buflen, "ASN1 - Memory allocation failed" );
+        polarssl_snprintf( buf, buflen, "ASN1 - Memory allocation failed" );
     if( use_ret == -(POLARSSL_ERR_ASN1_BUF_TOO_SMALL) )
-        snprintf( buf, buflen, "ASN1 - Buffer too small when writing ASN.1 data structure" );
+        polarssl_snprintf( buf, buflen, "ASN1 - Buffer too small when writing ASN.1 data structure" );
 #endif /* POLARSSL_ASN1_PARSE_C */
 
 #if defined(POLARSSL_BASE64_C)
     if( use_ret == -(POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL) )
-        snprintf( buf, buflen, "BASE64 - Output buffer too small" );
+        polarssl_snprintf( buf, buflen, "BASE64 - Output buffer too small" );
     if( use_ret == -(POLARSSL_ERR_BASE64_INVALID_CHARACTER) )
-        snprintf( buf, buflen, "BASE64 - Invalid character in input" );
+        polarssl_snprintf( buf, buflen, "BASE64 - Invalid character in input" );
 #endif /* POLARSSL_BASE64_C */
 
 #if defined(POLARSSL_BIGNUM_C)
     if( use_ret == -(POLARSSL_ERR_MPI_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "BIGNUM - An error occurred while reading from or writing to a file" );
+        polarssl_snprintf( buf, buflen, "BIGNUM - An error occurred while reading from or writing to a file" );
     if( use_ret == -(POLARSSL_ERR_MPI_BAD_INPUT_DATA) )
-        snprintf( buf, buflen, "BIGNUM - Bad input parameters to function" );
+        polarssl_snprintf( buf, buflen, "BIGNUM - Bad input parameters to function" );
     if( use_ret == -(POLARSSL_ERR_MPI_INVALID_CHARACTER) )
-        snprintf( buf, buflen, "BIGNUM - There is an invalid character in the digit string" );
+        polarssl_snprintf( buf, buflen, "BIGNUM - There is an invalid character in the digit string" );
     if( use_ret == -(POLARSSL_ERR_MPI_BUFFER_TOO_SMALL) )
-        snprintf( buf, buflen, "BIGNUM - The buffer is too small to write to" );
+        polarssl_snprintf( buf, buflen, "BIGNUM - The buffer is too small to write to" );
     if( use_ret == -(POLARSSL_ERR_MPI_NEGATIVE_VALUE) )
-        snprintf( buf, buflen, "BIGNUM - The input arguments are negative or result in illegal output" );
+        polarssl_snprintf( buf, buflen, "BIGNUM - The input arguments are negative or result in illegal output" );
     if( use_ret == -(POLARSSL_ERR_MPI_DIVISION_BY_ZERO) )
-        snprintf( buf, buflen, "BIGNUM - The input argument for division is zero, which is not allowed" );
+        polarssl_snprintf( buf, buflen, "BIGNUM - The input argument for division is zero, which is not allowed" );
     if( use_ret == -(POLARSSL_ERR_MPI_NOT_ACCEPTABLE) )
-        snprintf( buf, buflen, "BIGNUM - The input arguments are not acceptable" );
+        polarssl_snprintf( buf, buflen, "BIGNUM - The input arguments are not acceptable" );
     if( use_ret == -(POLARSSL_ERR_MPI_MALLOC_FAILED) )
-        snprintf( buf, buflen, "BIGNUM - Memory allocation failed" );
+        polarssl_snprintf( buf, buflen, "BIGNUM - Memory allocation failed" );
 #endif /* POLARSSL_BIGNUM_C */
 
 #if defined(POLARSSL_BLOWFISH_C)
     if( use_ret == -(POLARSSL_ERR_BLOWFISH_INVALID_KEY_LENGTH) )
-        snprintf( buf, buflen, "BLOWFISH - Invalid key length" );
+        polarssl_snprintf( buf, buflen, "BLOWFISH - Invalid key length" );
     if( use_ret == -(POLARSSL_ERR_BLOWFISH_INVALID_INPUT_LENGTH) )
-        snprintf( buf, buflen, "BLOWFISH - Invalid data input length" );
+        polarssl_snprintf( buf, buflen, "BLOWFISH - Invalid data input length" );
 #endif /* POLARSSL_BLOWFISH_C */
 
 #if defined(POLARSSL_CAMELLIA_C)
     if( use_ret == -(POLARSSL_ERR_CAMELLIA_INVALID_KEY_LENGTH) )
-        snprintf( buf, buflen, "CAMELLIA - Invalid key length" );
+        polarssl_snprintf( buf, buflen, "CAMELLIA - Invalid key length" );
     if( use_ret == -(POLARSSL_ERR_CAMELLIA_INVALID_INPUT_LENGTH) )
-        snprintf( buf, buflen, "CAMELLIA - Invalid data input length" );
+        polarssl_snprintf( buf, buflen, "CAMELLIA - Invalid data input length" );
 #endif /* POLARSSL_CAMELLIA_C */
 
 #if defined(POLARSSL_CCM_C)
     if( use_ret == -(POLARSSL_ERR_CCM_BAD_INPUT) )
-        snprintf( buf, buflen, "CCM - Bad input parameters to function" );
+        polarssl_snprintf( buf, buflen, "CCM - Bad input parameters to function" );
     if( use_ret == -(POLARSSL_ERR_CCM_AUTH_FAILED) )
-        snprintf( buf, buflen, "CCM - Authenticated decryption failed" );
+        polarssl_snprintf( buf, buflen, "CCM - Authenticated decryption failed" );
 #endif /* POLARSSL_CCM_C */
 
 #if defined(POLARSSL_CTR_DRBG_C)
     if( use_ret == -(POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) )
-        snprintf( buf, buflen, "CTR_DRBG - The entropy source failed" );
+        polarssl_snprintf( buf, buflen, "CTR_DRBG - The entropy source failed" );
     if( use_ret == -(POLARSSL_ERR_CTR_DRBG_REQUEST_TOO_BIG) )
-        snprintf( buf, buflen, "CTR_DRBG - Too many random requested in single call" );
+        polarssl_snprintf( buf, buflen, "CTR_DRBG - Too many random requested in single call" );
     if( use_ret == -(POLARSSL_ERR_CTR_DRBG_INPUT_TOO_BIG) )
-        snprintf( buf, buflen, "CTR_DRBG - Input too large (Entropy + additional)" );
+        polarssl_snprintf( buf, buflen, "CTR_DRBG - Input too large (Entropy + additional)" );
     if( use_ret == -(POLARSSL_ERR_CTR_DRBG_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "CTR_DRBG - Read/write error in file" );
+        polarssl_snprintf( buf, buflen, "CTR_DRBG - Read/write error in file" );
 #endif /* POLARSSL_CTR_DRBG_C */
 
 #if defined(POLARSSL_DES_C)
     if( use_ret == -(POLARSSL_ERR_DES_INVALID_INPUT_LENGTH) )
-        snprintf( buf, buflen, "DES - The data input has an invalid length" );
+        polarssl_snprintf( buf, buflen, "DES - The data input has an invalid length" );
 #endif /* POLARSSL_DES_C */
 
 #if defined(POLARSSL_ENTROPY_C)
     if( use_ret == -(POLARSSL_ERR_ENTROPY_SOURCE_FAILED) )
-        snprintf( buf, buflen, "ENTROPY - Critical entropy source failure" );
+        polarssl_snprintf( buf, buflen, "ENTROPY - Critical entropy source failure" );
     if( use_ret == -(POLARSSL_ERR_ENTROPY_MAX_SOURCES) )
-        snprintf( buf, buflen, "ENTROPY - No more sources can be added" );
+        polarssl_snprintf( buf, buflen, "ENTROPY - No more sources can be added" );
     if( use_ret == -(POLARSSL_ERR_ENTROPY_NO_SOURCES_DEFINED) )
-        snprintf( buf, buflen, "ENTROPY - No sources have been added to poll" );
+        polarssl_snprintf( buf, buflen, "ENTROPY - No sources have been added to poll" );
     if( use_ret == -(POLARSSL_ERR_ENTROPY_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "ENTROPY - Read/write error in file" );
+        polarssl_snprintf( buf, buflen, "ENTROPY - Read/write error in file" );
 #endif /* POLARSSL_ENTROPY_C */
 
 #if defined(POLARSSL_GCM_C)
     if( use_ret == -(POLARSSL_ERR_GCM_AUTH_FAILED) )
-        snprintf( buf, buflen, "GCM - Authenticated decryption failed" );
+        polarssl_snprintf( buf, buflen, "GCM - Authenticated decryption failed" );
     if( use_ret == -(POLARSSL_ERR_GCM_BAD_INPUT) )
-        snprintf( buf, buflen, "GCM - Bad input parameters to function" );
+        polarssl_snprintf( buf, buflen, "GCM - Bad input parameters to function" );
 #endif /* POLARSSL_GCM_C */
 
 #if defined(POLARSSL_HMAC_DRBG_C)
     if( use_ret == -(POLARSSL_ERR_HMAC_DRBG_REQUEST_TOO_BIG) )
-        snprintf( buf, buflen, "HMAC_DRBG - Too many random requested in single call" );
+        polarssl_snprintf( buf, buflen, "HMAC_DRBG - Too many random requested in single call" );
     if( use_ret == -(POLARSSL_ERR_HMAC_DRBG_INPUT_TOO_BIG) )
-        snprintf( buf, buflen, "HMAC_DRBG - Input too large (Entropy + additional)" );
+        polarssl_snprintf( buf, buflen, "HMAC_DRBG - Input too large (Entropy + additional)" );
     if( use_ret == -(POLARSSL_ERR_HMAC_DRBG_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "HMAC_DRBG - Read/write error in file" );
+        polarssl_snprintf( buf, buflen, "HMAC_DRBG - Read/write error in file" );
     if( use_ret == -(POLARSSL_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED) )
-        snprintf( buf, buflen, "HMAC_DRBG - The entropy source failed" );
+        polarssl_snprintf( buf, buflen, "HMAC_DRBG - The entropy source failed" );
 #endif /* POLARSSL_HMAC_DRBG_C */
 
 #if defined(POLARSSL_MD2_C)
     if( use_ret == -(POLARSSL_ERR_MD2_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "MD2 - Read/write error in file" );
+        polarssl_snprintf( buf, buflen, "MD2 - Read/write error in file" );
 #endif /* POLARSSL_MD2_C */
 
 #if defined(POLARSSL_MD4_C)
     if( use_ret == -(POLARSSL_ERR_MD4_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "MD4 - Read/write error in file" );
+        polarssl_snprintf( buf, buflen, "MD4 - Read/write error in file" );
 #endif /* POLARSSL_MD4_C */
 
 #if defined(POLARSSL_MD5_C)
     if( use_ret == -(POLARSSL_ERR_MD5_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "MD5 - Read/write error in file" );
+        polarssl_snprintf( buf, buflen, "MD5 - Read/write error in file" );
 #endif /* POLARSSL_MD5_C */
 
 #if defined(POLARSSL_NET_C)
     if( use_ret == -(POLARSSL_ERR_NET_SOCKET_FAILED) )
-        snprintf( buf, buflen, "NET - Failed to open a socket" );
+        polarssl_snprintf( buf, buflen, "NET - Failed to open a socket" );
     if( use_ret == -(POLARSSL_ERR_NET_CONNECT_FAILED) )
-        snprintf( buf, buflen, "NET - The connection to the given server / port failed" );
+        polarssl_snprintf( buf, buflen, "NET - The connection to the given server / port failed" );
     if( use_ret == -(POLARSSL_ERR_NET_BIND_FAILED) )
-        snprintf( buf, buflen, "NET - Binding of the socket failed" );
+        polarssl_snprintf( buf, buflen, "NET - Binding of the socket failed" );
     if( use_ret == -(POLARSSL_ERR_NET_LISTEN_FAILED) )
-        snprintf( buf, buflen, "NET - Could not listen on the socket" );
+        polarssl_snprintf( buf, buflen, "NET - Could not listen on the socket" );
     if( use_ret == -(POLARSSL_ERR_NET_ACCEPT_FAILED) )
-        snprintf( buf, buflen, "NET - Could not accept the incoming connection" );
+        polarssl_snprintf( buf, buflen, "NET - Could not accept the incoming connection" );
     if( use_ret == -(POLARSSL_ERR_NET_RECV_FAILED) )
-        snprintf( buf, buflen, "NET - Reading information from the socket failed" );
+        polarssl_snprintf( buf, buflen, "NET - Reading information from the socket failed" );
     if( use_ret == -(POLARSSL_ERR_NET_SEND_FAILED) )
-        snprintf( buf, buflen, "NET - Sending information through the socket failed" );
+        polarssl_snprintf( buf, buflen, "NET - Sending information through the socket failed" );
     if( use_ret == -(POLARSSL_ERR_NET_CONN_RESET) )
-        snprintf( buf, buflen, "NET - Connection was reset by peer" );
+        polarssl_snprintf( buf, buflen, "NET - Connection was reset by peer" );
     if( use_ret == -(POLARSSL_ERR_NET_WANT_READ) )
-        snprintf( buf, buflen, "NET - Connection requires a read call" );
+        polarssl_snprintf( buf, buflen, "NET - Connection requires a read call" );
     if( use_ret == -(POLARSSL_ERR_NET_WANT_WRITE) )
-        snprintf( buf, buflen, "NET - Connection requires a write call" );
+        polarssl_snprintf( buf, buflen, "NET - Connection requires a write call" );
     if( use_ret == -(POLARSSL_ERR_NET_UNKNOWN_HOST) )
-        snprintf( buf, buflen, "NET - Failed to get an IP address for the given hostname" );
+        polarssl_snprintf( buf, buflen, "NET - Failed to get an IP address for the given hostname" );
     if( use_ret == -(POLARSSL_ERR_NET_TIMEOUT) )
-        snprintf( buf, buflen, "NET - The operation timed out" );
+        polarssl_snprintf( buf, buflen, "NET - The operation timed out" );
 #endif /* POLARSSL_NET_C */
 
 #if defined(POLARSSL_OID_C)
     if( use_ret == -(POLARSSL_ERR_OID_NOT_FOUND) )
-        snprintf( buf, buflen, "OID - OID is not found" );
+        polarssl_snprintf( buf, buflen, "OID - OID is not found" );
     if( use_ret == -(POLARSSL_ERR_OID_BUF_TOO_SMALL) )
-        snprintf( buf, buflen, "OID - output buffer is too small" );
+        polarssl_snprintf( buf, buflen, "OID - output buffer is too small" );
 #endif /* POLARSSL_OID_C */
 
 #if defined(POLARSSL_PADLOCK_C)
     if( use_ret == -(POLARSSL_ERR_PADLOCK_DATA_MISALIGNED) )
-        snprintf( buf, buflen, "PADLOCK - Input data should be aligned" );
+        polarssl_snprintf( buf, buflen, "PADLOCK - Input data should be aligned" );
 #endif /* POLARSSL_PADLOCK_C */
 
 #if defined(POLARSSL_PBKDF2_C)
     if( use_ret == -(POLARSSL_ERR_PBKDF2_BAD_INPUT_DATA) )
-        snprintf( buf, buflen, "PBKDF2 - Bad input parameters to function" );
+        polarssl_snprintf( buf, buflen, "PBKDF2 - Bad input parameters to function" );
 #endif /* POLARSSL_PBKDF2_C */
 
 #if defined(POLARSSL_RIPEMD160_C)
     if( use_ret == -(POLARSSL_ERR_RIPEMD160_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "RIPEMD160 - Read/write error in file" );
+        polarssl_snprintf( buf, buflen, "RIPEMD160 - Read/write error in file" );
 #endif /* POLARSSL_RIPEMD160_C */
 
 #if defined(POLARSSL_SHA1_C)
     if( use_ret == -(POLARSSL_ERR_SHA1_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "SHA1 - Read/write error in file" );
+        polarssl_snprintf( buf, buflen, "SHA1 - Read/write error in file" );
 #endif /* POLARSSL_SHA1_C */
 
 #if defined(POLARSSL_SHA256_C)
     if( use_ret == -(POLARSSL_ERR_SHA256_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "SHA256 - Read/write error in file" );
+        polarssl_snprintf( buf, buflen, "SHA256 - Read/write error in file" );
 #endif /* POLARSSL_SHA256_C */
 
 #if defined(POLARSSL_SHA512_C)
     if( use_ret == -(POLARSSL_ERR_SHA512_FILE_IO_ERROR) )
-        snprintf( buf, buflen, "SHA512 - Read/write error in file" );
+        polarssl_snprintf( buf, buflen, "SHA512 - Read/write error in file" );
 #endif /* POLARSSL_SHA512_C */
 
 #if defined(POLARSSL_THREADING_C)
     if( use_ret == -(POLARSSL_ERR_THREADING_FEATURE_UNAVAILABLE) )
-        snprintf( buf, buflen, "THREADING - The selected feature is not available" );
+        polarssl_snprintf( buf, buflen, "THREADING - The selected feature is not available" );
     if( use_ret == -(POLARSSL_ERR_THREADING_BAD_INPUT_DATA) )
-        snprintf( buf, buflen, "THREADING - Bad input parameters to function" );
+        polarssl_snprintf( buf, buflen, "THREADING - Bad input parameters to function" );
     if( use_ret == -(POLARSSL_ERR_THREADING_MUTEX_ERROR) )
-        snprintf( buf, buflen, "THREADING - Locking / unlocking / free failed with error code" );
+        polarssl_snprintf( buf, buflen, "THREADING - Locking / unlocking / free failed with error code" );
 #endif /* POLARSSL_THREADING_C */
 
 #if defined(POLARSSL_XTEA_C)
     if( use_ret == -(POLARSSL_ERR_XTEA_INVALID_INPUT_LENGTH) )
-        snprintf( buf, buflen, "XTEA - The data input has an invalid length" );
+        polarssl_snprintf( buf, buflen, "XTEA - The data input has an invalid length" );
 #endif /* POLARSSL_XTEA_C */
     // END generated code
 
     if( strlen( buf ) != 0 )
         return;
 
-    snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret );
+    polarssl_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret );
 }
 
 #if defined(POLARSSL_ERROR_STRERROR_BC)
@@ -752,8 +758,6 @@
 
 #if defined(POLARSSL_ERROR_STRERROR_DUMMY)
 
-#include <string.h>
-
 /*
  * Provide an non-function in case POLARSSL_ERROR_C is not defined
  */
diff --git a/library/gcm.c b/library/gcm.c
index 415e53a..522a8b1 100644
--- a/library/gcm.c
+++ b/library/gcm.c
@@ -40,15 +40,20 @@
 
 #include "polarssl/gcm.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_AESNI_C)
 #include "polarssl/aesni.h"
 #endif
 
+#if defined(POLARSSL_SELF_TEST) && defined(POLARSSL_AES_C)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST && POLARSSL_AES_C */
 
 /*
  * 32-bit integer manipulation macros (big endian)
@@ -131,7 +136,7 @@
         ctx->HH[i] = vh;
     }
 
-    for( i = 2; i < 16; i <<= 1 )
+    for( i = 2; i <= 8; i *= 2 )
     {
         uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
         vh = *HiH;
@@ -496,9 +501,6 @@
 }
 
 #if defined(POLARSSL_SELF_TEST) && defined(POLARSSL_AES_C)
-
-#include <stdio.h>
-
 /*
  * AES-GCM test vectors from:
  *
diff --git a/library/hmac_drbg.c b/library/hmac_drbg.c
index ed06cce..5516301 100644
--- a/library/hmac_drbg.c
+++ b/library/hmac_drbg.c
@@ -36,15 +36,20 @@
 
 #include "polarssl/hmac_drbg.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_SELF_TEST */
+#endif /* POLARSSL_PLATFORM_C */
 
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
@@ -376,8 +381,6 @@
 
 #if defined(POLARSSL_SELF_TEST)
 
-#include <stdio.h>
-
 #if !defined(POLARSSL_SHA1_C)
 /* Dummy checkup routine */
 int hmac_drbg_self_test( int verbose )
diff --git a/library/md.c b/library/md.c
index b83e6ec..9df21b5 100644
--- a/library/md.c
+++ b/library/md.c
@@ -36,6 +36,7 @@
 #include "polarssl/md_wrap.h"
 
 #include <stdlib.h>
+#include <string.h>
 
 #if defined(_MSC_VER) && !defined strcasecmp && !defined(EFIX64) && \
     !defined(EFI32)
diff --git a/library/md2.c b/library/md2.c
index 9e9a3a2..43c129f 100644
--- a/library/md2.c
+++ b/library/md2.c
@@ -36,15 +36,20 @@
 
 #include "polarssl/md2.h"
 
-#if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST)
+#include <string.h>
+
+#if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
diff --git a/library/md4.c b/library/md4.c
index 47f5c9c..d14390b 100644
--- a/library/md4.c
+++ b/library/md4.c
@@ -36,15 +36,20 @@
 
 #include "polarssl/md4.h"
 
-#if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST)
+#include <string.h>
+
+#if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
diff --git a/library/md5.c b/library/md5.c
index 50f4ee3..b68bd4b 100644
--- a/library/md5.c
+++ b/library/md5.c
@@ -35,15 +35,20 @@
 
 #include "polarssl/md5.h"
 
-#if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST)
+#include <string.h>
+
+#if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
@@ -575,7 +580,7 @@
 
         if( i == 5 || i == 6 )
         {
-            memset( buf, '\xAA', buflen = 80 );
+            memset( buf, 0xAA, buflen = 80 );
             md5_hmac_starts( &ctx, buf, buflen );
         }
         else
diff --git a/library/md_wrap.c b/library/md_wrap.c
index 62110ce..ed5a63e 100644
--- a/library/md_wrap.c
+++ b/library/md_wrap.c
@@ -65,12 +65,11 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdlib.h>
 #define polarssl_malloc     malloc
 #define polarssl_free       free
 #endif
 
-#include <stdlib.h>
-
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
@@ -396,7 +395,7 @@
 static void * ripemd160_ctx_alloc( void )
 {
     ripemd160_context *ctx;
-    ctx = (ripemd160_context *) polarssl_malloc( sizeof( ripemd160_context ) );
+    ctx = polarssl_malloc( sizeof( ripemd160_context ) );
 
     if( ctx == NULL )
         return( NULL );
@@ -492,7 +491,7 @@
 static void * sha1_ctx_alloc( void )
 {
     sha1_context *ctx;
-    ctx = (sha1_context *) polarssl_malloc( sizeof( sha1_context ) );
+    ctx = polarssl_malloc( sizeof( sha1_context ) );
 
     if( ctx == NULL )
         return( NULL );
@@ -701,7 +700,7 @@
 static void * sha256_ctx_alloc( void )
 {
     sha256_context *ctx;
-    ctx = (sha256_context *) polarssl_malloc( sizeof( sha256_context ) );
+    ctx = polarssl_malloc( sizeof( sha256_context ) );
 
     if( ctx == NULL )
         return( NULL );
@@ -907,7 +906,7 @@
 static void * sha512_ctx_alloc( void )
 {
     sha512_context *ctx;
-    ctx = (sha512_context *) polarssl_malloc( sizeof( sha512_context ) );
+    ctx = polarssl_malloc( sizeof( sha512_context ) );
 
     if( ctx == NULL )
         return( NULL );
diff --git a/library/memory_buffer_alloc.c b/library/memory_buffer_alloc.c
index 6cde16a..7371008 100644
--- a/library/memory_buffer_alloc.c
+++ b/library/memory_buffer_alloc.c
@@ -27,14 +27,14 @@
 #endif
 
 #if defined(POLARSSL_MEMORY_BUFFER_ALLOC_C)
-
 #include "polarssl/memory_buffer_alloc.h"
 
+/* No need for the header guard as POLARSSL_MEMORY_BUFFER_ALLOC_C
+   is dependent upon POLARSSL_PLATFORM_C */
+#include "polarssl/platform.h"
+
 #include <string.h>
 
-#if defined(POLARSSL_MEMORY_DEBUG)
-#include <stdio.h>
-#endif
 #if defined(POLARSSL_MEMORY_BACKTRACE)
 #include <execinfo.h>
 #endif
@@ -43,12 +43,6 @@
 #include "polarssl/threading.h"
 #endif
 
-#if defined(POLARSSL_PLATFORM_C)
-#include "polarssl/platform.h"
-#else
-#define polarssl_fprintf fprintf
-#endif
-
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
@@ -81,7 +75,6 @@
     size_t          len;
     memory_header   *first;
     memory_header   *first_free;
-    size_t          current_alloc_size;
     int             verify;
 #if defined(POLARSSL_MEMORY_DEBUG)
     size_t          malloc_count;
@@ -274,7 +267,7 @@
         polarssl_fprintf( stderr, "FATAL: block in free_list but allocated "
                                   "data\n" );
 #endif
-        exit( 1 );
+        polarssl_exit( 1 );
     }
 
 #if defined(POLARSSL_MEMORY_DEBUG)
@@ -313,7 +306,7 @@
 #endif
 
         if( ( heap.verify & MEMORY_VERIFY_ALLOC ) && verify_chain() != 0 )
-            exit( 1 );
+            polarssl_exit( 1 );
 
         return( ( (unsigned char *) cur ) + sizeof(memory_header) );
     }
@@ -368,7 +361,7 @@
 #endif
 
     if( ( heap.verify & MEMORY_VERIFY_ALLOC ) && verify_chain() != 0 )
-        exit( 1 );
+        polarssl_exit( 1 );
 
     return( ( (unsigned char *) cur ) + sizeof(memory_header) );
 }
@@ -387,14 +380,14 @@
         polarssl_fprintf( stderr, "FATAL: polarssl_free() outside of managed "
                                   "space\n" );
 #endif
-        exit( 1 );
+        polarssl_exit( 1 );
     }
 
     p -= sizeof(memory_header);
     hdr = (memory_header *) p;
 
     if( verify_header( hdr ) != 0 )
-        exit( 1 );
+        polarssl_exit( 1 );
 
     if( hdr->alloc != 1 )
     {
@@ -402,7 +395,7 @@
         polarssl_fprintf( stderr, "FATAL: polarssl_free() on unallocated "
                                   "data\n" );
 #endif
-        exit( 1 );
+        polarssl_exit( 1 );
     }
 
     hdr->alloc = 0;
@@ -492,7 +485,7 @@
 #endif
 
     if( ( heap.verify & MEMORY_VERIFY_FREE ) && verify_chain() != 0 )
-        exit( 1 );
+        polarssl_exit( 1 );
 }
 
 void memory_buffer_set_verify( int verify )
@@ -525,6 +518,24 @@
         debug_chain();
     }
 }
+
+void memory_buffer_alloc_max_get( size_t *max_used, size_t *max_blocks )
+{
+    *max_used   = heap.maximum_used;
+    *max_blocks = heap.maximum_header_count;
+}
+
+void memory_buffer_alloc_max_reset( void )
+{
+    heap.maximum_used = 0;
+    heap.maximum_header_count = 0;
+}
+
+void memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks )
+{
+    *cur_used   = heap.total_used;
+    *cur_blocks = heap.header_count;
+}
 #endif /* POLARSSL_MEMORY_DEBUG */
 
 #if defined(POLARSSL_THREADING_C)
@@ -600,7 +611,10 @@
 
 static int check_all_free( )
 {
-    if( heap.current_alloc_size != 0 ||
+    if(
+#if defined(POLARSSL_MEMORY_DEBUG)
+        heap.total_used != 0 ||
+#endif
         heap.first != heap.first_free ||
         (void *) heap.first != (void *) heap.buf )
     {
diff --git a/library/net.c b/library/net.c
index 36fd06d..71246b5 100644
--- a/library/net.c
+++ b/library/net.c
@@ -30,6 +30,8 @@
 
 #include "polarssl/net.h"
 
+#include <string.h>
+
 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
     !defined(EFI32)
 
@@ -127,6 +129,12 @@
                            (((unsigned long )(n) & 0xFF000000) >> 24))
 #endif
 
+#if defined(POLARSSL_PLATFORM_C)
+#include "polarssl/platform.h"
+#else
+#define polarssl_snprintf snprintf
+#endif
+
 unsigned short net_htons( unsigned short n );
 unsigned long  net_htonl( unsigned long  n );
 #define net_htons(n) POLARSSL_HTONS(n)
@@ -171,7 +179,7 @@
 
     /* getaddrinfo expects port as a string */
     memset( port_str, 0, sizeof( port_str ) );
-    snprintf( port_str, sizeof( port_str ), "%d", port );
+    polarssl_snprintf( port_str, sizeof( port_str ), "%d", port );
 
     /* Do name resolution with both IPv6 and IPv4 */
     memset( &hints, 0, sizeof( hints ) );
@@ -259,7 +267,7 @@
 
     /* getaddrinfo expects port as a string */
     memset( port_str, 0, sizeof( port_str ) );
-    snprintf( port_str, sizeof( port_str ), "%d", port );
+    polarssl_snprintf( port_str, sizeof( port_str ), "%d", port );
 
     /* Bind to IPv6 and/or IPv4, but only in TCP */
     memset( &hints, 0, sizeof( hints ) );
diff --git a/library/oid.c b/library/oid.c
index e42f20d..7bb5631 100644
--- a/library/oid.c
+++ b/library/oid.c
@@ -33,12 +33,19 @@
 #include "polarssl/oid.h"
 #include "polarssl/rsa.h"
 
+#include <stdio.h>
+#include <string.h>
+
+#if defined(POLARSSL_PLATFORM_C)
+#include "polarssl/platform.h"
+#else
+#define polarssl_snprintf snprintf
+#endif
+
 #if defined(POLARSSL_X509_USE_C) || defined(POLARSSL_X509_CREATE_C)
 #include "polarssl/x509.h"
 #endif
 
-#include <stdio.h>
-
 /*
  * Macro to automatically add the size of #define'd OIDs
  */
@@ -366,7 +373,7 @@
     },
     {
         { NULL, 0, NULL, NULL },
-        0, 0,
+        POLARSSL_MD_NONE, POLARSSL_PK_NONE,
     },
 };
 
@@ -400,7 +407,7 @@
     },
     {
         { NULL, 0, NULL, NULL },
-        0,
+        POLARSSL_PK_NONE,
     },
 };
 
@@ -465,7 +472,7 @@
     },
     {
         { NULL, 0, NULL, NULL },
-        0,
+        POLARSSL_ECP_DP_NONE,
     },
 };
 
@@ -495,7 +502,7 @@
     },
     {
         { NULL, 0, NULL, NULL },
-        0,
+        POLARSSL_CIPHER_NONE,
     },
 };
 
@@ -548,7 +555,7 @@
     },
     {
         { NULL, 0, NULL, NULL },
-        0,
+        POLARSSL_MD_NONE,
     },
 };
 
@@ -579,7 +586,7 @@
     },
     {
         { NULL, 0, NULL, NULL },
-        0, 0,
+        POLARSSL_MD_NONE, POLARSSL_CIPHER_NONE,
     },
 };
 
@@ -652,7 +659,7 @@
     /* First byte contains first two dots */
     if( oid->len > 0 )
     {
-        ret = snprintf( p, n, "%d.%d", oid->p[0] / 40, oid->p[0] % 40 );
+        ret = polarssl_snprintf( p, n, "%d.%d", oid->p[0] / 40, oid->p[0] % 40 );
         SAFE_SNPRINTF();
     }
 
@@ -669,7 +676,7 @@
         if( !( oid->p[i] & 0x80 ) )
         {
             /* Last byte */
-            ret = snprintf( p, n, ".%d", value );
+            ret = polarssl_snprintf( p, n, ".%d", value );
             SAFE_SNPRINTF();
             value = 0;
         }
diff --git a/library/padlock.c b/library/padlock.c
index 3a59a22..bad25da 100644
--- a/library/padlock.c
+++ b/library/padlock.c
@@ -36,6 +36,8 @@
 
 #include "polarssl/padlock.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_HAVE_X86)
 
 /*
diff --git a/library/pem.c b/library/pem.c
index aeaa4b6..d850d40 100644
--- a/library/pem.c
+++ b/library/pem.c
@@ -27,6 +27,7 @@
 #endif
 
 #if defined(POLARSSL_PEM_PARSE_C) || defined(POLARSSL_PEM_WRITE_C)
+
 #include "polarssl/pem.h"
 #include "polarssl/base64.h"
 #include "polarssl/des.h"
@@ -34,15 +35,16 @@
 #include "polarssl/md5.h"
 #include "polarssl/cipher.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdlib.h>
 #define polarssl_malloc     malloc
 #define polarssl_free       free
 #endif
 
-#include <stdlib.h>
-
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
@@ -319,7 +321,7 @@
     if( ret == POLARSSL_ERR_BASE64_INVALID_CHARACTER )
         return( POLARSSL_ERR_PEM_INVALID_DATA + ret );
 
-    if( ( buf = (unsigned char *) polarssl_malloc( len ) ) == NULL )
+    if( ( buf = polarssl_malloc( len ) ) == NULL )
         return( POLARSSL_ERR_PEM_MALLOC_FAILED );
 
     if( ( ret = base64_decode( buf, &len, s1, s2 - s1 ) ) != 0 )
diff --git a/library/pk.c b/library/pk.c
index 572e6c8..6736bde 100644
--- a/library/pk.c
+++ b/library/pk.c
@@ -27,7 +27,6 @@
 #endif
 
 #if defined(POLARSSL_PK_C)
-
 #include "polarssl/pk.h"
 #include "polarssl/pk_wrap.h"
 
diff --git a/library/pk_wrap.c b/library/pk_wrap.c
index b6b8218..f0f09cb 100644
--- a/library/pk_wrap.c
+++ b/library/pk_wrap.c
@@ -27,12 +27,13 @@
 #endif
 
 #if defined(POLARSSL_PK_C)
-
 #include "polarssl/pk_wrap.h"
 
 /* Even if RSA not activated, for the sake of RSA-alt */
 #include "polarssl/rsa.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_ECP_C)
 #include "polarssl/ecp.h"
 #endif
diff --git a/library/pkcs11.c b/library/pkcs11.c
index a5ad23c..303b7b1 100644
--- a/library/pkcs11.c
+++ b/library/pkcs11.c
@@ -27,6 +27,7 @@
 #include "polarssl/pkcs11.h"
 
 #if defined(POLARSSL_PKCS11_C)
+
 #include "polarssl/md.h"
 #include "polarssl/oid.h"
 #include "polarssl/x509_crt.h"
diff --git a/library/pkcs12.c b/library/pkcs12.c
index b992dba..3b19051 100644
--- a/library/pkcs12.c
+++ b/library/pkcs12.c
@@ -38,6 +38,8 @@
 #include "polarssl/asn1.h"
 #include "polarssl/cipher.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_ARC4_C)
 #include "polarssl/arc4.h"
 #endif
@@ -196,7 +198,7 @@
     if( ( ret = cipher_init_ctx( &cipher_ctx, cipher_info ) ) != 0 )
         goto exit;
 
-    if( ( ret = cipher_setkey( &cipher_ctx, key, 8 * keylen, mode ) ) != 0 )
+    if( ( ret = cipher_setkey( &cipher_ctx, key, 8 * keylen, (operation_t) mode ) ) != 0 )
         goto exit;
 
     if( ( ret = cipher_set_iv( &cipher_ctx, iv, cipher_info->iv_size ) ) != 0 )
diff --git a/library/pkcs5.c b/library/pkcs5.c
index ca74046..182d632 100644
--- a/library/pkcs5.c
+++ b/library/pkcs5.c
@@ -43,9 +43,12 @@
 #include "polarssl/cipher.h"
 #include "polarssl/oid.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
 #endif
 
@@ -198,7 +201,7 @@
     if( ( ret = cipher_init_ctx( &cipher_ctx, cipher_info ) ) != 0 )
         goto exit;
 
-    if( ( ret = cipher_setkey( &cipher_ctx, key, 8 * keylen, mode ) ) != 0 )
+    if( ( ret = cipher_setkey( &cipher_ctx, key, 8 * keylen, (operation_t) mode ) ) != 0 )
         goto exit;
 
     if( ( ret = cipher_crypt( &cipher_ctx, iv, enc_scheme_params.len,
@@ -295,8 +298,6 @@
 }
 #else
 
-#include <stdio.h>
-
 #define MAX_TESTS   6
 
 size_t plen[MAX_TESTS] =
diff --git a/library/pkparse.c b/library/pkparse.c
index bc4fc6e..aec43f1 100644
--- a/library/pkparse.c
+++ b/library/pkparse.c
@@ -32,6 +32,8 @@
 #include "polarssl/asn1.h"
 #include "polarssl/oid.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_RSA_C)
 #include "polarssl/rsa.h"
 #endif
@@ -87,7 +89,7 @@
     *n = (size_t) size;
 
     if( *n + 1 == 0 ||
-        ( *buf = (unsigned char *) polarssl_malloc( *n + 1 ) ) == NULL )
+        ( *buf = polarssl_malloc( *n + 1 ) ) == NULL )
     {
         fclose( f );
         return( POLARSSL_ERR_PK_MALLOC_FAILED );
@@ -343,7 +345,7 @@
     /*
      * order INTEGER
      */
-    if( ( ret = asn1_get_mpi( &p, end, &grp->N ) ) )
+    if( ( ret = asn1_get_mpi( &p, end, &grp->N ) ) != 0 )
         return( POLARSSL_ERR_PK_KEY_INVALID_FORMAT + ret );
 
     grp->nbits = mpi_msb( &grp->N );
@@ -922,6 +924,7 @@
 /*
  * Parse an encrypted PKCS#8 encoded private key
  */
+#if defined(POLARSSL_PKCS12_C) || defined(POLARSSL_PKCS5_C)
 static int pk_parse_key_pkcs8_encrypted_der(
                                     pk_context *pk,
                                     const unsigned char *key, size_t keylen,
@@ -1039,6 +1042,7 @@
 
     return( pk_parse_key_pkcs8_unencrypted_der( pk, buf, len ) );
 }
+#endif /* POLARSSL_PKCS12_C || POLARSSL_PKCS5_C */
 
 /*
  * Parse a private key
@@ -1130,6 +1134,7 @@
     else if( ret != POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
         return( ret );
 
+#if defined(POLARSSL_PKCS12_C) || defined(POLARSSL_PKCS5_C)
     ret = pem_read_buffer( &pem,
                            "-----BEGIN ENCRYPTED PRIVATE KEY-----",
                            "-----END ENCRYPTED PRIVATE KEY-----",
@@ -1148,6 +1153,7 @@
     }
     else if( ret != POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
         return( ret );
+#endif /* POLARSSL_PKCS12_C || POLARSSL_PKCS5_C */
 #else
     ((void) pwd);
     ((void) pwdlen);
@@ -1160,6 +1166,7 @@
     * We try the different DER format parsers to see if one passes without
     * error
     */
+#if defined(POLARSSL_PKCS12_C) || defined(POLARSSL_PKCS5_C)
     if( ( ret = pk_parse_key_pkcs8_encrypted_der( pk, key, keylen,
                                                   pwd, pwdlen ) ) == 0 )
     {
@@ -1172,6 +1179,7 @@
     {
         return( ret );
     }
+#endif /* POLARSSL_PKCS12_C || POLARSSL_PKCS5_C */
 
     if( ( ret = pk_parse_key_pkcs8_unencrypted_der( pk, key, keylen ) ) == 0 )
         return( 0 );
diff --git a/library/pkwrite.c b/library/pkwrite.c
index f761ea0..29e172d 100644
--- a/library/pkwrite.c
+++ b/library/pkwrite.c
@@ -32,6 +32,8 @@
 #include "polarssl/asn1write.h"
 #include "polarssl/oid.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_RSA_C)
 #include "polarssl/rsa.h"
 #endif
diff --git a/library/platform.c b/library/platform.c
index 3eb4b1a..34295ad 100644
--- a/library/platform.c
+++ b/library/platform.c
@@ -62,6 +62,36 @@
 }
 #endif /* POLARSSL_PLATFORM_MEMORY */
 
+#if defined(POLARSSL_PLATFORM_SNPRINTF_ALT)
+#if !defined(POLARSSL_PLATFORM_STD_SNPRINTF)
+/*
+ * Make dummy function to prevent NULL pointer dereferences
+ */
+static int platform_snprintf_uninit( char * s, size_t n,
+                                     const char * format, ... )
+{
+    ((void) s);
+    ((void) n);
+    ((void) format)
+    return( 0 );
+}
+
+#define POLARSSL_PLATFORM_STD_SNPRINTF    platform_snprintf_uninit
+#endif /* !POLARSSL_PLATFORM_STD_SNPRINTF */
+
+int (*polarssl_snprintf)( char * s, size_t n,
+                          const char * format,
+                          ... ) = POLARSSL_PLATFORM_STD_SNPRINTF;
+
+int platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
+                                                 const char * format,
+                                                 ... ) )
+{
+    polarssl_snprintf = snprintf_func;
+    return( 0 );
+}
+#endif /* POLARSSL_PLATFORM_SNPRINTF_ALT */
+
 #if defined(POLARSSL_PLATFORM_PRINTF_ALT)
 #if !defined(POLARSSL_PLATFORM_STD_PRINTF)
 /*
@@ -110,4 +140,27 @@
 }
 #endif /* POLARSSL_PLATFORM_FPRINTF_ALT */
 
+#if defined(POLARSSL_PLATFORM_EXIT_ALT)
+#if !defined(POLARSSL_STD_EXIT)
+/*
+ * Make dummy function to prevent NULL pointer dereferences
+ */
+static void platform_exit_uninit( int status )
+{
+    ((void) status);
+    return( 0 );
+}
+
+#define POLARSSL_STD_EXIT   platform_exit_uninit
+#endif /* !POLARSSL_STD_EXIT */
+
+int (*polarssl_exit)( int status ) = POLARSSL_STD_EXIT;
+
+int platform_set_exit( void (*exit_func)( int status ) )
+{
+    polarssl_exit = exit_func;
+    return( 0 );
+}
+#endif /* POLARSSL_PLATFORM_EXIT_ALT */
+
 #endif /* POLARSSL_PLATFORM_C */
diff --git a/library/ripemd160.c b/library/ripemd160.c
index 768e265..2c81138 100644
--- a/library/ripemd160.c
+++ b/library/ripemd160.c
@@ -36,19 +36,20 @@
 
 #include "polarssl/ripemd160.h"
 
-#if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST)
+#include <string.h>
+
+#if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
 
 #if defined(POLARSSL_SELF_TEST)
-#include <string.h>
-#endif
-
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 /*
  * 32-bit integer manipulation macros (little endian)
diff --git a/library/rsa.c b/library/rsa.c
index f09231e..2338264 100644
--- a/library/rsa.c
+++ b/library/rsa.c
@@ -37,16 +37,20 @@
 #include "polarssl/rsa.h"
 #include "polarssl/oid.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_PKCS1_V21)
 #include "polarssl/md.h"
 #endif
 
+#if defined(POLARSSL_PKCS1_V15) && !defined(__OpenBSD__)
 #include <stdlib.h>
-#include <stdio.h>
+#endif
 
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
 #endif
 
@@ -522,7 +526,7 @@
     if( f_rng == NULL )
         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
 
-    md_info = md_info_from_type( ctx->hash_id );
+    md_info = md_info_from_type( (md_type_t) ctx->hash_id );
     if( md_info == NULL )
         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
 
@@ -701,7 +705,7 @@
     if( ilen < 16 || ilen > sizeof( buf ) )
         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
 
-    md_info = md_info_from_type( ctx->hash_id );
+    md_info = md_info_from_type( (md_type_t) ctx->hash_id );
     if( md_info == NULL )
         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
 
@@ -939,7 +943,7 @@
         hashlen = md_get_size( md_info );
     }
 
-    md_info = md_info_from_type( ctx->hash_id );
+    md_info = md_info_from_type( (md_type_t) ctx->hash_id );
     if( md_info == NULL )
         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
 
diff --git a/library/sha1.c b/library/sha1.c
index 455c780..604f8ee 100644
--- a/library/sha1.c
+++ b/library/sha1.c
@@ -35,15 +35,20 @@
 
 #include "polarssl/sha1.h"
 
-#if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST)
+#include <string.h>
+
+#if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
@@ -617,7 +622,7 @@
 
         if( i == 5 || i == 6 )
         {
-            memset( buf, '\xAA', buflen = 80 );
+            memset( buf, 0xAA, buflen = 80 );
             sha1_hmac_starts( &ctx, buf, buflen );
         }
         else
diff --git a/library/sha256.c b/library/sha256.c
index 102402e..39444bc 100644
--- a/library/sha256.c
+++ b/library/sha256.c
@@ -35,15 +35,20 @@
 
 #include "polarssl/sha256.h"
 
-#if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST)
+#include <string.h>
+
+#if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
@@ -698,7 +703,7 @@
 
         if( j == 5 || j == 6 )
         {
-            memset( buf, '\xAA', buflen = 131 );
+            memset( buf, 0xAA, buflen = 131 );
             sha256_hmac_starts( &ctx, buf, buflen, k );
         }
         else
diff --git a/library/sha512.c b/library/sha512.c
index b9dac62..5decc8f 100644
--- a/library/sha512.c
+++ b/library/sha512.c
@@ -35,15 +35,20 @@
 
 #include "polarssl/sha512.h"
 
-#if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST)
+#include <string.h>
+
+#if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
 
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
@@ -752,7 +757,7 @@
 
         if( j == 5 || j == 6 )
         {
-            memset( buf, '\xAA', buflen = 131 );
+            memset( buf, 0xAA, buflen = 131 );
             sha512_hmac_starts( &ctx, buf, buflen, k );
         }
         else
diff --git a/library/ssl_cache.c b/library/ssl_cache.c
index c649129..7fb3089 100644
--- a/library/ssl_cache.c
+++ b/library/ssl_cache.c
@@ -34,15 +34,16 @@
 
 #include "polarssl/ssl_cache.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdlib.h>
 #define polarssl_malloc     malloc
 #define polarssl_free       free
 #endif
 
-#include <stdlib.h>
-
 void ssl_cache_init( ssl_cache_context *cache )
 {
     memset( cache, 0, sizeof( ssl_cache_context ) );
@@ -102,7 +103,7 @@
          */
         if( entry->peer_cert.p != NULL )
         {
-            if( ( session->peer_cert = (x509_crt *) polarssl_malloc(
+            if( ( session->peer_cert = polarssl_malloc(
                                  sizeof(x509_crt) ) ) == NULL )
             {
                 ret = 1;
@@ -221,7 +222,7 @@
             /*
              * max_entries not reached, create new entry
              */
-            cur = (ssl_cache_entry *) polarssl_malloc( sizeof(ssl_cache_entry) );
+            cur = polarssl_malloc( sizeof(ssl_cache_entry) );
             if( cur == NULL )
             {
                 ret = 1;
@@ -258,8 +259,7 @@
      */
     if( session->peer_cert != NULL )
     {
-        cur->peer_cert.p = (unsigned char *) polarssl_malloc(
-                            session->peer_cert->raw.len );
+        cur->peer_cert.p = polarssl_malloc( session->peer_cert->raw.len );
         if( cur->peer_cert.p == NULL )
         {
             ret = 1;
diff --git a/library/ssl_ciphersuites.c b/library/ssl_ciphersuites.c
index 23690f6..4d8182e 100644
--- a/library/ssl_ciphersuites.c
+++ b/library/ssl_ciphersuites.c
@@ -33,7 +33,8 @@
 #include "polarssl/ssl_ciphersuites.h"
 #include "polarssl/ssl.h"
 
-#include <stdlib.h>
+// #include <stdlib.h>
+#include <string.h>
 
 #if defined(_MSC_VER) && !defined strcasecmp && !defined(EFIX64) && \
     !defined(EFI32)
@@ -1673,7 +1674,9 @@
 #endif /* POLARSSL_DES_C */
 #endif /* POLARSSL_ENABLE_WEAK_CIPHERSUITES */
 
-    { 0, "", 0, 0, 0, 0, 0, 0, 0, 0 }
+    { 0, "",
+      POLARSSL_CIPHER_NONE, POLARSSL_MD_NONE, POLARSSL_KEY_EXCHANGE_NONE,
+      0, 0, 0, 0, 0 }
 };
 
 #if defined(SSL_CIPHERSUITES)
diff --git a/library/ssl_cli.c b/library/ssl_cli.c
index 498f2df..cea7c10 100644
--- a/library/ssl_cli.c
+++ b/library/ssl_cli.c
@@ -31,16 +31,16 @@
 #include "polarssl/debug.h"
 #include "polarssl/ssl.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdlib.h>
 #define polarssl_malloc     malloc
 #define polarssl_free       free
 #endif
 
-#include <stdlib.h>
-#include <stdio.h>
-
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
 typedef UINT32 uint32_t;
diff --git a/library/ssl_cookie.c b/library/ssl_cookie.c
index 2f93116..5167e74 100644
--- a/library/ssl_cookie.c
+++ b/library/ssl_cookie.c
@@ -41,6 +41,8 @@
 #define polarssl_free       free
 #endif
 
+#include <string.h>
+
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
diff --git a/library/ssl_srv.c b/library/ssl_srv.c
index 597ede2..7280bbf 100644
--- a/library/ssl_srv.c
+++ b/library/ssl_srv.c
@@ -30,6 +30,9 @@
 
 #include "polarssl/debug.h"
 #include "polarssl/ssl.h"
+
+#include <string.h>
+
 #if defined(POLARSSL_ECP_C)
 #include "polarssl/ecp.h"
 #endif
@@ -37,13 +40,11 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdlib.h>
 #define polarssl_malloc     malloc
 #define polarssl_free       free
 #endif
 
-#include <stdlib.h>
-#include <stdio.h>
-
 #if defined(POLARSSL_HAVE_TIME)
 #include <time.h>
 #endif
@@ -3220,7 +3221,6 @@
     unsigned char ver[2];
     unsigned char fake_pms[48], peer_pms[48];
     unsigned char mask;
-    unsigned int uret;
     size_t i;
 
     if( ! pk_can_do( ssl_own_key( ssl ), POLARSSL_PK_RSA ) )
@@ -3287,10 +3287,7 @@
     }
     ssl->handshake->pmslen = 48;
 
-    uret = (unsigned) ret;
-    uret |= -uret; /* msb = ( ret != 0 ) */
-    uret >>= 8 * sizeof( uret ) - 1; /* uret = ( ret != 0 ) */
-    mask = (unsigned char)( -uret ) ; /* ret ? 0xff : 0x00 */
+    mask = (unsigned char)( - ( ret != 0 ) ); /* ret ? 0xff : 0x00 */
     for( i = 0; i < ssl->handshake->pmslen; i++ )
         pms[i] = ( mask & fake_pms[i] ) | ( (~mask) & peer_pms[i] );
 
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 1f06227..ea621ae 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -39,6 +39,8 @@
 #include "polarssl/debug.h"
 #include "polarssl/ssl.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_X509_CRT_PARSE_C) && \
     defined(POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE)
 #include "polarssl/oid.h"
@@ -47,12 +49,11 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdlib.h>
 #define polarssl_malloc     malloc
 #define polarssl_free       free
 #endif
 
-#include <stdlib.h>
-
 #if defined(_MSC_VER) && !defined strcasecmp && !defined(EFIX64) && \
     !defined(EFI32)
 #define strcasecmp _stricmp
@@ -166,7 +167,7 @@
     {
         int ret;
 
-        dst->peer_cert = (x509_crt *) polarssl_malloc( sizeof(x509_crt) );
+        dst->peer_cert = polarssl_malloc( sizeof(x509_crt) );
         if( dst->peer_cert == NULL )
             return( POLARSSL_ERR_SSL_MALLOC_FAILED );
 
@@ -185,7 +186,7 @@
 #if defined(POLARSSL_SSL_SESSION_TICKETS)
     if( src->ticket != NULL )
     {
-        dst->ticket = (unsigned char *) polarssl_malloc( src->ticket_len );
+        dst->ticket = polarssl_malloc( src->ticket_len );
         if( dst->ticket == NULL )
             return( POLARSSL_ERR_SSL_MALLOC_FAILED );
 
@@ -1553,7 +1554,7 @@
         unsigned char explicit_iv_len =  ssl->transform_in->ivlen -
                                          ssl->transform_in->fixed_ivlen;
 
-        if( ssl->in_msglen < explicit_iv_len + taglen )
+        if( ssl->in_msglen < (size_t) explicit_iv_len + taglen )
         {
             SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
                                 "+ taglen (%d)", ssl->in_msglen,
@@ -3892,7 +3893,7 @@
         polarssl_free( ssl->session_negotiate->peer_cert );
     }
 
-    if( ( ssl->session_negotiate->peer_cert = (x509_crt *) polarssl_malloc(
+    if( ( ssl->session_negotiate->peer_cert = polarssl_malloc(
                     sizeof( x509_crt ) ) ) == NULL )
     {
         SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed",
@@ -4798,20 +4799,17 @@
      */
     if( ssl->transform_negotiate == NULL )
     {
-        ssl->transform_negotiate = (ssl_transform *) polarssl_malloc(
-                             sizeof(ssl_transform) );
+        ssl->transform_negotiate = polarssl_malloc( sizeof(ssl_transform) );
     }
 
     if( ssl->session_negotiate == NULL )
     {
-        ssl->session_negotiate = (ssl_session *) polarssl_malloc(
-                           sizeof(ssl_session) );
+        ssl->session_negotiate = polarssl_malloc( sizeof(ssl_session) );
     }
 
     if( ssl->handshake == NULL )
     {
-        ssl->handshake = (ssl_handshake_params *)
-            polarssl_malloc( sizeof(ssl_handshake_params) );
+        ssl->handshake = polarssl_malloc( sizeof(ssl_handshake_params) );
     }
 
     /* All pointers should exist and can be directly freed without issue */
@@ -4927,8 +4925,8 @@
     /*
      * Prepare base structures
      */
-    ssl->in_buf = (unsigned char *) polarssl_malloc( len );
-    ssl->out_buf = (unsigned char *) polarssl_malloc( len );
+    ssl->in_buf  = polarssl_malloc( len );
+    ssl->out_buf = polarssl_malloc( len );
 
     if( ssl->in_buf == NULL || ssl->out_buf == NULL )
     {
@@ -5098,7 +5096,7 @@
     if( ssl->ticket_keys != NULL )
         return( 0 );
 
-    tkeys = (ssl_ticket_keys *) polarssl_malloc( sizeof(ssl_ticket_keys) );
+    tkeys = polarssl_malloc( sizeof(ssl_ticket_keys) );
     if( tkeys == NULL )
         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
 
@@ -5350,7 +5348,7 @@
 {
     ssl_key_cert *key_cert, *last;
 
-    key_cert = (ssl_key_cert *) polarssl_malloc( sizeof(ssl_key_cert) );
+    key_cert = polarssl_malloc( sizeof(ssl_key_cert) );
     if( key_cert == NULL )
         return( NULL );
 
@@ -5406,7 +5404,7 @@
     if( key_cert == NULL )
         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
 
-    key_cert->key = (pk_context *) polarssl_malloc( sizeof(pk_context) );
+    key_cert->key = polarssl_malloc( sizeof(pk_context) );
     if( key_cert->key == NULL )
         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
 
@@ -5438,7 +5436,7 @@
     if( key_cert == NULL )
         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
 
-    key_cert->key = (pk_context *) polarssl_malloc( sizeof(pk_context) );
+    key_cert->key = polarssl_malloc( sizeof(pk_context) );
     if( key_cert->key == NULL )
         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
 
@@ -5474,9 +5472,8 @@
     ssl->psk_len = psk_len;
     ssl->psk_identity_len = psk_identity_len;
 
-    ssl->psk = (unsigned char *) polarssl_malloc( ssl->psk_len );
-    ssl->psk_identity = (unsigned char *)
-                                polarssl_malloc( ssl->psk_identity_len );
+    ssl->psk = polarssl_malloc( ssl->psk_len );
+    ssl->psk_identity = polarssl_malloc( ssl->psk_identity_len );
 
     if( ssl->psk == NULL || ssl->psk_identity == NULL )
         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
@@ -5558,7 +5555,7 @@
     if( ssl->hostname_len + 1 == 0 )
         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
 
-    ssl->hostname = (unsigned char *) polarssl_malloc( ssl->hostname_len + 1 );
+    ssl->hostname = polarssl_malloc( ssl->hostname_len + 1 );
 
     if( ssl->hostname == NULL )
         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
diff --git a/library/timing.c b/library/timing.c
index fe1daa2..5791ef4 100644
--- a/library/timing.c
+++ b/library/timing.c
@@ -77,8 +77,10 @@
 #endif /* !POLARSSL_HAVE_HARDCLOCK && POLARSSL_HAVE_ASM &&
           ( _MSC_VER && _M_IX86 ) || __WATCOMC__ */
 
+/* some versions of mingw-64 have 32-bit longs even on x84_64 */
 #if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&  \
-    defined(__GNUC__) && defined(__i386__)
+    defined(__GNUC__) && ( defined(__i386__) || (                       \
+    ( defined(__amd64__) || defined( __x86_64__) ) && __SIZEOF_LONG__ == 4 ) )
 
 #define POLARSSL_HAVE_HARDCLOCK
 
@@ -249,9 +251,13 @@
     return( delta );
 }
 
-DWORD WINAPI TimerProc( LPVOID uElapse )
+/* It's OK to use a global because alarm() is supposed to be global anyway */
+static DWORD alarmMs;
+
+static DWORD WINAPI TimerProc( LPVOID TimerContext )
 {
-    Sleep( (DWORD) uElapse );
+    ((void) TimerContext);
+    Sleep( alarmMs );
     alarmed = 1;
     return( TRUE );
 }
@@ -261,8 +267,8 @@
     DWORD ThreadId;
 
     alarmed = 0;
-    CloseHandle( CreateThread( NULL, 0, TimerProc,
-        (LPVOID) ( seconds * 1000 ), 0, &ThreadId ) );
+    alarmMs = seconds * 1000;
+    CloseHandle( CreateThread( NULL, 0, TimerProc, NULL, 0, &ThreadId ) );
 }
 
 void m_sleep( int milliseconds )
diff --git a/library/version_features.c b/library/version_features.c
index 956b0ce..3e3405a 100644
--- a/library/version_features.c
+++ b/library/version_features.c
@@ -66,12 +66,18 @@
 #if defined(POLARSSL_PLATFORM_NO_STD_FUNCTIONS)
     "POLARSSL_PLATFORM_NO_STD_FUNCTIONS",
 #endif /* POLARSSL_PLATFORM_NO_STD_FUNCTIONS */
-#if defined(POLARSSL_PLATFORM_PRINTF_ALT)
-    "POLARSSL_PLATFORM_PRINTF_ALT",
-#endif /* POLARSSL_PLATFORM_PRINTF_ALT */
+#if defined(POLARSSL_PLATFORM_EXIT_ALT)
+    "POLARSSL_PLATFORM_EXIT_ALT",
+#endif /* POLARSSL_PLATFORM_EXIT_ALT */
 #if defined(POLARSSL_PLATFORM_FPRINTF_ALT)
     "POLARSSL_PLATFORM_FPRINTF_ALT",
 #endif /* POLARSSL_PLATFORM_FPRINTF_ALT */
+#if defined(POLARSSL_PLATFORM_PRINTF_ALT)
+    "POLARSSL_PLATFORM_PRINTF_ALT",
+#endif /* POLARSSL_PLATFORM_PRINTF_ALT */
+#if defined(POLARSSL_PLATFORM_SNPRINTF_ALT)
+    "POLARSSL_PLATFORM_SNPRINTF_ALT",
+#endif /* POLARSSL_PLATFORM_SNPRINTF_ALT */
 #if defined(POLARSSL_TIMING_ALT)
     "POLARSSL_TIMING_ALT",
 #endif /* POLARSSL_TIMING_ALT */
diff --git a/library/x509.c b/library/x509.c
index a3cb669..3818c3f 100644
--- a/library/x509.c
+++ b/library/x509.c
@@ -41,6 +41,10 @@
 #include "polarssl/x509.h"
 #include "polarssl/asn1.h"
 #include "polarssl/oid.h"
+
+#include <stdio.h>
+#include <string.h>
+
 #if defined(POLARSSL_PEM_PARSE_C)
 #include "polarssl/pem.h"
 #endif
@@ -48,22 +52,22 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
-#define polarssl_malloc     malloc
+#include <stdio.h>
+#include <stdlib.h>
 #define polarssl_free       free
+#define polarssl_malloc     malloc
+#define polarssl_printf     printf
+#define polarssl_snprintf   snprintf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
 #include <windows.h>
 #else
 #include <time.h>
 #endif
 
-#include <stdio.h>
-
 #if defined(POLARSSL_FS_IO)
+#include <stdio.h>
 #if !defined(_WIN32)
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -71,6 +75,8 @@
 #endif
 #endif
 
+#define CHECK(code) if( ( ret = code ) != 0 ){ return( ret ); }
+
 /*
  *  CertificateSerialNumber  ::=  INTEGER
  */
@@ -445,7 +451,7 @@
             /* Mark this item as being only one in a set */
             cur->next_merged = 1;
 
-            cur->next = (x509_name *) polarssl_malloc( sizeof( x509_name ) );
+            cur->next = polarssl_malloc( sizeof( x509_name ) );
 
             if( cur->next == NULL )
                 return( POLARSSL_ERR_X509_MALLOC_FAILED );
@@ -461,7 +467,7 @@
         if( *p == end )
             return( 0 );
 
-        cur->next = (x509_name *) polarssl_malloc( sizeof( x509_name ) );
+        cur->next = polarssl_malloc( sizeof( x509_name ) );
 
         if( cur->next == NULL )
             return( POLARSSL_ERR_X509_MALLOC_FAILED );
@@ -472,6 +478,16 @@
     }
 }
 
+static int x509_parse_int(unsigned char **p, unsigned n, int *res){
+    *res = 0;
+    for( ; n > 0; --n ){
+        if( ( **p < '0') || ( **p > '9' ) ) return POLARSSL_ERR_X509_INVALID_DATE;
+        *res *= 10;
+        *res += (*(*p)++ - '0');
+    }
+    return 0;
+}
+
 /*
  *  Time ::= CHOICE {
  *       utcTime        UTCTime,
@@ -482,7 +498,6 @@
 {
     int ret;
     size_t len;
-    char date[64];
     unsigned char tag;
 
     if( ( end - *p ) < 1 )
@@ -499,20 +514,19 @@
         if( ret != 0 )
             return( POLARSSL_ERR_X509_INVALID_DATE + ret );
 
-        memset( date,  0, sizeof( date ) );
-        memcpy( date, *p, ( len < sizeof( date ) - 1 ) ?
-                len : sizeof( date ) - 1 );
-
-        if( sscanf( date, "%2d%2d%2d%2d%2d%2dZ",
-                    &time->year, &time->mon, &time->day,
-                    &time->hour, &time->min, &time->sec ) < 5 )
+        CHECK( x509_parse_int( p, 2, &time->year ) );
+        CHECK( x509_parse_int( p, 2, &time->mon ) );
+        CHECK( x509_parse_int( p, 2, &time->day ) );
+        CHECK( x509_parse_int( p, 2, &time->hour ) );
+        CHECK( x509_parse_int( p, 2, &time->min ) );
+        if( len > 10 )
+            CHECK( x509_parse_int( p, 2, &time->sec ) );
+        if( len > 12 && *(*p)++ != 'Z' )
             return( POLARSSL_ERR_X509_INVALID_DATE );
 
         time->year +=  100 * ( time->year < 50 );
         time->year += 1900;
 
-        *p += len;
-
         return( 0 );
     }
     else if( tag == ASN1_GENERALIZED_TIME )
@@ -523,17 +537,16 @@
         if( ret != 0 )
             return( POLARSSL_ERR_X509_INVALID_DATE + ret );
 
-        memset( date,  0, sizeof( date ) );
-        memcpy( date, *p, ( len < sizeof( date ) - 1 ) ?
-                len : sizeof( date ) - 1 );
-
-        if( sscanf( date, "%4d%2d%2d%2d%2d%2dZ",
-                    &time->year, &time->mon, &time->day,
-                    &time->hour, &time->min, &time->sec ) < 5 )
+        CHECK( x509_parse_int( p, 4, &time->year ) );
+        CHECK( x509_parse_int( p, 2, &time->mon ) );
+        CHECK( x509_parse_int( p, 2, &time->day ) );
+        CHECK( x509_parse_int( p, 2, &time->hour ) );
+        CHECK( x509_parse_int( p, 2, &time->min ) );
+        if( len > 12 )
+            CHECK( x509_parse_int( p, 2, &time->sec ) );
+        if( len > 14 && *(*p)++ != 'Z' )
             return( POLARSSL_ERR_X509_INVALID_DATE );
 
-        *p += len;
-
         return( 0 );
     }
     else
@@ -733,16 +746,16 @@
 
         if( name != dn )
         {
-            ret = snprintf( p, n, merge ? " + " : ", " );
+            ret = polarssl_snprintf( p, n, merge ? " + " : ", " );
             SAFE_SNPRINTF();
         }
 
         ret = oid_get_attr_short_name( &name->oid, &short_name );
 
         if( ret == 0 )
-            ret = snprintf( p, n, "%s=", short_name );
+            ret = polarssl_snprintf( p, n, "%s=", short_name );
         else
-            ret = snprintf( p, n, "\?\?=" );
+            ret = polarssl_snprintf( p, n, "\?\?=" );
         SAFE_SNPRINTF();
 
         for( i = 0; i < name->val.len; i++ )
@@ -756,7 +769,7 @@
             else s[i] = c;
         }
         s[i] = '\0';
-        ret = snprintf( p, n, "%s", s );
+        ret = polarssl_snprintf( p, n, "%s", s );
         SAFE_SNPRINTF();
 
         merge = name->next_merged;
@@ -787,14 +800,14 @@
         if( i == 0 && nr > 1 && serial->p[i] == 0x0 )
             continue;
 
-        ret = snprintf( p, n, "%02X%s",
+        ret = polarssl_snprintf( p, n, "%02X%s",
                 serial->p[i], ( i < nr - 1 ) ? ":" : "" );
         SAFE_SNPRINTF();
     }
 
     if( nr != serial->len )
     {
-        ret = snprintf( p, n, "...." );
+        ret = polarssl_snprintf( p, n, "...." );
         SAFE_SNPRINTF();
     }
 
@@ -815,9 +828,9 @@
 
     ret = oid_get_sig_alg_desc( sig_oid, &desc );
     if( ret != 0 )
-        ret = snprintf( p, n, "???"  );
+        ret = polarssl_snprintf( p, n, "???"  );
     else
-        ret = snprintf( p, n, "%s", desc );
+        ret = polarssl_snprintf( p, n, "%s", desc );
     SAFE_SNPRINTF();
 
 #if defined(POLARSSL_X509_RSASSA_PSS_SUPPORT)
@@ -831,7 +844,7 @@
         md_info = md_info_from_type( md_alg );
         mgf_md_info = md_info_from_type( pss_opts->mgf1_hash_id );
 
-        ret = snprintf( p, n, " (%s, MGF1-%s, 0x%02X)",
+        ret = polarssl_snprintf( p, n, " (%s, MGF1-%s, 0x%02X)",
                               md_info ? md_info->name : "???",
                               mgf_md_info ? mgf_md_info->name : "???",
                               pss_opts->expected_salt_len );
@@ -858,7 +871,7 @@
     if( strlen( name ) + sizeof( " key size" ) > size )
         return( POLARSSL_ERR_DEBUG_BUF_TOO_SMALL );
 
-    ret = snprintf( p, n, "%s key size", name );
+    ret = polarssl_snprintf( p, n, "%s key size", name );
     SAFE_SNPRINTF();
 
     return( 0 );
diff --git a/library/x509_create.c b/library/x509_create.c
index ab87ac7..0a75c38 100644
--- a/library/x509_create.c
+++ b/library/x509_create.c
@@ -32,6 +32,8 @@
 #include "polarssl/asn1write.h"
 #include "polarssl/oid.h"
 
+#include <string.h>
+
 #if defined(_MSC_VER) && !defined strncasecmp && !defined(EFIX64) && \
     !defined(EFI32)
 #define strncasecmp _strnicmp
diff --git a/library/x509_crl.c b/library/x509_crl.c
index 2c90582..78b925c 100644
--- a/library/x509_crl.c
+++ b/library/x509_crl.c
@@ -40,6 +40,9 @@
 
 #include "polarssl/x509_crl.h"
 #include "polarssl/oid.h"
+
+#include <string.h>
+
 #if defined(POLARSSL_PEM_PARSE_C)
 #include "polarssl/pem.h"
 #endif
@@ -47,14 +50,13 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_malloc     malloc
+#include <stdlib.h>
 #define polarssl_free       free
+#define polarssl_malloc     malloc
+#define polarssl_snprintf   snprintf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
-
 #include <windows.h>
 #else
 #include <time.h>
@@ -277,7 +279,7 @@
 
     if( crl->version != 0 && crl->next == NULL )
     {
-        crl->next = (x509_crl *) polarssl_malloc( sizeof( x509_crl ) );
+        crl->next = polarssl_malloc( sizeof( x509_crl ) );
 
         if( crl->next == NULL )
         {
@@ -629,23 +631,23 @@
     p = buf;
     n = size;
 
-    ret = snprintf( p, n, "%sCRL version   : %d",
+    ret = polarssl_snprintf( p, n, "%sCRL version   : %d",
                                prefix, crl->version );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n%sissuer name   : ", prefix );
+    ret = polarssl_snprintf( p, n, "\n%sissuer name   : ", prefix );
     SAFE_SNPRINTF();
     ret = x509_dn_gets( p, n, &crl->issuer );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n%sthis update   : " \
+    ret = polarssl_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 );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n%snext update   : " \
+    ret = polarssl_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,
@@ -654,20 +656,20 @@
 
     entry = &crl->entry;
 
-    ret = snprintf( p, n, "\n%sRevoked certificates:",
+    ret = polarssl_snprintf( p, n, "\n%sRevoked certificates:",
                                prefix );
     SAFE_SNPRINTF();
 
     while( entry != NULL && entry->raw.len != 0 )
     {
-        ret = snprintf( p, n, "\n%sserial number: ",
+        ret = polarssl_snprintf( p, n, "\n%sserial number: ",
                                prefix );
         SAFE_SNPRINTF();
 
         ret = x509_serial_gets( p, n, &entry->serial );
         SAFE_SNPRINTF();
 
-        ret = snprintf( p, n, " revocation date: " \
+        ret = polarssl_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,
@@ -677,14 +679,14 @@
         entry = entry->next;
     }
 
-    ret = snprintf( p, n, "\n%ssigned using  : ", prefix );
+    ret = polarssl_snprintf( p, n, "\n%ssigned using  : ", prefix );
     SAFE_SNPRINTF();
 
     ret = x509_sig_alg_gets( p, n, &crl->sig_oid1, crl->sig_pk, crl->sig_md,
                              crl->sig_opts );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n" );
+    ret = polarssl_snprintf( p, n, "\n" );
     SAFE_SNPRINTF();
 
     return( (int) ( size - n ) );
diff --git a/library/x509_crt.c b/library/x509_crt.c
index d1d7d73..d9f5fac 100644
--- a/library/x509_crt.c
+++ b/library/x509_crt.c
@@ -40,6 +40,10 @@
 
 #include "polarssl/x509_crt.h"
 #include "polarssl/oid.h"
+
+#include <stdio.h>
+#include <string.h>
+
 #if defined(POLARSSL_PEM_PARSE_C)
 #include "polarssl/pem.h"
 #endif
@@ -47,30 +51,29 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_malloc     malloc
+#include <stdlib.h>
 #define polarssl_free       free
+#define polarssl_malloc     malloc
+#define polarssl_snprintf   snprintf
 #endif
 
 #if defined(POLARSSL_THREADING_C)
 #include "polarssl/threading.h"
 #endif
 
-#include <string.h>
-#include <stdlib.h>
 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
 #include <windows.h>
 #else
 #include <time.h>
 #endif
 
-#include <stdio.h>
-
 #if defined(POLARSSL_FS_IO)
+#include <stdio.h>
 #if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <dirent.h>
-#endif
+#endif /* !_WIN32 || EFIX64 || EFI32 */
 #endif
 
 /* Implementation that should never be optimized out by the compiler */
@@ -356,8 +359,7 @@
             if( cur->next != NULL )
                 return( POLARSSL_ERR_X509_INVALID_EXTENSIONS );
 
-            cur->next = (asn1_sequence *) polarssl_malloc(
-                 sizeof( asn1_sequence ) );
+            cur->next = polarssl_malloc( sizeof( asn1_sequence ) );
 
             if( cur->next == NULL )
                 return( POLARSSL_ERR_X509_INVALID_EXTENSIONS +
@@ -550,7 +552,7 @@
     if( crt == NULL || buf == NULL )
         return( POLARSSL_ERR_X509_BAD_INPUT_DATA );
 
-    p = (unsigned char *) polarssl_malloc( len = buflen );
+    p = polarssl_malloc( len = buflen );
 
     if( p == NULL )
         return( POLARSSL_ERR_X509_MALLOC_FAILED );
@@ -807,7 +809,7 @@
      */
     if( crt->version != 0 && crt->next == NULL )
     {
-        crt->next = (x509_crt *) polarssl_malloc( sizeof( x509_crt ) );
+        crt->next = polarssl_malloc( sizeof( x509_crt ) );
 
         if( crt->next == NULL )
             return( POLARSSL_ERR_X509_MALLOC_FAILED );
@@ -1038,7 +1040,7 @@
 
     while( ( entry = readdir( dir ) ) != NULL )
     {
-        snprintf( entry_name, sizeof entry_name, "%s/%s", path, entry->d_name );
+        polarssl_snprintf( entry_name, sizeof entry_name, "%s/%s", path, entry->d_name );
 
         if( stat( entry_name, &sb ) == -1 )
         {
@@ -1164,7 +1166,7 @@
 
 #define PRINT_ITEM(i)                           \
     {                                           \
-        ret = snprintf( p, n, "%s" i, sep );    \
+        ret = polarssl_snprintf( p, n, "%s" i, sep );    \
         SAFE_SNPRINTF();                        \
         sep = ", ";                             \
     }
@@ -1237,7 +1239,7 @@
         if( oid_get_extended_key_usage( &cur->buf, &desc ) != 0 )
             desc = "???";
 
-        ret = snprintf( p, n, "%s%s", sep, desc );
+        ret = polarssl_snprintf( p, n, "%s%s", sep, desc );
         SAFE_SNPRINTF();
 
         sep = ", ";
@@ -1267,41 +1269,41 @@
     p = buf;
     n = size;
 
-    ret = snprintf( p, n, "%scert. version     : %d\n",
+    ret = polarssl_snprintf( p, n, "%scert. version     : %d\n",
                                prefix, crt->version );
     SAFE_SNPRINTF();
-    ret = snprintf( p, n, "%sserial number     : ",
+    ret = polarssl_snprintf( p, n, "%sserial number     : ",
                                prefix );
     SAFE_SNPRINTF();
 
     ret = x509_serial_gets( p, n, &crt->serial );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n%sissuer name       : ", prefix );
+    ret = polarssl_snprintf( p, n, "\n%sissuer name       : ", prefix );
     SAFE_SNPRINTF();
     ret = x509_dn_gets( p, n, &crt->issuer  );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n%ssubject name      : ", prefix );
+    ret = polarssl_snprintf( p, n, "\n%ssubject name      : ", prefix );
     SAFE_SNPRINTF();
     ret = x509_dn_gets( p, n, &crt->subject );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n%sissued  on        : " \
+    ret = polarssl_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 );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n%sexpires on        : " \
+    ret = polarssl_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 );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n%ssigned using      : ", prefix );
+    ret = polarssl_snprintf( p, n, "\n%ssigned using      : ", prefix );
     SAFE_SNPRINTF();
 
     ret = x509_sig_alg_gets( p, n, &crt->sig_oid1, crt->sig_pk,
@@ -1315,7 +1317,7 @@
         return( ret );
     }
 
-    ret = snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
+    ret = polarssl_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
                           (int) pk_get_size( &crt->pk ) );
     SAFE_SNPRINTF();
 
@@ -1325,20 +1327,20 @@
 
     if( crt->ext_types & EXT_BASIC_CONSTRAINTS )
     {
-        ret = snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix,
+        ret = polarssl_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix,
                         crt->ca_istrue ? "true" : "false" );
         SAFE_SNPRINTF();
 
         if( crt->max_pathlen > 0 )
         {
-            ret = snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 );
+            ret = polarssl_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 );
             SAFE_SNPRINTF();
         }
     }
 
     if( crt->ext_types & EXT_SUBJECT_ALT_NAME )
     {
-        ret = snprintf( p, n, "\n%ssubject alt name  : ", prefix );
+        ret = polarssl_snprintf( p, n, "\n%ssubject alt name  : ", prefix );
         SAFE_SNPRINTF();
 
         if( ( ret = x509_info_subject_alt_name( &p, &n,
@@ -1348,7 +1350,7 @@
 
     if( crt->ext_types & EXT_NS_CERT_TYPE )
     {
-        ret = snprintf( p, n, "\n%scert. type        : ", prefix );
+        ret = polarssl_snprintf( p, n, "\n%scert. type        : ", prefix );
         SAFE_SNPRINTF();
 
         if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 )
@@ -1357,7 +1359,7 @@
 
     if( crt->ext_types & EXT_KEY_USAGE )
     {
-        ret = snprintf( p, n, "\n%skey usage         : ", prefix );
+        ret = polarssl_snprintf( p, n, "\n%skey usage         : ", prefix );
         SAFE_SNPRINTF();
 
         if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 )
@@ -1366,7 +1368,7 @@
 
     if( crt->ext_types & EXT_EXTENDED_KEY_USAGE )
     {
-        ret = snprintf( p, n, "\n%sext key usage     : ", prefix );
+        ret = polarssl_snprintf( p, n, "\n%sext key usage     : ", prefix );
         SAFE_SNPRINTF();
 
         if( ( ret = x509_info_ext_key_usage( &p, &n,
@@ -1374,7 +1376,7 @@
             return( ret );
     }
 
-    ret = snprintf( p, n, "\n" );
+    ret = polarssl_snprintf( p, n, "\n" );
     SAFE_SNPRINTF();
 
     return( (int) ( size - n ) );
diff --git a/library/x509_csr.c b/library/x509_csr.c
index a6fe581..ad49abc 100644
--- a/library/x509_csr.c
+++ b/library/x509_csr.c
@@ -40,6 +40,9 @@
 
 #include "polarssl/x509_csr.h"
 #include "polarssl/oid.h"
+
+#include <string.h>
+
 #if defined(POLARSSL_PEM_PARSE_C)
 #include "polarssl/pem.h"
 #endif
@@ -47,12 +50,11 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_malloc     malloc
-#define polarssl_free       free
-#endif
-
-#include <string.h>
 #include <stdlib.h>
+#define polarssl_free       free
+#define polarssl_malloc     malloc
+#define polarssl_snprintf   snprintf
+#endif
 
 #if defined(POLARSSL_FS_IO) || defined(EFIX64) || defined(EFI32)
 #include <stdio.h>
@@ -110,7 +112,7 @@
     /*
      * first copy the raw DER data
      */
-    p = (unsigned char *) polarssl_malloc( len = buflen );
+    p = polarssl_malloc( len = buflen );
 
     if( p == NULL )
         return( POLARSSL_ERR_X509_MALLOC_FAILED );
@@ -387,16 +389,16 @@
     p = buf;
     n = size;
 
-    ret = snprintf( p, n, "%sCSR version   : %d",
+    ret = polarssl_snprintf( p, n, "%sCSR version   : %d",
                                prefix, csr->version );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n%ssubject name  : ", prefix );
+    ret = polarssl_snprintf( p, n, "\n%ssubject name  : ", prefix );
     SAFE_SNPRINTF();
     ret = x509_dn_gets( p, n, &csr->subject );
     SAFE_SNPRINTF();
 
-    ret = snprintf( p, n, "\n%ssigned using  : ", prefix );
+    ret = polarssl_snprintf( p, n, "\n%ssigned using  : ", prefix );
     SAFE_SNPRINTF();
 
     ret = x509_sig_alg_gets( p, n, &csr->sig_oid, csr->sig_pk, csr->sig_md,
@@ -409,7 +411,7 @@
         return( ret );
     }
 
-    ret = snprintf( p, n, "\n%s%-" BC "s: %d bits\n", prefix, key_size_str,
+    ret = polarssl_snprintf( p, n, "\n%s%-" BC "s: %d bits\n", prefix, key_size_str,
                           (int) pk_get_size( &csr->pk ) );
     SAFE_SNPRINTF();
 
diff --git a/library/x509write_crt.c b/library/x509write_crt.c
index 3e850ce..5bf44a0 100644
--- a/library/x509write_crt.c
+++ b/library/x509write_crt.c
@@ -39,6 +39,8 @@
 #include "polarssl/asn1write.h"
 #include "polarssl/sha1.h"
 
+#include <string.h>
+
 #if defined(POLARSSL_PEM_WRITE_C)
 #include "polarssl/pem.h"
 #endif /* POLARSSL_PEM_WRITE_C */
diff --git a/library/x509write_csr.c b/library/x509write_csr.c
index 8f297a0..5e2a5e1 100644
--- a/library/x509write_csr.c
+++ b/library/x509write_csr.c
@@ -37,13 +37,13 @@
 #include "polarssl/oid.h"
 #include "polarssl/asn1write.h"
 
+#include <string.h>
+#include <stdlib.h>
+
 #if defined(POLARSSL_PEM_WRITE_C)
 #include "polarssl/pem.h"
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-
 /* Implementation that should never be optimized out by the compiler */
 static void polarssl_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
diff --git a/library/xtea.c b/library/xtea.c
index cea9ff8..e543d65 100644
--- a/library/xtea.c
+++ b/library/xtea.c
@@ -30,11 +30,16 @@
 
 #include "polarssl/xtea.h"
 
+#include <string.h>
+
+#if defined(POLARSSL_SELF_TEST)
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf printf
-#endif
+#endif /* POLARSSL_PLATFORM_C */
+#endif /* POLARSSL_SELF_TEST */
 
 #if !defined(POLARSSL_XTEA_ALT)
 
@@ -190,9 +195,6 @@
 
 #if defined(POLARSSL_SELF_TEST)
 
-#include <string.h>
-#include <stdio.h>
-
 /*
  * XTEA tests vectors (non-official)
  */