mbedtls: Avoid the use of unsupported libc functions

We intentionally don't provide free, calloc, fprintf, printf and exit
in pw_libc because they cannot be portably implemented on embedded
platforms. Use the mbedtls platform macros to avoid references to
undefined symbols.

Bug: 316936782
Change-Id: I3a28f6fe687794a6c1447850500684790069c893
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/199131
Commit-Queue: Auto-Submit <auto-submit@pigweed-service-accounts.iam.gserviceaccount.com>
Presubmit-Verified: CQ Bot Account <pigweed-scoped@luci-project-accounts.iam.gserviceaccount.com>
Commit-Queue: Prabhu Karthikeyan Rajasekaran <prabhukr@google.com>
Pigweed-Auto-Submit: Prabhu Karthikeyan Rajasekaran <prabhukr@google.com>
Reviewed-by: Armando Montanez <amontanez@google.com>
Reviewed-by: Petr Hosek <phosek@google.com>
diff --git a/third_party/mbedtls/BUILD.gn b/third_party/mbedtls/BUILD.gn
index 9511c97..3fe9eff 100644
--- a/third_party/mbedtls/BUILD.gn
+++ b/third_party/mbedtls/BUILD.gn
@@ -14,6 +14,7 @@
 
 import("//build_overrides/pigweed.gni")
 import("$dir_pw_build/target_types.gni")
+import("$dir_pw_toolchain/generate_toolchain.gni")
 import("mbedtls.gni")
 
 if (dir_pw_third_party_mbedtls != "") {
@@ -235,6 +236,12 @@
     config_header_file = rebase_path(pw_third_party_mbedtls_CONFIG_HEADER,
                                      get_label_info(":mbedtls", "dir"))
     defines = [ "MBEDTLS_CONFIG_FILE=\"$config_header_file\"" ]
+    if (defined(pw_toolchain_SCOPE.is_host_toolchain) &&
+        pw_toolchain_SCOPE.is_host_toolchain) {
+      defines += [ "_PW_MBEDTLS_IS_HOST=1" ]
+    } else {
+      defines += [ "_PW_MBEDTLS_IS_HOST=0" ]
+    }
   }
 
   pw_source_set("mbedtls") {
diff --git a/third_party/mbedtls/configs/config_pigweed_common.h b/third_party/mbedtls/configs/config_pigweed_common.h
index f0f3506..a23e489 100644
--- a/third_party/mbedtls/configs/config_pigweed_common.h
+++ b/third_party/mbedtls/configs/config_pigweed_common.h
@@ -48,4 +48,19 @@
 #undef MBEDTLS_HAVE_TIME
 #undef MBEDTLS_HAVE_TIME_DATE
 
+#if defined(_PW_MBEDTLS_IS_HOST) && !_PW_MBEDTLS_IS_HOST
+#define MBEDTLS_PLATFORM_MEMORY
+#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS
+
+#include <stdio.h>
+#define MBEDTLS_PLATFORM_SNPRINTF_ALT
+#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf
+#define MBEDTLS_PLATFORM_VSNPRINTF_ALT
+#define MBEDTLS_PLATFORM_STD_VSNPRINTF vsnprintf
+
+#define MBEDTLS_PLATFORM_FPRINTF_MACRO(stream, format, ...) (0)
+#define MBEDTLS_PLATFORM_PRINTF_MACRO(format, ...) (0)
+#define MBEDTLS_PLATFORM_EXIT_MACRO(exit_code)
+#endif  // defined(_PW_MBEDTLS_IS_HOST) && !_PW_MBEDTLS_IS_HOST
+
 #include "mbedtls/check_config.h"