Merge pull request #90 from dgreen-arm/fix-its-file-on-windows

Use Windows-specific renaming function
diff --git a/library/psa_its_file.c b/library/psa_its_file.c
index de60ecf..8cdf783 100644
--- a/library/psa_its_file.c
+++ b/library/psa_its_file.c
@@ -33,6 +33,10 @@
 #define mbedtls_snprintf   snprintf
 #endif
 
+#if defined(_WIN32)
+#include <windows.h>
+#endif
+
 #include "psa_crypto_its.h"
 
 #include <limits.h>
@@ -58,6 +62,16 @@
 #define PSA_ITS_MAGIC_STRING "PSA\0ITS\0"
 #define PSA_ITS_MAGIC_LENGTH 8
 
+/* As rename fails on Windows if the new filepath already exists,
+ * use MoveFileExA with the MOVEFILE_REPLACE_EXISTING flag instead.
+ * Returns 0 on success, nonzero on failure. */
+#if defined(_WIN32)
+#define rename_replace_existing( oldpath, newpath ) \
+    ( ! MoveFileExA( oldpath, newpath, MOVEFILE_REPLACE_EXISTING ) )
+#else
+#define rename_replace_existing( oldpath, newpath ) rename( oldpath, newpath )
+#endif
+
 typedef struct
 {
     uint8_t magic[PSA_ITS_MAGIC_LENGTH];
@@ -209,7 +223,7 @@
     }
     if( status == PSA_SUCCESS )
     {
-        if( rename( PSA_ITS_STORAGE_TEMP, filename ) != 0 )
+        if( rename_replace_existing( PSA_ITS_STORAGE_TEMP, filename ) != 0 )
             status = PSA_ERROR_STORAGE_FAILURE;
     }
     remove( PSA_ITS_STORAGE_TEMP );