Merge pull request #9302 from valeriosetti/psa-use-static-slots

PSA: use static key slots to store keys
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 561498c..3cab1a4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -150,7 +150,7 @@
 find_package(Threads)
 
 # If this is the root project add longer list of available CMAKE_BUILD_TYPE values
-if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
+if(NOT MBEDTLS_AS_SUBPROJECT)
     set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE}
         CACHE STRING "Choose the type of build: None Debug Release Coverage ASan ASanDbg MemSan MemSanDbg Check CheckFull TSan TSanDbg"
         FORCE)
@@ -318,10 +318,6 @@
     endif(CMAKE_COMPILER_IS_GNU OR CMAKE_COMPILER_IS_CLANG)
 endif(CMAKE_BUILD_TYPE STREQUAL "Coverage")
 
-if(LIB_INSTALL_DIR)
-    set(CMAKE_INSTALL_LIBDIR "${LIB_INSTALL_DIR}")
-endif()
-
 if (NOT EXISTS "${MBEDTLS_FRAMEWORK_DIR}/CMakeLists.txt")
     message(FATAL_ERROR "${MBEDTLS_FRAMEWORK_DIR}/CMakeLists.txt not found. Run `git submodule update --init` from the source tree to fetch the submodule contents.")
 endif()
diff --git a/ChangeLog.d/replace-close-with-mbedtls_net_close.txt b/ChangeLog.d/replace-close-with-mbedtls_net_close.txt
new file mode 100644
index 0000000..213cf55
--- /dev/null
+++ b/ChangeLog.d/replace-close-with-mbedtls_net_close.txt
@@ -0,0 +1,4 @@
+Bugfix
+   * Use 'mbedtls_net_close' instead of 'close' in 'mbedtls_net_bind'
+     and 'mbedtls_net_connect' to prevent possible double close fd
+     problems. Fixes #9711.
diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt
index 5cb5ec8..5b75b64 100644
--- a/library/CMakeLists.txt
+++ b/library/CMakeLists.txt
@@ -1,10 +1,3 @@
-# Set the project root directory if it's not already defined, as may happen if
-# the library folder is included directly by a parent project, without
-# including the top level CMakeLists.txt.
-if(NOT DEFINED MBEDTLS_DIR)
-    set(MBEDTLS_DIR ${CMAKE_SOURCE_DIR})
-endif()
-
 set(src_x509
     pkcs7.c
     x509.c
diff --git a/library/net_sockets.c b/library/net_sockets.c
index 33616bc..f752d13 100644
--- a/library/net_sockets.c
+++ b/library/net_sockets.c
@@ -190,7 +190,7 @@
             break;
         }
 
-        close(ctx->fd);
+        mbedtls_net_close(ctx);
         ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
     }
 
@@ -237,13 +237,13 @@
         n = 1;
         if (setsockopt(ctx->fd, SOL_SOCKET, SO_REUSEADDR,
                        (const char *) &n, sizeof(n)) != 0) {
-            close(ctx->fd);
+            mbedtls_net_close(ctx);
             ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
             continue;
         }
 
         if (bind(ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen) != 0) {
-            close(ctx->fd);
+            mbedtls_net_close(ctx);
             ret = MBEDTLS_ERR_NET_BIND_FAILED;
             continue;
         }
@@ -251,7 +251,7 @@
         /* Listen only makes sense for TCP */
         if (proto == MBEDTLS_NET_PROTO_TCP) {
             if (listen(ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG) != 0) {
-                close(ctx->fd);
+                mbedtls_net_close(ctx);
                 ret = MBEDTLS_ERR_NET_LISTEN_FAILED;
                 continue;
             }
diff --git a/scripts/lcov.sh b/scripts/lcov.sh
index 2d2f42b..79c5c9f 100755
--- a/scripts/lcov.sh
+++ b/scripts/lcov.sh
@@ -51,8 +51,8 @@
     # Ubuntu 16.04 is affected, 18.04 and above are not.
     # https://github.com/linux-test-project/lcov/commit/632c25a0d1f5e4d2f4fd5b28ce7c8b86d388c91f
     COVTMP=$PWD/Coverage/tmp
-    lcov --capture --initial --directory $library_dir -o "$COVTMP/files.info"
-    lcov --rc lcov_branch_coverage=1 --capture --directory $library_dir -o "$COVTMP/tests.info"
+    lcov --capture --initial ${lcov_dirs} -o "$COVTMP/files.info"
+    lcov --rc lcov_branch_coverage=1 --capture ${lcov_dirs} -o "$COVTMP/tests.info"
     lcov --rc lcov_branch_coverage=1 --add-tracefile "$COVTMP/files.info" --add-tracefile "$COVTMP/tests.info" -o "$COVTMP/all.info"
     lcov --rc lcov_branch_coverage=1 --remove "$COVTMP/all.info" -o "$COVTMP/final.info" '*.h'
     gendesc tests/Descriptions.txt -o "$COVTMP/descriptions"
@@ -64,9 +64,13 @@
 # Reset the traces to 0.
 lcov_reset_traces () {
     # Location with plain make
-    rm -f $library_dir/*.gcda
+    for dir in ${library_dirs}; do
+        rm -f ${dir}/*.gcda
+    done
     # Location with CMake
-    rm -f $library_dir/CMakeFiles/*.dir/*.gcda
+    for dir in ${library_dirs}; do
+        rm -f ${dir}/CMakeFiles/*.dir/*.gcda
+    done
 }
 
 if [ $# -gt 0 ] && [ "$1" = "--help" ]; then
@@ -75,13 +79,18 @@
 fi
 
 if in_mbedtls_repo; then
-    library_dir='library'
+    library_dirs='library tf-psa-crypto/core tf-psa-crypto/drivers/builtin'
     title='Mbed TLS'
 else
-    library_dir='core'
+    library_dirs='core drivers/builtin'
     title='TF-PSA-Crypto'
 fi
 
+lcov_dirs=""
+for dir in ${library_dirs}; do
+    lcov_dirs="${lcov_dirs} --directory ${dir}"
+done
+
 main=lcov_library_report
 while getopts r OPTLET; do
     case $OPTLET in
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 4e90bff..a9d5c84 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -3,13 +3,6 @@
     ${CMAKE_THREAD_LIBS_INIT}
 )
 
-# Set the project root directory if it's not already defined, as may happen if
-# the tests folder is included directly by a parent project, without including
-# the top level CMakeLists.txt.
-if(NOT DEFINED MBEDTLS_DIR)
-    set(MBEDTLS_DIR ${CMAKE_SOURCE_DIR})
-endif()
-
 if(NOT MBEDTLS_PYTHON_EXECUTABLE)
     message(FATAL_ERROR "Cannot build test suites without Python 3")
 endif()
diff --git a/tests/scripts/components-build-system.sh b/tests/scripts/components-build-system.sh
index a2c32f7..3047e76 100644
--- a/tests/scripts/components-build-system.sh
+++ b/tests/scripts/components-build-system.sh
@@ -135,7 +135,32 @@
     make
     ./cmake_package
     if [[ "$OSTYPE" == linux* ]]; then
-        PKG_CONFIG_PATH="${build_variant_dir}/mbedtls/pkgconfig" ${root_dir}/tests/scripts/pkgconfig.sh
+        PKG_CONFIG_PATH="${build_variant_dir}/mbedtls/pkgconfig" \
+        ${root_dir}/tests/scripts/pkgconfig.sh \
+        mbedtls mbedx509 mbedcrypto
+        # These are the EXPECTED package names. Renaming these could break
+        # consumers of pkg-config, consider carefully.
+    fi
+}
+
+component_test_tf_psa_crypto_cmake_as_package () {
+    # Remove existing generated files so that we use the ones CMake
+    # generates
+    make neat
+
+    msg "build: cmake 'as-package' build"
+    root_dir="$(pwd)"
+    cd tf-psa-crypto/programs/test/cmake_package
+    build_variant_dir="$(pwd)"
+    cmake .
+    make
+    ./cmake_package
+    if [[ "$OSTYPE" == linux* ]]; then
+        PKG_CONFIG_PATH="${build_variant_dir}/tf-psa-crypto/pkgconfig" \
+        ${root_dir}/tests/scripts/pkgconfig.sh \
+        tfpsacrypto
+        # This is the EXPECTED package name. Renaming it could break consumers
+        # of pkg-config, consider carefully.
     fi
 }
 
diff --git a/tests/scripts/pkgconfig.sh b/tests/scripts/pkgconfig.sh
index 2702bfa..07a73b3 100755
--- a/tests/scripts/pkgconfig.sh
+++ b/tests/scripts/pkgconfig.sh
@@ -18,11 +18,14 @@
 
 set -e -u
 
-# These are the EXPECTED package names. Renaming these could break
-# consumers of pkg-config, consider carefully.
-all_pcs="mbedtls mbedx509 mbedcrypto"
+if [ $# -le 0 ]
+then
+    echo " [!] No package names specified" >&2
+    echo "Usage: $0 <package name 1> <package name 2> ..." >&2
+    exit 1
+fi
 
-for pc in $all_pcs; do
+for pc in "$@"; do
     printf "testing package config file: ${pc} ... "
     pkg-config --validate "${pc}"
     version="$(pkg-config --modversion "${pc}")"
diff --git a/tf-psa-crypto/CMakeLists.txt b/tf-psa-crypto/CMakeLists.txt
index 63a71fc..21eb64e 100644
--- a/tf-psa-crypto/CMakeLists.txt
+++ b/tf-psa-crypto/CMakeLists.txt
@@ -33,10 +33,6 @@
 
 if(NOT (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR))
 
-if(LIB_INSTALL_DIR)
-    set(CMAKE_INSTALL_LIBDIR "${LIB_INSTALL_DIR}")
-endif()
-
 set(TF_PSA_CRYPTO_PYTHON_EXECUTABLE ${MBEDTLS_PYTHON_EXECUTABLE})
 set(USE_STATIC_TF_PSA_CRYPTO_LIBRARY ${USE_STATIC_MBEDTLS_LIBRARY})
 set(USE_SHARED_TF_PSA_CRYPTO_LIBRARY ${USE_SHARED_MBEDTLS_LIBRARY})
@@ -57,15 +53,18 @@
 
 else(NOT (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR))
 
+set(TF_PSA_CRYPTO_VERSION 0.1.0)
+set(TF_PSA_CRYPTO_SOVERSION 0)
+
 if(TEST_CPP)
     project("TF-PSA-Crypto"
         LANGUAGES C CXX
-        VERSION 0.1.0
+        VERSION ${TF_PSA_CRYPTO_VERSION}
     )
 else()
     project("TF-PSA-Crypto"
         LANGUAGES C
-        VERSION 0.1.0
+        VERSION ${TF_PSA_CRYPTO_VERSION}
     )
 endif()
 
diff --git a/tf-psa-crypto/TF-PSA-Crypto.cmake b/tf-psa-crypto/TF-PSA-Crypto.cmake
index e520ad1..b96dab2 100644
--- a/tf-psa-crypto/TF-PSA-Crypto.cmake
+++ b/tf-psa-crypto/TF-PSA-Crypto.cmake
@@ -1,3 +1,4 @@
+include(CMakePackageConfigHelpers)
 include(GNUInstallDirs)
 
 # Determine if TF-PSA-Crypto is being built as a subproject using add_subdirectory()
@@ -13,6 +14,19 @@
 set(MBEDTLS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/..)
 set(MBEDTLS_FRAMEWORK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framework)
 
+# Put the version numbers into relevant files
+set(version_number_files
+        doxygen/input/doc_mainpage.h
+        doxygen/tfpsacrypto.doxyfile)
+foreach(file ${version_number_files})
+    configure_file(${file}.in
+                   ${TF_PSA_CRYPTO_DIR}/${file})
+endforeach(file)
+
+ADD_CUSTOM_TARGET(${TF_PSA_CRYPTO_TARGET_PREFIX}apidoc
+    COMMAND doxygen tfpsacrypto.doxyfile
+    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doxygen)
+
 option(ENABLE_PROGRAMS "Build TF-PSA-Crypto programs." ON)
 
 option(UNSAFE_BUILD "Allow unsafe builds. These builds ARE NOT SECURE." OFF)
@@ -27,7 +41,7 @@
 endif()
 
 # Support for package config and install to be added later.
-option(DISABLE_PACKAGE_CONFIG_AND_INSTALL "Disable package configuration, target export and installation" ON)
+option(DISABLE_PACKAGE_CONFIG_AND_INSTALL "Disable package configuration, target export and installation" ${TF_PSA_CRYPTO_AS_SUBPROJECT})
 
 if (CMAKE_C_SIMULATE_ID)
     set(COMPILER_ID ${CMAKE_C_SIMULATE_ID})
@@ -101,7 +115,7 @@
 find_package(Threads)
 
 # If this is the root project add longer list of available CMAKE_BUILD_TYPE values
-if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
+if(NOT TF_PSA_CRYPTO_AS_SUBPROJECT)
     set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE}
         CACHE STRING "Choose the type of build: None Debug Release Coverage ASan ASanDbg MemSan MemSanDbg Check CheckFull TSan TSanDbg"
         FORCE)
@@ -261,10 +275,6 @@
     endif(CMAKE_COMPILER_IS_GNU OR CMAKE_COMPILER_IS_CLANG)
 endif(CMAKE_BUILD_TYPE STREQUAL "Coverage")
 
-if(LIB_INSTALL_DIR)
-    set(CMAKE_INSTALL_LIBDIR "${LIB_INSTALL_DIR}")
-endif()
-
 if (NOT EXISTS "${MBEDTLS_FRAMEWORK_DIR}/CMakeLists.txt")
     message(FATAL_ERROR "${MBEDTLS_FRAMEWORK_DIR}/CMakeLists.txt not found. Run `git submodule update --init` from the source tree to fetch the submodule contents.")
 endif()
@@ -272,6 +282,7 @@
 add_subdirectory(include)
 add_subdirectory(core)
 add_subdirectory(drivers)
+add_subdirectory(pkgconfig)
 
 #
 # The C files in tests/src directory contain test code shared among test suites
@@ -356,6 +367,17 @@
 
     # additional convenience targets for Unix only
     if(UNIX)
+        # For coverage testing:
+        # 1. Build with:
+        #         cmake -D CMAKE_BUILD_TYPE=Coverage /path/to/source && make
+        # 2. Run the relevant tests for the part of the code you're interested in.
+        #    For the reference coverage measurement, see
+        #    tests/scripts/basic-build-test.sh
+        # 3. Run scripts/lcov.sh to generate an HTML report.
+        ADD_CUSTOM_TARGET(lcov
+            COMMAND ${MBEDTLS_DIR}/scripts/lcov.sh
+        )
+
         ADD_CUSTOM_TARGET(memcheck
             COMMAND sed -i.bak s+/usr/bin/valgrind+`which valgrind`+ DartConfiguration.tcl
             COMMAND ctest -O memcheck.log -D ExperimentalMemCheck
@@ -374,3 +396,39 @@
                     ${CMAKE_CURRENT_BINARY_DIR}/DartConfiguration.tcl COPYONLY)
     endif()
 endif()
+
+if(NOT DISABLE_PACKAGE_CONFIG_AND_INSTALL)
+    configure_package_config_file(
+        "cmake/TF-PSA-CryptoConfig.cmake.in"
+        "cmake/TF-PSA-CryptoConfig.cmake"
+            INSTALL_DESTINATION "cmake")
+
+    write_basic_package_version_file(
+        "cmake/TF-PSA-CryptoConfigVersion.cmake"
+            COMPATIBILITY SameMajorVersion
+            VERSION 0.1.0)
+
+    install(
+        FILES "${CMAKE_CURRENT_BINARY_DIR}/cmake/TF-PSA-CryptoConfig.cmake"
+              "${CMAKE_CURRENT_BINARY_DIR}/cmake/TF-PSA-CryptoConfigVersion.cmake"
+        DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/TF-PSA-Crypto")
+
+    export(
+        EXPORT MbedTLSTargets
+        NAMESPACE TF-PSA-Crypto::
+        FILE "cmake/TF-PSA-CryptoTargets.cmake")
+
+    install(
+        EXPORT MbedTLSTargets
+        NAMESPACE TF-PSA-Crypto::
+        DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/TF-PSA-Crypto"
+        FILE "TF-PSA-CryptoTargets.cmake")
+
+    if(CMAKE_VERSION VERSION_GREATER 3.15 OR CMAKE_VERSION VERSION_EQUAL 3.15)
+        # Do not export the package by default
+        cmake_policy(SET CMP0090 NEW)
+
+        # Make this package visible to the system
+        export(PACKAGE TF-PSA-Crypto)
+    endif()
+endif()
diff --git a/tf-psa-crypto/cmake/.gitignore b/tf-psa-crypto/cmake/.gitignore
new file mode 100644
index 0000000..fc85262
--- /dev/null
+++ b/tf-psa-crypto/cmake/.gitignore
@@ -0,0 +1 @@
+TF-PSA-CryptoConfig.cmake
diff --git a/tf-psa-crypto/cmake/TF-PSA-CryptoConfig.cmake.in b/tf-psa-crypto/cmake/TF-PSA-CryptoConfig.cmake.in
new file mode 100644
index 0000000..94a9195
--- /dev/null
+++ b/tf-psa-crypto/cmake/TF-PSA-CryptoConfig.cmake.in
@@ -0,0 +1,3 @@
+@PACKAGE_INIT@
+
+include("${CMAKE_CURRENT_LIST_DIR}/TF-PSA-CryptoTargets.cmake")
diff --git a/tf-psa-crypto/doxygen/.gitignore b/tf-psa-crypto/doxygen/.gitignore
new file mode 100644
index 0000000..3d1b31d
--- /dev/null
+++ b/tf-psa-crypto/doxygen/.gitignore
@@ -0,0 +1 @@
+tfpsacrypto.doxyfile
diff --git a/tf-psa-crypto/doxygen/input/.gitignore b/tf-psa-crypto/doxygen/input/.gitignore
new file mode 100644
index 0000000..b806578
--- /dev/null
+++ b/tf-psa-crypto/doxygen/input/.gitignore
@@ -0,0 +1 @@
+doc_mainpage.h
diff --git a/tf-psa-crypto/doxygen/input/doc_mainpage.h.in b/tf-psa-crypto/doxygen/input/doc_mainpage.h.in
new file mode 100644
index 0000000..7c6ccb6
--- /dev/null
+++ b/tf-psa-crypto/doxygen/input/doc_mainpage.h.in
@@ -0,0 +1,19 @@
+/**
+ * \file doc_mainpage.h
+ *
+ * \brief Main page documentation file.
+ */
+/*
+ *
+ *  Copyright The Mbed TLS Contributors
+ *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+/**
+ * @mainpage TF-PSA-Crypto v@TF-PSA-Crypto_VERSION@ source code documentation
+ *
+ * This documentation describes the internal structure of the TF-PSA-Crypto
+ * library. It was automatically generated from specially formatted comment
+ * blocks in TF-PSA-Crypto source code using Doxygen (see
+ * http://www.stack.nl/~dimitri/doxygen/ for more information on Doxygen).
+ */
diff --git a/tf-psa-crypto/doxygen/tfpsacrypto.doxyfile.in b/tf-psa-crypto/doxygen/tfpsacrypto.doxyfile.in
new file mode 100644
index 0000000..56de487
--- /dev/null
+++ b/tf-psa-crypto/doxygen/tfpsacrypto.doxyfile.in
@@ -0,0 +1,54 @@
+PROJECT_NAME           = "TF-PSA-Crypto v@TF-PSA-Crypto_VERSION@"
+OUTPUT_DIRECTORY       = ../apidoc/
+FULL_PATH_NAMES        = NO
+OPTIMIZE_OUTPUT_FOR_C  = YES
+EXTRACT_ALL            = YES
+EXTRACT_PRIVATE        = YES
+EXTRACT_STATIC         = YES
+CASE_SENSE_NAMES       = NO
+INPUT                  = ../include input
+FILE_PATTERNS          = *.h
+EXCLUDE                = ../include/psa/crypto_se_driver.h
+RECURSIVE              = YES
+EXCLUDE_SYMLINKS       = YES
+SOURCE_BROWSER         = YES
+REFERENCED_BY_RELATION = YES
+REFERENCES_RELATION    = YES
+ALPHABETICAL_INDEX     = NO
+HTML_OUTPUT            = .
+HTML_TIMESTAMP         = YES
+SEARCHENGINE           = YES
+GENERATE_LATEX         = NO
+MACRO_EXPANSION        = YES
+EXPAND_ONLY_PREDEF     = YES
+INCLUDE_PATH           = ../include
+EXPAND_AS_DEFINED      = MBEDTLS_PRIVATE
+CLASS_DIAGRAMS         = NO
+HAVE_DOT               = YES
+DOT_GRAPH_MAX_NODES    = 200
+MAX_DOT_GRAPH_DEPTH    = 1000
+DOT_TRANSPARENT        = YES
+
+# We mostly use \retval declarations to document which error codes a function
+# can return. The reader can follow the hyperlink to the definition of the
+# constant to get the generic documentation of that error code. If we don't
+# have anything to say about the specific error code for the specific
+# function, we can leave the description part of the \retval command blank.
+# This is perfectly valid as far as Doxygen is concerned. However, with
+# Clang >=15, the -Wdocumentation option emits a warning for empty
+# descriptions.
+#   https://github.com/Mbed-TLS/mbedtls/issues/6960
+#   https://github.com/llvm/llvm-project/issues/60315
+# As a workaround, you can write something like
+#     \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+# This avoids writing redundant text and keeps Clang happy.
+ALIASES += emptydescription=""
+
+# Define away macros that make parsing definitions difficult.
+# MBEDTLS_DEPRECATED is not included in this list as it's important to
+# display deprecated status in the documentation.
+PREDEFINED             = "MBEDTLS_CHECK_RETURN_CRITICAL="   \
+                         "MBEDTLS_CHECK_RETURN_TYPICAL="    \
+                         "MBEDTLS_CHECK_RETURN_OPTIONAL="   \
+                         "MBEDTLS_PRINTF_ATTRIBUTE(a,b)="   \
+                         "__DOXYGEN__"                      \
diff --git a/tf-psa-crypto/drivers/p256-m/CMakeLists.txt b/tf-psa-crypto/drivers/p256-m/CMakeLists.txt
index bc53a5e..ede2831 100644
--- a/tf-psa-crypto/drivers/p256-m/CMakeLists.txt
+++ b/tf-psa-crypto/drivers/p256-m/CMakeLists.txt
@@ -29,7 +29,7 @@
 
 if(INSTALL_TF_PSA_CRYPTO_HEADERS)
 
-  install(DIRECTORY :${CMAKE_CURRENT_SOURCE_DIR}
+  install(DIRECTORY p256-m
     DESTINATION include
     FILE_PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
     DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
@@ -38,6 +38,6 @@
 endif(INSTALL_TF_PSA_CRYPTO_HEADERS)
 
 install(TARGETS ${p256m_target}
-EXPORT MbedTLSTargets
-DESTINATION ${CMAKE_INSTALL_LIBDIR}
-PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)
+  EXPORT MbedTLSTargets
+  DESTINATION ${CMAKE_INSTALL_LIBDIR}
+  PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)
diff --git a/tf-psa-crypto/pkgconfig/.gitignore b/tf-psa-crypto/pkgconfig/.gitignore
new file mode 100644
index 0000000..5460c20
--- /dev/null
+++ b/tf-psa-crypto/pkgconfig/.gitignore
@@ -0,0 +1,2 @@
+Makefile
+*.pc
diff --git a/tf-psa-crypto/pkgconfig/CMakeLists.txt b/tf-psa-crypto/pkgconfig/CMakeLists.txt
new file mode 100644
index 0000000..4b62a04
--- /dev/null
+++ b/tf-psa-crypto/pkgconfig/CMakeLists.txt
@@ -0,0 +1,15 @@
+if(NOT DISABLE_PACKAGE_CONFIG_AND_INSTALL)
+  include(JoinPaths.cmake)
+  join_paths(PKGCONFIG_INCLUDEDIR "\${prefix}" "${CMAKE_INSTALL_INCLUDEDIR}")
+  join_paths(PKGCONFIG_LIBDIR "\${prefix}" "${CMAKE_INSTALL_LIBDIR}")
+
+  #define these manually since minimum CMAKE version is not 3.9 for DESCRIPTION and 3.12 for HOMEPAGE_URL usage in project() below.
+  # Prefix with something that won't clash with newer versions of CMAKE.
+  set(PKGCONFIG_PROJECT_DESCRIPTION "TF-PSA-Crypto is a C library that implements cryptographic primitives. Its small code footprint makes it suitable for embedded systems.")
+  set(PKGCONFIG_PROJECT_HOMEPAGE_URL "https://www.trustedfirmware.org/projects/mbed-tls/")
+
+  configure_file(tfpsacrypto.pc.in tfpsacrypto.pc @ONLY)
+    install(FILES
+    ${CMAKE_CURRENT_BINARY_DIR}/tfpsacrypto.pc
+    DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)
+endif()
diff --git a/tf-psa-crypto/pkgconfig/JoinPaths.cmake b/tf-psa-crypto/pkgconfig/JoinPaths.cmake
new file mode 100644
index 0000000..193caed
--- /dev/null
+++ b/tf-psa-crypto/pkgconfig/JoinPaths.cmake
@@ -0,0 +1,27 @@
+# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+# This module provides function for joining paths
+# known from most languages
+#
+# Copyright The Mbed TLS Contributors
+#
+# This script originates from:
+#   - https://github.com/jtojnar/cmake-snips
+# Jan has provided re-licensing under Apache 2.0 and GPL 2.0+ and
+# allowed for the change of Copyright.
+#
+# Modelled after Python’s os.path.join
+# https://docs.python.org/3.7/library/os.path.html#os.path.join
+# Windows not supported
+function(join_paths joined_path first_path_segment)
+    set(temp_path "${first_path_segment}")
+    foreach(current_segment IN LISTS ARGN)
+        if(NOT ("${current_segment}" STREQUAL ""))
+            if(IS_ABSOLUTE "${current_segment}")
+                set(temp_path "${current_segment}")
+            else()
+                set(temp_path "${temp_path}/${current_segment}")
+            endif()
+        endif()
+    endforeach()
+    set(${joined_path} "${temp_path}" PARENT_SCOPE)
+endfunction()
diff --git a/tf-psa-crypto/pkgconfig/tfpsacrypto.pc.in b/tf-psa-crypto/pkgconfig/tfpsacrypto.pc.in
new file mode 100644
index 0000000..2d130ea
--- /dev/null
+++ b/tf-psa-crypto/pkgconfig/tfpsacrypto.pc.in
@@ -0,0 +1,10 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+includedir=@PKGCONFIG_INCLUDEDIR@
+libdir=@PKGCONFIG_LIBDIR@
+
+Name: @PROJECT_NAME@
+Description: @PKGCONFIG_PROJECT_DESCRIPTION@
+URL: @PKGCONFIG_PROJECT_HOMEPAGE_URL@
+Version: @PROJECT_VERSION@
+Cflags: -I"${includedir}"
+Libs: -L"${libdir}" -lmbedcrypto -lbuiltin -leverest -lp256m
diff --git a/tf-psa-crypto/programs/test/cmake_package/.gitignore b/tf-psa-crypto/programs/test/cmake_package/.gitignore
new file mode 100644
index 0000000..fd34d2b
--- /dev/null
+++ b/tf-psa-crypto/programs/test/cmake_package/.gitignore
@@ -0,0 +1,3 @@
+Makefile
+cmake_package
+tf-psa-crypto
diff --git a/tf-psa-crypto/programs/test/cmake_package/CMakeLists.txt b/tf-psa-crypto/programs/test/cmake_package/CMakeLists.txt
new file mode 100644
index 0000000..20b7322
--- /dev/null
+++ b/tf-psa-crypto/programs/test/cmake_package/CMakeLists.txt
@@ -0,0 +1,35 @@
+cmake_minimum_required(VERSION 2.8.12)
+
+#
+# Simulate configuring and building TF-PSA-Crypto as the user might do it.
+# We'll skip installing it, and use the build directory directly instead.
+#
+
+set(TF-PSA-Crypto_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../..")
+set(TF-PSA-Crypto_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/tf-psa-crypto")
+
+execute_process(
+    COMMAND "${CMAKE_COMMAND}"
+        "-H${TF-PSA-Crypto_SOURCE_DIR}"
+        "-B${TF-PSA-Crypto_BINARY_DIR}"
+        "-DENABLE_PROGRAMS=NO"
+        "-DENABLE_TESTING=NO")
+
+execute_process(
+    COMMAND "${CMAKE_COMMAND}"
+        --build "${TF-PSA-Crypto_BINARY_DIR}")
+
+#
+# Locate the package.
+#
+
+set(TF-PSA-Crypto_DIR "${TF-PSA-Crypto_BINARY_DIR}/cmake")
+find_package(TF-PSA-Crypto REQUIRED)
+
+#
+# At this point, the TF-PSA-Crypto targets should have been imported, and we
+# can now link to them from our own program.
+#
+
+add_executable(cmake_package cmake_package.c)
+target_link_libraries(cmake_package TF-PSA-Crypto::mbedcrypto)
diff --git a/tf-psa-crypto/programs/test/cmake_package/cmake_package.c b/tf-psa-crypto/programs/test/cmake_package/cmake_package.c
new file mode 100644
index 0000000..c12ae7b
--- /dev/null
+++ b/tf-psa-crypto/programs/test/cmake_package/cmake_package.c
@@ -0,0 +1,19 @@
+/*
+ *  Simple program to test that TF-PSA-Crypto builds correctly as a CMake
+ *  package.
+ *
+ *  Copyright The Mbed TLS Contributors
+ *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#include <psa/crypto.h>
+
+/* The main reason to build this is for testing the CMake build, so the program
+ * doesn't need to do very much. It calls a PSA cryptography API to ensure
+ * linkage works, but that is all. */
+int main()
+{
+    psa_crypto_init();
+
+    return 0;
+}
diff --git a/tf-psa-crypto/tests/CMakeLists.txt b/tf-psa-crypto/tests/CMakeLists.txt
index 862d862..0e84bab 100644
--- a/tf-psa-crypto/tests/CMakeLists.txt
+++ b/tf-psa-crypto/tests/CMakeLists.txt
@@ -3,13 +3,6 @@
     ${CMAKE_THREAD_LIBS_INIT}
 )
 
-# Set the project root directory if it's not already defined, as may happen if
-# the tests folder is included directly by a parent project, without including
-# the top level CMakeLists.txt.
-if(NOT DEFINED MBEDTLS_DIR)
-    set(MBEDTLS_DIR ${CMAKE_SOURCE_DIR})
-endif()
-
 if(NOT TF_PSA_CRYPTO_PYTHON_EXECUTABLE)
     message(FATAL_ERROR "Cannot build test suites without Python 3")
 endif()
@@ -357,5 +350,6 @@
     if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/seedfile")
         link_to_source(seedfile)
     endif()
+    link_to_source(Descriptions.txt)
     link_to_source(../../framework/data_files)
 endif()
diff --git a/tf-psa-crypto/tests/Descriptions.txt b/tf-psa-crypto/tests/Descriptions.txt
new file mode 100644
index 0000000..bc25056
--- /dev/null
+++ b/tf-psa-crypto/tests/Descriptions.txt
@@ -0,0 +1,5 @@
+test_suites
+    The various 'test_suite_XXX' programs from the 'tests' directory, executed
+    using 'make check' (Unix make) or 'make test' (Cmake), include test cases
+    (reference test vectors, sanity checks, malformed input for parsing
+    functions, etc.) for all modules except the SSL modules.