1#!/bin/sh
2#
3# Copyright The Mbed TLS Contributors
4# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
5#
6# Purpose
7#
8# Show external links in built libraries (X509 or TLS) or modules. This is
9# usually done to list Crypto dependencies or to check modules'
10# interdependencies.
11#
12# Usage:
13# - build the library with debug symbols and the config you're interested in
14#   (default, full minus MBEDTLS_USE_PSA_CRYPTO, full, etc.)
15# - launch this script with 1 or more arguments depending on the analysis' goal:
16#     - if only 1 argument is used (which is the name of the used config,
17#       ex: full), then the analysis is done on libmbedx509 and libmbedtls
18#       libraries by default
19#     - if multiple arguments are provided, then modules' names (ex: pk,
20#       pkparse, pkwrite, etc) are expected after the 1st one and the analysis
21#       will be done on those modules instead of the libraries.
22
23set -eu
24
25# list mbedtls_ symbols of a given type in a static library
26syms() {
27    TYPE="$1"
28    FILE="$2"
29
30    nm "$FILE" | sed -n "s/[0-9a-f ]*${TYPE} \(mbedtls_.*\)/\1/p" | sort -u
31}
32
33# Check if the provided name refers to a module or library and return the
34# same path with proper extension
35get_file_with_extension() {
36    BASE=$1
37    if [ -f $BASE.o ]; then
38        echo $BASE.o
39    elif [ -f $BASE.a ]; then
40        echo $BASE.a
41    fi
42}
43
44# create listings for the given library
45list() {
46    NAME="$1"
47    FILE=$(get_file_with_extension "library/${NAME}")
48    PREF="${CONFIG}-$NAME"
49
50    syms '[TRrD]' $FILE > ${PREF}-defined
51    syms U $FILE > ${PREF}-unresolved
52
53    diff ${PREF}-defined ${PREF}-unresolved \
54        | sed -n 's/^> //p' > ${PREF}-external
55    sed 's/mbedtls_\([^_]*\).*/\1/' ${PREF}-external \
56        | uniq -c | sort -rn > ${PREF}-modules
57
58    rm ${PREF}-defined ${PREF}-unresolved
59}
60
61CONFIG="${1:-unknown}"
62
63# List of modules to check is provided as parameters
64if [ $# -gt 1 ]; then
65    shift 1
66    ITEMS_TO_CHECK="$@"
67else
68    ITEMS_TO_CHECK="libmbedx509 libmbedtls"
69fi
70
71for ITEM in $ITEMS_TO_CHECK; do
72    list $ITEM
73done
74