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/.gitignore b/.gitignore
index 916d731..fee2a31 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,9 @@
 *.gcno
 *.gcda
 
+# generated by scripts/memory.sh
+massif-*
+
 # MSVC files generated by CMake:
 /*.sln
 /*.vcxproj
diff --git a/.travis.yml b/.travis.yml
index 7f100c3..0a51e7e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -3,7 +3,7 @@
 - clang
 - gcc
 before_install: sudo apt-get update
-install: sudo apt-get install gnutls-bin valgrind perl
+install: sudo apt-get install valgrind perl
 script:
 - cmake -D CMAKE_BUILD_TYPE:String="Check" .
 - make
diff --git a/ChangeLog b/ChangeLog
index 5fef052..a5bc2da 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -10,6 +10,39 @@
    * ssl_set_bio() now requires that p_send == p_recv.
    * ssl_set_bio() is deprecated in favor of ssl_set_bio_timeout().
 
+= mbed TLS 1.3 branch
+
+Security
+
+Features
+   * Add support for overriding snprintf() (except on Windows) and exit() in
+     the platform layer.
+   * Add an option to use macros instead of function pointers in the platform
+     layer (helps get rid of unwanted references).
+   * Improved Makefiles for Windows targets by fixing library targets and making
+     cross-compilation easier (thanks to Alon Bar-Lev).
+   * The benchmark program also prints heap usage for public-key primitives
+     if POLARSSL_MEMORY_BUFFER_ALLOC_C and POLARSSL_MEMORY_DEBUG are defined.
+   * New script ecc-heap.sh helps measuring the impact of ECC parameters on
+     speed and RAM (heap only for now) usage.
+   * New script memory.sh helps measuring the ROM and RAM requirements of two
+     reduced configurations (PSK-CCM and NSA suite B).
+
+Bugfix
+   * Fix hardclock() (only used in the benchmarking program) with some
+     versions of mingw64 (found by kxjhlele).
+   * Fix warnings from mingw64 in timing.c (found by kxjklele).
+   * Fix potential unintended sign extension in asn1_get_len() on 64-bit
+     platforms.
+
+Changes
+   * Move from SHA-1 to SHA-256 in example programs using signatures
+     (suggested by Thorsten Mühlfelder).
+   * Remove some unneeded inclusions of header files from the standard library
+     "minimize" others (eg use stddef.h if only size_t is needed).
+   * Change #include lines in test files to use double quotes instead of angle
+     brackets for uniformity with the rest of the code.
+   * Remove dependency on sscanf() in X.509 parsing modules.
 
 = mbed TLS 1.3.10 released 2015-02-09
 Security
diff --git a/README.rst b/README.rst
index 8e2a53f..14f725d 100644
--- a/README.rst
+++ b/README.rst
@@ -35,6 +35,8 @@
 
     make check
 
+In order to build for a Windows platform, you should use WINDOWS_BUILD=1 if the target is Windows but the build environment is Unix-like (eg when cross-compiling, or compiling from an MSYS shell), and WINDOWS=1 if the build environment is a Windows shell.
+
 Depending on your platform, you might run into some issues. Please check the Makefiles in *library/*, *programs/* and *tests/* for options to manually add or remove for specific platforms. You can also check `the mbed TLS Knowledge Base <https://polarssl.org/kb>`_ for articles on your platform or issue.
 
 In case you find that you need to do something else as well, please let us know what, so we can add it to the KB.
@@ -59,7 +61,7 @@
 - ASan.
   This instruments the code with AddressSanitizer to check for memory errors.
   (This includes LeakSanitizer, with recent version of gcc and clang.)
-  (With recent version of clang, this mode also intruments the code with
+  (With recent version of clang, this mode also instruments the code with
   UndefinedSanitizer to check for undefined behaviour.)
 - ASanDbg.
   Same as ASan but slower, with debug information and better stack traces.
@@ -70,7 +72,7 @@
   Same as ASan but slower, with debug information, better stack traces and
   origin tracking.
 - Check.
-  This activates the compiler warnings that depend on optimisation and treats
+  This activates the compiler warnings that depend on optimization and treats
   all warnings as errors.
 
 Switching build modes in CMake is simple. For debug mode, enter at the command line:
@@ -103,7 +105,7 @@
 
 mbed TLS includes an elaborate test suite in *tests/* that initially requires Perl to generate the tests files (e.g. *test_suite_mpi.c*). These files are generates from a **function file** (e.g. *suites/test_suite_mpi.function*) and a **data file** (e.g. *suites/test_suite_mpi.data*). The **function file** contains the template for each test function. The **data file** contains the test cases, specified as parameters that should be pushed into a template function.
 
-For machines with a Unix shell and OpenSSL (and optionnally GnuTLS) installed, additional test scripts are available:
+For machines with a Unix shell and OpenSSL (and optionally GnuTLS) installed, additional test scripts are available:
 
 - *tests/ssl-opt.sh* runs integration tests for various TLS options (renegotiation, resumption, etc.) and tests interoperability of these options with other implementations.
 - *tests/compat.sh* tests interoperability of every ciphersuite with other implementations.
diff --git a/configs/config-suite-b.h b/configs/config-suite-b.h
index 81ec725..3e8f153 100644
--- a/configs/config-suite-b.h
+++ b/configs/config-suite-b.h
@@ -68,8 +68,8 @@
 #define POLARSSL_ECP_WINDOW_SIZE        2
 #define POLARSSL_ECP_FIXED_POINT_OPTIM  0
 
-/* Uncomment for a significant speed benefit at the expense of some ROM */
-//#define POLARSSL_ECP_NIST_OPTIM
+/* Significant speed benefit at the expense of some ROM */
+#define POLARSSL_ECP_NIST_OPTIM
 
 /*
  * You should adjust this to the exact number of sources you're using: default
diff --git a/include/.gitignore b/include/.gitignore
index feab4e2..53a36d4 100644
--- a/include/.gitignore
+++ b/include/.gitignore
@@ -1,3 +1,4 @@
 Makefile
 *.sln
 *.vcxproj
+polarssl/check_config
diff --git a/include/polarssl/aes.h b/include/polarssl/aes.h
index 1b3f1e8..4ca69b7 100644
--- a/include/polarssl/aes.h
+++ b/include/polarssl/aes.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
diff --git a/include/polarssl/arc4.h b/include/polarssl/arc4.h
index 6c9788c..96e520d 100644
--- a/include/polarssl/arc4.h
+++ b/include/polarssl/arc4.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if !defined(POLARSSL_ARC4_ALT)
 // Regular implementation
diff --git a/include/polarssl/asn1.h b/include/polarssl/asn1.h
index 0a657e1..c723c00 100644
--- a/include/polarssl/asn1.h
+++ b/include/polarssl/asn1.h
@@ -30,12 +30,12 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
+#include <stddef.h>
+
 #if defined(POLARSSL_BIGNUM_C)
 #include "bignum.h"
 #endif
 
-#include <string.h>
-
 /**
  * \addtogroup asn1_module
  * \{
diff --git a/include/polarssl/base64.h b/include/polarssl/base64.h
index 2da935b..6610a18 100644
--- a/include/polarssl/base64.h
+++ b/include/polarssl/base64.h
@@ -24,7 +24,7 @@
 #ifndef POLARSSL_BASE64_H
 #define POLARSSL_BASE64_H
 
-#include <string.h>
+#include <stddef.h>
 
 #define POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL               -0x002A  /**< Output buffer too small. */
 #define POLARSSL_ERR_BASE64_INVALID_CHARACTER              -0x002C  /**< Invalid character in input. */
diff --git a/include/polarssl/bignum.h b/include/polarssl/bignum.h
index 8ffd562..9e4e05b 100644
--- a/include/polarssl/bignum.h
+++ b/include/polarssl/bignum.h
@@ -24,14 +24,14 @@
 #ifndef POLARSSL_BIGNUM_H
 #define POLARSSL_BIGNUM_H
 
-#include <string.h>
-
 #if !defined(POLARSSL_CONFIG_FILE)
 #include "config.h"
 #else
 #include POLARSSL_CONFIG_FILE
 #endif
 
+#include <stddef.h>
+
 #if defined(POLARSSL_FS_IO)
 #include <stdio.h>
 #endif
diff --git a/include/polarssl/blowfish.h b/include/polarssl/blowfish.h
index a03d6d7..246b053 100644
--- a/include/polarssl/blowfish.h
+++ b/include/polarssl/blowfish.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
diff --git a/include/polarssl/camellia.h b/include/polarssl/camellia.h
index dedfba9..c17988e 100644
--- a/include/polarssl/camellia.h
+++ b/include/polarssl/camellia.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
diff --git a/include/polarssl/check_config.h b/include/polarssl/check_config.h
index 42ea720..27b672e 100644
--- a/include/polarssl/check_config.h
+++ b/include/polarssl/check_config.h
@@ -145,13 +145,13 @@
 #endif
 
 #if defined(POLARSSL_KEY_EXCHANGE_RSA_PSK_ENABLED) &&                   \
-    ( !defined(POLARSSL_RSA_C) || !defined(POLARSSL_X509_CRT_PARSE_C) ||\
+    ( !defined(POLARSSL_RSA_C) || !defined(POLARSSL_X509_CRT_PARSE_C) || \
       !defined(POLARSSL_PKCS1_V15) )
 #error "POLARSSL_KEY_EXCHANGE_RSA_PSK_ENABLED defined, but not all prerequisites"
 #endif
 
 #if defined(POLARSSL_KEY_EXCHANGE_RSA_ENABLED) &&                       \
-    ( !defined(POLARSSL_RSA_C) || !defined(POLARSSL_X509_CRT_PARSE_C) ||\
+    ( !defined(POLARSSL_RSA_C) || !defined(POLARSSL_X509_CRT_PARSE_C) || \
       !defined(POLARSSL_PKCS1_V15) )
 #error "POLARSSL_KEY_EXCHANGE_RSA_ENABLED defined, but not all prerequisites"
 #endif
@@ -198,6 +198,136 @@
 #error "POLARSSL_PKCS11_C defined, but not all prerequisites"
 #endif
 
+#if defined(POLARSSL_PLATFORM_EXIT_ALT) && !defined(POLARSSL_PLATFORM_C)
+#error "POLARSSL_PLATFORM_EXIT_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_EXIT_MACRO) && !defined(POLARSSL_PLATFORM_C)
+#error "POLARSSL_PLATFORM_EXIT_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_EXIT_MACRO) &&\
+    ( defined(POLARSSL_PLATFORM_STD_EXIT) ||\
+        defined(POLARSSL_PLATFORM_EXIT_ALT) )
+#error "POLARSSL_PLATFORM_EXIT_MACRO and POLARSSL_PLATFORM_STD_EXIT/POLARSSL_PLATFORM_EXIT_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(POLARSSL_PLATFORM_FPRINTF_ALT) && !defined(POLARSSL_PLATFORM_C)
+#error "POLARSSL_PLATFORM_FPRINTF_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_FPRINTF_MACRO) && !defined(POLARSSL_PLATFORM_C)
+#error "POLARSSL_PLATFORM_FPRINTF_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_FPRINTF_MACRO) &&\
+    ( defined(POLARSSL_PLATFORM_STD_FPRINTF) ||\
+        defined(POLARSSL_PLATFORM_FPRINTF_ALT) )
+#error "POLARSSL_PLATFORM_FPRINTF_MACRO and POLARSSL_PLATFORM_STD_FPRINTF/POLARSSL_PLATFORM_FPRINTF_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(POLARSSL_PLATFORM_FREE_MACRO) &&\
+    ( !defined(POLARSSL_PLATFORM_C) || !defined(POLARSSL_PLATFORM_MEMORY) )
+#error "POLARSSL_PLATFORM_FREE_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_FREE_MACRO) &&\
+    defined(POLARSSL_PLATFORM_STD_FREE)
+#error "POLARSSL_PLATFORM_FREE_MACRO and POLARSSL_PLATFORM_STD_FREE cannot be defined simultaneously"
+#endif
+
+#if defined(POLARSSL_PLATFORM_FREE_MACRO) && !defined(POLARSSL_PLATFORM_MALLOC_MACRO)
+#error "POLARSSL_PLATFORM_MALLOC_MACRO must be defined if POLARSSL_PLATFORM_FREE_MACRO is"
+#endif
+
+#if defined(POLARSSL_PLATFORM_MALLOC_MACRO) &&\
+    ( !defined(POLARSSL_PLATFORM_C) || !defined(POLARSSL_PLATFORM_MEMORY) )
+#error "POLARSSL_PLATFORM_MALLOC_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_MALLOC_MACRO) &&\
+    defined(POLARSSL_PLATFORM_STD_MALLOC)
+#error "POLARSSL_PLATFORM_MALLOC_MACRO and POLARSSL_PLATFORM_STD_MALLOC cannot be defined simultaneously"
+#endif
+
+#if defined(POLARSSL_PLATFORM_MALLOC_MACRO) && !defined(POLARSSL_PLATFORM_FREE_MACRO)
+#error "POLARSSL_PLATFORM_FREE_MACRO must be defined if POLARSSL_PLATFORM_MALLOC_MACRO is"
+#endif
+
+#if defined(POLARSSL_PLATFORM_MEMORY) && !defined(POLARSSL_PLATFORM_C)
+#error "POLARSSL_PLATFORM_MEMORY defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_PRINTF_ALT) && !defined(POLARSSL_PLATFORM_C)
+#error "POLARSSL_PLATFORM_PRINTF_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_PRINTF_MACRO) && !defined(POLARSSL_PLATFORM_C)
+#error "POLARSSL_PLATFORM_PRINTF_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_PRINTF_MACRO) &&\
+    ( defined(POLARSSL_PLATFORM_STD_PRINTF) ||\
+        defined(POLARSSL_PLATFORM_PRINTF_ALT) )
+#error "POLARSSL_PLATFORM_PRINTF_MACRO and POLARSSL_PLATFORM_STD_PRINTF/POLARSSL_PLATFORM_PRINTF_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(POLARSSL_PLATFORM_SNPRINTF_ALT) && !defined(POLARSSL_PLATFORM_C)
+#error "POLARSSL_PLATFORM_SNPRINTF_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_SNPRINTF_ALT) && ( defined(_WIN32)\
+    && !defined(EFIX64) && !defined(EFI32) )
+#error "POLARSSL_PLATFORM_SNPRINTF_ALT defined but not available on Windows"
+#endif
+
+#if defined(POLARSSL_PLATFORM_SNPRINTF_MACRO) && !defined(POLARSSL_PLATFORM_C)
+#error "POLARSSL_PLATFORM_SNPRINTF_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_SNPRINTF_MACRO) &&\
+    ( defined(POLARSSL_PLATFORM_STD_SNPRINTF) ||\
+        defined(POLARSSL_PLATFORM_SNPRINTF_ALT) )
+#error "POLARSSL_PLATFORM_SNPRINTF_MACRO and POLARSSL_PLATFORM_STD_SNPRINTF/POLARSSL_PLATFORM_SNPRINTF_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(POLARSSL_PLATFORM_STD_MEM_HDR) &&\
+    !defined(POLARSSL_PLATFORM_NO_STD_FUNCTIONS)
+#error "POLARSSL_PLATFORM_STD_MEM_HDR defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_STD_MALLOC) && !defined(POLARSSL_PLATFORM_MEMORY)
+#error "POLARSSL_PLATFORM_STD_MALLOC defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_STD_MALLOC) && !defined(POLARSSL_PLATFORM_MEMORY)
+#error "POLARSSL_PLATFORM_STD_MALLOC defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_STD_FREE) && !defined(POLARSSL_PLATFORM_MEMORY)
+#error "POLARSSL_PLATFORM_STD_FREE defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_STD_EXIT) &&\
+    !defined(POLARSSL_PLATFORM_EXIT_ALT)
+#error "POLARSSL_PLATFORM_STD_EXIT defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_STD_FPRINTF) &&\
+    !defined(POLARSSL_PLATFORM_FPRINTF_ALT)
+#error "POLARSSL_PLATFORM_STD_FPRINTF defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_STD_PRINTF) &&\
+    !defined(POLARSSL_PLATFORM_PRINTF_ALT)
+#error "POLARSSL_PLATFORM_STD_PRINTF defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_PLATFORM_STD_SNPRINTF) &&\
+    !defined(POLARSSL_PLATFORM_SNPRINTF_ALT)
+#error "POLARSSL_PLATFORM_STD_SNPRINTF defined, but not all prerequisites"
+#endif
+
 #if defined(POLARSSL_RSA_C) && ( !defined(POLARSSL_BIGNUM_C) ||         \
     !defined(POLARSSL_OID_C) )
 #error "POLARSSL_RSA_C defined, but not all prerequisites"
diff --git a/include/polarssl/cipher.h b/include/polarssl/cipher.h
index 999d24b..d890ff9 100644
--- a/include/polarssl/cipher.h
+++ b/include/polarssl/cipher.h
@@ -33,6 +33,8 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
+#include <stddef.h>
+
 #if defined(POLARSSL_GCM_C) || defined(POLARSSL_CCM_C)
 #define POLARSSL_CIPHER_MODE_AEAD
 #endif
@@ -41,7 +43,9 @@
 #define POLARSSL_CIPHER_MODE_WITH_PADDING
 #endif
 
-#include <string.h>
+#if defined(POLARSSL_ARC4_C)
+#define POLARSSL_CIPHER_MODE_STREAM
+#endif
 
 #if defined(_MSC_VER) && !defined(inline)
 #define inline _inline
@@ -182,24 +186,32 @@
     int (*ecb_func)( void *ctx, operation_t mode,
                      const unsigned char *input, unsigned char *output );
 
+#if defined(POLARSSL_CIPHER_MODE_CBC)
     /** Encrypt using CBC */
     int (*cbc_func)( void *ctx, operation_t mode, size_t length,
                      unsigned char *iv, const unsigned char *input,
                      unsigned char *output );
+#endif
 
+#if defined(POLARSSL_CIPHER_MODE_CFB)
     /** Encrypt using CFB (Full length) */
     int (*cfb_func)( void *ctx, operation_t mode, size_t length, size_t *iv_off,
                      unsigned char *iv, const unsigned char *input,
                      unsigned char *output );
+#endif
 
+#if defined(POLARSSL_CIPHER_MODE_CTR)
     /** Encrypt using CTR */
     int (*ctr_func)( void *ctx, size_t length, size_t *nc_off,
                      unsigned char *nonce_counter, unsigned char *stream_block,
                      const unsigned char *input, unsigned char *output );
+#endif
 
+#if defined(POLARSSL_CIPHER_MODE_STREAM)
     /** Encrypt using STREAM */
     int (*stream_func)( void *ctx, size_t length,
                         const unsigned char *input, unsigned char *output );
+#endif
 
     /** Set key for encryption purposes */
     int (*setkey_enc_func)( void *ctx, const unsigned char *key,
@@ -262,9 +274,11 @@
     /** Operation that the context's key has been initialised for */
     operation_t operation;
 
+#if defined(POLARSSL_CIPHER_MODE_WITH_PADDING)
     /** Padding functions to use, if relevant for cipher mode */
     void (*add_padding)( unsigned char *output, size_t olen, size_t data_len );
     int (*get_padding)( unsigned char *input, size_t ilen, size_t *data_len );
+#endif
 
     /** Buffer for data that hasn't been encrypted yet */
     unsigned char unprocessed_data[POLARSSL_MAX_BLOCK_LENGTH];
diff --git a/include/polarssl/cipher_wrap.h b/include/polarssl/cipher_wrap.h
index 94ba578..92dfe45 100644
--- a/include/polarssl/cipher_wrap.h
+++ b/include/polarssl/cipher_wrap.h
@@ -31,6 +31,7 @@
 #else
 #include POLARSSL_CONFIG_FILE
 #endif
+
 #include "cipher.h"
 
 #ifdef __cplusplus
diff --git a/include/polarssl/config.h b/include/polarssl/config.h
index 89f08c7..7488114 100644
--- a/include/polarssl/config.h
+++ b/include/polarssl/config.h
@@ -120,8 +120,14 @@
  * This allows different allocators (self-implemented or provided) to be
  * provided to the platform abstraction layer.
  *
- * Enabling POLARSSL_PLATFORM_MEMORY will provide "platform_set_malloc_free()"
- * to allow you to set an alternative malloc() and free() function pointer.
+ * Enabling POLARSSL_PLATFORM_MEMORY without the
+ * POLARSSL_PLATFORM_{FREE,MALLOC}_MACROs will provide
+ * "platform_set_malloc_free()" allowing you to set an alternative malloc() and
+ * free() function pointer at runtime.
+ *
+ * Enabling POLARSSL_PLATFORM_MEMORY and specifying
+ * POLARSSL_PLATFORM_{MALLOC,FREE}_MACROs will allow you to specify the
+ * alternate function at compile time.
  *
  * Requires: POLARSSL_PLATFORM_C
  *
@@ -138,7 +144,8 @@
  * This makes sure there are no linking errors on platforms that do not support
  * these functions. You will HAVE to provide alternatives, either at runtime
  * via the platform_set_xxx() functions or at compile time by setting
- * the POLARSSL_PLATFORM_STD_XXX defines.
+ * the POLARSSL_PLATFORM_STD_XXX defines, or enabling a
+ * POLARSSL_PLATFORM_XXX_MACRO.
  *
  * Requires: POLARSSL_PLATFORM_C
  *
@@ -159,11 +166,19 @@
  *
  * All these define require POLARSSL_PLATFORM_C to be defined!
  *
+ * WARNING: POLARSSL_PLATFORM_SNPRINTF_ALT is not available on Windows
+ * for compatibility reasons.
+ *
+ * WARNING: POLARSSL_PLATFORM_XXX_ALT cannot be defined at the same time as
+ * POLARSSL_PLATFORM_XXX_MACRO!
+ *
  * Uncomment a macro to enable alternate implementation of specific base
  * platform function
  */
-//#define POLARSSL_PLATFORM_PRINTF_ALT
+//#define POLARSSL_PLATFORM_EXIT_ALT
 //#define POLARSSL_PLATFORM_FPRINTF_ALT
+//#define POLARSSL_PLATFORM_PRINTF_ALT
+//#define POLARSSL_PLATFORM_SNPRINTF_ALT
 /* \} name SECTION: System support */
 
 /**
@@ -1957,7 +1972,11 @@
  * \def POLARSSL_PLATFORM_C
  *
  * Enable the platform abstraction layer that allows you to re-assign
- * functions like malloc(), free(), printf(), fprintf()
+ * functions like malloc(), free(), snprintf(), printf(), fprintf(), exit()
+ *
+ * Enabling POLARSSL_PLATFORM_C enables to use of POLARSSL_PLATFORM_XXX_ALT
+ * or POLARSSL_PLATFORM_XXX_MACRO directives, allowing the functions mentioned
+ * above to be specified at runtime or compile time respectively.
  *
  * Module:  library/platform.c
  * Caller:  Most other .c files
@@ -2314,11 +2333,22 @@
 //#define POLARSSL_MEMORY_ALIGN_MULTIPLE      4 /**< Align on multiples of this value */
 
 /* Platform options */
-//#define POLARSSL_PLATFORM_STD_MEM_HDR <stdlib.h> /**< Header to include if POLARSSL_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */
-//#define POLARSSL_PLATFORM_STD_MALLOC   malloc /**< Default allocator to use, can be undefined */
-//#define POLARSSL_PLATFORM_STD_FREE       free /**< Default free to use, can be undefined */
-//#define POLARSSL_PLATFORM_STD_PRINTF   printf /**< Default printf to use, can be undefined */
-//#define POLARSSL_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use, can be undefined */
+//#define POLARSSL_PLATFORM_STD_MEM_HDR   <stdlib.h> /**< Header to include if POLARSSL_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */
+//#define POLARSSL_PLATFORM_STD_MALLOC        malloc /**< Default allocator to use, can be undefined */
+//#define POLARSSL_PLATFORM_STD_FREE            free /**< Default free to use, can be undefined */
+//#define POLARSSL_PLATFORM_STD_EXIT            exit /**< Default exit to use, can be undefined */
+//#define POLARSSL_PLATFORM_STD_FPRINTF      fprintf /**< Default fprintf to use, can be undefined */
+//#define POLARSSL_PLATFORM_STD_PRINTF        printf /**< Default printf to use, can be undefined */
+//#define POLARSSL_PLATFORM_STD_SNPRINTF    snprintf /**< Default snprintf to use, can be undefined */
+
+/* To Use Function Macros POLARSSL_PLATFORM_C must be enabled 							*/
+/* POLARSSL_PLATFORM_XXX_MACRO and POLARSSL_PLATFORM_XXX_ALT cannot both be defined 	*/
+//#define POLARSSL_PLATFORM_MALLOC_MACRO        malloc /**< Default allocator macro to use, can be undefined */
+//#define POLARSSL_PLATFORM_FREE_MACRO            free /**< Default free macro to use, can be undefined */
+//#define POLARSSL_PLATFORM_EXIT_MACRO            exit /**< Default exit macro to use, can be undefined */
+//#define POLARSSL_PLATFORM_FPRINTF_MACRO      fprintf /**< Default fprintf macro to use, can be undefined */
+//#define POLARSSL_PLATFORM_PRINTF_MACRO        printf /**< Default printf macro to use, can be undefined */
+//#define POLARSSL_PLATFORM_SNPRINTF_MACRO    snprintf /**< Default snprintf macro to use, can be undefined */
 
 /* SSL Cache options */
 //#define SSL_CACHE_DEFAULT_TIMEOUT       86400 /**< 1 day  */
diff --git a/include/polarssl/ctr_drbg.h b/include/polarssl/ctr_drbg.h
index 1424bd7..c473e76 100644
--- a/include/polarssl/ctr_drbg.h
+++ b/include/polarssl/ctr_drbg.h
@@ -24,8 +24,6 @@
 #ifndef POLARSSL_CTR_DRBG_H
 #define POLARSSL_CTR_DRBG_H
 
-#include <string.h>
-
 #include "aes.h"
 
 #define POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED        -0x0034  /**< The entropy source failed. */
diff --git a/include/polarssl/debug.h b/include/polarssl/debug.h
index a9d00f5..a4d2bdb 100644
--- a/include/polarssl/debug.h
+++ b/include/polarssl/debug.h
@@ -29,7 +29,9 @@
 #else
 #include POLARSSL_CONFIG_FILE
 #endif
+
 #include "ssl.h"
+
 #if defined(POLARSSL_ECP_C)
 #include "ecp.h"
 #endif
diff --git a/include/polarssl/des.h b/include/polarssl/des.h
index b18ca03..3155e5e 100644
--- a/include/polarssl/des.h
+++ b/include/polarssl/des.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
diff --git a/include/polarssl/entropy.h b/include/polarssl/entropy.h
index 92aa5a5..53a1f0e 100644
--- a/include/polarssl/entropy.h
+++ b/include/polarssl/entropy.h
@@ -24,14 +24,14 @@
 #ifndef POLARSSL_ENTROPY_H
 #define POLARSSL_ENTROPY_H
 
-#include <string.h>
-
 #if !defined(POLARSSL_CONFIG_FILE)
 #include "config.h"
 #else
 #include POLARSSL_CONFIG_FILE
 #endif
 
+#include <stddef.h>
+
 #if defined(POLARSSL_SHA512_C) && !defined(POLARSSL_ENTROPY_FORCE_SHA256)
 #include "sha512.h"
 #define POLARSSL_ENTROPY_SHA512_ACCUMULATOR
diff --git a/include/polarssl/entropy_poll.h b/include/polarssl/entropy_poll.h
index 9c349da..523a7cd 100644
--- a/include/polarssl/entropy_poll.h
+++ b/include/polarssl/entropy_poll.h
@@ -24,14 +24,14 @@
 #ifndef POLARSSL_ENTROPY_POLL_H
 #define POLARSSL_ENTROPY_POLL_H
 
-#include <string.h>
-
 #if !defined(POLARSSL_CONFIG_FILE)
 #include "config.h"
 #else
 #include POLARSSL_CONFIG_FILE
 #endif
 
+#include <stddef.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
diff --git a/include/polarssl/error.h b/include/polarssl/error.h
index 29c4d70..b1b5513 100644
--- a/include/polarssl/error.h
+++ b/include/polarssl/error.h
@@ -24,7 +24,7 @@
 #ifndef POLARSSL_ERROR_H
 #define POLARSSL_ERROR_H
 
-#include <string.h>
+#include <stddef.h>
 
 /**
  * Error code layout.
diff --git a/include/polarssl/havege.h b/include/polarssl/havege.h
index 1bad2b9..df26755 100644
--- a/include/polarssl/havege.h
+++ b/include/polarssl/havege.h
@@ -24,7 +24,7 @@
 #ifndef POLARSSL_HAVEGE_H
 #define POLARSSL_HAVEGE_H
 
-#include <string.h>
+#include <stddef.h>
 
 #define COLLECT_SIZE 1024
 
diff --git a/include/polarssl/md.h b/include/polarssl/md.h
index 33a67a3..3bbff6e 100644
--- a/include/polarssl/md.h
+++ b/include/polarssl/md.h
@@ -26,7 +26,7 @@
 #ifndef POLARSSL_MD_H
 #define POLARSSL_MD_H
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(inline)
 #define inline _inline
diff --git a/include/polarssl/md2.h b/include/polarssl/md2.h
index 6727ed2..8426037 100644
--- a/include/polarssl/md2.h
+++ b/include/polarssl/md2.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #define POLARSSL_ERR_MD2_FILE_IO_ERROR                 -0x0070  /**< Read/write error in file. */
 
diff --git a/include/polarssl/md4.h b/include/polarssl/md4.h
index 774300d..9fc7c86 100644
--- a/include/polarssl/md4.h
+++ b/include/polarssl/md4.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
diff --git a/include/polarssl/md5.h b/include/polarssl/md5.h
index 6566eb3..50c7774 100644
--- a/include/polarssl/md5.h
+++ b/include/polarssl/md5.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
diff --git a/include/polarssl/md_wrap.h b/include/polarssl/md_wrap.h
index 7aeb27a..92c3a2c 100644
--- a/include/polarssl/md_wrap.h
+++ b/include/polarssl/md_wrap.h
@@ -31,6 +31,7 @@
 #else
 #include POLARSSL_CONFIG_FILE
 #endif
+
 #include "md.h"
 
 #ifdef __cplusplus
diff --git a/include/polarssl/memory_buffer_alloc.h b/include/polarssl/memory_buffer_alloc.h
index 5f8e329..3bba1c1 100644
--- a/include/polarssl/memory_buffer_alloc.h
+++ b/include/polarssl/memory_buffer_alloc.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <stdlib.h>
+#include <stddef.h>
 
 /**
  * \name SECTION: Module settings
@@ -97,6 +97,27 @@
  *          trace if POLARSSL_MEMORY_BACKTRACE is defined.
  */
 void memory_buffer_alloc_status( void );
+
+/**
+ * \brief   Get the peak heap usage so far
+ *
+ * \param max_used      Peak number of bytes reauested by the application
+ * \param max_blocks    Peak number of blocks reauested by the application
+ */
+void memory_buffer_alloc_max_get( size_t *max_used, size_t *max_blocks );
+
+/**
+ * \brief   Reset peak statistics
+ */
+void memory_buffer_alloc_max_reset( void );
+
+/**
+ * \brief   Get the current heap usage
+ *
+ * \param cur_used      Number of bytes reauested by the application
+ * \param cur_blocks    Number of blocks reauested by the application
+ */
+void memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks );
 #endif /* POLARSSL_MEMORY_DEBUG */
 
 /**
diff --git a/include/polarssl/net.h b/include/polarssl/net.h
index 3c2b036..55ef40b 100644
--- a/include/polarssl/net.h
+++ b/include/polarssl/net.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(POLARSSL_HAVE_TIME)
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
diff --git a/include/polarssl/oid.h b/include/polarssl/oid.h
index 309d8c5..497eac8 100644
--- a/include/polarssl/oid.h
+++ b/include/polarssl/oid.h
@@ -24,14 +24,17 @@
 #ifndef POLARSSL_OID_H
 #define POLARSSL_OID_H
 
-#include <string.h>
 #if !defined(POLARSSL_CONFIG_FILE)
 #include "config.h"
 #else
 #include POLARSSL_CONFIG_FILE
 #endif
+
 #include "asn1.h"
 #include "pk.h"
+
+#include <stddef.h>
+
 #if defined(POLARSSL_CIPHER_C)
 #include "cipher.h"
 #endif
diff --git a/include/polarssl/padlock.h b/include/polarssl/padlock.h
index af84d63..185eff8 100644
--- a/include/polarssl/padlock.h
+++ b/include/polarssl/padlock.h
@@ -42,7 +42,6 @@
 #include <inttypes.h>
 #endif
 
-
 #define PADLOCK_RNG 0x000C
 #define PADLOCK_ACE 0x00C0
 #define PADLOCK_PHE 0x0C00
diff --git a/include/polarssl/pbkdf2.h b/include/polarssl/pbkdf2.h
index 0548ad0..7c98eae 100644
--- a/include/polarssl/pbkdf2.h
+++ b/include/polarssl/pbkdf2.h
@@ -27,10 +27,10 @@
 #ifndef POLARSSL_PBKDF2_H
 #define POLARSSL_PBKDF2_H
 
-#include <string.h>
-
 #include "md.h"
 
+#include <stddef.h>
+
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
 typedef UINT32 uint32_t;
diff --git a/include/polarssl/pem.h b/include/polarssl/pem.h
index c0775d0..9ccdbef 100644
--- a/include/polarssl/pem.h
+++ b/include/polarssl/pem.h
@@ -24,7 +24,7 @@
 #ifndef POLARSSL_PEM_H
 #define POLARSSL_PEM_H
 
-#include <string.h>
+#include <stddef.h>
 
 /**
  * \name PEM Error codes
diff --git a/include/polarssl/pkcs12.h b/include/polarssl/pkcs12.h
index 4a13102..0920cd1 100644
--- a/include/polarssl/pkcs12.h
+++ b/include/polarssl/pkcs12.h
@@ -24,12 +24,12 @@
 #ifndef POLARSSL_PKCS12_H
 #define POLARSSL_PKCS12_H
 
-#include <string.h>
-
 #include "md.h"
 #include "cipher.h"
 #include "asn1.h"
 
+#include <stddef.h>
+
 #define POLARSSL_ERR_PKCS12_BAD_INPUT_DATA                 -0x1F80  /**< Bad input parameters to function. */
 #define POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE            -0x1F00  /**< Feature not available, e.g. unsupported encryption scheme. */
 #define POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT             -0x1E80  /**< PBE ASN.1 data not as expected. */
diff --git a/include/polarssl/pkcs5.h b/include/polarssl/pkcs5.h
index d9b6856..fda40b5 100644
--- a/include/polarssl/pkcs5.h
+++ b/include/polarssl/pkcs5.h
@@ -26,11 +26,11 @@
 #ifndef POLARSSL_PKCS5_H
 #define POLARSSL_PKCS5_H
 
-#include <string.h>
-
 #include "asn1.h"
 #include "md.h"
 
+#include <stddef.h>
+
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
 typedef UINT32 uint32_t;
diff --git a/include/polarssl/platform.h b/include/polarssl/platform.h
index 4473d50..3e76c30 100644
--- a/include/polarssl/platform.h
+++ b/include/polarssl/platform.h
@@ -35,8 +35,6 @@
 #define POLARSSL_PLATFORM_MEMORY
 #endif
 
-#include <stdio.h>
-
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -50,7 +48,11 @@
  */
 
 #if !defined(POLARSSL_PLATFORM_NO_STD_FUNCTIONS)
+#include <stdio.h>
 #include <stdlib.h>
+#if !defined(POLARSSL_PLATFORM_STD_SNPRINTF)
+#define POLARSSL_PLATFORM_STD_SNPRINTF   snprintf /**< Default snprintf to use  */
+#endif
 #if !defined(POLARSSL_PLATFORM_STD_PRINTF)
 #define POLARSSL_PLATFORM_STD_PRINTF   printf /**< Default printf to use  */
 #endif
@@ -63,6 +65,9 @@
 #if !defined(POLARSSL_PLATFORM_STD_FREE)
 #define POLARSSL_PLATFORM_STD_FREE       free /**< Default free to use */
 #endif
+#if !defined(POLARSSL_PLATFORM_STD_EXIT)
+#define POLARSSL_PLATFORM_STD_EXIT      exit /**< Default free to use */
+#endif
 #else /* POLARSSL_PLATFORM_NO_STD_FUNCTIONS */
 #if defined(POLARSSL_PLATFORM_STD_MEM_HDR)
 #include POLARSSL_PLATFORM_STD_MEM_HDR
@@ -75,6 +80,11 @@
  * The function pointers for malloc and free
  */
 #if defined(POLARSSL_PLATFORM_MEMORY)
+#if defined(POLARSSL_PLATFORM_FREE_MACRO) &&\
+	defined(POLARSSL_PLATFORM_MALLOC_MACRO)
+#define polarssl_free    POLARSSL_PLATFORM_FREE_MACRO
+#define polarssl_malloc    POLARSSL_PLATFORM_MALLOC_MACRO
+#else
 extern void * (*polarssl_malloc)( size_t len );
 extern void (*polarssl_free)( void *ptr );
 
@@ -88,10 +98,34 @@
  */
 int platform_set_malloc_free( void * (*malloc_func)( size_t ),
                               void (*free_func)( void * ) );
-#else /* POLARSSL_PLATFORM_ENTROPY */
-#define polarssl_malloc     malloc
-#define polarssl_free       free
-#endif /* POLARSSL_PLATFORM_ENTROPY */
+#endif /* POLARSSL_PLATFORM_FREE_MACRO && POLARSSL_PLATFORM_MALLOC_MACRO */
+#else /* !POLARSSL_PLATFORM_MEMORY */
+#define polarssl_free    free
+#define polarssl_malloc    malloc
+#endif /* POLARSSL_PLATFORM_MEMORY && !POLARSSL_PLATFORM_{FREE,MALLOC}_MACRO */
+
+/*
+ * The function pointers for fprintf
+ */
+#if defined(POLARSSL_PLATFORM_FPRINTF_ALT)
+extern int (*polarssl_fprintf)( FILE *stream, const char *format, ... );
+
+/**
+ * \brief   Set your own fprintf function pointer
+ *
+ * \param fprintf_func   the fprintf function implementation
+ *
+ * \return              0
+ */
+int platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char *,
+                                               ... ) );
+#else
+#if defined(POLARSSL_PLATFORM_FPRINTF_MACRO)
+#define polarssl_fprintf    POLARSSL_PLATFORM_FPRINTF_MACRO
+#else
+#define polarssl_fprintf    fprintf
+#endif /* POLARSSL_PLATFORM_FPRINTF_MACRO */
+#endif /* POLARSSL_PLATFORM_FPRINTF_ALT */
 
 /*
  * The function pointers for printf
@@ -107,21 +141,58 @@
  * \return              0
  */
 int platform_set_printf( int (*printf_func)( const char *, ... ) );
-#else /* POLARSSL_PLATFORM_PRINTF_ALT */
+#else /* !POLARSSL_PLATFORM_PRINTF_ALT */
+#if defined(POLARSSL_PLATFORM_PRINTF_MACRO)
+#define polarssl_printf     POLARSSL_PLATFORM_PRINTF_MACRO
+#else
 #define polarssl_printf     printf
+#endif /* POLARSSL_PLATFORM_PRINTF_MACRO */
 #endif /* POLARSSL_PLATFORM_PRINTF_ALT */
 
 /*
- * The function pointers for fprintf
+ * The function pointers for snprintf
  */
-#if defined(POLARSSL_PLATFORM_FPRINTF_ALT)
-extern int (*polarssl_fprintf)( FILE *stream, const char *format, ... );
+#if defined(POLARSSL_PLATFORM_SNPRINTF_ALT)
+extern int (*polarssl_snprintf)( char * s, size_t n, const char * format, ... );
 
-int platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char *,
-                                               ... ) );
+/**
+ * \brief   Set your own snprintf function pointer
+ *
+ * \param snprintf_func   the snprintf function implementation
+ *
+ * \return              0
+ */
+int platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
+                                                 const char * format, ... ) );
+#else /* POLARSSL_PLATFORM_SNPRINTF_ALT */
+#if defined(POLARSSL_PLATFORM_SNPRINTF_MACRO)
+#define polarssl_snprintf   POLARSSL_PLATFORM_SNPRINTF_MACRO
 #else
-#define polarssl_fprintf    fprintf
-#endif
+#define polarssl_snprintf   snprintf
+#endif /* POLARSSL_PLATFORM_SNPRINTF_MACRO */
+#endif /* POLARSSL_PLATFORM_SNPRINTF_ALT */
+
+/*
+ * The function pointers for exit
+ */
+#if defined(POLARSSL_PLATFORM_EXIT_ALT)
+extern void (*polarssl_exit)( int status );
+
+/**
+ * \brief   Set your own exit function pointer
+ *
+ * \param exit_func   the exit function implementation
+ *
+ * \return              0
+ */
+int platform_set_exit( void (*exit_func)( int status ) );
+#else
+#if defined(POLARSSL_PLATFORM_EXIT_MACRO)
+#define polarssl_exit   POLARSSL_PLATFORM_EXIT_MACRO
+#else
+#define polarssl_exit   exit
+#endif /* POLARSSL_PLATFORM_EXIT_MACRO */
+#endif /* POLARSSL_PLATFORM_EXIT_ALT */
 
 #ifdef __cplusplus
 }
diff --git a/include/polarssl/ripemd160.h b/include/polarssl/ripemd160.h
index 49c36c0..4762720 100644
--- a/include/polarssl/ripemd160.h
+++ b/include/polarssl/ripemd160.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
diff --git a/include/polarssl/sha1.h b/include/polarssl/sha1.h
index 258a3de..8497501 100644
--- a/include/polarssl/sha1.h
+++ b/include/polarssl/sha1.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
diff --git a/include/polarssl/sha256.h b/include/polarssl/sha256.h
index 195996d..b7362dd 100644
--- a/include/polarssl/sha256.h
+++ b/include/polarssl/sha256.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
diff --git a/include/polarssl/sha512.h b/include/polarssl/sha512.h
index 6afb836..90b5e3e 100644
--- a/include/polarssl/sha512.h
+++ b/include/polarssl/sha512.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) || defined(__WATCOMC__)
   #define UL64(x) x##ui64
diff --git a/include/polarssl/timing.h b/include/polarssl/timing.h
index a3eb510..5f3acfa 100644
--- a/include/polarssl/timing.h
+++ b/include/polarssl/timing.h
@@ -65,6 +65,10 @@
  * \brief          Setup an alarm clock
  *
  * \param seconds  delay before the "alarmed" flag is set
+ *
+ * \warning        Only one alarm at a time  is supported. In a threaded
+ *                 context, this means one for the whole process, not one per
+ *                 thread.
  */
 void set_alarm( int seconds );
 
diff --git a/include/polarssl/x509_crt.h b/include/polarssl/x509_crt.h
index 4fad932..ab6b164 100644
--- a/include/polarssl/x509_crt.h
+++ b/include/polarssl/x509_crt.h
@@ -31,7 +31,6 @@
 #endif
 
 #include "x509.h"
-
 #include "x509_crl.h"
 
 /**
diff --git a/include/polarssl/xtea.h b/include/polarssl/xtea.h
index 0c58ab5..f055490 100644
--- a/include/polarssl/xtea.h
+++ b/include/polarssl/xtea.h
@@ -30,7 +30,7 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#include <string.h>
+#include <stddef.h>
 
 #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
 #include <basetsd.h>
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)
  */
diff --git a/programs/.gitignore b/programs/.gitignore
index c25ee3e..57334c4 100644
--- a/programs/.gitignore
+++ b/programs/.gitignore
@@ -40,6 +40,7 @@
 ssl/ssl_pthread_server
 ssl/ssl_server
 ssl/ssl_server2
+ssl/mini_client
 test/benchmark
 test/ecp-bench
 test/o_p_test
diff --git a/programs/Makefile b/programs/Makefile
index 7fa9019..29f3d73 100644
--- a/programs/Makefile
+++ b/programs/Makefile
@@ -5,14 +5,27 @@
 
 CFLAGS	+= -I../include -D_FILE_OFFSET_BITS=64 -Wall -W -Wdeclaration-after-statement
 OFLAGS	= -O2
-LDFLAGS	+= -L../library -lmbedtls $(SYS_LDFLAGS)
+LDFLAGS	+= -L../library -lmbedtls$(SHARED_SUFFIX) $(SYS_LDFLAGS)
 
 ifdef DEBUG
 CFLAGS += -g3
 endif
 
+#
+# if we running on Windows build
+# for Windows
+#
 ifdef WINDOWS
+WINDOWS_BUILD=1
+endif
+
+ifdef WINDOWS_BUILD
+DLEXT=dll
+EXEXT=.exe
 LDFLAGS += -lws2_32
+ifdef SHARED
+SHARED_SUFFIX=.$(DLEXT)
+endif
 endif
 
 # Zlib shared library extensions:
@@ -20,32 +33,32 @@
 LDFLAGS += -lz
 endif
 
-APPS =	aes/aescrypt2	aes/crypt_and_hash	\
-	hash/hello			hash/generic_sum	\
-	hash/md5sum			hash/sha1sum		\
-	hash/sha2sum		pkey/dh_client		\
-	pkey/dh_genprime	pkey/dh_server		\
-	pkey/gen_key							\
-	pkey/key_app		pkey/key_app_writer	\
-	pkey/mpi_demo		pkey/pk_decrypt		\
-	pkey/pk_encrypt		pkey/pk_sign		\
-	pkey/pk_verify		pkey/rsa_genkey		\
-	pkey/rsa_decrypt	pkey/rsa_encrypt	\
-	pkey/rsa_sign		pkey/rsa_verify		\
-	pkey/rsa_sign_pss	pkey/rsa_verify_pss \
-	ssl/dtls_client		ssl/dtls_server		\
-	ssl/ssl_client1		ssl/ssl_client2		\
-	ssl/ssl_server		ssl/ssl_server2		\
-	ssl/ssl_fork_server						\
-	ssl/ssl_mail_client	random/gen_entropy	\
-	random/gen_random_havege				\
-	random/gen_random_ctr_drbg				\
-	test/ssl_cert_test	test/benchmark		\
-	test/selftest		test/ssl_test		\
-	test/udp_proxy							\
-	util/pem2der		util/strerror		\
-	x509/cert_app		x509/crl_app		\
-	x509/cert_req
+APPS =	aes/aescrypt2$(EXEXT)		aes/crypt_and_hash$(EXEXT)	\
+	hash/hello$(EXEXT)		hash/generic_sum$(EXEXT)	\
+	hash/md5sum$(EXEXT)		hash/sha1sum$(EXEXT)		\
+	hash/sha2sum$(EXEXT)		pkey/dh_client$(EXEXT)		\
+	pkey/dh_genprime$(EXEXT)	pkey/dh_server$(EXEXT)		\
+	pkey/gen_key$(EXEXT)						\
+	pkey/key_app$(EXEXT)		pkey/key_app_writer$(EXEXT)	\
+	pkey/mpi_demo$(EXEXT)		pkey/pk_decrypt$(EXEXT)		\
+	pkey/pk_encrypt$(EXEXT)		pkey/pk_sign$(EXEXT)		\
+	pkey/pk_verify$(EXEXT)		pkey/rsa_genkey$(EXEXT)		\
+	pkey/rsa_decrypt$(EXEXT)	pkey/rsa_encrypt$(EXEXT)	\
+	pkey/rsa_sign$(EXEXT)		pkey/rsa_verify$(EXEXT)		\
+	pkey/rsa_sign_pss$(EXEXT)	pkey/rsa_verify_pss$(EXEXT)	\
+	ssl/dtls_client$(EXEXT)		ssl/dtls_server$(EXEXT)		\
+	ssl/ssl_client1$(EXEXT)		ssl/ssl_client2$(EXEXT)		\
+	ssl/ssl_server$(EXEXT)		ssl/ssl_server2$(EXEXT)		\
+	ssl/ssl_fork_server$(EXEXT)	ssl/mini_client$(EXEXT)		\
+	ssl/ssl_mail_client$(EXEXT)	random/gen_entropy$(EXEXT)	\
+	random/gen_random_havege$(EXEXT)				\
+	random/gen_random_ctr_drbg$(EXEXT)				\
+	test/ssl_cert_test$(EXEXT)	test/benchmark$(EXEXT)		\
+	test/selftest$(EXEXT)		test/ssl_test$(EXEXT)		\
+	test/udp_proxy$(EXEXT)						\
+	util/pem2der$(EXEXT)		util/strerror$(EXEXT)		\
+	x509/cert_app$(EXEXT)		x509/crl_app$(EXEXT)		\
+	x509/cert_req$(EXEXT)
 
 ifdef OPENSSL
 APPS +=	test/o_p_test
@@ -59,199 +72,203 @@
 
 all: $(APPS)
 
-aes/aescrypt2: aes/aescrypt2.c ../library/libmbedtls.a
+aes/aescrypt2$(EXEXT): aes/aescrypt2.c ../library/libmbedtls.a
 	echo   "  CC    aes/aescrypt2.c"
 	$(CC) $(CFLAGS) $(OFLAGS) aes/aescrypt2.c    $(LDFLAGS) -o $@
 
-aes/crypt_and_hash: aes/crypt_and_hash.c ../library/libmbedtls.a
+aes/crypt_and_hash$(EXEXT): aes/crypt_and_hash.c ../library/libmbedtls.a
 	echo   "  CC    aes/crypt_and_hash.c"
 	$(CC) $(CFLAGS) $(OFLAGS) aes/crypt_and_hash.c $(LDFLAGS) -o $@
 
-hash/hello: hash/hello.c ../library/libmbedtls.a
+hash/hello$(EXEXT): hash/hello.c ../library/libmbedtls.a
 	echo   "  CC    hash/hello.c"
 	$(CC) $(CFLAGS) $(OFLAGS) hash/hello.c       $(LDFLAGS) -o $@
 
-hash/generic_sum: hash/generic_sum.c ../library/libmbedtls.a
+hash/generic_sum$(EXEXT): hash/generic_sum.c ../library/libmbedtls.a
 	echo   "  CC    hash/generic_sum.c"
 	$(CC) $(CFLAGS) $(OFLAGS) hash/generic_sum.c $(LDFLAGS) -o $@
 
-hash/md5sum: hash/md5sum.c ../library/libmbedtls.a
+hash/md5sum$(EXEXT): hash/md5sum.c ../library/libmbedtls.a
 	echo   "  CC    hash/md5sum.c"
 	$(CC) $(CFLAGS) $(OFLAGS) hash/md5sum.c      $(LDFLAGS) -o $@
 
-hash/sha1sum: hash/sha1sum.c ../library/libmbedtls.a
+hash/sha1sum$(EXEXT): hash/sha1sum.c ../library/libmbedtls.a
 	echo   "  CC    hash/sha1sum.c"
 	$(CC) $(CFLAGS) $(OFLAGS) hash/sha1sum.c     $(LDFLAGS) -o $@
 
-hash/sha2sum: hash/sha2sum.c ../library/libmbedtls.a
+hash/sha2sum$(EXEXT): hash/sha2sum.c ../library/libmbedtls.a
 	echo   "  CC    hash/sha2sum.c"
 	$(CC) $(CFLAGS) $(OFLAGS) hash/sha2sum.c     $(LDFLAGS) -o $@
 
-pkey/dh_client: pkey/dh_client.c ../library/libmbedtls.a
+pkey/dh_client$(EXEXT): pkey/dh_client.c ../library/libmbedtls.a
 	echo   "  CC    pkey/dh_client.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/dh_client.c   $(LDFLAGS) -o $@
 
-pkey/dh_genprime: pkey/dh_genprime.c ../library/libmbedtls.a
+pkey/dh_genprime$(EXEXT): pkey/dh_genprime.c ../library/libmbedtls.a
 	echo   "  CC    pkey/dh_genprime.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/dh_genprime.c $(LDFLAGS) -o $@
 
-pkey/dh_server: pkey/dh_server.c ../library/libmbedtls.a
+pkey/dh_server$(EXEXT): pkey/dh_server.c ../library/libmbedtls.a
 	echo   "  CC    pkey/dh_server.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/dh_server.c   $(LDFLAGS) -o $@
 
-pkey/ecdsa: pkey/ecdsa.c ../library/libmbedtls.a
+pkey/ecdsa$(EXEXT): pkey/ecdsa.c ../library/libmbedtls.a
 	echo   "  CC    pkey/ecdsa.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/ecdsa.c       $(LDFLAGS) -o $@
 
-pkey/gen_key: pkey/gen_key.c ../library/libmbedtls.a
+pkey/gen_key$(EXEXT): pkey/gen_key.c ../library/libmbedtls.a
 	echo   "  CC    pkey/gen_key.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/gen_key.c   $(LDFLAGS) -o $@
 
-pkey/key_app: pkey/key_app.c ../library/libmbedtls.a
+pkey/key_app$(EXEXT): pkey/key_app.c ../library/libmbedtls.a
 	echo   "  CC    pkey/key_app.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/key_app.c   $(LDFLAGS) -o $@
 
-pkey/key_app_writer: pkey/key_app_writer.c ../library/libmbedtls.a
+pkey/key_app_writer$(EXEXT): pkey/key_app_writer.c ../library/libmbedtls.a
 	echo   "  CC    pkey/key_app_writer.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/key_app_writer.c   $(LDFLAGS) -o $@
 
-pkey/mpi_demo: pkey/mpi_demo.c ../library/libmbedtls.a
+pkey/mpi_demo$(EXEXT): pkey/mpi_demo.c ../library/libmbedtls.a
 	echo   "  CC    pkey/mpi_demo.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/mpi_demo.c    $(LDFLAGS) -o $@
 
-pkey/pk_decrypt: pkey/pk_decrypt.c ../library/libmbedtls.a
+pkey/pk_decrypt$(EXEXT): pkey/pk_decrypt.c ../library/libmbedtls.a
 	echo   "  CC    pkey/pk_decrypt.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/pk_decrypt.c    $(LDFLAGS) -o $@
 
-pkey/pk_encrypt: pkey/pk_encrypt.c ../library/libmbedtls.a
+pkey/pk_encrypt$(EXEXT): pkey/pk_encrypt.c ../library/libmbedtls.a
 	echo   "  CC    pkey/pk_encrypt.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/pk_encrypt.c    $(LDFLAGS) -o $@
 
-pkey/pk_sign: pkey/pk_sign.c ../library/libmbedtls.a
+pkey/pk_sign$(EXEXT): pkey/pk_sign.c ../library/libmbedtls.a
 	echo   "  CC    pkey/pk_sign.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/pk_sign.c    $(LDFLAGS) -o $@
 
-pkey/pk_verify: pkey/pk_verify.c ../library/libmbedtls.a
+pkey/pk_verify$(EXEXT): pkey/pk_verify.c ../library/libmbedtls.a
 	echo   "  CC    pkey/pk_verify.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/pk_verify.c  $(LDFLAGS) -o $@
 
-pkey/rsa_genkey: pkey/rsa_genkey.c ../library/libmbedtls.a
+pkey/rsa_genkey$(EXEXT): pkey/rsa_genkey.c ../library/libmbedtls.a
 	echo   "  CC    pkey/rsa_genkey.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/rsa_genkey.c  $(LDFLAGS) -o $@
 
-pkey/rsa_sign: pkey/rsa_sign.c ../library/libmbedtls.a
+pkey/rsa_sign$(EXEXT): pkey/rsa_sign.c ../library/libmbedtls.a
 	echo   "  CC    pkey/rsa_sign.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/rsa_sign.c    $(LDFLAGS) -o $@
 
-pkey/rsa_verify: pkey/rsa_verify.c ../library/libmbedtls.a
+pkey/rsa_verify$(EXEXT): pkey/rsa_verify.c ../library/libmbedtls.a
 	echo   "  CC    pkey/rsa_verify.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/rsa_verify.c  $(LDFLAGS) -o $@
 
-pkey/rsa_sign_pss: pkey/rsa_sign_pss.c ../library/libmbedtls.a
+pkey/rsa_sign_pss$(EXEXT): pkey/rsa_sign_pss.c ../library/libmbedtls.a
 	echo   "  CC    pkey/rsa_sign_pss.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/rsa_sign_pss.c    $(LDFLAGS) -o $@
 
-pkey/rsa_verify_pss: pkey/rsa_verify_pss.c ../library/libmbedtls.a
+pkey/rsa_verify_pss$(EXEXT): pkey/rsa_verify_pss.c ../library/libmbedtls.a
 	echo   "  CC    pkey/rsa_verify_pss.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/rsa_verify_pss.c  $(LDFLAGS) -o $@
 
-pkey/rsa_decrypt: pkey/rsa_decrypt.c ../library/libmbedtls.a
+pkey/rsa_decrypt$(EXEXT): pkey/rsa_decrypt.c ../library/libmbedtls.a
 	echo   "  CC    pkey/rsa_decrypt.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/rsa_decrypt.c    $(LDFLAGS) -o $@
 
-pkey/rsa_encrypt: pkey/rsa_encrypt.c ../library/libmbedtls.a
+pkey/rsa_encrypt$(EXEXT): pkey/rsa_encrypt.c ../library/libmbedtls.a
 	echo   "  CC    pkey/rsa_encrypt.c"
 	$(CC) $(CFLAGS) $(OFLAGS) pkey/rsa_encrypt.c    $(LDFLAGS) -o $@
 
-random/gen_entropy: random/gen_entropy.c ../library/libmbedtls.a
+random/gen_entropy$(EXEXT): random/gen_entropy.c ../library/libmbedtls.a
 	echo   "  CC    random/gen_entropy.c"
 	$(CC) $(CFLAGS) $(OFLAGS) random/gen_entropy.c $(LDFLAGS) -o $@
 
-random/gen_random_havege: random/gen_random_havege.c ../library/libmbedtls.a
+random/gen_random_havege$(EXEXT): random/gen_random_havege.c ../library/libmbedtls.a
 	echo   "  CC    random/gen_random_havege.c"
 	$(CC) $(CFLAGS) $(OFLAGS) random/gen_random_havege.c $(LDFLAGS) -o $@
 
-random/gen_random_ctr_drbg: random/gen_random_ctr_drbg.c ../library/libmbedtls.a
+random/gen_random_ctr_drbg$(EXEXT): random/gen_random_ctr_drbg.c ../library/libmbedtls.a
 	echo   "  CC    random/gen_random_ctr_drbg.c"
 	$(CC) $(CFLAGS) $(OFLAGS) random/gen_random_ctr_drbg.c $(LDFLAGS) -o $@
 
-ssl/dtls_client: ssl/dtls_client.c ../library/libmbedtls.a
+ssl/dtls_client$(EXEXT): ssl/dtls_client.c ../library/libmbedtls.a
 	echo   "  CC    ssl/dtls_client.c"
 	$(CC) $(CFLAGS) $(OFLAGS) ssl/dtls_client.c  $(LDFLAGS) -o $@
 
-ssl/dtls_server: ssl/dtls_server.c ../library/libmbedtls.a
+ssl/dtls_server$(EXEXT): ssl/dtls_server.c ../library/libmbedtls.a
 	echo   "  CC    ssl/dtls_server.c"
 	$(CC) $(CFLAGS) $(OFLAGS) ssl/dtls_server.c  $(LDFLAGS) -o $@
 
-ssl/ssl_client1: ssl/ssl_client1.c ../library/libmbedtls.a
+ssl/ssl_client1$(EXEXT): ssl/ssl_client1.c ../library/libmbedtls.a
 	echo   "  CC    ssl/ssl_client1.c"
 	$(CC) $(CFLAGS) $(OFLAGS) ssl/ssl_client1.c  $(LDFLAGS) -o $@
 
-ssl/ssl_client2: ssl/ssl_client2.c ../library/libmbedtls.a
+ssl/ssl_client2$(EXEXT): ssl/ssl_client2.c ../library/libmbedtls.a
 	echo   "  CC    ssl/ssl_client2.c"
 	$(CC) $(CFLAGS) $(OFLAGS) ssl/ssl_client2.c  $(LDFLAGS) -o $@
 
-ssl/ssl_server: ssl/ssl_server.c ../library/libmbedtls.a
+ssl/ssl_server$(EXEXT): ssl/ssl_server.c ../library/libmbedtls.a
 	echo   "  CC    ssl/ssl_server.c"
 	$(CC) $(CFLAGS) $(OFLAGS) ssl/ssl_server.c   $(LDFLAGS) -o $@
 
-ssl/ssl_server2: ssl/ssl_server2.c ../library/libmbedtls.a
+ssl/ssl_server2$(EXEXT): ssl/ssl_server2.c ../library/libmbedtls.a
 	echo   "  CC    ssl/ssl_server2.c"
 	$(CC) $(CFLAGS) $(OFLAGS) ssl/ssl_server2.c   $(LDFLAGS) -o $@
 
-ssl/ssl_fork_server: ssl/ssl_fork_server.c ../library/libmbedtls.a
+ssl/ssl_fork_server$(EXEXT): ssl/ssl_fork_server.c ../library/libmbedtls.a
 	echo   "  CC    ssl/ssl_fork_server.c"
 	$(CC) $(CFLAGS) $(OFLAGS) ssl/ssl_fork_server.c   $(LDFLAGS) -o $@
 
-ssl/ssl_pthread_server: ssl/ssl_pthread_server.c ../library/libmbedtls.a
+ssl/ssl_pthread_server$(EXEXT): ssl/ssl_pthread_server.c ../library/libmbedtls.a
 	echo   "  CC    ssl/ssl_pthread_server.c"
 	$(CC) $(CFLAGS) $(OFLAGS) ssl/ssl_pthread_server.c   $(LDFLAGS) -o $@ -lpthread
 
-ssl/ssl_mail_client: ssl/ssl_mail_client.c ../library/libmbedtls.a
+ssl/ssl_mail_client$(EXEXT): ssl/ssl_mail_client.c ../library/libmbedtls.a
 	echo   "  CC    ssl/ssl_mail_client.c"
 	$(CC) $(CFLAGS) $(OFLAGS) ssl/ssl_mail_client.c   $(LDFLAGS) -o $@
 
-test/ssl_cert_test: test/ssl_cert_test.c ../library/libmbedtls.a
+ssl/mini_client$(EXEXT): ssl/mini_client.c ../library/libmbedtls.a
+	echo   "  CC    ssl/mini_client.c"
+	$(CC) $(CFLAGS) $(OFLAGS) ssl/mini_client.c   $(LDFLAGS) -o $@
+
+test/ssl_cert_test$(EXEXT): test/ssl_cert_test.c ../library/libmbedtls.a
 	echo   "  CC    test/ssl_cert_test.c"
 	$(CC) $(CFLAGS) $(OFLAGS) test/ssl_cert_test.c   $(LDFLAGS) -o $@
 
-test/benchmark: test/benchmark.c ../library/libmbedtls.a
+test/benchmark$(EXEXT): test/benchmark.c ../library/libmbedtls.a
 	echo   "  CC    test/benchmark.c"
 	$(CC) $(CFLAGS) $(OFLAGS) test/benchmark.c   $(LDFLAGS) -o $@
 
-test/selftest: test/selftest.c ../library/libmbedtls.a
+test/selftest$(EXEXT): test/selftest.c ../library/libmbedtls.a
 	echo   "  CC    test/selftest.c"
 	$(CC) $(CFLAGS) $(OFLAGS) test/selftest.c    $(LDFLAGS) -o $@
 
-test/ssl_test: test/ssl_test.c ../library/libmbedtls.a
+test/ssl_test$(EXEXT): test/ssl_test.c ../library/libmbedtls.a
 	echo   "  CC    test/ssl_test.c"
 	$(CC) $(CFLAGS) $(OFLAGS) test/ssl_test.c    $(LDFLAGS) -o $@
 
-test/udp_proxy: test/udp_proxy.c ../library/libmbedtls.a
+test/udp_proxy$(EXEXT): test/udp_proxy.c ../library/libmbedtls.a
 	echo   "  CC    test/udp_proxy.c"
 	$(CC) $(CFLAGS) $(OFLAGS) test/udp_proxy.c    $(LDFLAGS) -o $@
 
-test/o_p_test: test/o_p_test.c ../library/libmbedtls.a
+test/o_p_test$(EXEXT): test/o_p_test.c ../library/libmbedtls.a
 	echo   "  CC    test/o_p_test.c"
 	$(CC) $(CFLAGS) $(OFLAGS) test/o_p_test.c    $(LDFLAGS) -o $@ -lssl -lcrypto
 
-util/pem2der: util/pem2der.c ../library/libmbedtls.a
+util/pem2der$(EXEXT): util/pem2der.c ../library/libmbedtls.a
 	echo   "  CC    util/pem2der.c"
 	$(CC) $(CFLAGS) $(OFLAGS) util/pem2der.c    $(LDFLAGS) -o $@
 
-util/strerror: util/strerror.c ../library/libmbedtls.a
+util/strerror$(EXEXT): util/strerror.c ../library/libmbedtls.a
 	echo   "  CC    util/strerror.c"
 	$(CC) $(CFLAGS) $(OFLAGS) util/strerror.c    $(LDFLAGS) -o $@
 
-x509/cert_app: x509/cert_app.c ../library/libmbedtls.a
+x509/cert_app$(EXEXT): x509/cert_app.c ../library/libmbedtls.a
 	echo   "  CC    x509/cert_app.c"
 	$(CC) $(CFLAGS) $(OFLAGS) x509/cert_app.c    $(LDFLAGS) -o $@
 
-x509/crl_app: x509/crl_app.c ../library/libmbedtls.a
+x509/crl_app$(EXEXT): x509/crl_app.c ../library/libmbedtls.a
 	echo   "  CC    x509/crl_app.c"
 	$(CC) $(CFLAGS) $(OFLAGS) x509/crl_app.c    $(LDFLAGS) -o $@
 
-x509/cert_req: x509/cert_req.c ../library/libmbedtls.a
+x509/cert_req$(EXEXT): x509/cert_req.c ../library/libmbedtls.a
 	echo   "  CC    x509/cert_req.c"
 	$(CC) $(CFLAGS) $(OFLAGS) x509/cert_req.c    $(LDFLAGS) -o $@
 
diff --git a/programs/aes/aescrypt2.c b/programs/aes/aescrypt2.c
index 1f34748..430b87f 100644
--- a/programs/aes/aescrypt2.c
+++ b/programs/aes/aescrypt2.c
@@ -29,8 +29,19 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
+#endif
+
+#if defined(POLARSSL_AES_C) && defined(POLARSSL_SHA256_C) && \
+ defined(POLARSSL_FS_IO)
+#include "polarssl/aes.h"
+#include "polarssl/sha256.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 #endif
 
 #if defined(_WIN32)
@@ -43,14 +54,6 @@
 #include <unistd.h>
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <time.h>
-
-#include "polarssl/aes.h"
-#include "polarssl/sha256.h"
-
 #define MODE_ENCRYPT    0
 #define MODE_DECRYPT    1
 
@@ -60,12 +63,11 @@
     "\n  example: aescrypt2 0 file file.aes hex:E76B2413958B00E193\n" \
     "\n"
 
-#if !defined(POLARSSL_AES_C) || !defined(POLARSSL_SHA256_C)
-int main( int argc, char *argv[] )
+#if !defined(POLARSSL_AES_C) || !defined(POLARSSL_SHA256_C) || \
+    !defined(POLARSSL_FS_IO)
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-    polarssl_printf("POLARSSL_AES_C and/or POLARSSL_SHA256_C not defined.\n");
+    polarssl_printf("POLARSSL_AES_C and/or POLARSSL_SHA256_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
 #else
@@ -442,4 +444,4 @@
 
     return( ret );
 }
-#endif /* POLARSSL_AES_C && POLARSSL_SHA256_C */
+#endif /* POLARSSL_AES_C && POLARSSL_SHA256_C && POLARSSL_FS_IO */
diff --git a/programs/aes/crypt_and_hash.c b/programs/aes/crypt_and_hash.c
index 7ad07b4..c76b8db 100644
--- a/programs/aes/crypt_and_hash.c
+++ b/programs/aes/crypt_and_hash.c
@@ -30,8 +30,19 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
+#endif
+
+#if defined(POLARSSL_CIPHER_C) && defined(POLARSSL_MD_C) && \
+ defined(POLARSSL_FS_IO)
+#include "polarssl/cipher.h"
+#include "polarssl/md.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 #endif
 
 #if defined(_WIN32)
@@ -44,14 +55,6 @@
 #include <unistd.h>
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <time.h>
-
-#include "polarssl/cipher.h"
-#include "polarssl/md.h"
-
 #define MODE_ENCRYPT    0
 #define MODE_DECRYPT    1
 
@@ -61,13 +64,11 @@
     "\n  example: crypt_and_hash 0 file file.aes AES-128-CBC SHA1 hex:E76B2413958B00E193\n" \
     "\n"
 
-#if !defined(POLARSSL_CIPHER_C) || !defined(POLARSSL_MD_C)
-int main( int argc, char *argv[] )
+#if !defined(POLARSSL_CIPHER_C) || !defined(POLARSSL_MD_C) || \
+    !defined(POLARSSL_FS_IO)
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf("POLARSSL_CIPHER_C and/or POLARSSL_MD_C not defined.\n");
+    polarssl_printf("POLARSSL_CIPHER_C and/or POLARSSL_MD_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
 #else
@@ -399,7 +400,7 @@
             goto exit;
         }
 
-        if( ( ( filesize - md_get_size( md_info ) ) % 
+        if( ( ( filesize - md_get_size( md_info ) ) %
                 cipher_get_block_size( &cipher_ctx ) ) != 0 )
         {
             polarssl_fprintf( stderr, "File content not a multiple of the block size (%d).\n",
@@ -542,4 +543,4 @@
 
     return( ret );
 }
-#endif /* POLARSSL_CIPHER_C && POLARSSL_MD_C */
+#endif /* POLARSSL_CIPHER_C && POLARSSL_MD_C && POLARSSL_FS_IO */
diff --git a/programs/hash/generic_sum.c b/programs/hash/generic_sum.c
index 20ff252..a49dbb7 100644
--- a/programs/hash/generic_sum.c
+++ b/programs/hash/generic_sum.c
@@ -29,22 +29,22 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_MD_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/md.h"
 
-#if !defined(POLARSSL_MD_C)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#include <stdio.h>
+#include <string.h>
+#endif
 
-    polarssl_printf("POLARSSL_MD_C not defined.\n");
+#if !defined(POLARSSL_MD_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
+    polarssl_printf("POLARSSL_MD_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
 #else
@@ -225,4 +225,4 @@
 
     return( ret );
 }
-#endif /* POLARSSL_MD_C */
+#endif /* POLARSSL_MD_C && POLARSSL_FS_IO */
diff --git a/programs/hash/hello.c b/programs/hash/hello.c
index 7c0546e..c774110 100644
--- a/programs/hash/hello.c
+++ b/programs/hash/hello.c
@@ -29,32 +29,27 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <stdio.h>
-
+#if defined(POLARSSL_MD5_C)
 #include "polarssl/md5.h"
+#endif
 
 #if !defined(POLARSSL_MD5_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_MD5_C not defined.\n");
     return( 0 );
 }
 #else
-int main( int argc, char *argv[] )
+int main( void )
 {
     int i;
     unsigned char digest[16];
     char str[] = "Hello, world!";
 
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf( "\n  MD5('%s') = ", str );
 
     md5( (unsigned char *) str, 13, digest );
diff --git a/programs/hash/md5sum.c b/programs/hash/md5sum.c
index 58c2d0c..afe3454 100644
--- a/programs/hash/md5sum.c
+++ b/programs/hash/md5sum.c
@@ -29,21 +29,21 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_MD5_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/md5.h"
 
-#if !defined(POLARSSL_MD5_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#include <stdio.h>
+#include <string.h>
+#endif
 
+#if !defined(POLARSSL_MD5_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
     polarssl_printf("POLARSSL_MD5_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
diff --git a/programs/hash/sha1sum.c b/programs/hash/sha1sum.c
index 3eafc4f..8dc4e08 100644
--- a/programs/hash/sha1sum.c
+++ b/programs/hash/sha1sum.c
@@ -29,21 +29,21 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_SHA1_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/sha1.h"
 
-#if !defined(POLARSSL_SHA1_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#include <stdio.h>
+#include <string.h>
+#endif
 
+#if !defined(POLARSSL_SHA1_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
     polarssl_printf("POLARSSL_SHA1_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
diff --git a/programs/hash/sha2sum.c b/programs/hash/sha2sum.c
index 3fc1baa..268d170 100644
--- a/programs/hash/sha2sum.c
+++ b/programs/hash/sha2sum.c
@@ -29,21 +29,21 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_SHA256_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/sha256.h"
 
-#if !defined(POLARSSL_SHA256_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#include <stdio.h>
+#include <string.h>
+#endif
 
+#if !defined(POLARSSL_SHA256_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
     polarssl_printf("POLARSSL_SHA256_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
diff --git a/programs/pkey/dh_client.c b/programs/pkey/dh_client.c
index a34bafa..b600584 100644
--- a/programs/pkey/dh_client.c
+++ b/programs/pkey/dh_client.c
@@ -29,12 +29,14 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_AES_C) && defined(POLARSSL_DHM_C) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_NET_C) && \
+    defined(POLARSSL_RSA_C) && defined(POLARSSL_SHA256_C) && \
+    defined(POLARSSL_FS_IO) && defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/net.h"
 #include "polarssl/aes.h"
 #include "polarssl/dhm.h"
@@ -43,26 +45,27 @@
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 #define SERVER_NAME "localhost"
 #define SERVER_PORT 11999
 
 #if !defined(POLARSSL_AES_C) || !defined(POLARSSL_DHM_C) ||     \
     !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_NET_C) ||  \
-    !defined(POLARSSL_RSA_C) || !defined(POLARSSL_SHA1_C) ||    \
+    !defined(POLARSSL_RSA_C) || !defined(POLARSSL_SHA256_C) ||    \
     !defined(POLARSSL_FS_IO) || !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_AES_C and/or POLARSSL_DHM_C and/or POLARSSL_ENTROPY_C "
            "and/or POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
-           "POLARSSL_SHA1_C and/or POLARSSL_FS_IO and/or "
+           "POLARSSL_SHA256_C and/or POLARSSL_FS_IO and/or "
            "POLARSSL_CTR_DRBG_C not defined.\n");
     return( 0 );
 }
 #else
-int main( int argc, char *argv[] )
+int main( void )
 {
     FILE *f;
 
@@ -81,9 +84,6 @@
     dhm_context dhm;
     aes_context aes;
 
-    ((void) argc);
-    ((void) argv);
-
     memset( &rsa, 0, sizeof( rsa ) );
     dhm_init( &dhm );
     aes_init( &aes );
@@ -193,7 +193,7 @@
 
     /*
      * 5. Check that the server's RSA signature matches
-     *    the SHA-1 hash of (P,G,Ys)
+     *    the SHA-256 hash of (P,G,Ys)
      */
     polarssl_printf( "\n  . Verifying the server's RSA signature" );
     fflush( stdout );
@@ -210,7 +210,7 @@
     sha1( buf, (int)( p - 2 - buf ), hash );
 
     if( ( ret = rsa_pkcs1_verify( &rsa, NULL, NULL, RSA_PUBLIC,
-                                  POLARSSL_MD_SHA1, 0, hash, p ) ) != 0 )
+                                  POLARSSL_MD_SHA256, 0, hash, p ) ) != 0 )
     {
         polarssl_printf( " failed\n  ! rsa_pkcs1_verify returned %d\n\n", ret );
         goto exit;
@@ -297,5 +297,5 @@
     return( ret );
 }
 #endif /* POLARSSL_AES_C && POLARSSL_DHM_C && POLARSSL_ENTROPY_C &&
-          POLARSSL_NET_C && POLARSSL_RSA_C && POLARSSL_SHA1_C && 
+          POLARSSL_NET_C && POLARSSL_RSA_C && POLARSSL_SHA256_C &&
           POLARSSL_FS_IO && POLARSSL_CTR_DRBG_C */
diff --git a/programs/pkey/dh_genprime.c b/programs/pkey/dh_genprime.c
index 720232f..e0ca260 100644
--- a/programs/pkey/dh_genprime.c
+++ b/programs/pkey/dh_genprime.c
@@ -29,15 +29,21 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_FS_IO) && defined(POLARSSL_CTR_DRBG_C) && \
+    defined(POLARSSL_GENPRIME)
 #include "polarssl/bignum.h"
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 /*
  * Note: G = 4 is always a quadratic residue mod P,
  * so it is a generator of order Q (with P = 2*Q+1).
@@ -48,18 +54,15 @@
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||   \
     !defined(POLARSSL_FS_IO) || !defined(POLARSSL_CTR_DRBG_C) ||     \
     !defined(POLARSSL_GENPRIME)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
            "POLARSSL_FS_IO and/or POLARSSL_CTR_DRBG_C and/or "
            "POLARSSL_GENPRIME not defined.\n");
     return( 0 );
 }
 #else
-int main( int argc, char *argv[] )
+int main( void )
 {
     int ret = 1;
     mpi G, P, Q;
@@ -68,9 +71,6 @@
     const char *pers = "dh_genprime";
     FILE *fout;
 
-    ((void) argc);
-    ((void) argv);
-
     mpi_init( &G ); mpi_init( &P ); mpi_init( &Q );
     entropy_init( &entropy );
 
diff --git a/programs/pkey/dh_server.c b/programs/pkey/dh_server.c
index f21e578..b623a68 100644
--- a/programs/pkey/dh_server.c
+++ b/programs/pkey/dh_server.c
@@ -29,12 +29,14 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_AES_C) && defined(POLARSSL_DHM_C) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_NET_C) && \
+    defined(POLARSSL_RSA_C) && defined(POLARSSL_SHA256_C) && \
+    defined(POLARSSL_FS_IO) && defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/net.h"
 #include "polarssl/aes.h"
 #include "polarssl/dhm.h"
@@ -43,26 +45,27 @@
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 #define SERVER_PORT 11999
 #define PLAINTEXT "==Hello there!=="
 
 #if !defined(POLARSSL_AES_C) || !defined(POLARSSL_DHM_C) ||     \
     !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_NET_C) ||  \
-    !defined(POLARSSL_RSA_C) || !defined(POLARSSL_SHA1_C) ||    \
+    !defined(POLARSSL_RSA_C) || !defined(POLARSSL_SHA256_C) ||    \
     !defined(POLARSSL_FS_IO) || !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_AES_C and/or POLARSSL_DHM_C and/or POLARSSL_ENTROPY_C "
            "and/or POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
-           "POLARSSL_SHA1_C and/or POLARSSL_FS_IO and/or "
+           "POLARSSL_SHA256_C and/or POLARSSL_FS_IO and/or "
            "POLARSSL_CTR_DBRG_C not defined.\n");
     return( 0 );
 }
 #else
-int main( int argc, char *argv[] )
+int main( void )
 {
     FILE *f;
 
@@ -82,9 +85,6 @@
     dhm_context dhm;
     aes_context aes;
 
-    ((void) argc);
-    ((void) argv);
-
     memset( &rsa, 0, sizeof( rsa ) );
     dhm_init( &dhm );
     aes_init( &aes );
@@ -134,7 +134,7 @@
     }
 
     rsa.len = ( mpi_msb( &rsa.N ) + 7 ) >> 3;
-    
+
     fclose( f );
 
     /*
@@ -201,7 +201,7 @@
     buf[n    ] = (unsigned char)( rsa.len >> 8 );
     buf[n + 1] = (unsigned char)( rsa.len      );
 
-    if( ( ret = rsa_pkcs1_sign( &rsa, NULL, NULL, RSA_PRIVATE, POLARSSL_MD_SHA1,
+    if( ( ret = rsa_pkcs1_sign( &rsa, NULL, NULL, RSA_PRIVATE, POLARSSL_MD_SHA256,
                                 0, hash, buf + n + 2 ) ) != 0 )
     {
         polarssl_printf( " failed\n  ! rsa_pkcs1_sign returned %d\n\n", ret );
@@ -298,5 +298,5 @@
     return( ret );
 }
 #endif /* POLARSSL_AES_C && POLARSSL_DHM_C && POLARSSL_ENTROPY_C &&
-          POLARSSL_NET_C && POLARSSL_RSA_C && POLARSSL_SHA1_C &&
+          POLARSSL_NET_C && POLARSSL_RSA_C && POLARSSL_SHA256_C &&
           POLARSSL_FS_IO && POLARSSL_CTR_DRBG_C */
diff --git a/programs/pkey/ecdsa.c b/programs/pkey/ecdsa.c
index b533673..640d3e7 100644
--- a/programs/pkey/ecdsa.c
+++ b/programs/pkey/ecdsa.c
@@ -29,15 +29,18 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
+#if defined(POLARSSL_ECDSA_C) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 #include "polarssl/ecdsa.h"
 
 #include <string.h>
-#include <stdio.h>
+#endif
 
 /*
  * Uncomment to show key and signature details
@@ -55,17 +58,13 @@
 
 #if !defined(POLARSSL_ECDSA_C) || \
     !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_ECDSA_C and/or "
            "POLARSSL_ENTROPY_C and/or POLARSSL_CTR_DRBG_C not defined\n");
     return( 0 );
 }
 #else
-
 #if defined(VERBOSE)
 static void dump_buf( const char *title, unsigned char *buf, size_t len )
 {
diff --git a/programs/pkey/gen_key.c b/programs/pkey/gen_key.c
index 2d981ab..a4095da 100644
--- a/programs/pkey/gen_key.c
+++ b/programs/pkey/gen_key.c
@@ -29,17 +29,12 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-#if !defined(_WIN32) && defined(POLARSSL_FS_IO)
-#include <unistd.h>
-#endif /* !_WIN32 && POLARSSL_FS_IO */
-
+#if defined(POLARSSL_PK_WRITE_C) && defined(POLARSSL_FS_IO) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/error.h"
 #include "polarssl/pk.h"
 #include "polarssl/ecdsa.h"
@@ -48,49 +43,12 @@
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 
-#if !defined(POLARSSL_PK_WRITE_C) || !defined(POLARSSL_FS_IO) ||    \
-    !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 
-    polarssl_printf( "POLARSSL_PK_WRITE_C and/or POLARSSL_FS_IO and/or "
-            "POLARSSL_ENTROPY_C and/or POLARSSL_CTR_DRBG_C "
-            "not defined.\n" );
-    return( 0 );
-}
-#else
-
-#define FORMAT_PEM              0
-#define FORMAT_DER              1
-
-#define DFL_TYPE                POLARSSL_PK_RSA
-#define DFL_RSA_KEYSIZE         4096
-#define DFL_FILENAME            "keyfile.key"
-#define DFL_FORMAT              FORMAT_PEM
-#define DFL_USE_DEV_RANDOM      0
-
-#if defined(POLARSSL_ECP_C)
-#define DFL_EC_CURVE            ecp_curve_list()->grp_id
-#else
-#define DFL_EC_CURVE            0
-#endif
-
-/*
- * global options
- */
-struct options
-{
-    int type;                   /* the type of key to generate          */
-    int rsa_keysize;            /* length of key in bits                */
-    int ec_curve;               /* curve identifier for EC keys         */
-    const char *filename;       /* filename of the key file             */
-    int format;                 /* the output format to use             */
-    int use_dev_random;         /* use /dev/random as entropy source    */
-} opt;
-
-#if !defined(_WIN32) && defined(POLARSSL_FS_IO)
+#if !defined(_WIN32)
+#include <unistd.h>
 
 #define DEV_RANDOM_THRESHOLD        32
 
@@ -127,8 +85,65 @@
 
     return( 0 );
 }
+#endif /* !_WIN32 */
+#endif
+
+#if defined(POLARSSL_ECP_C)
+#define DFL_EC_CURVE            ecp_curve_list()->grp_id
+#else
+#define DFL_EC_CURVE            0
+#endif
+
+#if !defined(_WIN32) && defined(POLARSSL_FS_IO)
+#define USAGE_DEV_RANDOM \
+    "    use_dev_random=0|1    default: 0\n"
+#else
+#define USAGE_DEV_RANDOM ""
 #endif /* !_WIN32 && POLARSSL_FS_IO */
 
+#define FORMAT_PEM              0
+#define FORMAT_DER              1
+
+#define DFL_TYPE                POLARSSL_PK_RSA
+#define DFL_RSA_KEYSIZE         4096
+#define DFL_FILENAME            "keyfile.key"
+#define DFL_FORMAT              FORMAT_PEM
+#define DFL_USE_DEV_RANDOM      0
+
+#define USAGE \
+    "\n usage: gen_key param=<>...\n"                   \
+    "\n acceptable parameters:\n"                       \
+    "    type=rsa|ec           default: rsa\n"          \
+    "    rsa_keysize=%%d        default: 4096\n"        \
+    "    ec_curve=%%s           see below\n"            \
+    "    filename=%%s           default: keyfile.key\n" \
+    "    format=pem|der        default: pem\n"          \
+    USAGE_DEV_RANDOM                                    \
+    "\n"
+
+#if !defined(POLARSSL_PK_WRITE_C) || !defined(POLARSSL_FS_IO) ||    \
+    !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_CTR_DRBG_C)
+int main( void )
+{
+    polarssl_printf( "POLARSSL_PK_WRITE_C and/or POLARSSL_FS_IO and/or "
+            "POLARSSL_ENTROPY_C and/or POLARSSL_CTR_DRBG_C "
+            "not defined.\n" );
+    return( 0 );
+}
+#else
+/*
+ * global options
+ */
+struct options
+{
+    int type;                   /* the type of key to generate          */
+    int rsa_keysize;            /* length of key in bits                */
+    int ec_curve;               /* curve identifier for EC keys         */
+    const char *filename;       /* filename of the key file             */
+    int format;                 /* the output format to use             */
+    int use_dev_random;         /* use /dev/random as entropy source    */
+} opt;
+
 static int write_private_key( pk_context *key, const char *output_file )
 {
     int ret;
@@ -168,24 +183,6 @@
     return( 0 );
 }
 
-#if !defined(_WIN32) && defined(POLARSSL_FS_IO)
-#define USAGE_DEV_RANDOM \
-    "    use_dev_random=0|1    default: 0\n"
-#else
-#define USAGE_DEV_RANDOM ""
-#endif /* !_WIN32 && POLARSSL_FS_IO */
-
-#define USAGE \
-    "\n usage: gen_key param=<>...\n"                   \
-    "\n acceptable parameters:\n"                       \
-    "    type=rsa|ec           default: rsa\n"          \
-    "    rsa_keysize=%%d        default: 4096\n"        \
-    "    ec_curve=%%s           see below\n"            \
-    "    filename=%%s           default: keyfile.key\n" \
-    "    format=pem|der        default: pem\n"          \
-    USAGE_DEV_RANDOM                                    \
-    "\n"
-
 int main( int argc, char *argv[] )
 {
     int ret = 0;
diff --git a/programs/pkey/key_app.c b/programs/pkey/key_app.c
index 04bad87..98f36db 100644
--- a/programs/pkey/key_app.c
+++ b/programs/pkey/key_app.c
@@ -29,29 +29,18 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && \
+    defined(POLARSSL_PK_PARSE_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/error.h"
 #include "polarssl/rsa.h"
 #include "polarssl/x509.h"
 
-#if !defined(POLARSSL_BIGNUM_C) ||                                  \
-    !defined(POLARSSL_PK_PARSE_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf("POLARSSL_BIGNUM_C and/or "
-           "POLARSSL_PK_PARSE_C and/or POLARSSL_FS_IO not defined.\n");
-    return( 0 );
-}
-#else
+#include <string.h>
+#endif
 
 #define MODE_NONE               0
 #define MODE_PRIVATE            1
@@ -63,6 +52,25 @@
 #define DFL_PASSWORD_FILE       ""
 #define DFL_DEBUG_LEVEL         0
 
+#define USAGE \
+    "\n usage: key_app param=<>...\n"                   \
+    "\n acceptable parameters:\n"                       \
+    "    mode=private|public default: none\n"           \
+    "    filename=%%s         default: keyfile.key\n"   \
+    "    password=%%s         default: \"\"\n"          \
+    "    password_file=%%s    default: \"\"\n"          \
+    "\n"
+
+
+#if !defined(POLARSSL_BIGNUM_C) ||                                  \
+    !defined(POLARSSL_PK_PARSE_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
+    polarssl_printf("POLARSSL_BIGNUM_C and/or "
+           "POLARSSL_PK_PARSE_C and/or POLARSSL_FS_IO not defined.\n");
+    return( 0 );
+}
+#else
 /*
  * global options
  */
@@ -74,15 +82,6 @@
     const char *password_file;  /* password_file for the private key    */
 } opt;
 
-#define USAGE \
-    "\n usage: key_app param=<>...\n"                   \
-    "\n acceptable parameters:\n"                       \
-    "    mode=private|public default: none\n"           \
-    "    filename=%%s         default: keyfile.key\n"   \
-    "    password=%%s         default: \"\"\n"          \
-    "    password_file=%%s    default: \"\"\n"          \
-    "\n"
-
 int main( int argc, char *argv[] )
 {
     int ret = 0;
diff --git a/programs/pkey/key_app_writer.c b/programs/pkey/key_app_writer.c
index c9830c2..09233ff 100644
--- a/programs/pkey/key_app_writer.c
+++ b/programs/pkey/key_app_writer.c
@@ -29,27 +29,41 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_PK_WRITE_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/error.h"
 #include "polarssl/pk.h"
 #include "polarssl/error.h"
 
-#if !defined(POLARSSL_PK_WRITE_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#include <stdio.h>
+#include <string.h>
+#endif
 
-    polarssl_printf( "POLARSSL_PK_WRITE_C and/or POLARSSL_FS_IO not defined.\n" );
-    return( 0 );
-}
+#if defined(POLARSSL_PEM_WRITE_C)
+#define USAGE_OUT \
+    "    output_file=%%s      default: keyfile.pem\n"   \
+    "    output_format=pem|der default: pem\n"
 #else
+#define USAGE_OUT \
+    "    output_file=%%s      default: keyfile.der\n"   \
+    "    output_format=der     default: der\n"
+#endif
+
+#if defined(POLARSSL_PEM_WRITE_C)
+#define DFL_OUTPUT_FILENAME     "keyfile.pem"
+#define DFL_OUTPUT_FORMAT       OUTPUT_FORMAT_PEM
+#else
+#define DFL_OUTPUT_FILENAME     "keyfile.der"
+#define DFL_OUTPUT_FORMAT       OUTPUT_FORMAT_DER
+#endif
+
+#define DFL_MODE                MODE_NONE
+#define DFL_FILENAME            "keyfile.key"
+#define DFL_DEBUG_LEVEL         0
+#define DFL_OUTPUT_MODE         OUTPUT_MODE_NONE
 
 #define MODE_NONE               0
 #define MODE_PRIVATE            1
@@ -62,18 +76,22 @@
 #define OUTPUT_FORMAT_PEM              0
 #define OUTPUT_FORMAT_DER              1
 
-#define DFL_MODE                MODE_NONE
-#define DFL_FILENAME            "keyfile.key"
-#define DFL_DEBUG_LEVEL         0
-#define DFL_OUTPUT_MODE         OUTPUT_MODE_NONE
-#if defined(POLARSSL_PEM_WRITE_C)
-#define DFL_OUTPUT_FILENAME     "keyfile.pem"
-#define DFL_OUTPUT_FORMAT       OUTPUT_FORMAT_PEM
-#else
-#define DFL_OUTPUT_FILENAME     "keyfile.der"
-#define DFL_OUTPUT_FORMAT       OUTPUT_FORMAT_DER
-#endif
+#define USAGE \
+    "\n usage: key_app param=<>...\n"                   \
+    "\n acceptable parameters:\n"                       \
+    "    mode=private|public default: none\n"           \
+    "    filename=%%s         default: keyfile.key\n"   \
+    "    output_mode=private|public default: none\n"    \
+    USAGE_OUT                                           \
+    "\n"
 
+#if !defined(POLARSSL_PK_WRITE_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
+    polarssl_printf( "POLARSSL_PK_WRITE_C and/or POLARSSL_FS_IO not defined.\n" );
+    return( 0 );
+}
+#else
 /*
  * global options
  */
@@ -170,25 +188,6 @@
     return( 0 );
 }
 
-#if defined(POLARSSL_PEM_WRITE_C)
-#define USAGE_OUT \
-    "    output_file=%%s      default: keyfile.pem\n"   \
-    "    output_format=pem|der default: pem\n"
-#else
-#define USAGE_OUT \
-    "    output_file=%%s      default: keyfile.der\n"   \
-    "    output_format=der     default: der\n"
-#endif
-
-#define USAGE \
-    "\n usage: key_app param=<>...\n"                   \
-    "\n acceptable parameters:\n"                       \
-    "    mode=private|public default: none\n"           \
-    "    filename=%%s         default: keyfile.key\n"   \
-    "    output_mode=private|public default: none\n"    \
-    USAGE_OUT                                           \
-    "\n"
-
 int main( int argc, char *argv[] )
 {
     int ret = 0;
diff --git a/programs/pkey/mpi_demo.c b/programs/pkey/mpi_demo.c
index b5ae13e..7281c3a 100644
--- a/programs/pkey/mpi_demo.c
+++ b/programs/pkey/mpi_demo.c
@@ -29,77 +29,82 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/bignum.h"
 
-#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#include <stdio.h>
+#endif
 
+#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
 #else
-int main( int argc, char *argv[] )
+int main( void )
 {
+    int ret;
     mpi E, P, Q, N, H, D, X, Y, Z;
 
-    ((void) argc);
-    ((void) argv);
-
     mpi_init( &E ); mpi_init( &P ); mpi_init( &Q ); mpi_init( &N );
     mpi_init( &H ); mpi_init( &D ); mpi_init( &X ); mpi_init( &Y );
     mpi_init( &Z );
 
-    mpi_read_string( &P, 10, "2789" );
-    mpi_read_string( &Q, 10, "3203" );
-    mpi_read_string( &E, 10,  "257" );
-    mpi_mul_mpi( &N, &P, &Q );
+    MPI_CHK( mpi_read_string( &P, 10, "2789" ) );
+    MPI_CHK( mpi_read_string( &Q, 10, "3203" ) );
+    MPI_CHK( mpi_read_string( &E, 10,  "257" ) );
+    MPI_CHK( mpi_mul_mpi( &N, &P, &Q ) );
 
     polarssl_printf( "\n  Public key:\n\n" );
-    mpi_write_file( "  N = ", &N, 10, NULL );
-    mpi_write_file( "  E = ", &E, 10, NULL );
+    MPI_CHK( mpi_write_file( "  N = ", &N, 10, NULL ) );
+    MPI_CHK( mpi_write_file( "  E = ", &E, 10, NULL ) );
 
     polarssl_printf( "\n  Private key:\n\n" );
-    mpi_write_file( "  P = ", &P, 10, NULL );
-    mpi_write_file( "  Q = ", &Q, 10, NULL );
+    MPI_CHK( mpi_write_file( "  P = ", &P, 10, NULL ) );
+    MPI_CHK( mpi_write_file( "  Q = ", &Q, 10, NULL ) );
 
 #if defined(POLARSSL_GENPRIME)
-    mpi_sub_int( &P, &P, 1 );
-    mpi_sub_int( &Q, &Q, 1 );
-    mpi_mul_mpi( &H, &P, &Q );
-    mpi_inv_mod( &D, &E, &H );
+    MPI_CHK( mpi_sub_int( &P, &P, 1 ) );
+    MPI_CHK( mpi_sub_int( &Q, &Q, 1 ) );
+    MPI_CHK( mpi_mul_mpi( &H, &P, &Q ) );
+    MPI_CHK( mpi_inv_mod( &D, &E, &H ) );
 
     mpi_write_file( "  D = E^-1 mod (P-1)*(Q-1) = ",
                     &D, 10, NULL );
 #else
     polarssl_printf("\nTest skipped (POLARSSL_GENPRIME not defined).\n\n");
 #endif
-    mpi_read_string( &X, 10, "55555" );
-    mpi_exp_mod( &Y, &X, &E, &N, NULL );
-    mpi_exp_mod( &Z, &Y, &D, &N, NULL );
+    MPI_CHK( mpi_read_string( &X, 10, "55555" ) );
+    MPI_CHK( mpi_exp_mod( &Y, &X, &E, &N, NULL ) );
+    MPI_CHK( mpi_exp_mod( &Z, &Y, &D, &N, NULL ) );
 
     polarssl_printf( "\n  RSA operation:\n\n" );
-    mpi_write_file( "  X (plaintext)  = ", &X, 10, NULL );
-    mpi_write_file( "  Y (ciphertext) = X^E mod N = ", &Y, 10, NULL );
-    mpi_write_file( "  Z (decrypted)  = Y^D mod N = ", &Z, 10, NULL );
+    MPI_CHK( mpi_write_file( "  X (plaintext)  = ", &X, 10, NULL ) );
+    MPI_CHK( mpi_write_file( "  Y (ciphertext) = X^E mod N = ", &Y, 10, NULL ) );
+    MPI_CHK( mpi_write_file( "  Z (decrypted)  = Y^D mod N = ", &Z, 10, NULL ) );
     polarssl_printf( "\n" );
 
+cleanup:
     mpi_free( &E ); mpi_free( &P ); mpi_free( &Q ); mpi_free( &N );
     mpi_free( &H ); mpi_free( &D ); mpi_free( &X ); mpi_free( &Y );
     mpi_free( &Z );
 
+    if( ret != 0 )
+    {
+        polarssl_printf( "\nAn error occured.\n" );
+        ret = 1;
+    }
+
 #if defined(_WIN32)
     polarssl_printf( "  Press Enter to exit this program.\n" );
     fflush( stdout ); getchar();
 #endif
 
-    return( 0 );
+    return( ret );
 }
 #endif /* POLARSSL_BIGNUM_C && POLARSSL_FS_IO */
diff --git a/programs/pkey/pk_decrypt.c b/programs/pkey/pk_decrypt.c
index 8644698..2bd8b34 100644
--- a/programs/pkey/pk_decrypt.c
+++ b/programs/pkey/pk_decrypt.c
@@ -29,25 +29,28 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_PK_PARSE_C) && \
+    defined(POLARSSL_FS_IO) && defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/error.h"
 #include "polarssl/pk.h"
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
+
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_PK_PARSE_C) ||  \
     !defined(POLARSSL_FS_IO) || !defined(POLARSSL_ENTROPY_C) || \
     !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_PK_PARSE_C and/or "
            "POLARSSL_FS_IO and/or POLARSSL_ENTROPY_C and/or "
            "POLARSSL_CTR_DRBG_C not defined.\n");
diff --git a/programs/pkey/pk_encrypt.c b/programs/pkey/pk_encrypt.c
index 663c2ee..9a3e782 100644
--- a/programs/pkey/pk_encrypt.c
+++ b/programs/pkey/pk_encrypt.c
@@ -29,26 +29,28 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_PK_PARSE_C) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_FS_IO) && \
+    defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/error.h"
 #include "polarssl/pk.h"
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_PK_PARSE_C) ||  \
     !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_FS_IO) || \
     !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_PK_PARSE_C and/or "
            "POLARSSL_ENTROPY_C and/or POLARSSL_FS_IO and/or "
            "POLARSSL_CTR_DRBG_C not defined.\n");
diff --git a/programs/pkey/pk_sign.c b/programs/pkey/pk_sign.c
index 981591d..e85350d 100644
--- a/programs/pkey/pk_sign.c
+++ b/programs/pkey/pk_sign.c
@@ -29,12 +29,16 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #define polarssl_printf     printf
+#define polarssl_snprintf   snprintf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_SHA256_C) && \
+    defined(POLARSSL_PK_PARSE_C) && defined(POLARSSL_FS_IO) && \
+    defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/error.h"
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
@@ -42,21 +46,22 @@
 #include "polarssl/pk.h"
 #include "polarssl/sha1.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 #if defined _MSC_VER && !defined snprintf
 #define snprintf _snprintf
 #endif
 
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||  \
-    !defined(POLARSSL_SHA1_C) ||                                    \
+    !defined(POLARSSL_SHA256_C) ||                                    \
     !defined(POLARSSL_PK_PARSE_C) || !defined(POLARSSL_FS_IO) ||    \
     !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
-           "POLARSSL_SHA1_C and/or "
+           "POLARSSL_SHA256_C and/or "
            "POLARSSL_PK_PARSE_C and/or POLARSSL_FS_IO and/or "
            "POLARSSL_CTR_DRBG_C not defined.\n");
     return( 0 );
@@ -111,10 +116,10 @@
     }
 
     /*
-     * Compute the SHA-1 hash of the input file,
+     * Compute the SHA-256 hash of the input file,
      * then calculate the signature of the hash.
      */
-    polarssl_printf( "\n  . Generating the SHA-1 signature" );
+    polarssl_printf( "\n  . Generating the SHA-256 signature" );
     fflush( stdout );
 
     if( ( ret = sha1_file( argv[2], hash ) ) != 0 )
@@ -123,7 +128,7 @@
         goto exit;
     }
 
-    if( ( ret = pk_sign( &pk, POLARSSL_MD_SHA1, hash, 0, buf, &olen,
+    if( ( ret = pk_sign( &pk, POLARSSL_MD_SHA256, hash, 0, buf, &olen,
                          ctr_drbg_random, &ctr_drbg ) ) != 0 )
     {
         polarssl_printf( " failed\n  ! pk_sign returned -0x%04x\n", -ret );
@@ -133,7 +138,7 @@
     /*
      * Write the signature into <filename>-sig.txt
      */
-    snprintf( filename, sizeof(filename), "%s.sig", argv[2] );
+    polarssl_snprintf( filename, sizeof(filename), "%s.sig", argv[2] );
 
     if( ( f = fopen( filename, "wb+" ) ) == NULL )
     {
@@ -170,5 +175,5 @@
     return( ret );
 }
 #endif /* POLARSSL_BIGNUM_C && POLARSSL_ENTROPY_C &&
-          POLARSSL_SHA1_C && POLARSSL_PK_PARSE_C && POLARSSL_FS_IO &&
+          POLARSSL_SHA256_C && POLARSSL_PK_PARSE_C && POLARSSL_FS_IO &&
           POLARSSL_CTR_DRBG_C */
diff --git a/programs/pkey/pk_verify.c b/programs/pkey/pk_verify.c
index 0ce45f6..923afc1 100644
--- a/programs/pkey/pk_verify.c
+++ b/programs/pkey/pk_verify.c
@@ -29,31 +29,35 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #define polarssl_printf     printf
+#define polarssl_snprintf   snprintf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && \
+    defined(POLARSSL_SHA256_C) && defined(POLARSSL_PK_PARSE_C) && \
+    defined(POLARSSL_FS_IO)
 #include "polarssl/error.h"
 #include "polarssl/md.h"
 #include "polarssl/pk.h"
 #include "polarssl/sha1.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 #if defined _MSC_VER && !defined snprintf
 #define snprintf _snprintf
 #endif
 
 #if !defined(POLARSSL_BIGNUM_C) ||                                  \
-    !defined(POLARSSL_SHA1_C) || !defined(POLARSSL_PK_PARSE_C) ||   \
+    !defined(POLARSSL_SHA256_C) || !defined(POLARSSL_PK_PARSE_C) ||   \
     !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or "
-           "POLARSSL_SHA1_C and/or POLARSSL_PK_PARSE_C and/or "
+           "POLARSSL_SHA256_C and/or POLARSSL_PK_PARSE_C and/or "
            "POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
@@ -94,7 +98,7 @@
      * Extract the signature from the text file
      */
     ret = 1;
-    snprintf( filename, sizeof(filename), "%s.sig", argv[2] );
+    polarssl_snprintf( filename, sizeof(filename), "%s.sig", argv[2] );
 
     if( ( f = fopen( filename, "rb" ) ) == NULL )
     {
@@ -108,10 +112,10 @@
     fclose( f );
 
     /*
-     * Compute the SHA-1 hash of the input file and compare
+     * Compute the SHA-256 hash of the input file and compare
      * it with the hash decrypted from the signature.
      */
-    polarssl_printf( "\n  . Verifying the SHA-1 signature" );
+    polarssl_printf( "\n  . Verifying the SHA-256 signature" );
     fflush( stdout );
 
     if( ( ret = sha1_file( argv[2], hash ) ) != 0 )
@@ -120,14 +124,14 @@
         goto exit;
     }
 
-    if( ( ret = pk_verify( &pk, POLARSSL_MD_SHA1, hash, 0,
+    if( ( ret = pk_verify( &pk, POLARSSL_MD_SHA256, hash, 0,
                            buf, i ) ) != 0 )
     {
         polarssl_printf( " failed\n  ! pk_verify returned -0x%04x\n", -ret );
         goto exit;
     }
 
-    polarssl_printf( "\n  . OK (the decrypted SHA-1 hash matches)\n\n" );
+    polarssl_printf( "\n  . OK (the decrypted SHA-256 hash matches)\n\n" );
 
     ret = 0;
 
@@ -146,5 +150,5 @@
 
     return( ret );
 }
-#endif /* POLARSSL_BIGNUM_C && POLARSSL_SHA1_C &&
+#endif /* POLARSSL_BIGNUM_C && POLARSSL_SHA256_C &&
           POLARSSL_PK_PARSE_C && POLARSSL_FS_IO */
diff --git a/programs/pkey/rsa_decrypt.c b/programs/pkey/rsa_decrypt.c
index 8df5f00..368089f 100644
--- a/programs/pkey/rsa_decrypt.c
+++ b/programs/pkey/rsa_decrypt.c
@@ -29,24 +29,26 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_FS_IO) && defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/rsa.h"
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) ||  \
     !defined(POLARSSL_FS_IO) || !defined(POLARSSL_ENTROPY_C) || \
     !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or "
            "POLARSSL_FS_IO and/or POLARSSL_ENTROPY_C and/or "
            "POLARSSL_CTR_DRBG_C not defined.\n");
diff --git a/programs/pkey/rsa_encrypt.c b/programs/pkey/rsa_encrypt.c
index 58817e3..e73ad2f 100644
--- a/programs/pkey/rsa_encrypt.c
+++ b/programs/pkey/rsa_encrypt.c
@@ -29,25 +29,27 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_FS_IO) && \
+    defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/rsa.h"
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) ||  \
     !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_FS_IO) || \
     !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or "
            "POLARSSL_ENTROPY_C and/or POLARSSL_FS_IO and/or "
            "POLARSSL_CTR_DRBG_C not defined.\n");
@@ -103,7 +105,7 @@
     }
 
     rsa_init( &rsa, RSA_PKCS_V15, 0 );
-    
+
     if( ( ret = mpi_read_file( &rsa.N, 16, f ) ) != 0 ||
         ( ret = mpi_read_file( &rsa.E, 16, f ) ) != 0 )
     {
diff --git a/programs/pkey/rsa_genkey.c b/programs/pkey/rsa_genkey.c
index ff31598..0314d39 100644
--- a/programs/pkey/rsa_genkey.c
+++ b/programs/pkey/rsa_genkey.c
@@ -29,35 +29,38 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_RSA_C) && defined(POLARSSL_GENPRIME) && \
+    defined(POLARSSL_FS_IO) && defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 #include "polarssl/bignum.h"
 #include "polarssl/x509.h"
 #include "polarssl/rsa.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 #define KEY_SIZE 1024
 #define EXPONENT 65537
 
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||   \
     !defined(POLARSSL_RSA_C) || !defined(POLARSSL_GENPRIME) ||      \
     !defined(POLARSSL_FS_IO) || !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
            "POLARSSL_RSA_C and/or POLARSSL_GENPRIME and/or "
            "POLARSSL_FS_IO and/or POLARSSL_CTR_DRBG_C not defined.\n");
     return( 0 );
 }
 #else
-int main( int argc, char *argv[] )
+int main( void )
 {
     int ret;
     rsa_context rsa;
@@ -67,9 +70,6 @@
     FILE *fpriv = NULL;
     const char *pers = "rsa_genkey";
 
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf( "\n  . Seeding the random number generator..." );
     fflush( stdout );
 
@@ -86,7 +86,7 @@
     fflush( stdout );
 
     rsa_init( &rsa, RSA_PKCS_V15, 0 );
-    
+
     if( ( ret = rsa_gen_key( &rsa, ctr_drbg_random, &ctr_drbg, KEY_SIZE,
                              EXPONENT ) ) != 0 )
     {
diff --git a/programs/pkey/rsa_sign.c b/programs/pkey/rsa_sign.c
index e4f4970..277034d 100644
--- a/programs/pkey/rsa_sign.c
+++ b/programs/pkey/rsa_sign.c
@@ -1,5 +1,5 @@
 /*
- *  RSA/SHA-1 signature creation program
+ *  RSA/SHA-256 signature creation program
  *
  *  Copyright (C) 2006-2011, ARM Limited, All Rights Reserved
  *
@@ -29,25 +29,26 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_SHA256_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/rsa.h"
 #include "polarssl/sha1.h"
 
-#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) ||  \
-    !defined(POLARSSL_SHA1_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#include <stdio.h>
+#include <string.h>
+#endif
 
+#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) ||  \
+    !defined(POLARSSL_SHA256_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or "
-           "POLARSSL_SHA1_C and/or POLARSSL_FS_IO not defined.\n");
+           "POLARSSL_SHA256_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
 #else
@@ -85,7 +86,7 @@
     }
 
     rsa_init( &rsa, RSA_PKCS_V15, 0 );
-    
+
     if( ( ret = mpi_read_file( &rsa.N , 16, f ) ) != 0 ||
         ( ret = mpi_read_file( &rsa.E , 16, f ) ) != 0 ||
         ( ret = mpi_read_file( &rsa.D , 16, f ) ) != 0 ||
@@ -112,10 +113,10 @@
     }
 
     /*
-     * Compute the SHA-1 hash of the input file,
+     * Compute the SHA-256 hash of the input file,
      * then calculate the RSA signature of the hash.
      */
-    polarssl_printf( "\n  . Generating the RSA/SHA-1 signature" );
+    polarssl_printf( "\n  . Generating the RSA/SHA-256 signature" );
     fflush( stdout );
 
     if( ( ret = sha1_file( argv[1], hash ) ) != 0 )
@@ -124,7 +125,7 @@
         goto exit;
     }
 
-    if( ( ret = rsa_pkcs1_sign( &rsa, NULL, NULL, RSA_PRIVATE, POLARSSL_MD_SHA1,
+    if( ( ret = rsa_pkcs1_sign( &rsa, NULL, NULL, RSA_PRIVATE, POLARSSL_MD_SHA256,
                                 20, hash, buf ) ) != 0 )
     {
         polarssl_printf( " failed\n  ! rsa_pkcs1_sign returned -0x%0x\n\n", -ret );
@@ -160,5 +161,5 @@
 
     return( ret );
 }
-#endif /* POLARSSL_BIGNUM_C && POLARSSL_RSA_C && POLARSSL_SHA1_C &&
+#endif /* POLARSSL_BIGNUM_C && POLARSSL_RSA_C && POLARSSL_SHA256_C &&
           POLARSSL_FS_IO */
diff --git a/programs/pkey/rsa_sign_pss.c b/programs/pkey/rsa_sign_pss.c
index e022db2..ad4d0b5 100644
--- a/programs/pkey/rsa_sign_pss.c
+++ b/programs/pkey/rsa_sign_pss.c
@@ -1,5 +1,5 @@
 /*
- *  RSASSA-PSS/SHA-1 signature creation program
+ *  RSASSA-PSS/SHA-256 signature creation program
  *
  *  Copyright (C) 2006-2011, ARM Limited, All Rights Reserved
  *
@@ -29,12 +29,16 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #define polarssl_printf     printf
+#define polarssl_snprintf   snprintf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_RSA_C) && defined(POLARSSL_SHA256_C) && \
+    defined(POLARSSL_PK_PARSE_C) && defined(POLARSSL_FS_IO) && \
+    defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 #include "polarssl/md.h"
@@ -42,21 +46,22 @@
 #include "polarssl/sha1.h"
 #include "polarssl/x509.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 #if defined _MSC_VER && !defined snprintf
 #define snprintf _snprintf
 #endif
 
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||  \
-    !defined(POLARSSL_RSA_C) || !defined(POLARSSL_SHA1_C) ||        \
+    !defined(POLARSSL_RSA_C) || !defined(POLARSSL_SHA256_C) ||        \
     !defined(POLARSSL_PK_PARSE_C) || !defined(POLARSSL_FS_IO) ||    \
     !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
-           "POLARSSL_RSA_C and/or POLARSSL_SHA1_C and/or "
+           "POLARSSL_RSA_C and/or POLARSSL_SHA256_C and/or "
            "POLARSSL_PK_PARSE_C and/or POLARSSL_FS_IO and/or "
            "POLARSSL_CTR_DRBG_C not defined.\n");
     return( 0 );
@@ -118,13 +123,13 @@
         goto exit;
     }
 
-    rsa_set_padding( pk_rsa( pk ), RSA_PKCS_V21, POLARSSL_MD_SHA1 );
+    rsa_set_padding( pk_rsa( pk ), RSA_PKCS_V21, POLARSSL_MD_SHA256 );
 
     /*
-     * Compute the SHA-1 hash of the input file,
+     * Compute the SHA-256 hash of the input file,
      * then calculate the RSA signature of the hash.
      */
-    polarssl_printf( "\n  . Generating the RSA/SHA-1 signature" );
+    polarssl_printf( "\n  . Generating the RSA/SHA-256 signature" );
     fflush( stdout );
 
     if( ( ret = sha1_file( argv[2], hash ) ) != 0 )
@@ -133,7 +138,7 @@
         goto exit;
     }
 
-    if( ( ret = pk_sign( &pk, POLARSSL_MD_SHA1, hash, 0, buf, &olen,
+    if( ( ret = pk_sign( &pk, POLARSSL_MD_SHA256, hash, 0, buf, &olen,
                          ctr_drbg_random, &ctr_drbg ) ) != 0 )
     {
         polarssl_printf( " failed\n  ! pk_sign returned %d\n\n", ret );
@@ -143,7 +148,7 @@
     /*
      * Write the signature into <filename>-sig.txt
      */
-    snprintf( filename, 512, "%s.sig", argv[2] );
+    polarssl_snprintf( filename, 512, "%s.sig", argv[2] );
 
     if( ( f = fopen( filename, "wb+" ) ) == NULL )
     {
@@ -175,5 +180,5 @@
     return( ret );
 }
 #endif /* POLARSSL_BIGNUM_C && POLARSSL_ENTROPY_C && POLARSSL_RSA_C &&
-          POLARSSL_SHA1_C && POLARSSL_PK_PARSE_C && POLARSSL_FS_IO &&
+          POLARSSL_SHA256_C && POLARSSL_PK_PARSE_C && POLARSSL_FS_IO &&
           POLARSSL_CTR_DRBG_C */
diff --git a/programs/pkey/rsa_verify.c b/programs/pkey/rsa_verify.c
index 6ff16e4..88d4d04 100644
--- a/programs/pkey/rsa_verify.c
+++ b/programs/pkey/rsa_verify.c
@@ -1,5 +1,5 @@
 /*
- *  RSA/SHA-1 signature verification program
+ *  RSA/SHA-256 signature verification program
  *
  *  Copyright (C) 2006-2011, ARM Limited, All Rights Reserved
  *
@@ -29,24 +29,25 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_SHA256_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/rsa.h"
 #include "polarssl/sha1.h"
 
-#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) ||  \
-    !defined(POLARSSL_SHA1_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#include <stdio.h>
+#include <string.h>
+#endif
 
+#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) ||  \
+    !defined(POLARSSL_SHA256_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or "
-           "POLARSSL_SHA1_C and/or POLARSSL_FS_IO not defined.\n");
+           "POLARSSL_SHA256_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
 #else
@@ -122,10 +123,10 @@
     }
 
     /*
-     * Compute the SHA-1 hash of the input file and compare
+     * Compute the SHA-256 hash of the input file and compare
      * it with the hash decrypted from the RSA signature.
      */
-    polarssl_printf( "\n  . Verifying the RSA/SHA-1 signature" );
+    polarssl_printf( "\n  . Verifying the RSA/SHA-256 signature" );
     fflush( stdout );
 
     if( ( ret = sha1_file( argv[1], hash ) ) != 0 )
@@ -135,13 +136,13 @@
     }
 
     if( ( ret = rsa_pkcs1_verify( &rsa, NULL, NULL, RSA_PUBLIC,
-                                  POLARSSL_MD_SHA1, 20, hash, buf ) ) != 0 )
+                                  POLARSSL_MD_SHA256, 20, hash, buf ) ) != 0 )
     {
         polarssl_printf( " failed\n  ! rsa_pkcs1_verify returned -0x%0x\n\n", -ret );
         goto exit;
     }
 
-    polarssl_printf( "\n  . OK (the decrypted SHA-1 hash matches)\n\n" );
+    polarssl_printf( "\n  . OK (the decrypted SHA-256 hash matches)\n\n" );
 
     ret = 0;
 
@@ -154,5 +155,5 @@
 
     return( ret );
 }
-#endif /* POLARSSL_BIGNUM_C && POLARSSL_RSA_C && POLARSSL_SHA1_C &&
+#endif /* POLARSSL_BIGNUM_C && POLARSSL_RSA_C && POLARSSL_SHA256_C &&
           POLARSSL_FS_IO */
diff --git a/programs/pkey/rsa_verify_pss.c b/programs/pkey/rsa_verify_pss.c
index 3ffdfbe..2b1570a 100644
--- a/programs/pkey/rsa_verify_pss.c
+++ b/programs/pkey/rsa_verify_pss.c
@@ -1,5 +1,5 @@
 /*
- *  RSASSA-PSS/SHA-1 signature verification program
+ *  RSASSA-PSS/SHA-256 signature verification program
  *
  *  Copyright (C) 2006-2011, ARM Limited, All Rights Reserved
  *
@@ -29,32 +29,36 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #define polarssl_printf     printf
+#define polarssl_snprintf   snprintf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_SHA256_C) && defined(POLARSSL_PK_PARSE_C) && \
+    defined(POLARSSL_FS_IO)
 #include "polarssl/md.h"
 #include "polarssl/pem.h"
 #include "polarssl/pk.h"
 #include "polarssl/sha1.h"
 #include "polarssl/x509.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
 #if defined _MSC_VER && !defined snprintf
 #define snprintf _snprintf
 #endif
 
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) ||      \
-    !defined(POLARSSL_SHA1_C) || !defined(POLARSSL_PK_PARSE_C) ||   \
+    !defined(POLARSSL_SHA256_C) || !defined(POLARSSL_PK_PARSE_C) ||   \
     !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or "
-           "POLARSSL_SHA1_C and/or POLARSSL_PK_PARSE_C and/or "
+           "POLARSSL_SHA256_C and/or POLARSSL_PK_PARSE_C and/or "
            "POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
@@ -99,13 +103,13 @@
         goto exit;
     }
 
-    rsa_set_padding( pk_rsa( pk ), RSA_PKCS_V21, POLARSSL_MD_SHA1 );
+    rsa_set_padding( pk_rsa( pk ), RSA_PKCS_V21, POLARSSL_MD_SHA256 );
 
     /*
      * Extract the RSA signature from the text file
      */
     ret = 1;
-    snprintf( filename, 512, "%s.sig", argv[2] );
+    polarssl_snprintf( filename, 512, "%s.sig", argv[2] );
 
     if( ( f = fopen( filename, "rb" ) ) == NULL )
     {
@@ -119,10 +123,10 @@
     fclose( f );
 
     /*
-     * Compute the SHA-1 hash of the input file and compare
+     * Compute the SHA-256 hash of the input file and compare
      * it with the hash decrypted from the RSA signature.
      */
-    polarssl_printf( "\n  . Verifying the RSA/SHA-1 signature" );
+    polarssl_printf( "\n  . Verifying the RSA/SHA-256 signature" );
     fflush( stdout );
 
     if( ( ret = sha1_file( argv[2], hash ) ) != 0 )
@@ -131,14 +135,14 @@
         goto exit;
     }
 
-    if( ( ret = pk_verify( &pk, POLARSSL_MD_SHA1, hash, 0,
+    if( ( ret = pk_verify( &pk, POLARSSL_MD_SHA256, hash, 0,
                            buf, i ) ) != 0 )
     {
         polarssl_printf( " failed\n  ! pk_verify returned %d\n\n", ret );
         goto exit;
     }
 
-    polarssl_printf( "\n  . OK (the decrypted SHA-1 hash matches)\n\n" );
+    polarssl_printf( "\n  . OK (the decrypted SHA-256 hash matches)\n\n" );
 
     ret = 0;
 
@@ -152,5 +156,5 @@
 
     return( ret );
 }
-#endif /* POLARSSL_BIGNUM_C && POLARSSL_RSA_C && POLARSSL_SHA1_C &&
+#endif /* POLARSSL_BIGNUM_C && POLARSSL_RSA_C && POLARSSL_SHA256_C &&
           POLARSSL_PK_PARSE_C && POLARSSL_FS_IO */
diff --git a/programs/random/gen_entropy.c b/programs/random/gen_entropy.c
index 0ff443f..54baa18 100644
--- a/programs/random/gen_entropy.c
+++ b/programs/random/gen_entropy.c
@@ -29,21 +29,21 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
+#if defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/entropy.h"
 
 #include <stdio.h>
+#endif
 
-#if !defined(POLARSSL_ENTROPY_C)
-int main( int argc, char *argv[] )
+#if !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_FS_IO)
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf("POLARSSL_ENTROPY_C not defined.\n");
+    polarssl_printf("POLARSSL_ENTROPY_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
 #else
diff --git a/programs/random/gen_random_ctr_drbg.c b/programs/random/gen_random_ctr_drbg.c
index c21e094..4c2286d 100644
--- a/programs/random/gen_random_ctr_drbg.c
+++ b/programs/random/gen_random_ctr_drbg.c
@@ -29,22 +29,24 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
+#if defined(POLARSSL_CTR_DRBG_C) && defined(POLARSSL_ENTROPY_C) && \
+ defined(POLARSSL_FS_IO)
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 
 #include <stdio.h>
+#endif
 
-#if !defined(POLARSSL_CTR_DRBG_C) || !defined(POLARSSL_ENTROPY_C)
-int main( int argc, char *argv[] )
+#if !defined(POLARSSL_CTR_DRBG_C) || !defined(POLARSSL_ENTROPY_C) || \
+ !defined(POLARSSL_FS_IO)
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf("POLARSSL_CTR_DRBG_C or POLARSSL_ENTROPY_C not defined.\n");
+    polarssl_printf("POLARSSL_CTR_DRBG_C and/or POLARSSL_ENTROPY_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
 #else
diff --git a/programs/random/gen_random_havege.c b/programs/random/gen_random_havege.c
index 5336fc4..0f5800c 100644
--- a/programs/random/gen_random_havege.c
+++ b/programs/random/gen_random_havege.c
@@ -29,21 +29,21 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
+#if defined(POLARSSL_HAVEGE_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/havege.h"
 
-#include <time.h>
 #include <stdio.h>
+#include <time.h>
+#endif
 
-#if !defined(POLARSSL_HAVEGE_C)
-int main( int argc, char *argv[] )
+#if !defined(POLARSSL_HAVEGE_C) || !defined(POLARSSL_FS_IO)
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_HAVEGE_C not defined.\n");
     return( 0 );
 }
diff --git a/programs/ssl/CMakeLists.txt b/programs/ssl/CMakeLists.txt
index a608687..a2f5dc2 100644
--- a/programs/ssl/CMakeLists.txt
+++ b/programs/ssl/CMakeLists.txt
@@ -13,6 +13,7 @@
      ssl_server
      ssl_fork_server
      ssl_mail_client
+     mini_client
 )
 
 if(USE_PKCS11_HELPER_LIBRARY)
@@ -47,6 +48,9 @@
 add_executable(ssl_mail_client ssl_mail_client.c)
 target_link_libraries(ssl_mail_client ${libs})
 
+add_executable(mini_client mini_client.c)
+target_link_libraries(mini_client ${libs})
+
 if(THREADS_FOUND)
     add_executable(ssl_pthread_server ssl_pthread_server.c)
     target_link_libraries(ssl_pthread_server ${libs} ${CMAKE_THREAD_LIBS_INIT})
diff --git a/programs/ssl/mini_client.c b/programs/ssl/mini_client.c
new file mode 100644
index 0000000..a06d345
--- /dev/null
+++ b/programs/ssl/mini_client.c
@@ -0,0 +1,270 @@
+/*
+ *  Minimal SSL client, used for memory measurements.
+ *  (meant to be used with config-suite-b.h or config-ccm-psk-tls1_2.h)
+ *
+ *  Copyright (C) 2014, ARM Limited, All Rights Reserved
+ *
+ *  This file is part of mbed TLS (https://polarssl.org)
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, write to the Free Software Foundation, Inc.,
+ *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#if !defined(POLARSSL_CONFIG_FILE)
+#include "polarssl/config.h"
+#else
+#include POLARSSL_CONFIG_FILE
+#endif
+
+/*
+ * We're creating and connecting the socket "manually" rather than using the
+ * NET module, in order to avoid the overhead of getaddrinfo() which tends to
+ * dominate memory usage in small configurations. For the sake of simplicity,
+ * only a Unix version is implemented.
+ */
+#if defined(unix) || defined(__unix__) || defined(__unix)
+#define UNIX
+#endif
+
+#if !defined(POLARSSL_CTR_DRBG_C) || !defined(POLARSSL_ENTROPY_C) || \
+    !defined(POLARSSL_NET_C) || !defined(POLARSSL_SSL_CLI_C) || \
+    !defined(UNIX)
+#if defined(POLARSSL_PLATFORM_C)
+#include "polarssl/platform.h"
+#else
+#include <stdio.h>
+#define polarssl_printf printf
+#endif
+int main( void )
+{
+    polarssl_printf( "POLARSSL_CTR_DRBG_C and/or POLARSSL_ENTROPY_C and/or "
+            "POLARSSL_NET_C and/or POLARSSL_SSL_CLI_C and/or UNIX "
+            "not defined.\n");
+    return( 0 );
+}
+#else
+
+#include <string.h>
+
+#include "polarssl/net.h"
+#include "polarssl/ssl.h"
+#include "polarssl/entropy.h"
+#include "polarssl/ctr_drbg.h"
+
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+/*
+ * Hardcoded values for server host and port
+ */
+#define PORT_BE 0x1151      /* 4433 */
+#define PORT_LE 0x5111
+#define ADDR_BE 0x7f000001  /* 127.0.0.1 */
+#define ADDR_LE 0x0100007f
+#define HOSTNAME "localhost" /* for cert verification if enabled */
+
+#define GET_REQUEST "GET / HTTP/1.0\r\n\r\n"
+
+const char *pers = "mini_client";
+
+#if defined(POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED)
+const unsigned char psk[] = {
+    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
+};
+const char psk_id[] = "Client_identity";
+#endif
+
+#if defined(POLARSSL_X509_CRT_PARSE_C)
+/* This is tests/data_files/test-ca2.crt, a CA using EC secp384r1 */
+const unsigned char ca_cert[] = {
+    0x30, 0x82, 0x02, 0x52, 0x30, 0x82, 0x01, 0xd7, 0xa0, 0x03, 0x02, 0x01,
+    0x02, 0x02, 0x09, 0x00, 0xc1, 0x43, 0xe2, 0x7e, 0x62, 0x43, 0xcc, 0xe8,
+    0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02,
+    0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+    0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a,
+    0x13, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x1c,
+    0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x13, 0x50, 0x6f, 0x6c,
+    0x61, 0x72, 0x73, 0x73, 0x6c, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x45,
+    0x43, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x33, 0x30, 0x39,
+    0x32, 0x34, 0x31, 0x35, 0x34, 0x39, 0x34, 0x38, 0x5a, 0x17, 0x0d, 0x32,
+    0x33, 0x30, 0x39, 0x32, 0x32, 0x31, 0x35, 0x34, 0x39, 0x34, 0x38, 0x5a,
+    0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+    0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a,
+    0x13, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x1c,
+    0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x13, 0x50, 0x6f, 0x6c,
+    0x61, 0x72, 0x73, 0x73, 0x6c, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x45,
+    0x43, 0x20, 0x43, 0x41, 0x30, 0x76, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86,
+    0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22,
+    0x03, 0x62, 0x00, 0x04, 0xc3, 0xda, 0x2b, 0x34, 0x41, 0x37, 0x58, 0x2f,
+    0x87, 0x56, 0xfe, 0xfc, 0x89, 0xba, 0x29, 0x43, 0x4b, 0x4e, 0xe0, 0x6e,
+    0xc3, 0x0e, 0x57, 0x53, 0x33, 0x39, 0x58, 0xd4, 0x52, 0xb4, 0x91, 0x95,
+    0x39, 0x0b, 0x23, 0xdf, 0x5f, 0x17, 0x24, 0x62, 0x48, 0xfc, 0x1a, 0x95,
+    0x29, 0xce, 0x2c, 0x2d, 0x87, 0xc2, 0x88, 0x52, 0x80, 0xaf, 0xd6, 0x6a,
+    0xab, 0x21, 0xdd, 0xb8, 0xd3, 0x1c, 0x6e, 0x58, 0xb8, 0xca, 0xe8, 0xb2,
+    0x69, 0x8e, 0xf3, 0x41, 0xad, 0x29, 0xc3, 0xb4, 0x5f, 0x75, 0xa7, 0x47,
+    0x6f, 0xd5, 0x19, 0x29, 0x55, 0x69, 0x9a, 0x53, 0x3b, 0x20, 0xb4, 0x66,
+    0x16, 0x60, 0x33, 0x1e, 0xa3, 0x81, 0xa0, 0x30, 0x81, 0x9d, 0x30, 0x1d,
+    0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x9d, 0x6d, 0x20,
+    0x24, 0x49, 0x01, 0x3f, 0x2b, 0xcb, 0x78, 0xb5, 0x19, 0xbc, 0x7e, 0x24,
+    0xc9, 0xdb, 0xfb, 0x36, 0x7c, 0x30, 0x6e, 0x06, 0x03, 0x55, 0x1d, 0x23,
+    0x04, 0x67, 0x30, 0x65, 0x80, 0x14, 0x9d, 0x6d, 0x20, 0x24, 0x49, 0x01,
+    0x3f, 0x2b, 0xcb, 0x78, 0xb5, 0x19, 0xbc, 0x7e, 0x24, 0xc9, 0xdb, 0xfb,
+    0x36, 0x7c, 0xa1, 0x42, 0xa4, 0x40, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09,
+    0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30,
+    0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x08, 0x50, 0x6f, 0x6c, 0x61,
+    0x72, 0x53, 0x53, 0x4c, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04,
+    0x03, 0x13, 0x13, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x73, 0x73, 0x6c, 0x20,
+    0x54, 0x65, 0x73, 0x74, 0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x82, 0x09,
+    0x00, 0xc1, 0x43, 0xe2, 0x7e, 0x62, 0x43, 0xcc, 0xe8, 0x30, 0x0c, 0x06,
+    0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30,
+    0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03,
+    0x69, 0x00, 0x30, 0x66, 0x02, 0x31, 0x00, 0xc3, 0xb4, 0x62, 0x73, 0x56,
+    0x28, 0x95, 0x00, 0x7d, 0x78, 0x12, 0x26, 0xd2, 0x71, 0x7b, 0x19, 0xf8,
+    0x8a, 0x98, 0x3e, 0x92, 0xfe, 0x33, 0x9e, 0xe4, 0x79, 0xd2, 0xfe, 0x7a,
+    0xb7, 0x87, 0x74, 0x3c, 0x2b, 0xb8, 0xd7, 0x69, 0x94, 0x0b, 0xa3, 0x67,
+    0x77, 0xb8, 0xb3, 0xbe, 0xd1, 0x36, 0x32, 0x02, 0x31, 0x00, 0xfd, 0x67,
+    0x9c, 0x94, 0x23, 0x67, 0xc0, 0x56, 0xba, 0x4b, 0x33, 0x15, 0x00, 0xc6,
+    0xe3, 0xcc, 0x31, 0x08, 0x2c, 0x9c, 0x8b, 0xda, 0xa9, 0x75, 0x23, 0x2f,
+    0xb8, 0x28, 0xe7, 0xf2, 0x9c, 0x14, 0x3a, 0x40, 0x01, 0x5c, 0xaf, 0x0c,
+    0xb2, 0xcf, 0x74, 0x7f, 0x30, 0x9f, 0x08, 0x43, 0xad, 0x20,
+};
+#endif /* POLARSSL_X509_CRT_PARSE_C */
+
+enum exit_codes
+{
+    exit_ok = 0,
+    ctr_drbg_init_failed,
+    ssl_init_failed,
+    socket_failed,
+    connect_failed,
+    x509_crt_parse_failed,
+    ssl_handshake_failed,
+    ssl_write_failed,
+};
+
+int main( void )
+{
+    int ret = exit_ok;
+    int server_fd = -1;
+    struct sockaddr_in addr;
+#if defined(POLARSSL_X509_CRT_PARSE_C)
+    x509_crt ca;
+#endif
+
+    entropy_context entropy;
+    ctr_drbg_context ctr_drbg;
+    ssl_context ssl;
+
+    /*
+     * 0. Initialize and setup stuff
+     */
+    memset( &ssl, 0, sizeof( ssl_context ) );
+#if defined(POLARSSL_X509_CRT_PARSE_C)
+    x509_crt_init( &ca );
+#endif
+
+    entropy_init( &entropy );
+    if( ctr_drbg_init( &ctr_drbg, entropy_func, &entropy,
+                       (const unsigned char *) pers, strlen( pers ) ) != 0 )
+    {
+        ret = ssl_init_failed;
+        goto exit;
+    }
+
+    if( ssl_init( &ssl ) != 0 )
+    {
+        ret = ssl_init_failed;
+        goto exit;
+    }
+
+    ssl_set_endpoint( &ssl, SSL_IS_CLIENT );
+
+    ssl_set_rng( &ssl, ctr_drbg_random, &ctr_drbg );
+
+#if defined(POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED)
+    ssl_set_psk( &ssl, psk, sizeof( psk ),
+                (const unsigned char *) psk_id, sizeof( psk_id ) - 1 );
+#endif
+
+#if defined(POLARSSL_X509_CRT_PARSE_C)
+    if( x509_crt_parse_der( &ca, ca_cert, sizeof( ca_cert ) ) != 0 )
+    {
+        ret = x509_crt_parse_failed;
+        goto exit;
+    }
+
+    ssl_set_ca_chain( &ssl, &ca, NULL, HOSTNAME );
+    ssl_set_authmode( &ssl, SSL_VERIFY_REQUIRED );
+#endif
+
+    /*
+     * 1. Start the connection
+     */
+    memset( &addr, 0, sizeof( addr ) );
+    addr.sin_family = AF_INET;
+
+    ret = 1; /* for endianness detection */
+    addr.sin_port = *((char *) &ret) == ret ? PORT_LE : PORT_BE;
+    addr.sin_addr.s_addr = *((char *) &ret) == ret ? ADDR_LE : ADDR_BE;
+    ret = 0;
+
+    if( ( server_fd = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
+    {
+        ret = socket_failed;
+        goto exit;
+    }
+
+    if( connect( server_fd,
+                (const struct sockaddr *) &addr, sizeof( addr ) ) < 0 )
+    {
+        ret = connect_failed;
+        goto exit;
+    }
+
+    ssl_set_bio( &ssl, net_recv, &server_fd, net_send, &server_fd );
+
+    if( ssl_handshake( &ssl ) != 0 )
+    {
+        ret = ssl_handshake_failed;
+        goto exit;
+    }
+
+    /*
+     * 2. Write the GET request and close the connection
+     */
+    if( ssl_write( &ssl, (const unsigned char *) GET_REQUEST,
+                         sizeof( GET_REQUEST ) - 1 ) <= 0 )
+    {
+        ret = ssl_write_failed;
+        goto exit;
+    }
+
+    ssl_close_notify( &ssl );
+
+exit:
+    if( server_fd != -1 )
+        net_close( server_fd );
+
+    ssl_free( &ssl );
+    ctr_drbg_free( &ctr_drbg );
+    entropy_free( &entropy );
+#if defined(POLARSSL_X509_CRT_PARSE_C)
+    x509_crt_free( &ca );
+#endif
+
+    return( ret );
+}
+#endif
diff --git a/programs/ssl/ssl_client1.c b/programs/ssl/ssl_client1.c
index d0bc7f5..c5ed4c3 100644
--- a/programs/ssl/ssl_client1.c
+++ b/programs/ssl/ssl_client1.c
@@ -29,13 +29,15 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_SSL_TLS_C) && defined(POLARSSL_SSL_CLI_C) && \
+    defined(POLARSSL_NET_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_CTR_DRBG_C) && defined(POLARSSL_X509_CRT_PARSE_C)
 #include "polarssl/net.h"
 #include "polarssl/debug.h"
 #include "polarssl/ssl.h"
@@ -44,15 +46,22 @@
 #include "polarssl/error.h"
 #include "polarssl/certs.h"
 
+#include <stdio.h>
+#include <string.h>
+#endif
+
+#define SERVER_PORT 4433
+#define SERVER_NAME "localhost"
+#define GET_REQUEST "GET / HTTP/1.0\r\n\r\n"
+
+#define DEBUG_LEVEL 1
+
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||  \
     !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_CLI_C) || \
     !defined(POLARSSL_NET_C) || !defined(POLARSSL_RSA_C) ||         \
     !defined(POLARSSL_CTR_DRBG_C) || !defined(POLARSSL_X509_CRT_PARSE_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
            "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_CLI_C and/or "
            "POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
@@ -61,13 +70,6 @@
     return( 0 );
 }
 #else
-
-#define SERVER_PORT 4433
-#define SERVER_NAME "localhost"
-#define GET_REQUEST "GET / HTTP/1.0\r\n\r\n"
-
-#define DEBUG_LEVEL 1
-
 static void my_debug( void *ctx, int level, const char *str )
 {
     ((void) level);
@@ -76,7 +78,7 @@
     fflush(  (FILE *) ctx  );
 }
 
-int main( int argc, char *argv[] )
+int main( void )
 {
     int ret, len, server_fd = -1;
     unsigned char buf[1024];
@@ -87,9 +89,6 @@
     ssl_context ssl;
     x509_crt cacert;
 
-    ((void) argc);
-    ((void) argv);
-
 #if defined(POLARSSL_DEBUG_C)
     debug_set_threshold( DEBUG_LEVEL );
 #endif
diff --git a/programs/ssl/ssl_client2.c b/programs/ssl/ssl_client2.c
index c84980c..2f40fec 100644
--- a/programs/ssl/ssl_client2.c
+++ b/programs/ssl/ssl_client2.c
@@ -29,30 +29,16 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
+#define polarssl_snprintf   snprintf
 #endif
 
-#if !defined(POLARSSL_ENTROPY_C) ||  \
-    !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_CLI_C) || \
-    !defined(POLARSSL_NET_C) || !defined(POLARSSL_CTR_DRBG_C)
-#include <stdio.h>
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf("POLARSSL_ENTROPY_C and/or "
-           "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_CLI_C and/or "
-           "POLARSSL_NET_C and/or POLARSSL_CTR_DRBG_C not defined.\n");
-    return( 0 );
-}
-#else
-
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_FS_IO) && \
+    defined(POLARSSL_SSL_TLS_C) && defined(POLARSSL_SSL_CLI_C) && \
+    defined(POLARSSL_NET_C) && defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/net.h"
 #include "polarssl/ssl.h"
 #include "polarssl/entropy.h"
@@ -62,6 +48,11 @@
 #include "polarssl/error.h"
 #include "polarssl/debug.h"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
 #if defined(POLARSSL_TIMING_C)
 #include "polarssl/timing.h"
 #endif
@@ -113,138 +104,6 @@
 #define GET_REQUEST "GET %s HTTP/1.0\r\nExtra-header: "
 #define GET_REQUEST_END "\r\n\r\n"
 
-/*
- * global options
- */
-struct options
-{
-    const char *server_name;    /* hostname of the server (client only)     */
-    const char *server_addr;    /* address of the server (client only)      */
-    int server_port;            /* port on which the ssl service runs       */
-    int debug_level;            /* level of debugging                       */
-    int nbio;                   /* should I/O be blocking?                  */
-    uint32_t read_timeout;      /* timeout on ssl_read() in milliseconds    */
-    int max_resend;             /* DTLS times to resend on read timeout     */
-    const char *request_page;   /* page on server to request                */
-    int request_size;           /* pad request with header to requested size */
-    const char *ca_file;        /* the file with the CA certificate(s)      */
-    const char *ca_path;        /* the path with the CA certificate(s) reside */
-    const char *crt_file;       /* the file with the client certificate     */
-    const char *key_file;       /* the file with the client key             */
-    const char *psk;            /* the pre-shared key                       */
-    const char *psk_identity;   /* the pre-shared key identity              */
-    int force_ciphersuite[2];   /* protocol/ciphersuite to use, or all      */
-    int renegotiation;          /* enable / disable renegotiation           */
-    int allow_legacy;           /* allow legacy renegotiation               */
-    int renegotiate;            /* attempt renegotiation?                   */
-    int renego_delay;           /* delay before enforcing renegotiation     */
-    int exchanges;              /* number of data exchanges                 */
-    int min_version;            /* minimum protocol version accepted        */
-    int max_version;            /* maximum protocol version accepted        */
-    int arc4;                   /* flag for arc4 suites support             */
-    int auth_mode;              /* verify mode for connection               */
-    unsigned char mfl_code;     /* code for maximum fragment length         */
-    int trunc_hmac;             /* negotiate truncated hmac or not          */
-    int recsplit;               /* enable record splitting?                 */
-    int reconnect;              /* attempt to resume session                */
-    int reco_delay;             /* delay in seconds before resuming session */
-    int tickets;                /* enable / disable session tickets         */
-    const char *alpn_string;    /* ALPN supported protocols                 */
-    int transport;              /* TLS or DTLS?                             */
-    uint32_t hs_to_min;         /* Initial value of DTLS handshake timer    */
-    uint32_t hs_to_max;         /* Max value of DTLS handshake timer        */
-    int fallback;               /* is this a fallback connection?           */
-    int extended_ms;            /* negotiate extended master secret?        */
-    int etm;                    /* negotiate encrypt then mac?              */
-} opt;
-
-static void my_debug( void *ctx, int level, const char *str )
-{
-    ((void) level);
-
-    polarssl_fprintf( (FILE *) ctx, "%s", str );
-    fflush(  (FILE *) ctx  );
-}
-
-/*
- * Test recv/send functions that make sure each try returns
- * WANT_READ/WANT_WRITE at least once before sucesseding
- */
-static int my_recv( void *ctx, unsigned char *buf, size_t len )
-{
-    static int first_try = 1;
-    int ret;
-
-    if( first_try )
-    {
-        first_try = 0;
-        return( POLARSSL_ERR_NET_WANT_READ );
-    }
-
-    ret = net_recv( ctx, buf, len );
-    if( ret != POLARSSL_ERR_NET_WANT_READ )
-        first_try = 1; /* Next call will be a new operation */
-    return( ret );
-}
-
-static int my_send( void *ctx, const unsigned char *buf, size_t len )
-{
-    static int first_try = 1;
-    int ret;
-
-    if( first_try )
-    {
-        first_try = 0;
-        return( POLARSSL_ERR_NET_WANT_WRITE );
-    }
-
-    ret = net_send( ctx, buf, len );
-    if( ret != POLARSSL_ERR_NET_WANT_WRITE )
-        first_try = 1; /* Next call will be a new operation */
-    return( ret );
-}
-
-#if defined(POLARSSL_X509_CRT_PARSE_C)
-/*
- * Enabled if debug_level > 1 in code below
- */
-static int my_verify( void *data, x509_crt *crt, int depth, int *flags )
-{
-    char buf[1024];
-    ((void) data);
-
-    polarssl_printf( "\nVerify requested for (Depth %d):\n", depth );
-    x509_crt_info( buf, sizeof( buf ) - 1, "", crt );
-    polarssl_printf( "%s", buf );
-
-    if( ( (*flags) & BADCERT_EXPIRED ) != 0 )
-        polarssl_printf( "  ! server certificate has expired\n" );
-
-    if( ( (*flags) & BADCERT_REVOKED ) != 0 )
-        polarssl_printf( "  ! server certificate has been revoked\n" );
-
-    if( ( (*flags) & BADCERT_CN_MISMATCH ) != 0 )
-        polarssl_printf( "  ! CN mismatch\n" );
-
-    if( ( (*flags) & BADCERT_NOT_TRUSTED ) != 0 )
-        polarssl_printf( "  ! self-signed or not signed by a trusted CA\n" );
-
-    if( ( (*flags) & BADCRL_NOT_TRUSTED ) != 0 )
-        polarssl_printf( "  ! CRL not trusted\n" );
-
-    if( ( (*flags) & BADCRL_EXPIRED ) != 0 )
-        polarssl_printf( "  ! CRL expired\n" );
-
-    if( ( (*flags) & BADCERT_OTHER ) != 0 )
-        polarssl_printf( "  ! other (unknown) flag\n" );
-
-    if ( ( *flags ) == 0 )
-        polarssl_printf( "  This certificate has no flags\n" );
-
-    return( 0 );
-}
-#endif /* POLARSSL_X509_CRT_PARSE_C */
-
 #if defined(POLARSSL_X509_CRT_PARSE_C)
 #if defined(POLARSSL_FS_IO)
 #define USAGE_IO \
@@ -399,6 +258,149 @@
     "    force_ciphersuite=<name>    default: all enabled\n"\
     " acceptable ciphersuite names:\n"
 
+#if !defined(POLARSSL_ENTROPY_C) ||  !defined(POLARSSL_FS_IO) || \
+    !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_CLI_C) || \
+    !defined(POLARSSL_NET_C) || !defined(POLARSSL_CTR_DRBG_C)
+int main( void )
+{
+    polarssl_printf("POLARSSL_ENTROPY_C and/or "
+           "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_CLI_C and/or "
+           "POLARSSL_NET_C and/or POLARSSL_CTR_DRBG_C not defined.\n");
+    return( 0 );
+}
+#else
+/*
+ * global options
+ */
+struct options
+{
+    const char *server_name;    /* hostname of the server (client only)     */
+    const char *server_addr;    /* address of the server (client only)      */
+    int server_port;            /* port on which the ssl service runs       */
+    int debug_level;            /* level of debugging                       */
+    int nbio;                   /* should I/O be blocking?                  */
+    uint32_t read_timeout;      /* timeout on ssl_read() in milliseconds    */
+    int max_resend;             /* DTLS times to resend on read timeout     */
+    const char *request_page;   /* page on server to request                */
+    int request_size;           /* pad request with header to requested size */
+    const char *ca_file;        /* the file with the CA certificate(s)      */
+    const char *ca_path;        /* the path with the CA certificate(s) reside */
+    const char *crt_file;       /* the file with the client certificate     */
+    const char *key_file;       /* the file with the client key             */
+    const char *psk;            /* the pre-shared key                       */
+    const char *psk_identity;   /* the pre-shared key identity              */
+    int force_ciphersuite[2];   /* protocol/ciphersuite to use, or all      */
+    int renegotiation;          /* enable / disable renegotiation           */
+    int allow_legacy;           /* allow legacy renegotiation               */
+    int renegotiate;            /* attempt renegotiation?                   */
+    int renego_delay;           /* delay before enforcing renegotiation     */
+    int exchanges;              /* number of data exchanges                 */
+    int min_version;            /* minimum protocol version accepted        */
+    int max_version;            /* maximum protocol version accepted        */
+    int arc4;                   /* flag for arc4 suites support             */
+    int auth_mode;              /* verify mode for connection               */
+    unsigned char mfl_code;     /* code for maximum fragment length         */
+    int trunc_hmac;             /* negotiate truncated hmac or not          */
+    int recsplit;               /* enable record splitting?                 */
+    int reconnect;              /* attempt to resume session                */
+    int reco_delay;             /* delay in seconds before resuming session */
+    int tickets;                /* enable / disable session tickets         */
+    const char *alpn_string;    /* ALPN supported protocols                 */
+    int transport;              /* TLS or DTLS?                             */
+    uint32_t hs_to_min;         /* Initial value of DTLS handshake timer    */
+    uint32_t hs_to_max;         /* Max value of DTLS handshake timer        */
+    int fallback;               /* is this a fallback connection?           */
+    int extended_ms;            /* negotiate extended master secret?        */
+    int etm;                    /* negotiate encrypt then mac?              */
+} opt;
+
+static void my_debug( void *ctx, int level, const char *str )
+{
+    ((void) level);
+
+    polarssl_fprintf( (FILE *) ctx, "%s", str );
+    fflush(  (FILE *) ctx  );
+}
+
+/*
+ * Test recv/send functions that make sure each try returns
+ * WANT_READ/WANT_WRITE at least once before sucesseding
+ */
+static int my_recv( void *ctx, unsigned char *buf, size_t len )
+{
+    static int first_try = 1;
+    int ret;
+
+    if( first_try )
+    {
+        first_try = 0;
+        return( POLARSSL_ERR_NET_WANT_READ );
+    }
+
+    ret = net_recv( ctx, buf, len );
+    if( ret != POLARSSL_ERR_NET_WANT_READ )
+        first_try = 1; /* Next call will be a new operation */
+    return( ret );
+}
+
+static int my_send( void *ctx, const unsigned char *buf, size_t len )
+{
+    static int first_try = 1;
+    int ret;
+
+    if( first_try )
+    {
+        first_try = 0;
+        return( POLARSSL_ERR_NET_WANT_WRITE );
+    }
+
+    ret = net_send( ctx, buf, len );
+    if( ret != POLARSSL_ERR_NET_WANT_WRITE )
+        first_try = 1; /* Next call will be a new operation */
+    return( ret );
+}
+
+#if defined(POLARSSL_X509_CRT_PARSE_C)
+/*
+ * Enabled if debug_level > 1 in code below
+ */
+static int my_verify( void *data, x509_crt *crt, int depth, int *flags )
+{
+    char buf[1024];
+    ((void) data);
+
+    polarssl_printf( "\nVerify requested for (Depth %d):\n", depth );
+    x509_crt_info( buf, sizeof( buf ) - 1, "", crt );
+    polarssl_printf( "%s", buf );
+
+    if( ( (*flags) & BADCERT_EXPIRED ) != 0 )
+        polarssl_printf( "  ! server certificate has expired\n" );
+
+    if( ( (*flags) & BADCERT_REVOKED ) != 0 )
+        polarssl_printf( "  ! server certificate has been revoked\n" );
+
+    if( ( (*flags) & BADCERT_CN_MISMATCH ) != 0 )
+        polarssl_printf( "  ! CN mismatch\n" );
+
+    if( ( (*flags) & BADCERT_NOT_TRUSTED ) != 0 )
+        polarssl_printf( "  ! self-signed or not signed by a trusted CA\n" );
+
+    if( ( (*flags) & BADCRL_NOT_TRUSTED ) != 0 )
+        polarssl_printf( "  ! CRL not trusted\n" );
+
+    if( ( (*flags) & BADCRL_EXPIRED ) != 0 )
+        polarssl_printf( "  ! CRL expired\n" );
+
+    if( ( (*flags) & BADCERT_OTHER ) != 0 )
+        polarssl_printf( "  ! other (unknown) flag\n" );
+
+    if ( ( *flags ) == 0 )
+        polarssl_printf( "  This certificate has no flags\n" );
+
+    return( 0 );
+}
+#endif /* POLARSSL_X509_CRT_PARSE_C */
+
 int main( int argc, char *argv[] )
 {
     int ret = 0, len, tail_len, server_fd, i, written, frags, retry_left;
@@ -1323,7 +1325,7 @@
     polarssl_printf( "  > Write to server:" );
     fflush( stdout );
 
-    len = snprintf( (char *) buf, sizeof(buf) - 1, GET_REQUEST,
+    len = polarssl_snprintf( (char *) buf, sizeof(buf) - 1, GET_REQUEST,
                     opt.request_page );
     tail_len = strlen( GET_REQUEST_END );
 
diff --git a/programs/ssl/ssl_fork_server.c b/programs/ssl/ssl_fork_server.c
index 6424311..71a3aa9 100644
--- a/programs/ssl/ssl_fork_server.c
+++ b/programs/ssl/ssl_fork_server.c
@@ -29,23 +29,21 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
 #if defined(_WIN32)
 #include <windows.h>
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <signal.h>
-
-#if !defined(_MSC_VER) || defined(EFIX64) || defined(EFI32)
-#include <unistd.h>
-#endif
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_CERTS_C) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_SSL_TLS_C) && \
+    defined(POLARSSL_SSL_SRV_C) && defined(POLARSSL_NET_C) && \
+    defined(POLARSSL_RSA_C) && defined(POLARSSL_CTR_DRBG_C) && \
+    defined(POLARSSL_X509_CRT_PARSE_C) && defined(POLARSSL_TIMING_C) && \
+    defined(POLARSSL_FS_IO)
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 #include "polarssl/certs.h"
@@ -54,6 +52,15 @@
 #include "polarssl/net.h"
 #include "polarssl/timing.h"
 
+#include <string.h>
+#include <stdio.h>
+#include <signal.h>
+#endif
+
+#if !defined(_MSC_VER) || defined(EFIX64) || defined(EFI32)
+#include <unistd.h>
+#endif
+
 #define HTTP_RESPONSE \
     "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" \
     "<h2>mbed TLS Test Server</h2>\r\n" \
@@ -63,7 +70,8 @@
     !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_SSL_TLS_C) || \
     !defined(POLARSSL_SSL_SRV_C) || !defined(POLARSSL_NET_C) ||     \
     !defined(POLARSSL_RSA_C) || !defined(POLARSSL_CTR_DRBG_C) ||    \
-    !defined(POLARSSL_X509_CRT_PARSE_C) || !defined(POLARSSL_TIMING_C)
+    !defined(POLARSSL_X509_CRT_PARSE_C) || !defined(POLARSSL_TIMING_C) || \
+    !defined(POLARSSL_FS_IO)
 int main( int argc, char *argv[] )
 {
     ((void) argc);
@@ -77,11 +85,8 @@
     return( 0 );
 }
 #elif defined(_WIN32)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("_WIN32 defined. This application requires fork() and signals "
            "to work correctly.\n");
     return( 0 );
@@ -99,7 +104,7 @@
     }
 }
 
-int main( int argc, char *argv[] )
+int main( void )
 {
     int ret, len, cnt = 0, pid;
     int listen_fd;
@@ -113,9 +118,6 @@
     x509_crt srvcert;
     pk_context pkey;
 
-    ((void) argc);
-    ((void) argv);
-
     memset( &ssl, 0, sizeof(ssl_context) );
 
     entropy_init( &entropy );
@@ -340,8 +342,11 @@
 
             len = ret;
             polarssl_printf( " %d bytes read\n\n%s", len, (char *) buf );
+
+            if( ret > 0 )
+                break;
         }
-        while( 0 );
+        while( 1 );
 
         /*
          * 7. Write the 200 Response
diff --git a/programs/ssl/ssl_mail_client.c b/programs/ssl/ssl_mail_client.c
index 7259d65..8794c98 100644
--- a/programs/ssl/ssl_mail_client.c
+++ b/programs/ssl/ssl_mail_client.c
@@ -29,13 +29,29 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_SSL_TLS_C) && defined(POLARSSL_SSL_CLI_C) && \
+    defined(POLARSSL_NET_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_CTR_DRBG_C) && defined(POLARSSL_X509_CRT_PARSE_C) && \
+    defined(POLARSSL_FS_IO)
+#include "polarssl/base64.h"
+#include "polarssl/error.h"
+#include "polarssl/net.h"
+#include "polarssl/ssl.h"
+#include "polarssl/entropy.h"
+#include "polarssl/ctr_drbg.h"
+#include "polarssl/certs.h"
+#include "polarssl/x509.h"
+
 #include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
 
 #if !defined(_MSC_VER) || defined(EFIX64) || defined(EFI32)
 #include <unistd.h>
@@ -46,7 +62,6 @@
 #endif
 
 #if defined(_WIN32) || defined(_WIN32_WCE)
-
 #include <winsock2.h>
 #include <windows.h>
 
@@ -59,33 +74,6 @@
 #endif /* _MSC_VER */
 #endif
 
-#include "polarssl/base64.h"
-#include "polarssl/error.h"
-#include "polarssl/net.h"
-#include "polarssl/ssl.h"
-#include "polarssl/entropy.h"
-#include "polarssl/ctr_drbg.h"
-#include "polarssl/certs.h"
-#include "polarssl/x509.h"
-
-#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||  \
-    !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_CLI_C) || \
-    !defined(POLARSSL_NET_C) || !defined(POLARSSL_RSA_C) ||         \
-    !defined(POLARSSL_CTR_DRBG_C) || !defined(POLARSSL_X509_CRT_PARSE_C)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
-           "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_CLI_C and/or "
-           "POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
-           "POLARSSL_CTR_DRBG_C and/or POLARSSL_X509_CRT_PARSE_C "
-           "not defined.\n");
-    return( 0 );
-}
-#else
-
 #define DFL_SERVER_NAME         "localhost"
 #define DFL_SERVER_PORT         465
 #define DFL_USER_NAME           "user"
@@ -103,6 +91,55 @@
 #define MODE_SSL_TLS            0
 #define MODE_STARTTLS           0
 
+#if defined(POLARSSL_BASE64_C)
+#define USAGE_AUTH \
+    "    authentication=%%d   default: 0 (disabled)\n"      \
+    "    user_name=%%s        default: \"user\"\n"          \
+    "    user_pwd=%%s         default: \"password\"\n"
+#else
+#define USAGE_AUTH \
+    "    authentication options disabled. (Require POLARSSL_BASE64_C)\n"
+#endif /* POLARSSL_BASE64_C */
+
+#if defined(POLARSSL_FS_IO)
+#define USAGE_IO \
+    "    ca_file=%%s          default: \"\" (pre-loaded)\n" \
+    "    crt_file=%%s         default: \"\" (pre-loaded)\n" \
+    "    key_file=%%s         default: \"\" (pre-loaded)\n"
+#else
+#define USAGE_IO \
+    "    No file operations available (POLARSSL_FS_IO not defined)\n"
+#endif /* POLARSSL_FS_IO */
+
+#define USAGE \
+    "\n usage: ssl_mail_client param=<>...\n"               \
+    "\n acceptable parameters:\n"                           \
+    "    server_name=%%s      default: localhost\n"         \
+    "    server_port=%%d      default: 4433\n"              \
+    "    debug_level=%%d      default: 0 (disabled)\n"      \
+    "    mode=%%d             default: 0 (SSL/TLS) (1 for STARTTLS)\n"  \
+    USAGE_AUTH                                              \
+    "    mail_from=%%s        default: \"\"\n"              \
+    "    mail_to=%%s          default: \"\"\n"              \
+    USAGE_IO                                                \
+    "    force_ciphersuite=<name>    default: all enabled\n"\
+    " acceptable ciphersuite names:\n"
+
+#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||  \
+    !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_CLI_C) || \
+    !defined(POLARSSL_NET_C) || !defined(POLARSSL_RSA_C) ||         \
+    !defined(POLARSSL_CTR_DRBG_C) || !defined(POLARSSL_X509_CRT_PARSE_C) || \
+    !defined(POLARSSL_FS_IO)
+int main( void )
+{
+    polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
+           "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_CLI_C and/or "
+           "POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
+           "POLARSSL_CTR_DRBG_C and/or POLARSSL_X509_CRT_PARSE_C "
+           "not defined.\n");
+    return( 0 );
+}
+#else
 /*
  * global options
  */
@@ -312,47 +349,13 @@
                 code[3] = '\0';
                 return atoi( code );
             }
-            
+
             idx = 0;
         }
     }
     while( 1 );
 }
 
-#if defined(POLARSSL_BASE64_C)
-#define USAGE_AUTH \
-    "    authentication=%%d   default: 0 (disabled)\n"      \
-    "    user_name=%%s        default: \"user\"\n"          \
-    "    user_pwd=%%s         default: \"password\"\n"      
-#else
-#define USAGE_AUTH \
-    "    authentication options disabled. (Require POLARSSL_BASE64_C)\n"
-#endif /* POLARSSL_BASE64_C */
-
-#if defined(POLARSSL_FS_IO)
-#define USAGE_IO \
-    "    ca_file=%%s          default: \"\" (pre-loaded)\n" \
-    "    crt_file=%%s         default: \"\" (pre-loaded)\n" \
-    "    key_file=%%s         default: \"\" (pre-loaded)\n"
-#else
-#define USAGE_IO \
-    "    No file operations available (POLARSSL_FS_IO not defined)\n"
-#endif /* POLARSSL_FS_IO */
-
-#define USAGE \
-    "\n usage: ssl_mail_client param=<>...\n"               \
-    "\n acceptable parameters:\n"                           \
-    "    server_name=%%s      default: localhost\n"         \
-    "    server_port=%%d      default: 4433\n"              \
-    "    debug_level=%%d      default: 0 (disabled)\n"      \
-    "    mode=%%d             default: 0 (SSL/TLS) (1 for STARTTLS)\n"  \
-    USAGE_AUTH                                              \
-    "    mail_from=%%s        default: \"\"\n"              \
-    "    mail_to=%%s          default: \"\"\n"              \
-    USAGE_IO                                                \
-    "    force_ciphersuite=<name>    default: all enabled\n"\
-    " acceptable ciphersuite names:\n"
-
 int main( int argc, char *argv[] )
 {
     int ret = 0, len, server_fd;
diff --git a/programs/ssl/ssl_pthread_server.c b/programs/ssl/ssl_pthread_server.c
index d642a24..8ae4113 100644
--- a/programs/ssl/ssl_pthread_server.c
+++ b/programs/ssl/ssl_pthread_server.c
@@ -30,18 +30,22 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
+#define polarssl_snprintf   snprintf
 #endif
 
 #if defined(_WIN32)
 #include <windows.h>
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_CERTS_C) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_SSL_TLS_C) && \
+    defined(POLARSSL_SSL_SRV_C) && defined(POLARSSL_NET_C) && \
+    defined(POLARSSL_RSA_C) && defined(POLARSSL_CTR_DRBG_C) && \
+    defined(POLARSSL_X509_CRT_PARSE_C) && defined(POLARSSL_FS_IO) && \
+    defined(POLARSSL_THREADING_C) && defined(POLARSSL_THREADING_PTHREAD)
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 #include "polarssl/certs.h"
@@ -50,6 +54,11 @@
 #include "polarssl/net.h"
 #include "polarssl/error.h"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
 #if defined(POLARSSL_SSL_CACHE_C)
 #include "polarssl/ssl_cache.h"
 #endif
@@ -58,17 +67,23 @@
 #include "polarssl/memory_buffer_alloc.h"
 #endif
 
+#define HTTP_RESPONSE \
+    "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" \
+    "<h2>mbed TLS Test Server</h2>\r\n" \
+    "<p>Successful connection using: %s</p>\r\n"
+
+#define DEBUG_LEVEL 0
+
+#define MAX_NUM_THREADS 5
+
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_CERTS_C) ||            \
     !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_SSL_TLS_C) ||         \
     !defined(POLARSSL_SSL_SRV_C) || !defined(POLARSSL_NET_C) ||             \
     !defined(POLARSSL_RSA_C) || !defined(POLARSSL_CTR_DRBG_C) ||            \
-    !defined(POLARSSL_X509_CRT_PARSE_C) ||                                  \
+    !defined(POLARSSL_X509_CRT_PARSE_C) || !defined(POLARSSL_FS_IO) ||      \
     !defined(POLARSSL_THREADING_C) || !defined(POLARSSL_THREADING_PTHREAD)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_CERTS_C and/or POLARSSL_ENTROPY_C "
            "and/or POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_SRV_C and/or "
            "POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
@@ -78,14 +93,6 @@
     return( 0 );
 }
 #else
-
-#define HTTP_RESPONSE \
-    "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" \
-    "<h2>mbed TLS Test Server</h2>\r\n" \
-    "<p>Successful connection using: %s</p>\r\n"
-
-#define DEBUG_LEVEL 0
-
 threading_mutex_t debug_mutex;
 
 static void my_mutexed_debug( void *ctx, int level, const char *str )
@@ -117,8 +124,6 @@
     pthread_t       thread;
 } pthread_info_t;
 
-#define MAX_NUM_THREADS 5
-
 static thread_info_t    base_info;
 static pthread_info_t   threads[MAX_NUM_THREADS];
 
@@ -137,7 +142,7 @@
     memset( &ssl, 0, sizeof( ssl_context ) );
     memset( &ctr_drbg, 0, sizeof( ctr_drbg_context ) );
 
-    snprintf( pers, sizeof(pers), "SSL Pthread Thread %d", thread_id );
+    polarssl_snprintf( pers, sizeof(pers), "SSL Pthread Thread %d", thread_id );
     polarssl_printf( "  [ #%d ]  Client FD %d\n", thread_id, client_fd );
     polarssl_printf( "  [ #%d ]  Seeding the random number generator...\n", thread_id );
 
@@ -366,7 +371,7 @@
     return( 0 );
 }
 
-int main( int argc, char *argv[] )
+int main( void )
 {
     int ret;
     int listen_fd;
@@ -382,9 +387,6 @@
     ssl_cache_context cache;
 #endif
 
-    ((void) argc);
-    ((void) argv);
-
 #if defined(POLARSSL_MEMORY_BUFFER_ALLOC_C)
     memory_buffer_alloc_init( alloc_buf, sizeof(alloc_buf) );
 #endif
diff --git a/programs/ssl/ssl_server.c b/programs/ssl/ssl_server.c
index f590bad..83430f6 100644
--- a/programs/ssl/ssl_server.c
+++ b/programs/ssl/ssl_server.c
@@ -29,18 +29,20 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
 #if defined(_WIN32)
 #include <windows.h>
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_CERTS_C) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_SSL_TLS_C) && \
+    defined(POLARSSL_SSL_SRV_C) && defined(POLARSSL_NET_C) && \
+    defined(POLARSSL_RSA_C) && defined(POLARSSL_CTR_DRBG_C) && \
+    defined(POLARSSL_X509_CRT_PARSE_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 #include "polarssl/certs.h"
@@ -50,29 +52,15 @@
 #include "polarssl/error.h"
 #include "polarssl/debug.h"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
 #if defined(POLARSSL_SSL_CACHE_C)
 #include "polarssl/ssl_cache.h"
 #endif
 
-#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_CERTS_C) ||    \
-    !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_SSL_TLS_C) || \
-    !defined(POLARSSL_SSL_SRV_C) || !defined(POLARSSL_NET_C) ||     \
-    !defined(POLARSSL_RSA_C) || !defined(POLARSSL_CTR_DRBG_C) ||    \
-    !defined(POLARSSL_X509_CRT_PARSE_C)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_CERTS_C and/or POLARSSL_ENTROPY_C "
-           "and/or POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_SRV_C and/or "
-           "POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
-           "POLARSSL_CTR_DRBG_C and/or POLARSSL_X509_CRT_PARSE_C "
-           "not defined.\n");
-    return( 0 );
-}
-#else
-
 #define HTTP_RESPONSE \
     "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" \
     "<h2>mbed TLS Test Server</h2>\r\n" \
@@ -80,6 +68,21 @@
 
 #define DEBUG_LEVEL 0
 
+#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_CERTS_C) ||    \
+    !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_SSL_TLS_C) || \
+    !defined(POLARSSL_SSL_SRV_C) || !defined(POLARSSL_NET_C) ||     \
+    !defined(POLARSSL_RSA_C) || !defined(POLARSSL_CTR_DRBG_C) ||    \
+    !defined(POLARSSL_X509_CRT_PARSE_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
+    polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_CERTS_C and/or POLARSSL_ENTROPY_C "
+           "and/or POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_SRV_C and/or "
+           "POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
+           "POLARSSL_CTR_DRBG_C and/or POLARSSL_X509_CRT_PARSE_C "
+           "not defined.\n");
+    return( 0 );
+}
+#else
 static void my_debug( void *ctx, int level, const char *str )
 {
     ((void) level);
@@ -88,7 +91,7 @@
     fflush(  (FILE *) ctx  );
 }
 
-int main( int argc, char *argv[] )
+int main( void )
 {
     int ret, len;
     int listen_fd;
@@ -105,9 +108,6 @@
     ssl_cache_context cache;
 #endif
 
-    ((void) argc);
-    ((void) argv);
-
     memset( &ssl, 0, sizeof(ssl_context) );
 #if defined(POLARSSL_SSL_CACHE_C)
     ssl_cache_init( &cache );
diff --git a/programs/ssl/ssl_server2.c b/programs/ssl/ssl_server2.c
index 5d6fe40..5319c7e 100644
--- a/programs/ssl/ssl_server2.c
+++ b/programs/ssl/ssl_server2.c
@@ -29,27 +29,12 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
-#define polarssl_fprintf    fprintf
-#define polarssl_malloc     malloc
-#define polarssl_free       free
-#endif
-
-#if !defined(POLARSSL_ENTROPY_C) ||  \
-    !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_SRV_C) || \
-    !defined(POLARSSL_NET_C) || !defined(POLARSSL_CTR_DRBG_C)
 #include <stdio.h>
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf("POLARSSL_ENTROPY_C and/or "
-           "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_SRV_C and/or "
-           "POLARSSL_NET_C and/or POLARSSL_CTR_DRBG_C not defined.\n");
-    return( 0 );
-}
-#else
+#define polarssl_free       free
+#define polarssl_malloc     malloc
+#define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
+#endif
 
 #if defined(POLARSSL_SSL_SERVER_NAME_INDICATION) && defined(POLARSSL_FS_IO)
 #define POLARSSL_SNI
@@ -59,14 +44,9 @@
 #include <windows.h>
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-#if !defined(_WIN32)
-#include <signal.h>
-#endif
-
+#if defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_SSL_TLS_C) && defined(POLARSSL_SSL_SRV_C) && \
+    defined(POLARSSL_NET_C) && defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/net.h"
 #include "polarssl/ssl.h"
 #include "polarssl/entropy.h"
@@ -76,6 +56,15 @@
 #include "polarssl/error.h"
 #include "polarssl/debug.h"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
+#if !defined(_WIN32)
+#include <signal.h>
+#endif
+
 #if defined(POLARSSL_SSL_CACHE_C)
 #include "polarssl/ssl_cache.h"
 #endif
@@ -155,102 +144,6 @@
  */
 #define IO_BUF_LEN      200
 
-/*
- * global options
- */
-struct options
-{
-    const char *server_addr;    /* address on which the ssl service runs    */
-    int server_port;            /* port on which the ssl service runs       */
-    int debug_level;            /* level of debugging                       */
-    int nbio;                   /* should I/O be blocking?                  */
-    uint32_t read_timeout;      /* timeout on ssl_read() in milliseconds    */
-    const char *ca_file;        /* the file with the CA certificate(s)      */
-    const char *ca_path;        /* the path with the CA certificate(s) reside */
-    const char *crt_file;       /* the file with the server certificate     */
-    const char *key_file;       /* the file with the server key             */
-    const char *crt_file2;      /* the file with the 2nd server certificate */
-    const char *key_file2;      /* the file with the 2nd server key         */
-    const char *psk;            /* the pre-shared key                       */
-    const char *psk_identity;   /* the pre-shared key identity              */
-    char *psk_list;             /* list of PSK id/key pairs for callback    */
-    int force_ciphersuite[2];   /* protocol/ciphersuite to use, or all      */
-    const char *version_suites; /* per-version ciphersuites                 */
-    int renegotiation;          /* enable / disable renegotiation           */
-    int allow_legacy;           /* allow legacy renegotiation               */
-    int renegotiate;            /* attempt renegotiation?                   */
-    int renego_delay;           /* delay before enforcing renegotiation     */
-    int renego_period;          /* period for automatic renegotiation       */
-    int exchanges;              /* number of data exchanges                 */
-    int min_version;            /* minimum protocol version accepted        */
-    int max_version;            /* maximum protocol version accepted        */
-    int arc4;                   /* flag for arc4 suites support             */
-    int auth_mode;              /* verify mode for connection               */
-    unsigned char mfl_code;     /* code for maximum fragment length         */
-    int trunc_hmac;             /* accept truncated hmac?                   */
-    int tickets;                /* enable / disable session tickets         */
-    int ticket_timeout;         /* session ticket lifetime                  */
-    int cache_max;              /* max number of session cache entries      */
-    int cache_timeout;          /* expiration delay of session cache entries */
-    char *sni;                  /* string describing sni information        */
-    const char *alpn_string;    /* ALPN supported protocols                 */
-    const char *dhm_file;       /* the file with the DH parameters          */
-    int extended_ms;            /* allow negotiation of extended MS?        */
-    int etm;                    /* allow negotiation of encrypt-then-MAC?   */
-    int transport;              /* TLS or DTLS?                             */
-    int cookies;                /* Use cookies for DTLS? -1 to break them   */
-    int anti_replay;            /* Use anti-replay for DTLS? -1 for default */
-    uint32_t hs_to_min;         /* Initial value of DTLS handshake timer    */
-    uint32_t hs_to_max;         /* Max value of DTLS handshake timer        */
-    int badmac_limit;           /* Limit of records with bad MAC            */
-} opt;
-
-static void my_debug( void *ctx, int level, const char *str )
-{
-    ((void) level);
-
-    polarssl_fprintf( (FILE *) ctx, "%s", str );
-    fflush(  (FILE *) ctx  );
-}
-
-/*
- * Test recv/send functions that make sure each try returns
- * WANT_READ/WANT_WRITE at least once before sucesseding
- */
-static int my_recv( void *ctx, unsigned char *buf, size_t len )
-{
-    static int first_try = 1;
-    int ret;
-
-    if( first_try )
-    {
-        first_try = 0;
-        return( POLARSSL_ERR_NET_WANT_READ );
-    }
-
-    ret = net_recv( ctx, buf, len );
-    if( ret != POLARSSL_ERR_NET_WANT_READ )
-        first_try = 1; /* Next call will be a new operation */
-    return( ret );
-}
-
-static int my_send( void *ctx, const unsigned char *buf, size_t len )
-{
-    static int first_try = 1;
-    int ret;
-
-    if( first_try )
-    {
-        first_try = 0;
-        return( POLARSSL_ERR_NET_WANT_WRITE );
-    }
-
-    ret = net_send( ctx, buf, len );
-    if( ret != POLARSSL_ERR_NET_WANT_WRITE )
-        first_try = 1; /* Next call will be a new operation */
-    return( ret );
-}
-
 #if defined(POLARSSL_X509_CRT_PARSE_C)
 #if defined(POLARSSL_FS_IO)
 #define USAGE_IO \
@@ -434,6 +327,114 @@
     "    force_ciphersuite=<name>    default: all enabled\n"            \
     " acceptable ciphersuite names:\n"
 
+#if !defined(POLARSSL_ENTROPY_C) || \
+    !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_SRV_C) || \
+    !defined(POLARSSL_NET_C) || !defined(POLARSSL_CTR_DRBG_C)
+#include <stdio.h>
+int main( void )
+{
+    polarssl_printf("POLARSSL_ENTROPY_C and/or "
+           "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_SRV_C and/or "
+           "POLARSSL_NET_C and/or POLARSSL_CTR_DRBG_C not defined.\n");
+    return( 0 );
+}
+#else
+/*
+ * global options
+ */
+struct options
+{
+    const char *server_addr;    /* address on which the ssl service runs    */
+    int server_port;            /* port on which the ssl service runs       */
+    int debug_level;            /* level of debugging                       */
+    int nbio;                   /* should I/O be blocking?                  */
+    uint32_t read_timeout;      /* timeout on ssl_read() in milliseconds    */
+    const char *ca_file;        /* the file with the CA certificate(s)      */
+    const char *ca_path;        /* the path with the CA certificate(s) reside */
+    const char *crt_file;       /* the file with the server certificate     */
+    const char *key_file;       /* the file with the server key             */
+    const char *crt_file2;      /* the file with the 2nd server certificate */
+    const char *key_file2;      /* the file with the 2nd server key         */
+    const char *psk;            /* the pre-shared key                       */
+    const char *psk_identity;   /* the pre-shared key identity              */
+    char *psk_list;             /* list of PSK id/key pairs for callback    */
+    int force_ciphersuite[2];   /* protocol/ciphersuite to use, or all      */
+    const char *version_suites; /* per-version ciphersuites                 */
+    int renegotiation;          /* enable / disable renegotiation           */
+    int allow_legacy;           /* allow legacy renegotiation               */
+    int renegotiate;            /* attempt renegotiation?                   */
+    int renego_delay;           /* delay before enforcing renegotiation     */
+    int renego_period;          /* period for automatic renegotiation       */
+    int exchanges;              /* number of data exchanges                 */
+    int min_version;            /* minimum protocol version accepted        */
+    int max_version;            /* maximum protocol version accepted        */
+    int arc4;                   /* flag for arc4 suites support             */
+    int auth_mode;              /* verify mode for connection               */
+    unsigned char mfl_code;     /* code for maximum fragment length         */
+    int trunc_hmac;             /* accept truncated hmac?                   */
+    int tickets;                /* enable / disable session tickets         */
+    int ticket_timeout;         /* session ticket lifetime                  */
+    int cache_max;              /* max number of session cache entries      */
+    int cache_timeout;          /* expiration delay of session cache entries */
+    char *sni;                  /* string describing sni information        */
+    const char *alpn_string;    /* ALPN supported protocols                 */
+    const char *dhm_file;       /* the file with the DH parameters          */
+    int extended_ms;            /* allow negotiation of extended MS?        */
+    int etm;                    /* allow negotiation of encrypt-then-MAC?   */
+    int transport;              /* TLS or DTLS?                             */
+    int cookies;                /* Use cookies for DTLS? -1 to break them   */
+    int anti_replay;            /* Use anti-replay for DTLS? -1 for default */
+    uint32_t hs_to_min;         /* Initial value of DTLS handshake timer    */
+    uint32_t hs_to_max;         /* Max value of DTLS handshake timer        */
+    int badmac_limit;           /* Limit of records with bad MAC            */
+} opt;
+
+static void my_debug( void *ctx, int level, const char *str )
+{
+    ((void) level);
+
+    polarssl_fprintf( (FILE *) ctx, "%s", str );
+    fflush(  (FILE *) ctx  );
+}
+
+/*
+ * Test recv/send functions that make sure each try returns
+ * WANT_READ/WANT_WRITE at least once before sucesseding
+ */
+static int my_recv( void *ctx, unsigned char *buf, size_t len )
+{
+    static int first_try = 1;
+    int ret;
+
+    if( first_try )
+    {
+        first_try = 0;
+        return( POLARSSL_ERR_NET_WANT_READ );
+    }
+
+    ret = net_recv( ctx, buf, len );
+    if( ret != POLARSSL_ERR_NET_WANT_READ )
+        first_try = 1; /* Next call will be a new operation */
+    return( ret );
+}
+
+static int my_send( void *ctx, const unsigned char *buf, size_t len )
+{
+    static int first_try = 1;
+    int ret;
+
+    if( first_try )
+    {
+        first_try = 0;
+        return( POLARSSL_ERR_NET_WANT_WRITE );
+    }
+
+    ret = net_send( ctx, buf, len );
+    if( ret != POLARSSL_ERR_NET_WANT_WRITE )
+        first_try = 1; /* Next call will be a new operation */
+    return( ret );
+}
+
 /*
  * Used by sni_parse and psk_parse to handle coma-separated lists
  */
@@ -441,7 +442,7 @@
     dst = p;                    \
     while( *p != ',' )          \
         if( ++p > end )         \
-            return( NULL );     \
+            goto error;         \
     *p++ = '\0';
 
 #if defined(POLARSSL_SNI)
@@ -454,53 +455,6 @@
     sni_entry *next;
 };
 
-/*
- * Parse a string of triplets name1,crt1,key1[,name2,crt2,key2[,...]]
- * into a usable sni_entry list.
- *
- * Modifies the input string! This is not production quality!
- * (leaks memory if parsing fails, no error reporting, ...)
- */
-sni_entry *sni_parse( char *sni_string )
-{
-    sni_entry *cur = NULL, *new = NULL;
-    char *p = sni_string;
-    char *end = p;
-    char *crt_file, *key_file;
-
-    while( *end != '\0' )
-        ++end;
-    *end = ',';
-
-    while( p <= end )
-    {
-        if( ( new = polarssl_malloc( sizeof( sni_entry ) ) ) == NULL )
-            return( NULL );
-
-        memset( new, 0, sizeof( sni_entry ) );
-
-        if( ( new->cert = polarssl_malloc( sizeof( x509_crt ) ) ) == NULL ||
-            ( new->key = polarssl_malloc( sizeof( pk_context ) ) ) == NULL )
-            return( NULL );
-
-        x509_crt_init( new->cert );
-        pk_init( new->key );
-
-        GET_ITEM( new->name );
-        GET_ITEM( crt_file );
-        GET_ITEM( key_file );
-
-        if( x509_crt_parse_file( new->cert, crt_file ) != 0 ||
-            pk_parse_keyfile( new->key, key_file, "" ) != 0 )
-            return( NULL );
-
-        new->next = cur;
-        cur = new;
-    }
-
-    return( cur );
-}
-
 void sni_free( sni_entry *head )
 {
     sni_entry *cur = head, *next;
@@ -520,6 +474,67 @@
 }
 
 /*
+ * Parse a string of triplets name1,crt1,key1[,name2,crt2,key2[,...]]
+ * into a usable sni_entry list.
+ *
+ * Modifies the input string! This is not production quality!
+ */
+sni_entry *sni_parse( char *sni_string )
+{
+    sni_entry *cur = NULL, *new = NULL;
+    char *p = sni_string;
+    char *end = p;
+    char *crt_file, *key_file;
+
+    while( *end != '\0' )
+        ++end;
+    *end = ',';
+
+    while( p <= end )
+    {
+        if( ( new = polarssl_malloc( sizeof( sni_entry ) ) ) == NULL )
+        {
+            sni_free( cur );
+            return( NULL );
+        }
+
+        memset( new, 0, sizeof( sni_entry ) );
+
+        if( ( new->cert = polarssl_malloc( sizeof( x509_crt ) ) ) == NULL ||
+            ( new->key = polarssl_malloc( sizeof( pk_context ) ) ) == NULL )
+        {
+            polarssl_free( new->cert );
+            polarssl_free( new );
+            sni_free( cur );
+            return( NULL );
+        }
+
+        x509_crt_init( new->cert );
+        pk_init( new->key );
+
+        GET_ITEM( new->name );
+        GET_ITEM( crt_file );
+        GET_ITEM( key_file );
+
+        if( x509_crt_parse_file( new->cert, crt_file ) != 0 ||
+            pk_parse_keyfile( new->key, key_file, "" ) != 0 )
+        {
+            goto error;
+        }
+
+        new->next = cur;
+        cur = new;
+    }
+
+    return( cur );
+
+error:
+    sni_free( new );
+    sni_free( cur );
+    return( NULL );
+}
+
+/*
  * SNI callback.
  */
 int sni_callback( void *p_info, ssl_context *ssl,
@@ -594,11 +609,25 @@
 };
 
 /*
+ * Free a list of psk_entry's
+ */
+void psk_free( psk_entry *head )
+{
+    psk_entry *next;
+
+    while( head != NULL )
+    {
+        next = head->next;
+        polarssl_free( head );
+        head = next;
+    }
+}
+
+/*
  * Parse a string of pairs name1,key1[,name2,key2[,...]]
  * into a usable psk_entry list.
  *
  * Modifies the input string! This is not production quality!
- * (leaks memory if parsing fails, no error reporting, ...)
  */
 psk_entry *psk_parse( char *psk_string )
 {
@@ -622,28 +651,18 @@
         GET_ITEM( key_hex );
 
         if( unhexify( new->key, key_hex, &new->key_len ) != 0 )
-            return( NULL );
+            goto error;
 
         new->next = cur;
         cur = new;
     }
 
     return( cur );
-}
 
-/*
- * Free a list of psk_entry's
- */
-void psk_free( psk_entry *head )
-{
-    psk_entry *next;
-
-    while( head != NULL )
-    {
-        next = head->next;
-        polarssl_free( head );
-        head = next;
-    }
+error:
+    psk_free( new );
+    psk_free( cur );
+    return( 0 );
 }
 
 /*
diff --git a/programs/test/benchmark.c b/programs/test/benchmark.c
index cc83746..735b443 100644
--- a/programs/test/benchmark.c
+++ b/programs/test/benchmark.c
@@ -29,12 +29,21 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_exit       exit
 #define polarssl_printf     printf
+#define polarssl_snprintf   snprintf
 #endif
 
+#if !defined(POLARSSL_TIMING_C)
+int main( void )
+{
+    polarssl_printf("POLARSSL_TIMING_C not defined.\n");
+    return( 0 );
+}
+#else
+
 #include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
 
 #include "polarssl/timing.h"
 
@@ -60,24 +69,128 @@
 #include "polarssl/ecdh.h"
 #include "polarssl/error.h"
 
+#if defined(POLARSSL_MEMORY_BUFFER_ALLOC_C)
+#include "polarssl/memory_buffer_alloc.h"
+#endif
+
 #if defined _MSC_VER && !defined snprintf
 #define snprintf _snprintf
 #endif
 
+/*
+ * For heap usage estimates, we need an estimate of the overhead per allocated
+ * block. ptmalloc2/3 (used in gnu libc for instance) uses 2 size_t per block,
+ * so use that as our baseline.
+ */
+#define MEM_BLOCK_OVERHEAD  ( 2 * sizeof( size_t ) )
+
+/*
+ * Size to use for the malloc buffer if MEMORY_BUFFER_ALLOC_C is defined.
+ */
+#define HEAP_SIZE       (1u << 16)  // 64k
+
 #define BUFSIZE         1024
 #define HEADER_FORMAT   "  %-24s :  "
 #define TITLE_LEN       25
 
-#if !defined(POLARSSL_TIMING_C)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#define DHM_SIZES 3
 
-    polarssl_printf("POLARSSL_TIMING_C not defined.\n");
-    return( 0 );
-}
+#define OPTIONS                                                         \
+    "md4, md5, ripemd160, sha1, sha256, sha512,\n"                      \
+    "arc4, des3, des, aes_cbc, aes_gcm, aes_ccm, camellia, blowfish,\n" \
+    "havege, ctr_drbg, hmac_drbg\n"                                     \
+    "rsa, dhm, ecdsa, ecdh.\n"
+
+#if defined(POLARSSL_ERROR_C)
+#define PRINT_ERROR                                                     \
+        polarssl_strerror( ret, ( char * )tmp, sizeof( tmp ) );         \
+        polarssl_printf( "FAILED: %s\n", tmp );
 #else
+#define PRINT_ERROR                                                     \
+        polarssl_printf( "FAILED: -0x%04x\n", -ret );
+#endif
+
+#define TIME_AND_TSC( TITLE, CODE )                                     \
+do {                                                                    \
+    unsigned long i, j, tsc;                                            \
+                                                                        \
+    polarssl_printf( HEADER_FORMAT, TITLE );                            \
+    fflush( stdout );                                                   \
+                                                                        \
+    set_alarm( 1 );                                                     \
+    for( i = 1; ! alarmed; i++ )                                        \
+    {                                                                   \
+        CODE;                                                           \
+    }                                                                   \
+                                                                        \
+    tsc = hardclock();                                                  \
+    for( j = 0; j < 1024; j++ )                                         \
+    {                                                                   \
+        CODE;                                                           \
+    }                                                                   \
+                                                                        \
+    polarssl_printf( "%9lu Kb/s,  %9lu cycles/byte\n",                  \
+                     i * BUFSIZE / 1024,                                \
+                     ( hardclock() - tsc ) / ( j * BUFSIZE ) );         \
+} while( 0 )
+
+#if defined(POLARSSL_ERROR_C)
+#define PRINT_ERROR                                                     \
+        polarssl_strerror( ret, ( char * )tmp, sizeof( tmp ) );         \
+        polarssl_printf( "FAILED: %s\n", tmp );
+#else
+#define PRINT_ERROR                                                     \
+        polarssl_printf( "FAILED: -0x%04x\n", -ret );
+#endif
+
+#if defined(POLARSSL_MEMORY_BUFFER_ALLOC_C) && defined(POLARSSL_MEMORY_DEBUG)
+
+#define MEMORY_MEASURE_INIT                                             \
+    size_t max_used, max_blocks, max_bytes;                             \
+    size_t prv_used, prv_blocks;                                        \
+    memory_buffer_alloc_cur_get( &prv_used, &prv_blocks );              \
+    memory_buffer_alloc_max_reset( );
+
+#define MEMORY_MEASURE_PRINT( title_len )                               \
+    memory_buffer_alloc_max_get( &max_used, &max_blocks );              \
+    for( i = 12 - title_len; i != 0; i-- ) polarssl_printf( " " );      \
+    max_used -= prv_used;                                               \
+    max_blocks -= prv_blocks;                                           \
+    max_bytes = max_used + MEM_BLOCK_OVERHEAD * max_blocks;             \
+    polarssl_printf( "%6u heap bytes", (unsigned) max_bytes );
+
+#else
+#define MEMORY_MEASURE_INIT
+#define MEMORY_MEASURE_PRINT( title_len )
+#endif
+
+#define TIME_PUBLIC( TITLE, TYPE, CODE )                                \
+do {                                                                    \
+    unsigned long i;                                                    \
+    int ret;                                                            \
+    MEMORY_MEASURE_INIT;                                                \
+                                                                        \
+    polarssl_printf( HEADER_FORMAT, TITLE );                            \
+    fflush( stdout );                                                   \
+    set_alarm( 3 );                                                     \
+                                                                        \
+    ret = 0;                                                            \
+    for( i = 1; ! alarmed && ! ret ; i++ )                              \
+    {                                                                   \
+        CODE;                                                           \
+    }                                                                   \
+                                                                        \
+    if( ret != 0 )                                                      \
+    {                                                                   \
+        PRINT_ERROR;                                                    \
+    }                                                                   \
+    else                                                                \
+    {                                                                   \
+        polarssl_printf( "%6lu " TYPE "/s", i / 3 );                    \
+        MEMORY_MEASURE_PRINT( sizeof( TYPE ) + 1 );                     \
+        polarssl_printf( "\n" );                                        \
+    }                                                                   \
+} while( 0 )
 
 static int myrand( void *rng_state, unsigned char *output, size_t len )
 {
@@ -102,61 +215,26 @@
     return( 0 );
 }
 
-#define TIME_AND_TSC( TITLE, CODE )                                     \
-do {                                                                    \
-    unsigned long i, j, tsc;                                            \
-                                                                        \
-    polarssl_printf( HEADER_FORMAT, TITLE );                                     \
-    fflush( stdout );                                                   \
-                                                                        \
-    set_alarm( 1 );                                                     \
-    for( i = 1; ! alarmed; i++ )                                        \
-    {                                                                   \
-        CODE;                                                           \
-    }                                                                   \
-                                                                        \
-    tsc = hardclock();                                                  \
-    for( j = 0; j < 1024; j++ )                                         \
-    {                                                                   \
-        CODE;                                                           \
-    }                                                                   \
-                                                                        \
-    polarssl_printf( "%9lu Kb/s,  %9lu cycles/byte\n", i * BUFSIZE / 1024,       \
-                    ( hardclock() - tsc ) / ( j * BUFSIZE ) );          \
-} while( 0 )
-
-#if defined(POLARSSL_ERROR_C)
-#define PRINT_ERROR                                                     \
-        polarssl_strerror( ret, ( char * )tmp, sizeof( tmp ) );         \
-        polarssl_printf( "FAILED: %s\n", tmp );
+/*
+ * Clear some memory that was used to prepare the context
+ */
+#if defined(POLARSSL_ECP_C)
+void ecp_clear_precomputed( ecp_group *grp )
+{
+    if( grp->T != NULL )
+    {
+        size_t i;
+        for( i = 0; i < grp->T_size; i++ )
+            ecp_point_free( &grp->T[i] );
+        polarssl_free( grp->T );
+    }
+    grp->T = NULL;
+    grp->T_size = 0;
+}
 #else
-#define PRINT_ERROR                                                     \
-        polarssl_printf( "FAILED: -0x%04x\n", -ret );
+#define ecp_clear_precomputed( g )
 #endif
 
-#define TIME_PUBLIC( TITLE, TYPE, CODE )                                \
-do {                                                                    \
-    unsigned long i;                                                    \
-    int ret;                                                            \
-                                                                        \
-    polarssl_printf( HEADER_FORMAT, TITLE );                                     \
-    fflush( stdout );                                                   \
-    set_alarm( 3 );                                                     \
-                                                                        \
-    ret = 0;                                                            \
-    for( i = 1; ! alarmed && ! ret ; i++ )                              \
-    {                                                                   \
-        CODE;                                                           \
-    }                                                                   \
-                                                                        \
-    if( ret != 0 )                                                      \
-    {                                                                   \
-PRINT_ERROR;                                                            \
-    }                                                                   \
-    else                                                                \
-        polarssl_printf( "%9lu " TYPE "/s\n", i / 3 );                           \
-} while( 0 )
-
 unsigned char buf[BUFSIZE];
 
 typedef struct {
@@ -166,18 +244,15 @@
          rsa, dhm, ecdsa, ecdh;
 } todo_list;
 
-#define OPTIONS                                                         \
-    "md4, md5, ripemd160, sha1, sha256, sha512,\n"                      \
-    "arc4, des3, des, aes_cbc, aes_gcm, aes_ccm, camellia, blowfish,\n" \
-    "havege, ctr_drbg, hmac_drbg\n"                                     \
-    "rsa, dhm, ecdsa, ecdh.\n"
-
 int main( int argc, char *argv[] )
 {
-    int keysize, i;
+    int i;
     unsigned char tmp[200];
     char title[TITLE_LEN];
     todo_list todo;
+#if defined(POLARSSL_MEMORY_BUFFER_ALLOC_C)
+    unsigned char malloc_buf[HEAP_SIZE] = { 0 };
+#endif
 
     if( argc == 1 )
         memset( &todo, 1, sizeof( todo ) );
@@ -239,6 +314,9 @@
 
     polarssl_printf( "\n" );
 
+#if defined(POLARSSL_MEMORY_BUFFER_ALLOC_C)
+    memory_buffer_alloc_init( malloc_buf, sizeof( malloc_buf ) );
+#endif
     memset( buf, 0xAA, sizeof( buf ) );
     memset( tmp, 0xBB, sizeof( tmp ) );
 
@@ -309,11 +387,12 @@
 #if defined(POLARSSL_CIPHER_MODE_CBC)
     if( todo.aes_cbc )
     {
+        int keysize;
         aes_context aes;
         aes_init( &aes );
         for( keysize = 128; keysize <= 256; keysize += 64 )
         {
-            snprintf( title, sizeof( title ), "AES-CBC-%d", keysize );
+            polarssl_snprintf( title, sizeof( title ), "AES-CBC-%d", keysize );
 
             memset( buf, 0, sizeof( buf ) );
             memset( tmp, 0, sizeof( tmp ) );
@@ -328,10 +407,11 @@
 #if defined(POLARSSL_GCM_C)
     if( todo.aes_gcm )
     {
+        int keysize;
         gcm_context gcm;
         for( keysize = 128; keysize <= 256; keysize += 64 )
         {
-            snprintf( title, sizeof( title ), "AES-GCM-%d", keysize );
+            polarssl_snprintf( title, sizeof( title ), "AES-GCM-%d", keysize );
 
             memset( buf, 0, sizeof( buf ) );
             memset( tmp, 0, sizeof( tmp ) );
@@ -348,10 +428,11 @@
 #if defined(POLARSSL_CCM_C)
     if( todo.aes_ccm )
     {
+        int keysize;
         ccm_context ccm;
         for( keysize = 128; keysize <= 256; keysize += 64 )
         {
-            snprintf( title, sizeof( title ), "AES-CCM-%d", keysize );
+            polarssl_snprintf( title, sizeof( title ), "AES-CCM-%d", keysize );
 
             memset( buf, 0, sizeof( buf ) );
             memset( tmp, 0, sizeof( tmp ) );
@@ -370,11 +451,12 @@
 #if defined(POLARSSL_CAMELLIA_C) && defined(POLARSSL_CIPHER_MODE_CBC)
     if( todo.camellia )
     {
+        int keysize;
         camellia_context camellia;
         camellia_init( &camellia );
         for( keysize = 128; keysize <= 256; keysize += 64 )
         {
-            snprintf( title, sizeof( title ), "CAMELLIA-CBC-%d", keysize );
+            polarssl_snprintf( title, sizeof( title ), "CAMELLIA-CBC-%d", keysize );
 
             memset( buf, 0, sizeof( buf ) );
             memset( tmp, 0, sizeof( tmp ) );
@@ -391,12 +473,13 @@
 #if defined(POLARSSL_BLOWFISH_C) && defined(POLARSSL_CIPHER_MODE_CBC)
     if( todo.blowfish )
     {
+        int keysize;
         blowfish_context blowfish;
         blowfish_init( &blowfish );
 
         for( keysize = 128; keysize <= 256; keysize += 64 )
         {
-            snprintf( title, sizeof( title ), "BLOWFISH-CBC-%d", keysize );
+            polarssl_snprintf( title, sizeof( title ), "BLOWFISH-CBC-%d", keysize );
 
             memset( buf, 0, sizeof( buf ) );
             memset( tmp, 0, sizeof( tmp ) );
@@ -427,17 +510,17 @@
         ctr_drbg_context ctr_drbg;
 
         if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 )
-            exit(1);
+            polarssl_exit(1);
         TIME_AND_TSC( "CTR_DRBG (NOPR)",
                 if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )
-                exit(1) );
+                polarssl_exit(1) );
 
         if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 )
-            exit(1);
+            polarssl_exit(1);
         ctr_drbg_set_prediction_resistance( &ctr_drbg, CTR_DRBG_PR_ON );
         TIME_AND_TSC( "CTR_DRBG (PR)",
                 if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )
-                exit(1) );
+                polarssl_exit(1) );
         ctr_drbg_free( &ctr_drbg );
     }
 #endif
@@ -450,43 +533,43 @@
 
 #if defined(POLARSSL_SHA1_C)
         if( ( md_info = md_info_from_type( POLARSSL_MD_SHA1 ) ) == NULL )
-            exit(1);
+            polarssl_exit(1);
 
         if( hmac_drbg_init( &hmac_drbg, md_info, myrand, NULL, NULL, 0 ) != 0 )
-            exit(1);
+            polarssl_exit(1);
         TIME_AND_TSC( "HMAC_DRBG SHA-1 (NOPR)",
                 if( hmac_drbg_random( &hmac_drbg, buf, BUFSIZE ) != 0 )
-                exit(1) );
+                polarssl_exit(1) );
         hmac_drbg_free( &hmac_drbg );
 
         if( hmac_drbg_init( &hmac_drbg, md_info, myrand, NULL, NULL, 0 ) != 0 )
-            exit(1);
+            polarssl_exit(1);
         hmac_drbg_set_prediction_resistance( &hmac_drbg,
                                              POLARSSL_HMAC_DRBG_PR_ON );
         TIME_AND_TSC( "HMAC_DRBG SHA-1 (PR)",
                 if( hmac_drbg_random( &hmac_drbg, buf, BUFSIZE ) != 0 )
-                exit(1) );
+                polarssl_exit(1) );
         hmac_drbg_free( &hmac_drbg );
 #endif
 
 #if defined(POLARSSL_SHA256_C)
         if( ( md_info = md_info_from_type( POLARSSL_MD_SHA256 ) ) == NULL )
-            exit(1);
+            polarssl_exit(1);
 
         if( hmac_drbg_init( &hmac_drbg, md_info, myrand, NULL, NULL, 0 ) != 0 )
-            exit(1);
+            polarssl_exit(1);
         TIME_AND_TSC( "HMAC_DRBG SHA-256 (NOPR)",
                 if( hmac_drbg_random( &hmac_drbg, buf, BUFSIZE ) != 0 )
-                exit(1) );
+                polarssl_exit(1) );
         hmac_drbg_free( &hmac_drbg );
 
         if( hmac_drbg_init( &hmac_drbg, md_info, myrand, NULL, NULL, 0 ) != 0 )
-            exit(1);
+            polarssl_exit(1);
         hmac_drbg_set_prediction_resistance( &hmac_drbg,
                                              POLARSSL_HMAC_DRBG_PR_ON );
         TIME_AND_TSC( "HMAC_DRBG SHA-256 (PR)",
                 if( hmac_drbg_random( &hmac_drbg, buf, BUFSIZE ) != 0 )
-                exit(1) );
+                polarssl_exit(1) );
         hmac_drbg_free( &hmac_drbg );
 #endif
     }
@@ -495,10 +578,11 @@
 #if defined(POLARSSL_RSA_C) && defined(POLARSSL_GENPRIME)
     if( todo.rsa )
     {
+        int keysize;
         rsa_context rsa;
         for( keysize = 1024; keysize <= 4096; keysize *= 2 )
         {
-            snprintf( title, sizeof( title ), "RSA-%d", keysize );
+            polarssl_snprintf( title, sizeof( title ), "RSA-%d", keysize );
 
             rsa_init( &rsa, RSA_PKCS_V15, 0 );
             rsa_gen_key( &rsa, myrand, NULL, keysize, 65537 );
@@ -519,7 +603,6 @@
 #if defined(POLARSSL_DHM_C) && defined(POLARSSL_BIGNUM_C)
     if( todo.dhm )
     {
-#define DHM_SIZES 3
         int dhm_sizes[DHM_SIZES] = { 1024, 2048, 3072 };
         const char *dhm_P[DHM_SIZES] = {
             POLARSSL_DHM_RFC5114_MODP_1024_P,
@@ -541,22 +624,22 @@
             if( mpi_read_string( &dhm.P, 16, dhm_P[i] ) != 0 ||
                 mpi_read_string( &dhm.G, 16, dhm_G[i] ) != 0 )
             {
-                exit( 1 );
+                polarssl_exit( 1 );
             }
 
             dhm.len = mpi_size( &dhm.P );
             dhm_make_public( &dhm, (int) dhm.len, buf, dhm.len, myrand, NULL );
             if( mpi_copy( &dhm.GY, &dhm.GX ) != 0 )
-                exit( 1 );
+                polarssl_exit( 1 );
 
-            snprintf( title, sizeof( title ), "DHE-%d", dhm_sizes[i] );
+            polarssl_snprintf( title, sizeof( title ), "DHE-%d", dhm_sizes[i] );
             TIME_PUBLIC( title, "handshake",
                     olen = sizeof( buf );
                     ret |= dhm_make_public( &dhm, (int) dhm.len, buf, dhm.len,
                                             myrand, NULL );
                     ret |= dhm_calc_secret( &dhm, buf, &olen, myrand, NULL ) );
 
-            snprintf( title, sizeof( title ), "DH-%d", dhm_sizes[i] );
+            polarssl_snprintf( title, sizeof( title ), "DH-%d", dhm_sizes[i] );
             TIME_PUBLIC( title, "handshake",
                     olen = sizeof( buf );
                     ret |= dhm_calc_secret( &dhm, buf, &olen, myrand, NULL ) );
@@ -582,14 +665,34 @@
             ecdsa_init( &ecdsa );
 
             if( ecdsa_genkey( &ecdsa, curve_info->grp_id, myrand, NULL ) != 0 )
-                exit( 1 );
+                polarssl_exit( 1 );
+            ecp_clear_precomputed( &ecdsa.grp );
 
-            snprintf( title, sizeof( title ), "ECDSA-%s",
+            polarssl_snprintf( title, sizeof( title ), "ECDSA-%s",
                                               curve_info->name );
             TIME_PUBLIC( title, "sign",
                     ret = ecdsa_write_signature( &ecdsa, buf, curve_info->size,
                                                 tmp, &sig_len, myrand, NULL ) );
 
+            ecdsa_free( &ecdsa );
+        }
+
+        for( curve_info = ecp_curve_list();
+             curve_info->grp_id != POLARSSL_ECP_DP_NONE;
+             curve_info++ )
+        {
+            ecdsa_init( &ecdsa );
+
+            if( ecdsa_genkey( &ecdsa, curve_info->grp_id, myrand, NULL ) != 0 ||
+                ecdsa_write_signature( &ecdsa, buf, curve_info->size,
+                                               tmp, &sig_len, myrand, NULL ) != 0 )
+            {
+                polarssl_exit( 1 );
+            }
+            ecp_clear_precomputed( &ecdsa.grp );
+
+            polarssl_snprintf( title, sizeof( title ), "ECDSA-%s",
+                                              curve_info->name );
             TIME_PUBLIC( title, "verify",
                     ret = ecdsa_read_signature( &ecdsa, buf, curve_info->size,
                                                 tmp, sig_len ) );
@@ -603,6 +706,9 @@
     if( todo.ecdh )
     {
         ecdh_context ecdh;
+#if defined(POLARSSL_ECP_DP_M255_ENABLED)
+        mpi z;
+#endif
         const ecp_curve_info *curve_info;
         size_t olen;
 
@@ -617,28 +723,95 @@
                                   myrand, NULL ) != 0 ||
                 ecp_copy( &ecdh.Qp, &ecdh.Q ) != 0 )
             {
-                exit( 1 );
+                polarssl_exit( 1 );
             }
+            ecp_clear_precomputed( &ecdh.grp );
 
-            snprintf( title, sizeof( title ), "ECDHE-%s",
+            polarssl_snprintf( title, sizeof( title ), "ECDHE-%s",
                                               curve_info->name );
             TIME_PUBLIC( title, "handshake",
                     ret |= ecdh_make_public( &ecdh, &olen, buf, sizeof( buf),
                                              myrand, NULL );
                     ret |= ecdh_calc_secret( &ecdh, &olen, buf, sizeof( buf ),
                                              myrand, NULL ) );
+            ecdh_free( &ecdh );
+        }
 
-            snprintf( title, sizeof( title ), "ECDH-%s",
+        /* Curve25519 needs to be handled separately */
+#if defined(POLARSSL_ECP_DP_M255_ENABLED)
+        ecdh_init( &ecdh );
+        mpi_init( &z );
+
+        if( ecp_use_known_dp( &ecdh.grp, POLARSSL_ECP_DP_M255 ) != 0 ||
+            ecdh_gen_public( &ecdh.grp, &ecdh.d, &ecdh.Qp, myrand, NULL ) != 0 )
+        {
+            polarssl_exit( 1 );
+        }
+
+        TIME_PUBLIC(  "ECDHE-Curve25519", "handshake",
+                ret |= ecdh_gen_public( &ecdh.grp, &ecdh.d, &ecdh.Q,
+                                        myrand, NULL );
+                ret |= ecdh_compute_shared( &ecdh.grp, &z, &ecdh.Qp, &ecdh.d,
+                                            myrand, NULL ) );
+
+        ecdh_free( &ecdh );
+        mpi_free( &z );
+#endif
+
+        for( curve_info = ecp_curve_list();
+             curve_info->grp_id != POLARSSL_ECP_DP_NONE;
+             curve_info++ )
+        {
+            ecdh_init( &ecdh );
+
+            if( ecp_use_known_dp( &ecdh.grp, curve_info->grp_id ) != 0 ||
+                ecdh_make_public( &ecdh, &olen, buf, sizeof( buf),
+                                  myrand, NULL ) != 0 ||
+                ecp_copy( &ecdh.Qp, &ecdh.Q ) != 0 ||
+                ecdh_make_public( &ecdh, &olen, buf, sizeof( buf),
+                                  myrand, NULL ) != 0 )
+            {
+                polarssl_exit( 1 );
+            }
+            ecp_clear_precomputed( &ecdh.grp );
+
+            polarssl_snprintf( title, sizeof( title ), "ECDH-%s",
                                               curve_info->name );
             TIME_PUBLIC( title, "handshake",
                     ret |= ecdh_calc_secret( &ecdh, &olen, buf, sizeof( buf ),
                                              myrand, NULL ) );
             ecdh_free( &ecdh );
         }
+
+        /* Curve25519 needs to be handled separately */
+#if defined(POLARSSL_ECP_DP_M255_ENABLED)
+        ecdh_init( &ecdh );
+        mpi_init( &z );
+
+        if( ecp_use_known_dp( &ecdh.grp, POLARSSL_ECP_DP_M255 ) != 0 ||
+            ecdh_gen_public( &ecdh.grp, &ecdh.d, &ecdh.Qp,
+                             myrand, NULL ) != 0 ||
+            ecdh_gen_public( &ecdh.grp, &ecdh.d, &ecdh.Q, myrand, NULL ) != 0 )
+        {
+            polarssl_exit( 1 );
+        }
+
+        TIME_PUBLIC(  "ECDH-Curve25519", "handshake",
+                ret |= ecdh_compute_shared( &ecdh.grp, &z, &ecdh.Qp, &ecdh.d,
+                                            myrand, NULL ) );
+
+        ecdh_free( &ecdh );
+        mpi_free( &z );
+#endif
     }
 #endif
+
     polarssl_printf( "\n" );
 
+#if defined(POLARSSL_MEMORY_BUFFER_ALLOC_C)
+    memory_buffer_alloc_free();
+#endif
+
 #if defined(_WIN32)
     polarssl_printf( "  Press Enter to exit this program.\n" );
     fflush( stdout ); getchar();
diff --git a/programs/test/o_p_test.c b/programs/test/o_p_test.c
index b904a9f..0d1cccf 100644
--- a/programs/test/o_p_test.c
+++ b/programs/test/o_p_test.c
@@ -29,19 +29,18 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <sys/stat.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_PK_PARSE_C) && defined(POLARSSL_FS_IO)
 #include <openssl/rsa.h>
+
 #ifndef OPENSSL_NO_ENGINE
 #include <openssl/engine.h>
 #endif
+
 #include <openssl/pem.h>
 #include <openssl/bio.h>
 
@@ -50,13 +49,17 @@
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#endif
+
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) ||         \
     !defined(POLARSSL_PK_PARSE_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or "
            "POLARSSL_PK_PARSE_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
diff --git a/programs/test/selftest.c b/programs/test/selftest.c
index d2f70d2..edecbb8 100644
--- a/programs/test/selftest.c
+++ b/programs/test/selftest.c
@@ -26,15 +26,6 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
-#if defined(POLARSSL_PLATFORM_C)
-#include "polarssl/platform.h"
-#else
-#define polarssl_printf     printf
-#endif
-
-#include <string.h>
-#include <stdio.h>
-
 #include "polarssl/entropy.h"
 #include "polarssl/hmac_drbg.h"
 #include "polarssl/ctr_drbg.h"
@@ -62,6 +53,16 @@
 #include "polarssl/ecp.h"
 #include "polarssl/timing.h"
 
+#include <stdio.h>
+#include <string.h>
+
+#if defined(POLARSSL_PLATFORM_C)
+#include "polarssl/platform.h"
+#else
+#include <stdio.h>
+#define polarssl_printf     printf
+#endif
+
 #if defined(POLARSSL_MEMORY_BUFFER_ALLOC_C)
 #include "polarssl/memory_buffer_alloc.h"
 #endif
diff --git a/programs/test/ssl_cert_test.c b/programs/test/ssl_cert_test.c
index 037c474..4978603 100644
--- a/programs/test/ssl_cert_test.c
+++ b/programs/test/ssl_cert_test.c
@@ -29,36 +29,37 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #define polarssl_printf     printf
+#define polarssl_snprintf   snprintf
 #endif
 
-#include <string.h>
+#if defined(POLARSSL_RSA_C) && defined(POLARSSL_X509_CRT_PARSE_C) && \
+    defined(POLARSSL_FS_IO) && defined(POLARSSL_X509_CRL_PARSE_C)
+#include "polarssl/certs.h"
+#include "polarssl/x509_crt.h"
+
 #include <stdio.h>
+#include <string.h>
+#endif
+
+#if defined _MSC_VER && !defined snprintf
+#define snprintf _snprintf
+#endif
+
+#define MAX_CLIENT_CERTS    8
 
 #if !defined(POLARSSL_RSA_C) || !defined(POLARSSL_X509_CRT_PARSE_C) || \
     !defined(POLARSSL_FS_IO) || !defined(POLARSSL_X509_CRL_PARSE_C)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_RSA_C and/or POLARSSL_X509_CRT_PARSE_C "
            "POLARSSL_FS_IO and/or POLARSSL_X509_CRL_PARSE_C "
            "not defined.\n");
     return( 0 );
 }
 #else
-
-#include "polarssl/certs.h"
-#include "polarssl/x509_crt.h"
-
-#if defined _MSC_VER && !defined snprintf
-#define snprintf _snprintf
-#endif
-
-
-#define MAX_CLIENT_CERTS    8
-
 const char *client_certificates[MAX_CLIENT_CERTS] =
 {
     "client1.crt",
@@ -83,16 +84,13 @@
     "cert_digest.key"
 };
 
-int main( int argc, char *argv[] )
+int main( void )
 {
     int ret, i;
     x509_crt cacert;
     x509_crl crl;
     char buf[10240];
 
-    ((void) argc);
-    ((void) argv);
-
     x509_crt_init( &cacert );
     x509_crl_init( &crl );
 
@@ -149,7 +147,7 @@
         x509_crt_init( &clicert );
         pk_init( &pk );
 
-        snprintf(name, 512, "ssl/test-ca/%s", client_certificates[i]);
+        polarssl_snprintf(name, 512, "ssl/test-ca/%s", client_certificates[i]);
 
         polarssl_printf( "  . Loading the client certificate %s...", name );
         fflush( stdout );
@@ -198,7 +196,7 @@
         /*
          * 1.5. Load own private key
          */
-        snprintf(name, 512, "ssl/test-ca/%s", client_private_keys[i]);
+        polarssl_snprintf(name, 512, "ssl/test-ca/%s", client_private_keys[i]);
 
         polarssl_printf( "  . Loading the client private key %s...", name );
         fflush( stdout );
diff --git a/programs/test/ssl_test.c b/programs/test/ssl_test.c
index 23e0d3c..49bbd15 100644
--- a/programs/test/ssl_test.c
+++ b/programs/test/ssl_test.c
@@ -29,44 +29,33 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
-#define polarssl_fprintf    fprintf
-#define polarssl_malloc     malloc
+#include <stdio.h>
 #define polarssl_free       free
+#define polarssl_malloc     malloc
+#define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_SSL_TLS_C) && defined(POLARSSL_SSL_SRV_C) && \
+    defined(POLARSSL_SSL_CLI_C) && defined(POLARSSL_NET_C) && \
+    defined(POLARSSL_RSA_C) && defined(POLARSSL_CTR_DRBG_C) && \
+    defined(POLARSSL_X509_CRT_PARSE_C)
 #include "polarssl/net.h"
 #include "polarssl/ssl.h"
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 #include "polarssl/certs.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
 #if defined(POLARSSL_TIMING_C)
 #include "polarssl/timing.h"
 #endif
 
-#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||  \
-    !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_SRV_C) || \
-    !defined(POLARSSL_SSL_CLI_C) || !defined(POLARSSL_NET_C) ||     \
-    !defined(POLARSSL_RSA_C) || !defined(POLARSSL_CTR_DRBG_C) ||    \
-    !defined(POLARSSL_X509_CRT_PARSE_C)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
-           "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_SRV_C and/or "
-           "POLARSSL_SSL_CLI_C and/or POLARSSL_NET_C and/or "
-           "POLARSSL_RSA_C and/or POLARSSL_CTR_DRBG_C and/or "
-           "POLARSSL_X509_CRT_PARSE_C not defined.\n");
-    return( 0 );
-}
-#else
-
 #define OPMODE_NONE             0
 #define OPMODE_CLIENT           1
 #define OPMODE_SERVER           2
@@ -92,6 +81,21 @@
 #define DFL_SESSION_LIFETIME    86400
 #define DFL_FORCE_CIPHER        0
 
+#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||  \
+    !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_SRV_C) || \
+    !defined(POLARSSL_SSL_CLI_C) || !defined(POLARSSL_NET_C) ||     \
+    !defined(POLARSSL_RSA_C) || !defined(POLARSSL_CTR_DRBG_C) ||    \
+    !defined(POLARSSL_X509_CRT_PARSE_C)
+int main( void )
+{
+    polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
+           "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_SRV_C and/or "
+           "POLARSSL_SSL_CLI_C and/or POLARSSL_NET_C and/or "
+           "POLARSSL_RSA_C and/or POLARSSL_CTR_DRBG_C and/or "
+           "POLARSSL_X509_CRT_PARSE_C not defined.\n");
+    return( 0 );
+}
+#else
 int server_fd = -1;
 
 /*
@@ -295,8 +299,8 @@
         }
     }
 
-     read_buf = (unsigned char *) polarssl_malloc( opt->buffer_size );
-    write_buf = (unsigned char *) polarssl_malloc( opt->buffer_size );
+     read_buf = polarssl_malloc( opt->buffer_size );
+    write_buf = polarssl_malloc( opt->buffer_size );
 
     if( read_buf == NULL || write_buf == NULL )
     {
@@ -453,7 +457,7 @@
     "    session_reuse=on/off        default: on (enabled)\n"    \
     "    session_lifetime=%%d (s)     default: 86400\n"          \
     "    force_ciphersuite=<name>    default: all enabled\n"     \
-    " acceptable ciphersuite names:\n" 
+    " acceptable ciphersuite names:\n"
 
 int main( int argc, char *argv[] )
 {
diff --git a/programs/test/udp_proxy.c b/programs/test/udp_proxy.c
index a8cb3c6..778b604 100644
--- a/programs/test/udp_proxy.c
+++ b/programs/test/udp_proxy.c
@@ -47,6 +47,7 @@
 
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 #include <time.h>
 
 /* For select() */
diff --git a/programs/util/pem2der.c b/programs/util/pem2der.c
index 74f7a3e..2c0e585 100644
--- a/programs/util/pem2der.c
+++ b/programs/util/pem2der.c
@@ -29,27 +29,34 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
-#define polarssl_malloc     malloc
+#include <stdio.h>
 #define polarssl_free       free
+#define polarssl_malloc     malloc
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BASE64_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/error.h"
 #include "polarssl/base64.h"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
 #define DFL_FILENAME            "file.pem"
 #define DFL_OUTPUT_FILENAME     "file.der"
 
-#if !defined(POLARSSL_BASE64_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
+#define USAGE \
+    "\n usage: pem2der param=<>...\n"                   \
+    "\n acceptable parameters:\n"                       \
+    "    filename=%%s         default: file.pem\n"      \
+    "    output_file=%%s      default: file.der\n"      \
+    "\n"
 
+#if !defined(POLARSSL_BASE64_C) || !defined(POLARSSL_FS_IO)
+int main( void )
+{
     polarssl_printf("POLARSSL_BASE64_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
@@ -129,7 +136,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( -1 );
@@ -170,13 +177,6 @@
     return( 0 );
 }
 
-#define USAGE \
-    "\n usage: pem2der param=<>...\n"                   \
-    "\n acceptable parameters:\n"                       \
-    "    filename=%%s         default: file.pem\n"      \
-    "    output_file=%%s      default: file.der\n"      \
-    "\n"
-
 int main( int argc, char *argv[] )
 {
     int ret = 0;
diff --git a/programs/util/strerror.c b/programs/util/strerror.c
index c5598fc..e785ffa 100644
--- a/programs/util/strerror.c
+++ b/programs/util/strerror.c
@@ -29,25 +29,25 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
+#if defined(POLARSSL_ERROR_C) || defined(POLARSSL_ERROR_STRERROR_DUMMY)
+#include "polarssl/error.h"
+
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <stdio.h>
-
-#include "polarssl/error.h"
+#endif
 
 #define USAGE \
     "\n usage: strerror <errorcode>\n" \
     "\n where <errorcode> can be a decimal or hexadecimal (starts with 0x or -0x)\n"
 
 #if !defined(POLARSSL_ERROR_C) && !defined(POLARSSL_ERROR_STRERROR_DUMMY)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_ERROR_C and/or POLARSSL_ERROR_STRERROR_DUMMY not defined.\n");
     return( 0 );
 }
diff --git a/programs/x509/cert_app.c b/programs/x509/cert_app.c
index 3eb7d6d..cc36b7c 100644
--- a/programs/x509/cert_app.c
+++ b/programs/x509/cert_app.c
@@ -29,38 +29,26 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
+#include <stdio.h>
 #define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_ENTROPY_C) && \
+    defined(POLARSSL_SSL_TLS_C) && defined(POLARSSL_SSL_CLI_C) && \
+    defined(POLARSSL_NET_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_X509_CRT_PARSE_C) && defined(POLARSSL_FS_IO) && \
+    defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 #include "polarssl/net.h"
 #include "polarssl/ssl.h"
 #include "polarssl/x509.h"
 
-#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||  \
-    !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_CLI_C) || \
-    !defined(POLARSSL_NET_C) || !defined(POLARSSL_RSA_C) ||         \
-    !defined(POLARSSL_X509_CRT_PARSE_C) || !defined(POLARSSL_FS_IO) ||  \
-    !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
-           "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_CLI_C and/or "
-           "POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
-           "POLARSSL_X509_CRT_PARSE_C and/or POLARSSL_FS_IO and/or "
-           "POLARSSL_CTR_DRBG_C not defined.\n");
-    return( 0 );
-}
-#else
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
 
 #define MODE_NONE               0
 #define MODE_FILE               1
@@ -76,6 +64,41 @@
 #define DFL_DEBUG_LEVEL         0
 #define DFL_PERMISSIVE          0
 
+#define USAGE_IO \
+    "    ca_file=%%s          The single file containing the top-level CA(s) you fully trust\n" \
+    "                        default: \"\" (none)\n" \
+    "    crl_file=%%s         The single CRL file you want to use\n" \
+    "                        default: \"\" (none)\n" \
+    "    ca_path=%%s          The path containing the top-level CA(s) you fully trust\n" \
+    "                        default: \"\" (none) (overrides ca_file)\n"
+
+#define USAGE \
+    "\n usage: cert_app param=<>...\n"                  \
+    "\n acceptable parameters:\n"                       \
+    "    mode=file|ssl       default: none\n"           \
+    "    filename=%%s         default: cert.crt\n"      \
+    USAGE_IO                                            \
+    "    server_name=%%s      default: localhost\n"     \
+    "    server_port=%%d      default: 4433\n"          \
+    "    debug_level=%%d      default: 0 (disabled)\n"  \
+    "    permissive=%%d       default: 0 (disabled)\n"  \
+    "\n"
+
+#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_ENTROPY_C) ||  \
+    !defined(POLARSSL_SSL_TLS_C) || !defined(POLARSSL_SSL_CLI_C) || \
+    !defined(POLARSSL_NET_C) || !defined(POLARSSL_RSA_C) ||         \
+    !defined(POLARSSL_X509_CRT_PARSE_C) || !defined(POLARSSL_FS_IO) ||  \
+    !defined(POLARSSL_CTR_DRBG_C)
+int main( void )
+{
+    polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_ENTROPY_C and/or "
+           "POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_CLI_C and/or "
+           "POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
+           "POLARSSL_X509_CRT_PARSE_C and/or POLARSSL_FS_IO and/or "
+           "POLARSSL_CTR_DRBG_C not defined.\n");
+    return( 0 );
+}
+#else
 /*
  * global options
  */
@@ -137,26 +160,6 @@
     return( 0 );
 }
 
-#define USAGE_IO \
-    "    ca_file=%%s          The single file containing the top-level CA(s) you fully trust\n" \
-    "                        default: \"\" (none)\n" \
-    "    crl_file=%%s         The single CRL file you want to use\n" \
-    "                        default: \"\" (none)\n" \
-    "    ca_path=%%s          The path containing the top-level CA(s) you fully trust\n" \
-    "                        default: \"\" (none) (overrides ca_file)\n"
-
-#define USAGE \
-    "\n usage: cert_app param=<>...\n"                  \
-    "\n acceptable parameters:\n"                       \
-    "    mode=file|ssl       default: none\n"           \
-    "    filename=%%s         default: cert.crt\n"      \
-    USAGE_IO                                            \
-    "    server_name=%%s      default: localhost\n"     \
-    "    server_port=%%d      default: 4433\n"          \
-    "    debug_level=%%d      default: 0 (disabled)\n"  \
-    "    permissive=%%d       default: 0 (disabled)\n"  \
-    "\n"
-
 int main( int argc, char *argv[] )
 {
     int ret = 0, server_fd;
@@ -348,6 +351,8 @@
             cur = cur->next;
         }
 
+        ret = 0;
+
         /*
          * 1.3 Verify the certificate
          */
diff --git a/programs/x509/cert_req.c b/programs/x509/cert_req.c
index 3b67f65..d8527c6 100644
--- a/programs/x509/cert_req.c
+++ b/programs/x509/cert_req.c
@@ -29,33 +29,22 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_X509_CSR_WRITE_C) && defined(POLARSSL_FS_IO) && \
+    defined(POLARSSL_PK_PARSE_C) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_CTR_DRBG_C)
 #include "polarssl/x509_csr.h"
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 #include "polarssl/error.h"
 
-#if !defined(POLARSSL_X509_CSR_WRITE_C) || !defined(POLARSSL_FS_IO) ||  \
-    !defined(POLARSSL_PK_PARSE_C) ||                                    \
-    !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_CTR_DRBG_C)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf( "POLARSSL_X509_CSR_WRITE_C and/or POLARSSL_FS_IO and/or "
-            "POLARSSL_PK_PARSE_C and/or "
-            "POLARSSL_ENTROPY_C and/or POLARSSL_CTR_DRBG_C "
-            "not defined.\n");
-    return( 0 );
-}
-#else
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
 
 #define DFL_FILENAME            "keyfile.key"
 #define DFL_DEBUG_LEVEL         0
@@ -64,6 +53,45 @@
 #define DFL_KEY_USAGE           0
 #define DFL_NS_CERT_TYPE        0
 
+#define USAGE \
+    "\n usage: cert_req param=<>...\n"                  \
+    "\n acceptable parameters:\n"                       \
+    "    filename=%%s         default: keyfile.key\n"   \
+    "    debug_level=%%d      default: 0 (disabled)\n"  \
+    "    output_file=%%s      default: cert.req\n"      \
+    "    subject_name=%%s     default: CN=Cert,O=mbed TLS,C=UK\n"   \
+    "    key_usage=%%s        default: (empty)\n"       \
+    "                        Comma-separated-list of values:\n"     \
+    "                          digital_signature\n"     \
+    "                          non_repudiation\n"       \
+    "                          key_encipherment\n"      \
+    "                          data_encipherment\n"     \
+    "                          key_agreement\n"         \
+    "                          key_certificate_sign\n"  \
+    "                          crl_sign\n"              \
+    "    ns_cert_type=%%s     default: (empty)\n"       \
+    "                        Comma-separated-list of values:\n"     \
+    "                          ssl_client\n"            \
+    "                          ssl_server\n"            \
+    "                          email\n"                 \
+    "                          object_signing\n"        \
+    "                          ssl_ca\n"                \
+    "                          email_ca\n"              \
+    "                          object_signing_ca\n"     \
+    "\n"
+
+#if !defined(POLARSSL_X509_CSR_WRITE_C) || !defined(POLARSSL_FS_IO) ||  \
+    !defined(POLARSSL_PK_PARSE_C) ||                                    \
+    !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_CTR_DRBG_C)
+int main( void )
+{
+    polarssl_printf( "POLARSSL_X509_CSR_WRITE_C and/or POLARSSL_FS_IO and/or "
+            "POLARSSL_PK_PARSE_C and/or "
+            "POLARSSL_ENTROPY_C and/or POLARSSL_CTR_DRBG_C "
+            "not defined.\n");
+    return( 0 );
+}
+#else
 /*
  * global options
  */
@@ -106,33 +134,6 @@
     return( 0 );
 }
 
-#define USAGE \
-    "\n usage: cert_req param=<>...\n"                  \
-    "\n acceptable parameters:\n"                       \
-    "    filename=%%s         default: keyfile.key\n"   \
-    "    debug_level=%%d      default: 0 (disabled)\n"  \
-    "    output_file=%%s      default: cert.req\n"      \
-    "    subject_name=%%s     default: CN=Cert,O=mbed TLS,C=UK\n"   \
-    "    key_usage=%%s        default: (empty)\n"       \
-    "                        Comma-separated-list of values:\n"     \
-    "                          digital_signature\n"     \
-    "                          non_repudiation\n"       \
-    "                          key_encipherment\n"      \
-    "                          data_encipherment\n"     \
-    "                          key_agreement\n"         \
-    "                          key_certificate_sign\n"  \
-    "                          crl_sign\n"              \
-    "    ns_cert_type=%%s     default: (empty)\n"       \
-    "                        Comma-separated-list of values:\n"     \
-    "                          ssl_client\n"            \
-    "                          ssl_server\n"            \
-    "                          email\n"                 \
-    "                          object_signing\n"        \
-    "                          ssl_ca\n"                \
-    "                          email_ca\n"              \
-    "                          object_signing_ca\n"     \
-    "\n"
-
 int main( int argc, char *argv[] )
 {
     int ret = 0;
@@ -149,7 +150,7 @@
      * Set to sane values
      */
     x509write_csr_init( &req );
-    x509write_csr_set_md_alg( &req, POLARSSL_MD_SHA1 );
+    x509write_csr_set_md_alg( &req, POLARSSL_MD_SHA256 );
     pk_init( &key );
     memset( buf, 0, sizeof( buf ) );
 
diff --git a/programs/x509/cert_write.c b/programs/x509/cert_write.c
index eed12cf..45e2456 100644
--- a/programs/x509/cert_write.c
+++ b/programs/x509/cert_write.c
@@ -29,36 +29,34 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-#if !defined(POLARSSL_X509_CRT_WRITE_C) ||                                  \
-    !defined(POLARSSL_X509_CRT_PARSE_C) || !defined(POLARSSL_FS_IO) ||      \
-    !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_CTR_DRBG_C) ||        \
-    !defined(POLARSSL_ERROR_C)
-int main( int argc, char *argv[] )
-{
-    ((void) argc);
-    ((void) argv);
-
-    polarssl_printf( "POLARSSL_X509_CRT_WRITE_C and/or POLARSSL_X509_CRT_PARSE_C and/or "
-            "POLARSSL_FS_IO and/or "
-            "POLARSSL_ENTROPY_C and/or POLARSSL_CTR_DRBG_C and/or "
-            "POLARSSL_ERROR_C not defined.\n");
-    return( 0 );
-}
-#else
-
+#if defined(POLARSSL_X509_CRT_WRITE_C) && \
+    defined(POLARSSL_X509_CRT_PARSE_C) && defined(POLARSSL_FS_IO) && \
+    defined(POLARSSL_ENTROPY_C) && defined(POLARSSL_CTR_DRBG_C) && \
+    defined(POLARSSL_ERROR_C)
 #include "polarssl/x509_crt.h"
 #include "polarssl/x509_csr.h"
 #include "polarssl/entropy.h"
 #include "polarssl/ctr_drbg.h"
 #include "polarssl/error.h"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
+#if defined(POLARSSL_X509_CSR_PARSE_C)
+#define USAGE_CSR                                                           \
+    "    request_file=%%s     default: (empty)\n"                           \
+    "                        If request_file is specified, subject_key,\n"  \
+    "                        subject_pwd and subject_name are ignored!\n"
+#else
+#define USAGE_CSR ""
+#endif /* POLARSSL_X509_CSR_PARSE_C */
+
 #define DFL_ISSUER_CRT          ""
 #define DFL_REQUEST_FILE        ""
 #define DFL_SUBJECT_KEY         "subject.key"
@@ -77,6 +75,64 @@
 #define DFL_KEY_USAGE           0
 #define DFL_NS_CERT_TYPE        0
 
+#define USAGE \
+    "\n usage: cert_write param=<>...\n"                \
+    "\n acceptable parameters:\n"                       \
+    USAGE_CSR                                           \
+    "    subject_key=%%s      default: subject.key\n"   \
+    "    subject_pwd=%%s      default: (empty)\n"       \
+    "    subject_name=%%s     default: CN=Cert,O=mbed TLS,C=UK\n"   \
+    "\n"                                                \
+    "    issuer_crt=%%s       default: (empty)\n"       \
+    "                        If issuer_crt is specified, issuer_name is\n"  \
+    "                        ignored!\n"                \
+    "    issuer_name=%%s      default: CN=CA,O=mbed TLS,C=UK\n"     \
+    "\n"                                                \
+    "    selfsign=%%d         default: 0 (false)\n"     \
+    "                        If selfsign is enabled, issuer_name and\n" \
+    "                        issuer_key are required (issuer_crt and\n" \
+    "                        subject_* are ignored\n"   \
+    "    issuer_key=%%s       default: ca.key\n"        \
+    "    issuer_pwd=%%s       default: (empty)\n"       \
+    "    output_file=%%s      default: cert.crt\n"      \
+    "    serial=%%s           default: 1\n"             \
+    "    not_before=%%s       default: 20010101000000\n"\
+    "    not_after=%%s        default: 20301231235959\n"\
+    "    is_ca=%%d            default: 0 (disabled)\n"  \
+    "    max_pathlen=%%d      default: -1 (none)\n"     \
+    "    key_usage=%%s        default: (empty)\n"       \
+    "                        Comma-separated-list of values:\n"     \
+    "                          digital_signature\n"     \
+    "                          non_repudiation\n"       \
+    "                          key_encipherment\n"      \
+    "                          data_encipherment\n"     \
+    "                          key_agreement\n"         \
+    "                          key_certificate_sign\n"  \
+    "                          crl_sign\n"              \
+    "    ns_cert_type=%%s     default: (empty)\n"       \
+    "                        Comma-separated-list of values:\n"     \
+    "                          ssl_client\n"            \
+    "                          ssl_server\n"            \
+    "                          email\n"                 \
+    "                          object_signing\n"        \
+    "                          ssl_ca\n"                \
+    "                          email_ca\n"              \
+    "                          object_signing_ca\n"     \
+    "\n"
+
+#if !defined(POLARSSL_X509_CRT_WRITE_C) ||                                  \
+    !defined(POLARSSL_X509_CRT_PARSE_C) || !defined(POLARSSL_FS_IO) ||      \
+    !defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_CTR_DRBG_C) ||        \
+    !defined(POLARSSL_ERROR_C)
+int main( void )
+{
+    polarssl_printf( "POLARSSL_X509_CRT_WRITE_C and/or POLARSSL_X509_CRT_PARSE_C and/or "
+            "POLARSSL_FS_IO and/or "
+            "POLARSSL_ENTROPY_C and/or POLARSSL_CTR_DRBG_C and/or "
+            "POLARSSL_ERROR_C not defined.\n");
+    return( 0 );
+}
+#else
 /*
  * global options
  */
@@ -130,60 +186,6 @@
     return( 0 );
 }
 
-#if defined(POLARSSL_X509_CSR_PARSE_C)
-#define USAGE_CSR                                                           \
-    "    request_file=%%s     default: (empty)\n"                           \
-    "                        If request_file is specified, subject_key,\n"  \
-    "                        subject_pwd and subject_name are ignored!\n"
-#else
-#define USAGE_CSR ""
-#endif /* POLARSSL_X509_CSR_PARSE_C */
-
-#define USAGE \
-    "\n usage: cert_write param=<>...\n"                \
-    "\n acceptable parameters:\n"                       \
-    USAGE_CSR                                           \
-    "    subject_key=%%s      default: subject.key\n"   \
-    "    subject_pwd=%%s      default: (empty)\n"       \
-    "    subject_name=%%s     default: CN=Cert,O=mbed TLS,C=UK\n"   \
-    "\n"                                                \
-    "    issuer_crt=%%s       default: (empty)\n"       \
-    "                        If issuer_crt is specified, issuer_name is\n"  \
-    "                        ignored!\n"                \
-    "    issuer_name=%%s      default: CN=CA,O=mbed TLS,C=UK\n"     \
-    "\n"                                                \
-    "    selfsign=%%d         default: 0 (false)\n"     \
-    "                        If selfsign is enabled, issuer_name and\n" \
-    "                        issuer_key are required (issuer_crt and\n" \
-    "                        subject_* are ignored\n"   \
-    "    issuer_key=%%s       default: ca.key\n"        \
-    "    issuer_pwd=%%s       default: (empty)\n"       \
-    "    output_file=%%s      default: cert.crt\n"      \
-    "    serial=%%s           default: 1\n"             \
-    "    not_before=%%s       default: 20010101000000\n"\
-    "    not_after=%%s        default: 20301231235959\n"\
-    "    is_ca=%%d            default: 0 (disabled)\n"  \
-    "    max_pathlen=%%d      default: -1 (none)\n"     \
-    "    key_usage=%%s        default: (empty)\n"       \
-    "                        Comma-separated-list of values:\n"     \
-    "                          digital_signature\n"     \
-    "                          non_repudiation\n"       \
-    "                          key_encipherment\n"      \
-    "                          data_encipherment\n"     \
-    "                          key_agreement\n"         \
-    "                          key_certificate_sign\n"  \
-    "                          crl_sign\n"              \
-    "    ns_cert_type=%%s     default: (empty)\n"       \
-    "                        Comma-separated-list of values:\n"     \
-    "                          ssl_client\n"            \
-    "                          ssl_server\n"            \
-    "                          email\n"                 \
-    "                          object_signing\n"        \
-    "                          ssl_ca\n"                \
-    "                          email_ca\n"              \
-    "                          object_signing_ca\n"     \
-    "\n"
-
 int main( int argc, char *argv[] )
 {
     int ret = 0;
@@ -209,7 +211,7 @@
      * Set to sane values
      */
     x509write_crt_init( &crt );
-    x509write_crt_set_md_alg( &crt, POLARSSL_MD_SHA1 );
+    x509write_crt_set_md_alg( &crt, POLARSSL_MD_SHA256 );
     pk_init( &loaded_issuer_key );
     pk_init( &loaded_subject_key );
     mpi_init( &serial );
diff --git a/programs/x509/crl_app.c b/programs/x509/crl_app.c
index 4370227..8354391 100644
--- a/programs/x509/crl_app.c
+++ b/programs/x509/crl_app.c
@@ -29,31 +29,37 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_X509_CRL_PARSE_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/x509_crl.h"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
+#define DFL_FILENAME            "crl.pem"
+#define DFL_DEBUG_LEVEL         0
+
+#define USAGE \
+    "\n usage: crl_app param=<>...\n"                   \
+    "\n acceptable parameters:\n"                       \
+    "    filename=%%s         default: crl.pem\n"      \
+    "\n"
+
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) ||  \
     !defined(POLARSSL_X509_CRL_PARSE_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or "
            "POLARSSL_X509_CRL_PARSE_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
 #else
-
-#define DFL_FILENAME            "crl.pem"
-#define DFL_DEBUG_LEVEL         0
-
 /*
  * global options
  */
@@ -62,12 +68,6 @@
     const char *filename;       /* filename of the certificate file     */
 } opt;
 
-#define USAGE \
-    "\n usage: crl_app param=<>...\n"                   \
-    "\n acceptable parameters:\n"                       \
-    "    filename=%%s         default: crl.pem\n"      \
-    "\n"
-
 int main( int argc, char *argv[] )
 {
     int ret = 0;
diff --git a/programs/x509/req_app.c b/programs/x509/req_app.c
index a4be7e6..0b070fc 100644
--- a/programs/x509/req_app.c
+++ b/programs/x509/req_app.c
@@ -29,31 +29,37 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
 #define polarssl_printf     printf
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_BIGNUM_C) && defined(POLARSSL_RSA_C) && \
+    defined(POLARSSL_X509_CSR_PARSE_C) && defined(POLARSSL_FS_IO)
 #include "polarssl/x509_csr.h"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
+#define DFL_FILENAME            "cert.req"
+#define DFL_DEBUG_LEVEL         0
+
+#define USAGE \
+    "\n usage: req_app param=<>...\n"                   \
+    "\n acceptable parameters:\n"                       \
+    "    filename=%%s         default: cert.req\n"      \
+    "\n"
+
 #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) ||  \
     !defined(POLARSSL_X509_CSR_PARSE_C) || !defined(POLARSSL_FS_IO)
-int main( int argc, char *argv[] )
+int main( void )
 {
-    ((void) argc);
-    ((void) argv);
-
     polarssl_printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or "
            "POLARSSL_X509_CSR_PARSE_C and/or POLARSSL_FS_IO not defined.\n");
     return( 0 );
 }
 #else
-
-#define DFL_FILENAME            "cert.req"
-#define DFL_DEBUG_LEVEL         0
-
 /*
  * global options
  */
@@ -62,12 +68,6 @@
     const char *filename;       /* filename of the certificate request  */
 } opt;
 
-#define USAGE \
-    "\n usage: req_app param=<>...\n"                   \
-    "\n acceptable parameters:\n"                       \
-    "    filename=%%s         default: cert.req\n"      \
-    "\n"
-
 int main( int argc, char *argv[] )
 {
     int ret = 0;
diff --git a/scripts/bump_version.sh b/scripts/bump_version.sh
index ae74451..64af2dc 100755
--- a/scripts/bump_version.sh
+++ b/scripts/bump_version.sh
@@ -56,7 +56,7 @@
   mv tmp library/CMakeLists.txt
 
   [ $VERBOSE ] && echo "Bumping SOVERSION in library/Makefile"
-  sed -e "s/SONAME=libpolarssl.so.[0-9]\+/SONAME=libpolarssl.so.$SOVERSION/g" -e "s/DLEXT=so.[0-9]\+/DLEXT=so.$SOVERSION/g" < library/Makefile > tmp
+  sed -e "s/SOEXT=so.[0-9]\+/SOEXT=so.$SOVERSION/g" < library/Makefile > tmp
   mv tmp library/Makefile
 fi
 
diff --git a/scripts/data_files/error.fmt b/scripts/data_files/error.fmt
index b7bfbf2..eeefd7b 100644
--- a/scripts/data_files/error.fmt
+++ b/scripts/data_files/error.fmt
@@ -28,14 +28,20 @@
 
 #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)
 
-HEADER_INCLUDED
 #include <stdio.h>
-#include <string.h>
 
+HEADER_INCLUDED
 #if defined(_MSC_VER) && !defined  snprintf && !defined(EFIX64) && \
     !defined(EFI32)
 #define  snprintf  _snprintf
@@ -67,7 +73,7 @@
         // 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;
@@ -85,7 +91,7 @@
         if( buflen - len < 5 )
             return;
 
-        snprintf( buf + len, buflen - len, " : " );
+        polarssl_snprintf( buf + len, buflen - len, " : " );
 
         buf += len + 3;
         buflen -= len + 3;
@@ -100,7 +106,7 @@
     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)
@@ -114,8 +120,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/scripts/ecc-heap.sh b/scripts/ecc-heap.sh
new file mode 100755
index 0000000..4f88a44
--- /dev/null
+++ b/scripts/ecc-heap.sh
@@ -0,0 +1,74 @@
+#!/bin/sh
+
+# Measure heap usage (and perfomance) of ECC operations with various values of
+# the relevant tunable compile-time parameters.
+#
+# Usage (preferably on a 32-bit platform):
+# cmake -D CMAKE_BUILD_TYPE=Release .
+# scripts/ecc-heap.sh | tee ecc-heap.log
+
+set -eu
+
+CONFIG_H='include/polarssl/config.h'
+
+if [ -r $CONFIG_H ]; then :; else
+    echo "$CONFIG_H not found" >&2
+    exit 1
+fi
+
+if grep -i cmake Makefile >/dev/null; then :; else
+    echo "Needs Cmake" >&2
+    exit 1
+fi
+
+if git status | grep -F $CONFIG_H >/dev/null 2>&1; then
+    echo "config.h not clean" >&2
+    exit 1
+fi
+
+CONFIG_BAK=${CONFIG_H}.bak
+cp $CONFIG_H $CONFIG_BAK
+
+cat << EOF >$CONFIG_H
+#define POLARSSL_PLATFORM_C
+#define POLARSSL_PLATFORM_MEMORY
+#define POLARSSL_MEMORY_BUFFER_ALLOC_C
+#define POLARSSL_MEMORY_DEBUG
+
+#define POLARSSL_TIMING_C
+
+#define POLARSSL_BIGNUM_C
+#define POLARSSL_ECP_C
+#define POLARSSL_ASN1_PARSE_C
+#define POLARSSL_ASN1_WRITE_C
+#define POLARSSL_ECDSA_C
+#define POLARSSL_ECDH_C
+
+#define POLARSSL_ECP_DP_SECP192R1_ENABLED
+#define POLARSSL_ECP_DP_SECP224R1_ENABLED
+#define POLARSSL_ECP_DP_SECP256R1_ENABLED
+#define POLARSSL_ECP_DP_SECP384R1_ENABLED
+#define POLARSSL_ECP_DP_SECP521R1_ENABLED
+#define POLARSSL_ECP_DP_M255_ENABLED
+
+#include "check_config.h"
+
+//#define POLARSSL_ECP_WINDOW_SIZE            6
+//#define POLARSSL_ECP_FIXED_POINT_OPTIM      1
+EOF
+
+for F in 0 1; do
+    for W in 2 3 4 5 6; do
+        scripts/config.pl set POLARSSL_ECP_WINDOW_SIZE $W
+        scripts/config.pl set POLARSSL_ECP_FIXED_POINT_OPTIM $F
+        make benchmark >/dev/null 2>&1
+        echo "fixed point optim = $F, max window size = $W"
+        echo "--------------------------------------------"
+        programs/test/benchmark
+    done
+done
+
+# cleanup
+
+mv $CONFIG_BAK $CONFIG_H
+make clean
diff --git a/scripts/generate_errors.pl b/scripts/generate_errors.pl
index 04591b2..c0d9685 100755
--- a/scripts/generate_errors.pl
+++ b/scripts/generate_errors.pl
@@ -152,14 +152,14 @@
     {
         ${$code_check} .= "${white_space}if( use_ret == -($error_name) )\n".
                           "${white_space}\{\n".
-                          "${white_space}    snprintf( buf, buflen, \"$module_name - $description\" );\n".
+                          "${white_space}    polarssl_snprintf( buf, buflen, \"$module_name - $description\" );\n".
                           "${white_space}    return;\n".
                           "${white_space}}\n"
     }
     else
     {
         ${$code_check} .= "${white_space}if( use_ret == -($error_name) )\n".
-                          "${white_space}    snprintf( buf, buflen, \"$module_name - $description\" );\n"
+                          "${white_space}    polarssl_snprintf( buf, buflen, \"$module_name - $description\" );\n"
     }
 };
 
diff --git a/scripts/massif_max.pl b/scripts/massif_max.pl
new file mode 100755
index 0000000..d1ce4ca
--- /dev/null
+++ b/scripts/massif_max.pl
@@ -0,0 +1,33 @@
+#!/usr/bin/perl
+
+# Parse a massif.out.xxx file and output peak total memory usage
+
+use warnings;
+use strict;
+
+use utf8;
+use open qw(:std utf8);
+
+die unless @ARGV == 1;
+
+my @snaps;
+open my $fh, '<', $ARGV[0] or die;
+{ local $/ = 'snapshot='; @snaps = <$fh>; }
+close $fh or die;
+
+my ($max, $max_heap, $max_he, $max_stack) = (0, 0, 0, 0);
+for (@snaps)
+{
+    my ($heap, $heap_extra, $stack) = m{
+        mem_heap_B=(\d+)\n
+        mem_heap_extra_B=(\d+)\n
+        mem_stacks_B=(\d+)
+    }xm;
+    next unless defined $heap;
+    my $total = $heap + $heap_extra + $stack;
+    if( $total > $max ) {
+        ($max, $max_heap, $max_he, $max_stack) = ($total, $heap, $heap_extra, $stack);
+    }
+}
+
+printf "$max (heap $max_heap+$max_he, stack $max_stack)\n";
diff --git a/scripts/memory.sh b/scripts/memory.sh
new file mode 100755
index 0000000..710ee96
--- /dev/null
+++ b/scripts/memory.sh
@@ -0,0 +1,119 @@
+#!/bin/sh
+
+# Measure memory usage of a minimal client using a small configuration
+# Currently hardwired to ccm-psk and suite-b, may be expanded later
+#
+# Use different build options for measuring executable size and memory usage,
+# since for memory we want debug information.
+
+set -eu
+
+CONFIG_H='include/polarssl/config.h'
+
+CLIENT='mini_client'
+
+CFLAGS_EXEC=-fno-asynchronous-unwind-tables
+CFLAGS_MEM=-g3
+
+if [ -r $CONFIG_H ]; then :; else
+    echo "$CONFIG_H not found" >&2
+    exit 1
+fi
+
+if grep -i cmake Makefile >/dev/null; then
+    echo "Not compatible with CMake" >&2
+    exit 1
+fi
+
+if git status | grep -F $CONFIG_H >/dev/null 2>&1; then
+    echo "config.h not clean" >&2
+    exit 1
+fi
+
+# make measurements with one configuration
+# usage: do_config <name> <unset-list> <server-args>
+do_config()
+{
+    NAME=$1
+    UNSET_LIST=$2
+    SERVER_ARGS=$3
+
+    echo ""
+    echo "config-$NAME:"
+    cp configs/config-$NAME.h $CONFIG_H
+    scripts/config.pl unset POLARSSL_SSL_SRV_C
+
+    for FLAG in $UNSET_LIST; do
+        scripts/config.pl unset $FLAG
+    done
+
+    printf "    Executable size... "
+
+    make clean
+    CFLAGS=$CFLAGS_EXEC make OFLAGS=-Os lib >/dev/null 2>&1
+    cd programs
+    CFLAGS=$CFLAGS_EXEC make OFLAGS=-Os ssl/$CLIENT >/dev/null
+    strip ssl/$CLIENT
+    stat -f '%z' ssl/$CLIENT
+    cd ..
+
+    printf "    Peak ram usage... "
+
+    make clean
+    CFLAGS=$CFLAGS_MEM make OFLAGS=-Os lib >/dev/null 2>&1
+    cd programs
+    CFLAGS=$CFLAGS_MEM make OFLAGS=-Os ssl/$CLIENT >/dev/null
+    cd ..
+
+    ./ssl_server2 $SERVER_ARGS >/dev/null &
+    SRV_PID=$!
+    sleep 1;
+
+    if valgrind --tool=massif --stacks=yes programs/ssl/$CLIENT >/dev/null 2>&1
+    then
+        FAILED=0
+    else
+        echo "client failed" >&2
+        FAILED=1
+    fi
+
+    kill $SRV_PID
+    wait $SRV_PID
+
+    scripts/massif_max.pl massif.out.*
+    mv massif.out.* massif-$NAME.$$
+}
+
+# preparation
+
+CONFIG_BAK=${CONFIG_H}.bak
+cp $CONFIG_H $CONFIG_BAK
+
+rm -f massif.out.*
+
+printf "building server... "
+
+make clean
+make lib >/dev/null 2>&1
+(cd programs && make ssl/ssl_server2) >/dev/null
+cp programs/ssl/ssl_server2 .
+
+echo "done"
+
+# actual measurements
+
+do_config   "ccm-psk-tls1_2" \
+            "" \
+            "psk=000102030405060708090A0B0C0D0E0F"
+
+do_config   "suite-b" \
+            "POLARSSL_BASE64_C POLARSSL_PEM_PARSE_C POLARSSL_CERTS_C" \
+            ""
+
+# cleanup
+
+mv $CONFIG_BAK $CONFIG_H
+make clean
+rm ssl_server2
+
+exit $FAILED
diff --git a/scripts/rm-malloc-cast.cocci b/scripts/rm-malloc-cast.cocci
new file mode 100644
index 0000000..04893d9
--- /dev/null
+++ b/scripts/rm-malloc-cast.cocci
@@ -0,0 +1,7 @@
+@rm_malloc_cast@
+expression x, n;
+type T;
+@@
+  x =
+- (T *)
+  polarssl_malloc(n)
diff --git a/tests/Makefile b/tests/Makefile
index 0bd6ee9..408e953 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -7,22 +7,36 @@
 			-Wno-unused-function -Wno-unused-value
 
 OFLAGS	= -O2
-LDFLAGS	+= -L../library -lmbedtls $(SYS_LDFLAGS)
+LDFLAGS	+= -L../library -lmbedtls$(SHARED_SUFFIX) $(SYS_LDFLAGS)
+DLEXT=so
 
 ifndef SHARED
 DEP=../library/libmbedtls.a
 CHECK_PRELOAD=
 else
-DEP=../library/libmbedtls.so
-CHECK_PRELOAD= LD_PRELOAD=../library/libmbedtls.so
+DEP=../library/libmbedtls.$(DLEXT)
+CHECK_PRELOAD= LD_PRELOAD=../library/libmbedtls.$(DLEXT)
 endif
 
 ifdef DEBUG
 CFLAGS += -g3
 endif
 
+#
+# if we running on Windows build
+# for Windows
+#
 ifdef WINDOWS
+WINDOWS_BUILD=1
+endif
+
+ifdef WINDOWS_BUILD
+DLEXT=dll
+EXEXT=.exe
 LDFLAGS += -lws2_32
+ifdef SHARED
+SHARED_SUFFIX=.$(DLEXT)
+endif
 endif
 
 # Zlib shared library extensions:
@@ -30,45 +44,45 @@
 LDFLAGS += -lz
 endif
 
-APPS =	test_suite_aes.ecb		test_suite_aes.cbc		\
-		test_suite_aes.cfb		test_suite_aes.rest		\
-		test_suite_arc4			test_suite_asn1write	\
-		test_suite_base64		test_suite_blowfish		\
-		test_suite_camellia		test_suite_ccm			\
-		test_suite_cipher.aes							\
-		test_suite_cipher.arc4	test_suite_cipher.ccm	\
-		test_suite_cipher.gcm							\
-		test_suite_cipher.blowfish						\
-		test_suite_cipher.camellia						\
-		test_suite_cipher.des	test_suite_cipher.null	\
-		test_suite_cipher.padding						\
-		test_suite_ctr_drbg		test_suite_debug		\
-		test_suite_des			test_suite_dhm			\
-		test_suite_ecdh			test_suite_ecdsa		\
-		test_suite_ecp									\
-		test_suite_error		test_suite_entropy		\
-		test_suite_gcm.aes128_de						\
-		test_suite_gcm.aes192_de						\
-		test_suite_gcm.aes256_de						\
-		test_suite_gcm.aes128_en						\
-		test_suite_gcm.aes192_en						\
-		test_suite_gcm.aes256_en						\
-		test_suite_gcm.camellia	test_suite_hmac_shax	\
-		test_suite_hmac_drbg.misc						\
-		test_suite_hmac_drbg.no_reseed					\
-		test_suite_hmac_drbg.nopr						\
-		test_suite_hmac_drbg.pr							\
-		test_suite_md			test_suite_mdx			\
-		test_suite_memory_buffer_alloc					\
-		test_suite_mpi			test_suite_pbkdf2		\
-		test_suite_pem									\
-		test_suite_pkcs1_v21	test_suite_pkcs5		\
-		test_suite_pkparse		test_suite_pkwrite		\
-		test_suite_pk									\
-		test_suite_rsa			test_suite_shax			\
-		test_suite_ssl									\
-		test_suite_x509parse	test_suite_x509write	\
-		test_suite_xtea			test_suite_version
+APPS =	test_suite_aes.ecb$(EXEXT)	test_suite_aes.cbc$(EXEXT)	\
+	test_suite_aes.cfb$(EXEXT)	test_suite_aes.rest$(EXEXT)	\
+	test_suite_arc4$(EXEXT)		test_suite_asn1write$(EXEXT)	\
+	test_suite_base64$(EXEXT)	test_suite_blowfish$(EXEXT)	\
+	test_suite_camellia$(EXEXT)	test_suite_ccm$(EXEXT)		\
+	test_suite_cipher.aes$(EXEXT)					\
+	test_suite_cipher.arc4$(EXEXT)	test_suite_cipher.ccm$(EXEXT)	\
+	test_suite_cipher.gcm$(EXEXT)					\
+	test_suite_cipher.blowfish$(EXEXT)				\
+	test_suite_cipher.camellia$(EXEXT)				\
+	test_suite_cipher.des$(EXEXT)	test_suite_cipher.null$(EXEXT)	\
+	test_suite_cipher.padding$(EXEXT)				\
+	test_suite_ctr_drbg$(EXEXT)	test_suite_debug$(EXEXT)	\
+	test_suite_des$(EXEXT)		test_suite_dhm$(EXEXT)		\
+	test_suite_ecdh$(EXEXT)		test_suite_ecdsa$(EXEXT)	\
+	test_suite_ecp$(EXEXT)						\
+	test_suite_error$(EXEXT)	test_suite_entropy$(EXEXT)	\
+	test_suite_gcm.aes128_de$(EXEXT)				\
+	test_suite_gcm.aes192_de$(EXEXT)				\
+	test_suite_gcm.aes256_de$(EXEXT)				\
+	test_suite_gcm.aes128_en$(EXEXT)				\
+	test_suite_gcm.aes192_en$(EXEXT)				\
+	test_suite_gcm.aes256_en$(EXEXT)				\
+	test_suite_gcm.camellia$(EXEXT)	test_suite_hmac_shax$(EXEXT)	\
+	test_suite_hmac_drbg.misc$(EXEXT)				\
+	test_suite_hmac_drbg.no_reseed$(EXEXT)				\
+	test_suite_hmac_drbg.nopr$(EXEXT)				\
+	test_suite_hmac_drbg.pr$(EXEXT)					\
+	test_suite_md$(EXEXT)		test_suite_mdx$(EXEXT)		\
+	test_suite_memory_buffer_alloc$(EXEXT)				\
+	test_suite_mpi$(EXEXT)		test_suite_pbkdf2$(EXEXT)	\
+	test_suite_pem$(EXEXT)						\
+	test_suite_pkcs1_v21$(EXEXT)	test_suite_pkcs5$(EXEXT)	\
+	test_suite_pkparse$(EXEXT)	test_suite_pkwrite$(EXEXT)	\
+	test_suite_pk$(EXEXT)						\
+	test_suite_rsa$(EXEXT)		test_suite_shax$(EXEXT)		\
+	test_suite_ssl$(EXEXT)						\
+	test_suite_x509parse$(EXEXT)	test_suite_x509write$(EXEXT)	\
+	test_suite_xtea$(EXEXT)		test_suite_version$(EXEXT)
 
 .SILENT:
 
@@ -174,237 +188,237 @@
 	echo   "  Generate	$@"
 	scripts/generate_code.pl suites $* $*
 
-test_suite_aes.ecb: test_suite_aes.ecb.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_aes.ecb$(EXEXT): test_suite_aes.ecb.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_aes.cbc: test_suite_aes.cbc.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_aes.cbc$(EXEXT): test_suite_aes.cbc.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_aes.cfb: test_suite_aes.cfb.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_aes.cfb$(EXEXT): test_suite_aes.cfb.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_aes.rest: test_suite_aes.rest.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_aes.rest$(EXEXT): test_suite_aes.rest.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_arc4: test_suite_arc4.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_arc4$(EXEXT): test_suite_arc4.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_asn1write: test_suite_asn1write.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_asn1write$(EXEXT): test_suite_asn1write.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_base64: test_suite_base64.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_base64$(EXEXT): test_suite_base64.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_blowfish: test_suite_blowfish.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_blowfish$(EXEXT): test_suite_blowfish.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_camellia: test_suite_camellia.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_camellia$(EXEXT): test_suite_camellia.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_ccm: test_suite_ccm.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_ccm$(EXEXT): test_suite_ccm.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_cipher.aes: test_suite_cipher.aes.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_cipher.aes$(EXEXT): test_suite_cipher.aes.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_cipher.arc4: test_suite_cipher.arc4.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_cipher.arc4$(EXEXT): test_suite_cipher.arc4.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_cipher.ccm: test_suite_cipher.ccm.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_cipher.ccm$(EXEXT): test_suite_cipher.ccm.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_cipher.gcm: test_suite_cipher.gcm.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_cipher.gcm$(EXEXT): test_suite_cipher.gcm.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_cipher.blowfish: test_suite_cipher.blowfish.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_cipher.blowfish$(EXEXT): test_suite_cipher.blowfish.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_cipher.camellia: test_suite_cipher.camellia.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_cipher.camellia$(EXEXT): test_suite_cipher.camellia.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_cipher.des: test_suite_cipher.des.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_cipher.des$(EXEXT): test_suite_cipher.des.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_cipher.null: test_suite_cipher.null.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_cipher.null$(EXEXT): test_suite_cipher.null.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_cipher.padding: test_suite_cipher.padding.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_cipher.padding$(EXEXT): test_suite_cipher.padding.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_ctr_drbg: test_suite_ctr_drbg.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_ctr_drbg$(EXEXT): test_suite_ctr_drbg.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_des: test_suite_des.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_des$(EXEXT): test_suite_des.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_dhm: test_suite_dhm.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_dhm$(EXEXT): test_suite_dhm.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_ecdh: test_suite_ecdh.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_ecdh$(EXEXT): test_suite_ecdh.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_ecdsa: test_suite_ecdsa.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_ecdsa$(EXEXT): test_suite_ecdsa.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_ecp: test_suite_ecp.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_ecp$(EXEXT): test_suite_ecp.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_entropy: test_suite_entropy.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_entropy$(EXEXT): test_suite_entropy.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_error: test_suite_error.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_error$(EXEXT): test_suite_error.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_gcm.aes128_de: test_suite_gcm.aes128_de.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_gcm.aes128_de$(EXEXT): test_suite_gcm.aes128_de.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_gcm.aes192_de: test_suite_gcm.aes192_de.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_gcm.aes192_de$(EXEXT): test_suite_gcm.aes192_de.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_gcm.aes256_de: test_suite_gcm.aes256_de.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_gcm.aes256_de$(EXEXT): test_suite_gcm.aes256_de.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_gcm.aes128_en: test_suite_gcm.aes128_en.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_gcm.aes128_en$(EXEXT): test_suite_gcm.aes128_en.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_gcm.aes192_en: test_suite_gcm.aes192_en.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_gcm.aes192_en$(EXEXT): test_suite_gcm.aes192_en.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_gcm.aes256_en: test_suite_gcm.aes256_en.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_gcm.aes256_en$(EXEXT): test_suite_gcm.aes256_en.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_gcm.camellia: test_suite_gcm.camellia.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_gcm.camellia$(EXEXT): test_suite_gcm.camellia.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_hmac_drbg.misc: test_suite_hmac_drbg.misc.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_hmac_drbg.misc$(EXEXT): test_suite_hmac_drbg.misc.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_hmac_drbg.no_reseed: test_suite_hmac_drbg.no_reseed.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_hmac_drbg.no_reseed$(EXEXT): test_suite_hmac_drbg.no_reseed.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_hmac_drbg.nopr: test_suite_hmac_drbg.nopr.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_hmac_drbg.nopr$(EXEXT): test_suite_hmac_drbg.nopr.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_hmac_drbg.pr: test_suite_hmac_drbg.pr.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_hmac_drbg.pr$(EXEXT): test_suite_hmac_drbg.pr.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_hmac_shax: test_suite_hmac_shax.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_hmac_shax$(EXEXT): test_suite_hmac_shax.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_md: test_suite_md.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_md$(EXEXT): test_suite_md.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_mdx: test_suite_mdx.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_mdx$(EXEXT): test_suite_mdx.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_memory_buffer_alloc: test_suite_memory_buffer_alloc.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_memory_buffer_alloc$(EXEXT): test_suite_memory_buffer_alloc.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_mpi: test_suite_mpi.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_mpi$(EXEXT): test_suite_mpi.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_pbkdf2: test_suite_pbkdf2.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_pbkdf2$(EXEXT): test_suite_pbkdf2.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_pem: test_suite_pem.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_pem$(EXEXT): test_suite_pem.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_pkcs1_v21: test_suite_pkcs1_v21.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_pkcs1_v21$(EXEXT): test_suite_pkcs1_v21.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_pkcs5: test_suite_pkcs5.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_pkcs5$(EXEXT): test_suite_pkcs5.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_pkparse: test_suite_pkparse.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_pkparse$(EXEXT): test_suite_pkparse.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_pkwrite: test_suite_pkwrite.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_pkwrite$(EXEXT): test_suite_pkwrite.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_pk: test_suite_pk.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_pk$(EXEXT): test_suite_pk.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_rsa: test_suite_rsa.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_rsa$(EXEXT): test_suite_rsa.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_shax: test_suite_shax.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_shax$(EXEXT): test_suite_shax.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_ssl: test_suite_ssl.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_ssl$(EXEXT): test_suite_ssl.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_x509parse: test_suite_x509parse.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_x509parse$(EXEXT): test_suite_x509parse.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_x509write: test_suite_x509write.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_x509write$(EXEXT): test_suite_x509write.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_xtea: test_suite_xtea.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_xtea$(EXEXT): test_suite_xtea.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_debug: test_suite_debug.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_debug$(EXEXT): test_suite_debug.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
-test_suite_version: test_suite_version.c $(DEP)
-	echo   "  CC    	$@.c"
-	$(CC) $(CFLAGS) $(OFLAGS) $@.c	$(LDFLAGS) -o $@
+test_suite_version$(EXEXT): test_suite_version.c $(DEP)
+	echo   "  CC    	$<"
+	$(CC) $(CFLAGS) $(OFLAGS) $<	$(LDFLAGS) -o $@
 
 clean:
 ifndef WINDOWS
@@ -422,9 +436,9 @@
 	do																		\
 		echo " - $${i}";													\
 		RESULT=`$(CHECK_PRELOAD) ./$${i} | grep -v 'PASS$$' | grep -v -- '----' | grep -v '^$$'`;	\
-		FAILED=`echo $$RESULT |grep FAILED`; 								\
+		PASSED=`echo $$RESULT |grep PASSED`; 								\
 		echo "   $$RESULT";													\
-		if [ "$$FAILED" != "" ];											\
+		if [ "$$PASSED" == "" ];											\
 		then																\
 			echo "**** Failed ***************";								\
 			RETURN=1;														\
diff --git a/tests/scripts/all.sh b/tests/scripts/all.sh
index fb0fe26..62d0274 100755
--- a/tests/scripts/all.sh
+++ b/tests/scripts/all.sh
@@ -73,6 +73,9 @@
 msg "test: recursion.pl" # < 1s
 scripts/recursion.pl library/*.c
 
+msg "test: freshness of generated source files" # < 1s
+tests/scripts/check-generated-files.sh
+
 msg "build: cmake, gcc, ASan" # ~ 1 min 50s
 cleanup
 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan .
@@ -128,10 +131,70 @@
 
 msg "build: Unix make, -O2 (gcc)" # ~ 30s
 cleanup
-CC=gcc make
+CC=gcc CFLAGS=-Werror make
 
-# MemSan currently only available on Linux
-if [ `uname` = 'Linux' ]; then
+# this is meant to cath missing #define polarssl_printf etc
+msg "build: full config except platform.c" # ~ 30s
+cleanup
+cp "$CONFIG_H" "$CONFIG_BAK"
+scripts/config.pl full
+scripts/config.pl unset POLARSSL_PLATFORM_C
+scripts/config.pl unset POLARSSL_PLATFORM_MEMORY
+scripts/config.pl unset POLARSSL_MEMORY_C
+scripts/config.pl unset POLARSSL_MEMORY_BUFFER_ALLOC_C
+CC=gcc CFLAGS=-Werror make
+
+if uname -a | grep -F x86_64 >/dev/null; then
+msg "build: i386, make, gcc" # ~ 30s
+cleanup
+CC=gcc CFLAGS='-Werror -m32' make
+fi # x86_64
+
+if which arm-none-eabi-gcc >/dev/null; then
+msg "build: arm-none-eabi-gcc, make" # ~ 10s
+cleanup
+cp "$CONFIG_H" "$CONFIG_BAK"
+scripts/config.pl full
+scripts/config.pl unset POLARSSL_NET_C
+scripts/config.pl unset POLARSSL_TIMING_C
+scripts/config.pl unset POLARSSL_FS_IO
+# following things are not in the default config
+scripts/config.pl unset POLARSSL_HAVEGE_C # depends on timing.c
+scripts/config.pl unset POLARSSL_THREADING_PTHREAD
+scripts/config.pl unset POLARSSL_THREADING_C
+scripts/config.pl unset POLARSSL_MEMORY_BACKTRACE # execinfo.h
+scripts/config.pl unset POLARSSL_MEMORY_BUFFER_ALLOC_C # calls exit
+CC=arm-none-eabi-gcc CFLAGS=-Werror make lib
+fi # arm-gcc
+
+if which armcc >/dev/null; then
+msg "build: armcc, make"
+cleanup
+cp "$CONFIG_H" "$CONFIG_BAK"
+scripts/config.pl full
+scripts/config.pl unset POLARSSL_NET_C
+scripts/config.pl unset POLARSSL_TIMING_C
+scripts/config.pl unset POLARSSL_FS_IO
+scripts/config.pl unset POLARSSL_HAVE_TIME
+# following things are not in the default config
+scripts/config.pl unset POLARSSL_HAVEGE_C # depends on timing.c
+scripts/config.pl unset POLARSSL_THREADING_PTHREAD
+scripts/config.pl unset POLARSSL_THREADING_C
+scripts/config.pl unset POLARSSL_MEMORY_BACKTRACE # execinfo.h
+scripts/config.pl unset POLARSSL_MEMORY_BUFFER_ALLOC_C # calls exit
+CC=arm-none-eabi-gcc CFLAGS=-Werror make lib 2> armcc.stderr
+grep -v '^ar: creating' armcc.stderr || exit 1
+rm armcc.stderr
+fi # armcc
+
+if which i686-w64-mingw32-gcc >/dev/null; then
+msg "build: cross-mingw64, make" # ~ 30s
+cleanup
+CC=i686-w64-mingw32-gcc AR=i686-w64-mingw32-ar CFLAGS=-Werror WINDOWS_BUILD=1 make
+fi
+
+# MemSan currently only available on Linux 64 bits
+if uname -a | grep 'Linux.*x86_64' >/dev/null; then
 
 msg "build: MSan (clang)" # ~ 1 min 20s
 cleanup
diff --git a/tests/scripts/check-generated-files.sh b/tests/scripts/check-generated-files.sh
new file mode 100755
index 0000000..0400bc7
--- /dev/null
+++ b/tests/scripts/check-generated-files.sh
@@ -0,0 +1,24 @@
+#!/bin/sh
+
+# check if generated files are up-to-date
+
+set -eu
+
+if [ -d library -a -d include -a -d tests ]; then :; else
+    echo "Must be run from mbed TLS root" >&2
+    exit 1
+fi
+
+check()
+{
+    FILE=$1
+    SCRIPT=$2
+
+    cp $FILE $FILE.bak
+    $SCRIPT
+    diff $FILE $FILE.bak
+    mv $FILE.bak $FILE
+}
+
+check library/error.c scripts/generate_errors.pl
+check library/version_features.c scripts/generate_features.pl
diff --git a/tests/scripts/generate_code.pl b/tests/scripts/generate_code.pl
index 4591378..ba74738 100755
--- a/tests/scripts/generate_code.pl
+++ b/tests/scripts/generate_code.pl
@@ -65,12 +65,12 @@
 #include POLARSSL_CONFIG_FILE
 #endif
 
+$test_helpers
+
 $suite_pre_code
 $suite_header
 $suite_post_code
 
-$test_helpers
-
 END
 
 $test_main =~ s/SUITE_PRE_DEP/$suite_pre_code/;
diff --git a/tests/suites/helpers.function b/tests/suites/helpers.function
index 2cc129a..0f07485 100644
--- a/tests/suites/helpers.function
+++ b/tests/suites/helpers.function
@@ -1,8 +1,15 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_printf     printf
+#define polarssl_fprintf    fprintf
 #define polarssl_malloc     malloc
 #define polarssl_free       free
+#define polarssl_exit       exit
+#define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
+#define polarssl_snprintf   snprintf
 #endif
 
 #ifdef _MSC_VER
@@ -12,10 +19,17 @@
 #include <inttypes.h>
 #endif
 
-#include <assert.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
+#define assert(a) if( !( a ) )                                      \
+{                                                                   \
+    polarssl_fprintf( stderr, "Assertion Failed at %s:%d - %s\n",   \
+                             __FILE__, __LINE__, #a );              \
+    polarssl_exit( 1 );                                             \
+}
+
 /*
  * 32-bit integer manipulation macros (big endian)
  */
@@ -39,13 +53,13 @@
 }
 #endif
 
-static int unhexify(unsigned char *obuf, const char *ibuf)
+static int unhexify( unsigned char *obuf, const char *ibuf )
 {
     unsigned char c, c2;
-    int len = strlen(ibuf) / 2;
-    assert(!(strlen(ibuf) %1)); // must be even number of bytes
+    int len = strlen( ibuf ) / 2;
+    assert( strlen( ibuf ) % 2 == 0 ); // must be even number of bytes
 
-    while (*ibuf != 0)
+    while( *ibuf != 0 )
     {
         c = *ibuf++;
         if( c >= '0' && c <= '9' )
@@ -73,14 +87,14 @@
     return len;
 }
 
-static void hexify(unsigned char *obuf, const unsigned char *ibuf, int len)
+static void hexify( unsigned char *obuf, const unsigned char *ibuf, int len )
 {
     unsigned char l, h;
 
-    while (len != 0)
+    while( len != 0 )
     {
-        h = (*ibuf) / 16;
-        l = (*ibuf) % 16;
+        h = *ibuf / 16;
+        l = *ibuf % 16;
 
         if( h < 10 )
             *obuf++ = '0' + h;
@@ -107,7 +121,7 @@
 static unsigned char *zero_alloc( size_t len )
 {
     void *p;
-    size_t actual_len = len != 0 ? len : 1;
+    size_t actual_len = ( len != 0 ) ? len : 1;
 
     p = polarssl_malloc( actual_len );
     assert( p != NULL );
@@ -131,7 +145,7 @@
 {
     unsigned char *obuf;
 
-    *olen = strlen(ibuf) / 2;
+    *olen = strlen( ibuf ) / 2;
 
     if( *olen == 0 )
         return( zero_alloc( *olen ) );
@@ -269,9 +283,11 @@
 
         for( i = 0; i < 32; i++ )
         {
-            info->v0 += (((info->v1 << 4) ^ (info->v1 >> 5)) + info->v1) ^ (sum + k[sum & 3]);
+            info->v0 += ( ( ( info->v1 << 4 ) ^ ( info->v1 >> 5 ) )
+                            + info->v1 ) ^ ( sum + k[sum & 3] );
             sum += delta;
-            info->v1 += (((info->v0 << 4) ^ (info->v0 >> 5)) + info->v0) ^ (sum + k[(sum>>11) & 3]);
+            info->v1 += ( ( ( info->v0 << 4 ) ^ ( info->v0 >> 5 ) )
+                            + info->v0 ) ^ ( sum + k[( sum>>11 ) & 3] );
         }
 
         PUT_UINT32_BE( info->v0, result, 0 );
diff --git a/tests/suites/main_test.function b/tests/suites/main_test.function
index 4a5e104..d67d875 100644
--- a/tests/suites/main_test.function
+++ b/tests/suites/main_test.function
@@ -1,13 +1,14 @@
-#include <stdio.h>
 #include <string.h>
 
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
-#define polarssl_printf     printf
-#define polarssl_fprintf    fprintf
-#define polarssl_malloc     malloc
+#include <stdio.h>
+#define polarssl_exit       exit
 #define polarssl_free       free
+#define polarssl_malloc     malloc
+#define polarssl_fprintf    fprintf
+#define polarssl_printf     printf
 #endif
 
 #if defined(POLARSSL_MEMORY_BUFFER_ALLOC_C)
@@ -280,7 +281,7 @@
         {
             polarssl_fprintf( stderr, "FAILED: FATAL PARSE ERROR\n" );
             fclose(file);
-            exit( 2 );
+            polarssl_exit( 2 );
         }
         else
             total_errors++;
diff --git a/tests/suites/test_suite_aes.function b/tests/suites/test_suite_aes.function
index 3bd7d4a..7027247 100644
--- a/tests/suites/test_suite_aes.function
+++ b/tests/suites/test_suite_aes.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/aes.h>
+#include "polarssl/aes.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_arc4.function b/tests/suites/test_suite_arc4.function
index b6d3d4c..dc7b24b 100644
--- a/tests/suites/test_suite_arc4.function
+++ b/tests/suites/test_suite_arc4.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/arc4.h>
+#include "polarssl/arc4.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_asn1write.function b/tests/suites/test_suite_asn1write.function
index 72e9b4b..49b073a 100644
--- a/tests/suites/test_suite_asn1write.function
+++ b/tests/suites/test_suite_asn1write.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/asn1write.h>
+#include "polarssl/asn1write.h"
 
 #define GUARD_LEN 4
 #define GUARD_VAL 0x2a
diff --git a/tests/suites/test_suite_base64.function b/tests/suites/test_suite_base64.function
index 01d8aa6..a8348d2 100644
--- a/tests/suites/test_suite_base64.function
+++ b/tests/suites/test_suite_base64.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/base64.h>
+#include "polarssl/base64.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_camellia.function b/tests/suites/test_suite_camellia.function
index 6d88f8c..e73aa86 100644
--- a/tests/suites/test_suite_camellia.function
+++ b/tests/suites/test_suite_camellia.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/camellia.h>
+#include "polarssl/camellia.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_ccm.function b/tests/suites/test_suite_ccm.function
index d513a15..d8ca4f5 100644
--- a/tests/suites/test_suite_ccm.function
+++ b/tests/suites/test_suite_ccm.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/ccm.h>
+#include "polarssl/ccm.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
@@ -146,6 +146,7 @@
     if( strcmp( "FAIL", result_hex ) == 0 )
     {
         ret = POLARSSL_ERR_CCM_AUTH_FAILED;
+        result_len = -1;
     }
     else
     {
diff --git a/tests/suites/test_suite_cipher.function b/tests/suites/test_suite_cipher.function
index 2bc1ef9..448bfcc 100644
--- a/tests/suites/test_suite_cipher.function
+++ b/tests/suites/test_suite_cipher.function
@@ -1,8 +1,8 @@
 /* BEGIN_HEADER */
-#include <polarssl/cipher.h>
+#include "polarssl/cipher.h"
 
 #if defined(POLARSSL_GCM_C)
-#include <polarssl/gcm.h>
+#include "polarssl/gcm.h"
 #endif
 /* END_HEADER */
 
diff --git a/tests/suites/test_suite_ctr_drbg.function b/tests/suites/test_suite_ctr_drbg.function
index a36bab2..644eb46 100644
--- a/tests/suites/test_suite_ctr_drbg.function
+++ b/tests/suites/test_suite_ctr_drbg.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/ctr_drbg.h>
+#include "polarssl/ctr_drbg.h"
 
 int test_offset_idx;
 int entropy_func( void *data, unsigned char *buf, size_t len )
diff --git a/tests/suites/test_suite_debug.function b/tests/suites/test_suite_debug.function
index b31b72a..7db04e5 100644
--- a/tests/suites/test_suite_debug.function
+++ b/tests/suites/test_suite_debug.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/debug.h>
+#include "polarssl/debug.h"
 
 struct buffer_data
 {
diff --git a/tests/suites/test_suite_des.function b/tests/suites/test_suite_des.function
index 4b5d53d..dfa168f 100644
--- a/tests/suites/test_suite_des.function
+++ b/tests/suites/test_suite_des.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/des.h>
+#include "polarssl/des.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_dhm.function b/tests/suites/test_suite_dhm.function
index ba9477f..d7cabf4 100644
--- a/tests/suites/test_suite_dhm.function
+++ b/tests/suites/test_suite_dhm.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/dhm.h>
+#include "polarssl/dhm.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_ecdh.function b/tests/suites/test_suite_ecdh.function
index c84d2b1..27be969 100644
--- a/tests/suites/test_suite_ecdh.function
+++ b/tests/suites/test_suite_ecdh.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/ecdh.h>
+#include "polarssl/ecdh.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_ecdsa.function b/tests/suites/test_suite_ecdsa.function
index 144326b..ee379dc 100644
--- a/tests/suites/test_suite_ecdsa.function
+++ b/tests/suites/test_suite_ecdsa.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/ecdsa.h>
+#include "polarssl/ecdsa.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_ecp.function b/tests/suites/test_suite_ecp.function
index 1c22a84..696c597 100644
--- a/tests/suites/test_suite_ecp.function
+++ b/tests/suites/test_suite_ecp.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/ecp.h>
+#include "polarssl/ecp.h"
 
 #define POLARSSL_ECP_PF_UNKNOWN     -1
 /* END_HEADER */
diff --git a/tests/suites/test_suite_entropy.function b/tests/suites/test_suite_entropy.function
index 6d137ad..c46246c 100644
--- a/tests/suites/test_suite_entropy.function
+++ b/tests/suites/test_suite_entropy.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/entropy.h>
+#include "polarssl/entropy.h"
 
 /*
  * Number of calls made to entropy_dummy_source()
diff --git a/tests/suites/test_suite_error.function b/tests/suites/test_suite_error.function
index 4532530..87287b7 100644
--- a/tests/suites/test_suite_error.function
+++ b/tests/suites/test_suite_error.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/error.h>
+#include "polarssl/error.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_gcm.function b/tests/suites/test_suite_gcm.function
index c30b755..2ac7628 100644
--- a/tests/suites/test_suite_gcm.function
+++ b/tests/suites/test_suite_gcm.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/gcm.h>
+#include "polarssl/gcm.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_hmac_drbg.function b/tests/suites/test_suite_hmac_drbg.function
index bd45112..56267e0 100644
--- a/tests/suites/test_suite_hmac_drbg.function
+++ b/tests/suites/test_suite_hmac_drbg.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/hmac_drbg.h>
+#include "polarssl/hmac_drbg.h"
 
 typedef struct
 {
diff --git a/tests/suites/test_suite_hmac_shax.function b/tests/suites/test_suite_hmac_shax.function
index 54ad02f..b31d772 100644
--- a/tests/suites/test_suite_hmac_shax.function
+++ b/tests/suites/test_suite_hmac_shax.function
@@ -1,7 +1,7 @@
 /* BEGIN_HEADER */
-#include <polarssl/sha1.h>
-#include <polarssl/sha256.h>
-#include <polarssl/sha512.h>
+#include "polarssl/sha1.h"
+#include "polarssl/sha256.h"
+#include "polarssl/sha512.h"
 /* END_HEADER */
 
 /* BEGIN_CASE depends_on:POLARSSL_SHA1_C */
diff --git a/tests/suites/test_suite_md.function b/tests/suites/test_suite_md.function
index ea92726..40eb717 100644
--- a/tests/suites/test_suite_md.function
+++ b/tests/suites/test_suite_md.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/md.h>
+#include "polarssl/md.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_mdx.function b/tests/suites/test_suite_mdx.function
index ecc1b92..6e4c6d8 100644
--- a/tests/suites/test_suite_mdx.function
+++ b/tests/suites/test_suite_mdx.function
@@ -1,8 +1,8 @@
 /* BEGIN_HEADER */
-#include <polarssl/md2.h>
-#include <polarssl/md4.h>
-#include <polarssl/md5.h>
-#include <polarssl/ripemd160.h>
+#include "polarssl/md2.h"
+#include "polarssl/md4.h"
+#include "polarssl/md5.h"
+#include "polarssl/ripemd160.h"
 /* END_HEADER */
 
 /* BEGIN_CASE depends_on:POLARSSL_MD2_C */
diff --git a/tests/suites/test_suite_memory_buffer_alloc.function b/tests/suites/test_suite_memory_buffer_alloc.function
index 88c36ab..e9cd021 100644
--- a/tests/suites/test_suite_memory_buffer_alloc.function
+++ b/tests/suites/test_suite_memory_buffer_alloc.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/memory_buffer_alloc.h>
+#include "polarssl/memory_buffer_alloc.h"
 #define TEST_SUITE_MEMORY_BUFFER_ALLOC
 /* END_HEADER */
 
diff --git a/tests/suites/test_suite_mpi.function b/tests/suites/test_suite_mpi.function
index 2835acb..ce1a072 100644
--- a/tests/suites/test_suite_mpi.function
+++ b/tests/suites/test_suite_mpi.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/bignum.h>
+#include "polarssl/bignum.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
@@ -97,6 +97,7 @@
     unsigned char buf[1000];
     size_t buflen;
     FILE *file;
+    int ret;
 
     memset( buf, 0x00, 1000 );
     memset( str, 0x00, 1000 );
@@ -105,8 +106,9 @@
 
     file = fopen( input_file, "r" );
     TEST_ASSERT( file != NULL );
-    TEST_ASSERT( mpi_read_file( &X, radix_X, file ) == result );
+    ret = mpi_read_file( &X, radix_X, file );
     fclose(file);
+    TEST_ASSERT( ret == result );
 
     if( result == 0 )
     {
diff --git a/tests/suites/test_suite_pbkdf2.function b/tests/suites/test_suite_pbkdf2.function
index cbac80e..f99cb6d 100644
--- a/tests/suites/test_suite_pbkdf2.function
+++ b/tests/suites/test_suite_pbkdf2.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/pbkdf2.h>
+#include "polarssl/pbkdf2.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_pem.function b/tests/suites/test_suite_pem.function
index e8b05eb..f8aab47 100644
--- a/tests/suites/test_suite_pem.function
+++ b/tests/suites/test_suite_pem.function
@@ -1,6 +1,6 @@
 /* BEGIN_HEADER */
-#include <polarssl/base64.h>
-#include <polarssl/pem.h>
+#include "polarssl/base64.h"
+#include "polarssl/pem.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_pk.function b/tests/suites/test_suite_pk.function
index fb86c99..cc378c4 100644
--- a/tests/suites/test_suite_pk.function
+++ b/tests/suites/test_suite_pk.function
@@ -1,9 +1,9 @@
 /* BEGIN_HEADER */
-#include <polarssl/pk.h>
+#include "polarssl/pk.h"
 
 /* For error codes */
-#include <polarssl/ecp.h>
-#include <polarssl/rsa.h>
+#include "polarssl/ecp.h"
+#include "polarssl/rsa.h"
 
 static int rnd_std_rand( void *rng_state, unsigned char *output, size_t len );
 
diff --git a/tests/suites/test_suite_pkcs1_v21.function b/tests/suites/test_suite_pkcs1_v21.function
index 24b200e..6fbe2e1 100644
--- a/tests/suites/test_suite_pkcs1_v21.function
+++ b/tests/suites/test_suite_pkcs1_v21.function
@@ -1,6 +1,6 @@
 /* BEGIN_HEADER */
-#include <polarssl/rsa.h>
-#include <polarssl/md.h>
+#include "polarssl/rsa.h"
+#include "polarssl/md.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_pkcs5.function b/tests/suites/test_suite_pkcs5.function
index 1f61db6..f7165f6 100644
--- a/tests/suites/test_suite_pkcs5.function
+++ b/tests/suites/test_suite_pkcs5.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/pkcs5.h>
+#include "polarssl/pkcs5.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_pkparse.function b/tests/suites/test_suite_pkparse.function
index c074326..9479cd9 100644
--- a/tests/suites/test_suite_pkparse.function
+++ b/tests/suites/test_suite_pkparse.function
@@ -1,7 +1,7 @@
 /* BEGIN_HEADER */
-#include <polarssl/pk.h>
-#include <polarssl/pem.h>
-#include <polarssl/oid.h>
+#include "polarssl/pk.h"
+#include "polarssl/pem.h"
+#include "polarssl/oid.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_pkwrite.function b/tests/suites/test_suite_pkwrite.function
index b6cb943..8b5fafb 100644
--- a/tests/suites/test_suite_pkwrite.function
+++ b/tests/suites/test_suite_pkwrite.function
@@ -1,7 +1,7 @@
 /* BEGIN_HEADER */
-#include <polarssl/pk.h>
-#include <polarssl/pem.h>
-#include <polarssl/oid.h>
+#include "polarssl/pk.h"
+#include "polarssl/pem.h"
+#include "polarssl/oid.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_rsa.function b/tests/suites/test_suite_rsa.function
index bafacac..45d5723 100644
--- a/tests/suites/test_suite_rsa.function
+++ b/tests/suites/test_suite_rsa.function
@@ -1,13 +1,13 @@
 /* BEGIN_HEADER */
-#include <polarssl/rsa.h>
-#include <polarssl/md2.h>
-#include <polarssl/md4.h>
-#include <polarssl/md5.h>
-#include <polarssl/sha1.h>
-#include <polarssl/sha256.h>
-#include <polarssl/sha512.h>
-#include <polarssl/entropy.h>
-#include <polarssl/ctr_drbg.h>
+#include "polarssl/rsa.h"
+#include "polarssl/md2.h"
+#include "polarssl/md4.h"
+#include "polarssl/md5.h"
+#include "polarssl/sha1.h"
+#include "polarssl/sha256.h"
+#include "polarssl/sha512.h"
+#include "polarssl/entropy.h"
+#include "polarssl/ctr_drbg.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_shax.function b/tests/suites/test_suite_shax.function
index 73190dc..51c3301 100644
--- a/tests/suites/test_suite_shax.function
+++ b/tests/suites/test_suite_shax.function
@@ -1,7 +1,7 @@
 /* BEGIN_HEADER */
-#include <polarssl/sha1.h>
-#include <polarssl/sha256.h>
-#include <polarssl/sha512.h>
+#include "polarssl/sha1.h"
+#include "polarssl/sha256.h"
+#include "polarssl/sha512.h"
 /* END_HEADER */
 
 /* BEGIN_CASE depends_on:POLARSSL_SHA1_C */
diff --git a/tests/suites/test_suite_version.function b/tests/suites/test_suite_version.function
index 72c3ab1..fd12032 100644
--- a/tests/suites/test_suite_version.function
+++ b/tests/suites/test_suite_version.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/version.h>
+#include "polarssl/version.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
@@ -17,10 +17,10 @@
     memset( build_str, 0, 100 );
     memset( build_str_full, 0, 100 );
 
-    snprintf (build_str, 100, "%d.%d.%d", POLARSSL_VERSION_MAJOR,
+    polarssl_snprintf( build_str, 100, "%d.%d.%d", POLARSSL_VERSION_MAJOR,
         POLARSSL_VERSION_MINOR, POLARSSL_VERSION_PATCH );
 
-    snprintf( build_str_full, 100, "mbed TLS %d.%d.%d", POLARSSL_VERSION_MAJOR,
+    polarssl_snprintf( build_str_full, 100, "mbed TLS %d.%d.%d", POLARSSL_VERSION_MAJOR,
         POLARSSL_VERSION_MINOR, POLARSSL_VERSION_PATCH );
 
     build_int = POLARSSL_VERSION_MAJOR << 24 |
@@ -52,11 +52,11 @@
     version_get_string( get_str );
     version_get_string_full( get_str_full );
 
-    snprintf( build_str, 100, "%d.%d.%d",
+    polarssl_snprintf( build_str, 100, "%d.%d.%d",
         (get_int >> 24) & 0xFF,
         (get_int >> 16) & 0xFF,
         (get_int >> 8) & 0xFF );
-    snprintf( build_str_full, 100, "mbed TLS %s", version_str );
+    polarssl_snprintf( build_str_full, 100, "mbed TLS %s", version_str );
 
     TEST_ASSERT( strcmp( build_str, version_str ) == 0 );
     TEST_ASSERT( strcmp( build_str_full, get_str_full ) == 0 );
diff --git a/tests/suites/test_suite_x509parse.function b/tests/suites/test_suite_x509parse.function
index 4329dcc..50de457 100644
--- a/tests/suites/test_suite_x509parse.function
+++ b/tests/suites/test_suite_x509parse.function
@@ -1,10 +1,10 @@
 /* BEGIN_HEADER */
-#include <polarssl/x509_crt.h>
-#include <polarssl/x509_crl.h>
-#include <polarssl/x509_csr.h>
-#include <polarssl/pem.h>
-#include <polarssl/oid.h>
-#include <polarssl/base64.h>
+#include "polarssl/x509_crt.h"
+#include "polarssl/x509_crl.h"
+#include "polarssl/x509_csr.h"
+#include "polarssl/pem.h"
+#include "polarssl/oid.h"
+#include "polarssl/base64.h"
 
 int verify_none( void *data, x509_crt *crt, int certificate_depth, int *flags )
 {
diff --git a/tests/suites/test_suite_x509write.function b/tests/suites/test_suite_x509write.function
index 701ed00..63f35a6 100644
--- a/tests/suites/test_suite_x509write.function
+++ b/tests/suites/test_suite_x509write.function
@@ -1,8 +1,8 @@
 /* BEGIN_HEADER */
-#include <polarssl/x509_crt.h>
-#include <polarssl/x509_csr.h>
-#include <polarssl/pem.h>
-#include <polarssl/oid.h>
+#include "polarssl/x509_crt.h"
+#include "polarssl/x509_csr.h"
+#include "polarssl/pem.h"
+#include "polarssl/oid.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
diff --git a/tests/suites/test_suite_xtea.function b/tests/suites/test_suite_xtea.function
index 74ca678..d22c7fd 100644
--- a/tests/suites/test_suite_xtea.function
+++ b/tests/suites/test_suite_xtea.function
@@ -1,5 +1,5 @@
 /* BEGIN_HEADER */
-#include <polarssl/xtea.h>
+#include "polarssl/xtea.h"
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES