1"""Mbed TLS build tree information and manipulation.
2"""
3
4# Copyright The Mbed TLS Contributors
5# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6#
7
8import os
9import inspect
10from typing import Optional
11
12def looks_like_tf_psa_crypto_root(path: str) -> bool:
13    """Whether the given directory looks like the root of the PSA Crypto source tree."""
14    return all(os.path.isdir(os.path.join(path, subdir))
15               for subdir in ['include', 'core', 'drivers', 'programs', 'tests'])
16
17def looks_like_mbedtls_root(path: str) -> bool:
18    """Whether the given directory looks like the root of the Mbed TLS source tree."""
19    return all(os.path.isdir(os.path.join(path, subdir))
20               for subdir in ['include', 'library', 'programs', 'tests'])
21
22def looks_like_root(path: str) -> bool:
23    return looks_like_tf_psa_crypto_root(path) or looks_like_mbedtls_root(path)
24
25def crypto_core_directory(root: Optional[str] = None, relative: Optional[bool] = False) -> str:
26    """
27    Return the path of the directory containing the PSA crypto core
28    for either TF-PSA-Crypto or Mbed TLS.
29
30    Returns either the full path or relative path depending on the
31    "relative" boolean argument.
32    """
33    if root is None:
34        root = guess_project_root()
35    if looks_like_tf_psa_crypto_root(root):
36        if relative:
37            return "core"
38        return os.path.join(root, "core")
39    elif looks_like_mbedtls_root(root):
40        if relative:
41            return "library"
42        return os.path.join(root, "library")
43    else:
44        raise Exception('Neither Mbed TLS nor TF-PSA-Crypto source tree found')
45
46def crypto_library_filename(root: Optional[str] = None) -> str:
47    """Return the crypto library filename for either TF-PSA-Crypto or Mbed TLS."""
48    if root is None:
49        root = guess_project_root()
50    if looks_like_tf_psa_crypto_root(root):
51        return "tfpsacrypto"
52    elif looks_like_mbedtls_root(root):
53        return "mbedcrypto"
54    else:
55        raise Exception('Neither Mbed TLS nor TF-PSA-Crypto source tree found')
56
57def check_repo_path():
58    """Check that the current working directory is the project root, and throw
59    an exception if not.
60    """
61    if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
62        raise Exception("This script must be run from Mbed TLS root")
63
64def chdir_to_root() -> None:
65    """Detect the root of the Mbed TLS source tree and change to it.
66
67    The current directory must be up to two levels deep inside an Mbed TLS
68    source tree.
69    """
70    for d in [os.path.curdir,
71              os.path.pardir,
72              os.path.join(os.path.pardir, os.path.pardir)]:
73        if looks_like_root(d):
74            os.chdir(d)
75            return
76    raise Exception('Mbed TLS source tree not found')
77
78def guess_project_root():
79    """Guess project source code directory.
80
81    Return the first possible project root directory.
82    """
83    dirs = set({})
84    for frame in inspect.stack():
85        path = os.path.dirname(frame.filename)
86        for d in ['.', os.path.pardir] \
87                 + [os.path.join(*([os.path.pardir]*i)) for i in range(2, 10)]:
88            d = os.path.abspath(os.path.join(path, d))
89            if d in dirs:
90                continue
91            dirs.add(d)
92            if looks_like_root(d):
93                return d
94    raise Exception('Neither Mbed TLS nor TF-PSA-Crypto source tree found')
95
96def guess_mbedtls_root(root: Optional[str] = None) -> str:
97    """Guess Mbed TLS source code directory.
98
99    Return the first possible Mbed TLS root directory.
100    Raise an exception if we are not in Mbed TLS.
101    """
102    if root is None:
103        root = guess_project_root()
104    if looks_like_mbedtls_root(root):
105        return root
106    else:
107        raise Exception('Mbed TLS source tree not found')
108
109def guess_tf_psa_crypto_root(root: Optional[str] = None) -> str:
110    """Guess TF-PSA-Crypto source code directory.
111
112    Return the first possible TF-PSA-Crypto root directory.
113    Raise an exception if we are not in TF-PSA-Crypto.
114    """
115    if root is None:
116        root = guess_project_root()
117    if looks_like_tf_psa_crypto_root(root):
118        return root
119    else:
120        raise Exception('TF-PSA-Crypto source tree not found')
121