Merge branch 'build' into development

* build:
  build: make: support windows cross compile
diff --git a/ChangeLog b/ChangeLog
index f5a3867..82f2310 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,31 @@
 mbed TLS ChangeLog (Sorted per branch, date)
 
+= 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).
+
+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
    * NULL pointer dereference in the buffer-based allocator when the buffer is
diff --git a/README.rst b/README.rst
index 8e2a53f..004f094 100644
--- a/README.rst
+++ b/README.rst
@@ -59,7 +59,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 +70,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 +103,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/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 51b124d..5372c69 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..e291ef6 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,8 +43,6 @@
 #define POLARSSL_CIPHER_MODE_WITH_PADDING
 #endif
 
-#include <string.h>
-
 #if defined(_MSC_VER) && !defined(inline)
 #define inline _inline
 #else
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 02e8985..7425508 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 */
 
 /**
@@ -1890,7 +1905,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
@@ -2235,11 +2254,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 b642c08..da3ef3d 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..ab36b41 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
diff --git a/include/polarssl/net.h b/include/polarssl/net.h
index d86732f..5f0b9ca 100644
--- a/include/polarssl/net.h
+++ b/include/polarssl/net.h
@@ -24,7 +24,7 @@
 #ifndef POLARSSL_NET_H
 #define POLARSSL_NET_H
 
-#include <string.h>
+#include <stddef.h>
 
 #define POLARSSL_ERR_NET_UNKNOWN_HOST                      -0x0056  /**< Failed to get an IP address for the given hostname. */
 #define POLARSSL_ERR_NET_SOCKET_FAILED                     -0x0042  /**< Failed to open a socket. */
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 9feecb0..1580bad 100644
--- a/library/Makefile
+++ b/library/Makefile
@@ -19,8 +19,11 @@
 
 # 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
 
 SOEXT=so.8
 
@@ -93,7 +96,7 @@
 
 libmbedtls.a: $(OBJS)
 	echo "  AR    $@"
-	$(AR) r $@ $(OBJS)
+	$(AR) rc $@ $(OBJS)
 	echo "  RL    $@"
 	$(AR) s $@
 
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..c958cf6 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 )
@@ -179,7 +182,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 );
@@ -541,7 +544,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 );
@@ -922,7 +925,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 +944,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 );
@@ -1145,7 +1148,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 );
@@ -1247,7 +1250,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 );
@@ -1439,7 +1442,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 a4e6fc3..91e804b 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,297 +210,297 @@
         // 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_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;
@@ -512,7 +518,7 @@
         if( buflen - len < 5 )
             return;
 
-        snprintf( buf + len, buflen - len, " : " );
+        polarssl_snprintf( buf + len, buflen - len, " : " );
 
         buf += len + 3;
         buflen -= len + 3;
@@ -523,216 +529,216 @@
     // 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_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_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" );
 #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)
@@ -746,8 +752,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..bf48883 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;
@@ -274,7 +268,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 +307,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 +362,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 +381,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 +396,7 @@
         polarssl_fprintf( stderr, "FATAL: polarssl_free() on unallocated "
                                   "data\n" );
 #endif
-        exit( 1 );
+        polarssl_exit( 1 );
     }
 
     hdr->alloc = 0;
@@ -492,7 +486,7 @@
 #endif
 
     if( ( heap.verify & MEMORY_VERIFY_FREE ) && verify_chain() != 0 )
-        exit( 1 );
+        polarssl_exit( 1 );
 }
 
 void memory_buffer_set_verify( int verify )
diff --git a/library/net.c b/library/net.c
index fefeaab..023e0e3 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, but only TCP */
     memset( &hints, 0, sizeof( hints ) );
@@ -257,7 +265,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..d8ee64a 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 );
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 014cfc9..dffcd22 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 62ff3cf..c84f8d2 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_srv.c b/library/ssl_srv.c
index 8cb140e..7ff203b 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
@@ -2886,7 +2887,6 @@
     unsigned char *pms = ssl->handshake->premaster + pms_offset;
     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 ) )
@@ -2950,10 +2950,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 4b54187..c0fc3a2 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
@@ -92,7 +93,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 );
 
@@ -111,7 +112,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 );
 
@@ -1489,7 +1490,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,
@@ -2747,7 +2748,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",
@@ -3544,20 +3545,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 */
@@ -3630,7 +3628,7 @@
     /*
      * Prepare base structures
      */
-    ssl->in_ctr = (unsigned char *) polarssl_malloc( len );
+    ssl->in_ctr = polarssl_malloc( len );
     ssl->in_hdr = ssl->in_ctr +  8;
     ssl->in_iv  = ssl->in_ctr + 13;
     ssl->in_msg = ssl->in_ctr + 13;
@@ -3641,7 +3639,7 @@
         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
     }
 
-    ssl->out_ctr = (unsigned char *) polarssl_malloc( len );
+    ssl->out_ctr = polarssl_malloc( len );
     ssl->out_hdr = ssl->out_ctr +  8;
     ssl->out_iv  = ssl->out_ctr + 13;
     ssl->out_msg = ssl->out_ctr + 13;
@@ -3782,7 +3780,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 );
 
@@ -3939,7 +3937,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 );
 
@@ -3995,7 +3993,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 );
 
@@ -4027,7 +4025,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 );
 
@@ -4063,9 +4061,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 );
@@ -4147,7 +4144,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 658b7cd..adaf5de 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/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 6fb569b..6c77a56 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 b7e6482..c625d02 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..88561b1 100644
--- a/programs/pkey/pk_sign.c
+++ b/programs/pkey/pk_sign.c
@@ -29,12 +29,15 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #define polarssl_printf     printf
 #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 +45,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 +115,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 +127,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 +137,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 +174,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..d8cd9a1 100644
--- a/programs/pkey/pk_verify.c
+++ b/programs/pkey/pk_verify.c
@@ -29,31 +29,34 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #define polarssl_printf     printf
 #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 +97,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 +111,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 +123,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 +149,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..2433096 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,15 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #define polarssl_printf     printf
 #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 +45,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 +122,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 +137,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 +147,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 +179,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..65fcfbe 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,35 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #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_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 +102,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 +122,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 +134,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 +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_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/ssl_client1.c b/programs/ssl/ssl_client1.c
index 10a21d1..25554f4 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 0d4a0f2..e2dac43 100644
--- a/programs/ssl/ssl_client2.c
+++ b/programs/ssl/ssl_client2.c
@@ -29,30 +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
+#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 +47,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
@@ -108,133 +98,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?                  */
-    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 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 \
@@ -376,6 +239,144 @@
     "    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?                  */
+    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 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;
@@ -1197,7 +1198,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 ee2e1b8..42bba72 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 769dd26..d39e6c5 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 8c67173..524413c 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 fe8eca4..58d99d6 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 a98eff8..d1b76ac 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
@@ -144,95 +133,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?                  */
-    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?   */
-} 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 \
@@ -378,6 +278,107 @@
     "    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?                  */
+    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?   */
+} 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
  */
@@ -385,7 +386,7 @@
     dst = p;                    \
     while( *p != ',' )          \
         if( ++p > end )         \
-            return( NULL );     \
+            goto error;         \
     *p++ = '\0';
 
 #if defined(POLARSSL_SNI)
@@ -398,53 +399,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;
@@ -464,6 +418,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,
@@ -538,11 +553,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 )
 {
@@ -566,28 +595,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..edb7c07 100644
--- a/programs/test/benchmark.c
+++ b/programs/test/benchmark.c
@@ -29,13 +29,13 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #define polarssl_printf     printf
+#define polarssl_exit       exit
 #endif
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
+#if defined(POLARSSL_TIMING_C)
 #include "polarssl/timing.h"
 
 #include "polarssl/md4.h"
@@ -60,6 +60,11 @@
 #include "polarssl/ecdh.h"
 #include "polarssl/error.h"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
 #if defined _MSC_VER && !defined snprintf
 #define snprintf _snprintf
 #endif
@@ -68,39 +73,22 @@
 #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
-
-static int myrand( void *rng_state, unsigned char *output, size_t len )
-{
-    size_t use_len;
-    int rnd;
-
-    if( rng_state != NULL )
-        rng_state  = NULL;
-
-    while( len > 0 )
-    {
-        use_len = len;
-        if( use_len > sizeof(int) )
-            use_len = sizeof(int);
-
-        rnd = rand();
-        memcpy( output, &rnd, use_len );
-        output += use_len;
-        len -= use_len;
-    }
-
-    return( 0 );
-}
+#define PRINT_ERROR                                                     \
+        polarssl_printf( "FAILED: -0x%04x\n", -ret );
+#endif
 
 #define TIME_AND_TSC( TITLE, CODE )                                     \
 do {                                                                    \
@@ -125,15 +113,6 @@
                     ( 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
-
 #define TIME_PUBLIC( TITLE, TYPE, CODE )                                \
 do {                                                                    \
     unsigned long i;                                                    \
@@ -157,6 +136,36 @@
         polarssl_printf( "%9lu " TYPE "/s\n", i / 3 );                           \
 } while( 0 )
 
+#if !defined(POLARSSL_TIMING_C)
+int main( void )
+{
+    polarssl_printf("POLARSSL_TIMING_C not defined.\n");
+    return( 0 );
+}
+#else
+static int myrand( void *rng_state, unsigned char *output, size_t len )
+{
+    size_t use_len;
+    int rnd;
+
+    if( rng_state != NULL )
+        rng_state  = NULL;
+
+    while( len > 0 )
+    {
+        use_len = len;
+        if( use_len > sizeof(int) )
+            use_len = sizeof(int);
+
+        rnd = rand();
+        memcpy( output, &rnd, use_len );
+        output += use_len;
+        len -= use_len;
+    }
+
+    return( 0 );
+}
+
 unsigned char buf[BUFSIZE];
 
 typedef struct {
@@ -166,12 +175,6 @@
          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;
@@ -313,7 +316,7 @@
         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 ) );
@@ -331,7 +334,7 @@
         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 ) );
@@ -351,7 +354,7 @@
         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 ) );
@@ -374,7 +377,7 @@
         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 ) );
@@ -396,7 +399,7 @@
 
         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 +430,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 +453,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
     }
@@ -498,7 +501,7 @@
         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 +522,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 +543,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,9 +584,9 @@
             ecdsa_init( &ecdsa );
 
             if( ecdsa_genkey( &ecdsa, curve_info->grp_id, myrand, NULL ) != 0 )
-                exit( 1 );
+                polarssl_exit( 1 );
 
-            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,
@@ -617,10 +619,10 @@
                                   myrand, NULL ) != 0 ||
                 ecp_copy( &ecdh.Qp, &ecdh.Q ) != 0 )
             {
-                exit( 1 );
+                polarssl_exit( 1 );
             }
 
-            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),
@@ -628,7 +630,7 @@
                     ret |= ecdh_calc_secret( &ecdh, &olen, buf, sizeof( buf ),
                                              myrand, NULL ) );
 
-            snprintf( title, sizeof( title ), "ECDH-%s",
+            polarssl_snprintf( title, sizeof( title ), "ECDH-%s",
                                               curve_info->name );
             TIME_PUBLIC( title, "handshake",
                     ret |= ecdh_calc_secret( &ecdh, &olen, buf, sizeof( buf ),
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..782d6f3 100644
--- a/programs/test/ssl_cert_test.c
+++ b/programs/test/ssl_cert_test.c
@@ -29,36 +29,36 @@
 #if defined(POLARSSL_PLATFORM_C)
 #include "polarssl/platform.h"
 #else
+#include <stdio.h>
+#define polarssl_snprintf   snprintf
 #define polarssl_printf     printf
 #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 +83,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 +146,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 +195,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 63c3220..4e89eac 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/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 a945440..c97fa04 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/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/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/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 a39027e..f83d186 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -431,9 +431,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..bbd59ba 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,64 @@
 
 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
+
+# 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..bb1083a 100644
--- a/tests/suites/main_test.function
+++ b/tests/suites/main_test.function
@@ -1,13 +1,13 @@
-#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
+#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 +280,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