diff --git a/.gitmodules b/.gitmodules index 54e3f307..f969d056 100644 --- a/.gitmodules +++ b/.gitmodules @@ -20,3 +20,6 @@ [submodule "external/zlib/zlib_code"] path = external/zlib/zlib_code url = https://github.com/madler/zlib.git +[submodule "external/sgx-emm/emm_src"] + path = external/sgx-emm/emm_src + url = https://github.com/intel/sgx-emm.git diff --git a/Makefile b/Makefile index 868eed71..6b61a34e 100644 --- a/Makefile +++ b/Makefile @@ -55,6 +55,7 @@ preparation: cd external/openmp/openmp_code && git apply ../0001-Enable-OpenMP-in-SGX.patch >/dev/null 2>&1 || git apply ../0001-Enable-OpenMP-in-SGX.patch --check -R cd external/protobuf/protobuf_code && git apply ../sgx_protobuf.patch >/dev/null 2>&1 || git apply ../sgx_protobuf.patch --check -R cd external/zlib/zlib_code && git apply ../sgx_zlib.patch >/dev/null 2>&1 || git apply ../sgx_zlib.patch --check -R + ./external/sgx-emm/create_symlink.sh @# download prebuilt binaries ./download_prebuilt.sh ./external/dcap_source/QuoteGeneration/download_prebuilt.sh diff --git a/Makefile.psw_dcap b/Makefile.psw_dcap index 402c907d..c180e2b7 100644 --- a/Makefile.psw_dcap +++ b/Makefile.psw_dcap @@ -64,12 +64,19 @@ ippcp: $(MAKE) -C external/ippcp_internal/ sdk: ippcp - $(MAKE) -C sdk/ USE_OPT_LIBS=$(USE_OPT_LIBS) + $(MAKE) -C sdk/ MITIGATION-CVE-2020-0551=LOAD + $(MAKE) -C sdk/ clean + $(MAKE) -C sdk/ MITIGATION-CVE-2020-0551=CF + $(MAKE) -C sdk/ clean + $(MAKE) -C sdk/ + $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl MITIGATION-CVE-2020-0551=LOAD + $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl MITIGATION-CVE-2020-0551=CF clean + $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl MITIGATION-CVE-2020-0551=CF $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl clean $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl install_sdk: sdk - ./linux/installer/bin/build-installpkg.sh sdk + ./linux/installer/bin/build-installpkg.sh sdk cve-2020-0551 ifeq ($(call DIR_EXISTS,$(SGX_SDK)),) ./linux/installer/bin/sgx_linux_x64_sdk_*.bin --prefix=$(dir $(SGX_SDK)) endif diff --git a/Makefile.psw_tdx b/Makefile.psw_tdx new file mode 100644 index 00000000..1fc8c144 --- /dev/null +++ b/Makefile.psw_tdx @@ -0,0 +1,81 @@ +# +# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# + +include buildenv.mk + +define DIR_EXISTS +$(shell test -d $(1) && echo "$(1)") +endef + +SGX_SDK := /tmp/intel/sgxsdk +export SGX_SDK + +.PHONY: build psw dcap install clean sdk install_sdk ippcp + +build: psw dcap + +psw: install_sdk + @$(MAKE) -C psw/urts/linux/ USE_OPT_LIBS=$(USE_OPT_LIBS) + +dcap: install_sdk + @$(MAKE) -C external/dcap_source/ + +install: + @$(MAKE) -I linux/installer/common/psw-tdx -f linux/installer/common/psw-tdx/Makefile SRCDIR=. DESTDIR=$(DESTDIR) install + +clean: + @$(MAKE) -C psw/urts/linux/ clean + @$(MAKE) -C external/dcap_source/ clean + @$(MAKE) -C sdk/ clean + @$(MAKE) -C external/ippcp_internal/ clean +ifneq ($(call DIR_EXISTS,$(SGX_SDK)),) + $(SGX_SDK)/uninstall.sh +endif + +ippcp: + $(MAKE) -C external/ippcp_internal/ +sdk: ippcp + $(MAKE) -C sdk/ MITIGATION-CVE-2020-0551=LOAD + $(MAKE) -C sdk/ clean + $(MAKE) -C sdk/ MITIGATION-CVE-2020-0551=CF + $(MAKE) -C sdk/ clean + $(MAKE) -C sdk/ + $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl MITIGATION-CVE-2020-0551=LOAD + $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl MITIGATION-CVE-2020-0551=CF clean + $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl MITIGATION-CVE-2020-0551=CF + $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl clean + $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl + +install_sdk: sdk + ./linux/installer/bin/build-installpkg.sh sdk cve-2020-0551 +ifeq ($(call DIR_EXISTS,$(SGX_SDK)),) + ./linux/installer/bin/sgx_linux_x64_sdk_*.bin --prefix=$(dir $(SGX_SDK)) +endif diff --git a/README.md b/README.md index 77e69baf..3acc74c6 100644 --- a/README.md +++ b/README.md @@ -104,50 +104,74 @@ Build the Intel(R) SGX SDK and Intel(R) SGX PSW Package * Ubuntu\* 18.04 LTS Server 64bits * Ubuntu\* 20.04 LTS Desktop 64bits * Ubuntu\* 20.04 LTS Server 64bits - * Red Hat Enterprise Linux Server release 8.4 64bits + * Ubuntu\* 22.04 LTS Server 64bits + * Red Hat Enterprise Linux Server release 8.6 64bits * CentOS Stream 8 64bits + * CentOS 8.3 64bits + * SUSE Linux Enterprise Server 15.4 64bits + * Anolis OS 8.6 64bits + * Debian 10 64bits - Use the following command(s) to install the required tools to build the Intel(R) SGX SDK: - * On Ubuntu 18.04: + * On Ubuntu 18.04 and Debian 10: ``` $ sudo apt-get install build-essential ocaml ocamlbuild automake autoconf libtool wget python libssl-dev git cmake perl ``` - * On Ubuntu 20.04: + * On Ubuntu 20.04 and Ubuntu 22.04: ``` $ sudo apt-get install build-essential ocaml ocamlbuild automake autoconf libtool wget python-is-python3 libssl-dev git cmake perl ``` - * On Red Hat Enterprise Linux 8.4: + * On Red Hat Enterprise Linux 8.6: ``` $ sudo yum groupinstall 'Development Tools' $ sudo yum install ocaml ocaml-ocamlbuild wget python2 openssl-devel git cmake perl $ sudo alternatives --set python /usr/bin/python2 ``` - * On CentOS Stream 8: + * On CentOS Stream 8 and CentOS 8.3: ``` $ sudo dnf group install 'Development Tools' $ sudo dnf --enablerepo=powertools install ocaml ocaml-ocamlbuild redhat-rpm-config openssl-devel wget rpm-build git cmake perl python2 $ sudo alternatives --set python /usr/bin/python2 + ``` + * On Anolis 8.6: + ``` + $ sudo dnf group install 'Development Tools' + $ sudo dnf --enablerepo=PowerTools install ocaml ocaml-ocamlbuild redhat-rpm-config openssl-devel wget rpm-build git cmake perl python2 + $ sudo alternatives --set python /usr/bin/python2 + ``` + * On SUSE Linux Enterprise Server 15.4: + ``` + $ sudo zypper install --type pattern devel_basis + $ sudo zypper install ocaml ocaml-ocamlbuild automake autoconf libtool wget python libopenssl-devel rpm-build git cmake perl ``` **Note**: To build Intel(R) SGX SDK, gcc version is required to be 7.3 or above and glibc version is required to be 2.27 or above. - Use the following command to install additional required tools and latest Intel(R) SGX SDK Installer to build the Intel(R) SGX PSW: 1) To install the additional required tools: - * On Ubuntu 18.04: + * On Debian 10: ``` - $ sudo apt-get install libssl-dev libcurl4-openssl-dev protobuf-compiler libprotobuf-dev debhelper cmake reprepro unzip lsb-release + $ sudo apt-get install libssl-dev libcurl4-openssl-dev protobuf-compiler libprotobuf-dev debhelper cmake reprepro unzip lsb-release libsystemd0 ``` - * On Ubuntu 20.04: + * On Ubuntu 20.04 and Ubuntu 22.04: ``` - $ sudo apt-get install libssl-dev libcurl4-openssl-dev protobuf-compiler libprotobuf-dev debhelper cmake reprepro unzip pkgconf libboost-dev libboost-system-dev protobuf-c-compiler libprotobuf-c-dev lsb-release + $ sudo apt-get install libssl-dev libcurl4-openssl-dev protobuf-compiler libprotobuf-dev debhelper cmake reprepro unzip pkgconf libboost-dev libboost-system-dev libboost-thread-dev protobuf-c-compiler libprotobuf-c-dev lsb-release libsystemd0 ``` - * On Red Hat Enterprise Linux 8.4: + * On Red Hat Enterprise Linux 8.6: ``` - $ sudo yum install openssl-devel libcurl-devel protobuf-devel cmake rpm-build createrepo yum-utils pkgconf boost-devel protobuf-lite-devel protobuf-c-compiler protobuf-c-devel + $ sudo yum install openssl-devel libcurl-devel protobuf-devel cmake rpm-build createrepo yum-utils pkgconf boost-devel protobuf-lite-devel protobuf-c-compiler protobuf-c-devel systemd-libs ``` - * On CentOS Stream 8: + * On CentOS Stream 8 and CentOS 8.3: ``` - $ sudo dnf --enablerepo=powertools install openssl-devel libcurl-devel protobuf-devel cmake rpm-build createrepo yum-utils pkgconf boost-devel protobuf-lite-devel protobuf-c-compiler protobuf-c-devel + $ sudo dnf --enablerepo=powertools install openssl-devel libcurl-devel protobuf-devel cmake rpm-build createrepo yum-utils pkgconf boost-devel protobuf-lite-devel protobuf-c-compiler protobuf-c-devel systemd-libs ``` - 2) To install latest Intel(R) SGX SDK Installer + * On Anolis 8.6: + ``` + $ sudo dnf --enablerepo=PowerTools install openssl-devel libcurl-devel protobuf-devel cmake rpm-build createrepo yum-utils pkgconf boost-devel protobuf-lite-devel protobuf-c-compiler protobuf-c-devel systemd-libs + ``` + * On SUSE Linux Enterprise Server 15.4: + ``` + $ sudo zypper install libopenssl-devel libcurl-devel protobuf-devel cmake rpm-build createrepo libsystemd0 + ``` + 2) To install latest Intel(R) SGX SDK Installer Ensure that you have downloaded latest Intel(R) SGX SDK Installer from the [Intel(R) SGX SDK](https://software.intel.com/en-us/sgx-sdk/download) and followed the Installation Guide in the same page to install latest Intel(R) SGX SDK Installer. - Download the source code and prepare the submodules and prebuilt binaries: @@ -228,27 +252,27 @@ You can find the tools and libraries generated in the `build/linux` directory. ``` $ make clean ``` -- The build above uses prebuilt Intel(R) Architecture Enclaves(LE/PvE/QE/PCE) - the files ``psw/ae/data/prebuilt/libsgx_*.signed.so``, which have been signed by Intel in advance. - To build those enclaves by yourself (without a signature), first you need to install latest Intel(R) SGX SDK from the [Intel(R) SGX SDK](https://software.intel.com/en-us/sgx-sdk/download) and then build PSW with the default configuration. After that, you can build each Architecture Enclave by using the `make` command from the corresponding folder: + The build above uses prebuilt Intel(R) Architecture Enclaves(LE/PvE/QE/PCE) - the files ``psw/ae/data/prebuilt/libsgx_*.signed.so``, which have been signed by Intel in advance. +- To build those enclaves by yourself (without a signature), first you need to install latest Intel(R) SGX SDK from the [Intel(R) SGX SDK](https://software.intel.com/en-us/sgx-sdk/download) and then build PSW with the default configuration. After that, you can build each Architecture Enclave by using the `make` command from the corresponding folder: ``` $ cd psw/ae/le $ make ``` - To build the Intel(R) SGX PSW installer, enter the following command: - * On Ubuntu 18.04 and Ubuntu 20.04: + * On Ubuntu 18.04, Ubuntu 20.04, Ubuntu 22.04 and Debian 10: ``` $ make deb_psw_pkg ``` You can find the generated Intel(R) SGX PSW installers located under `linux/installer/deb/libsgx-urts`, `linux/installer/deb/libsgx-enclave-common`, `linux/installer/deb/libsgx-uae-service`, `linux/installer/deb/libsgx-epid`, `linux/installer/deb/libsgx-launch`, `linux/installer/deb/libsgx-quote-ex` and `linux/installer/deb/sgx-aesm-service` respectively. - **Note**: On Ubuntu 18.04 and Ubuntu 20.04, besides the Intel(R) SGX PSW installer, the above command generates another debug symbol package named ``package-name-dbgsym_${version}-${revision}_amd64.ddeb`` for debug purpose. + **Note**: Besides the Intel(R) SGX PSW installer, the above command generates another debug symbol package named ``package-name-dbgsym_${version}-${revision}_amd64.ddeb`` for debug purpose. **Note**: Starting with the 2.10 release, besides the Intel(R) SGX PSW installer, the above command generates [SGXDataCenterAttestationPrimitives](https://github.com/intel/SGXDataCenterAttestationPrimitives/) installers as well. - + **Note**: On Debian 10, the default PATH environment may not include /sbin. In this case, before trigger the build, please add /sbin to PATH environment by `export PATH=$PATH:/sbin`. **Note**: The above command builds the Intel(R) SGX PSW with default configuration firstly and then generates the target PSW Installer. To build the Intel(R) SGX PSW Installer without optimization and with full debug information kept in the tools and libraries, enter the following command: ``` $ make deb_psw_pkg DEBUG=1 ``` - * On Red Hat Enterprise Linux 8.4 and CentOS Stream 8: + * On Red Hat Enterprise Linux 8.6, CentOS Stream 8, CentOS 8.3, Anolis OS 8.6 and SUSE Linux Enterprise Server 15.4: ``` $ make rpm_psw_pkg ``` @@ -259,7 +283,7 @@ You can find the tools and libraries generated in the `build/linux` directory. $ make rpm_psw_pkg DEBUG=1 ``` - - To build local Debian package repository, enter the following command: +- To build local Debian package repository, enter the following command: ``` $ make deb_local_repo ``` @@ -267,8 +291,7 @@ You can find the tools and libraries generated in the `build/linux` directory. **Note**: The above command builds the local package repository. If you want to use it, you need to add it to the system repository configuration. The local package repository is not signed, you need to trust it for the purpose of development. - - To add the local Debian package repository to the system repository configuration, append the following line to /etc/apt/sources.list. You need to replace PATH_TO_LOCAL_REPO with the proper path on your system: - +- To add the local Debian package repository to the system repository configuration, append the following line to /etc/apt/sources.list. You need to replace PATH_TO_LOCAL_REPO with the proper path on your system: * On Ubuntu 18.04: ``` deb [trusted=yes arch=amd64] file:/PATH_TO_LOCAL_REPO bionic main @@ -277,13 +300,20 @@ You can find the tools and libraries generated in the `build/linux` directory. ``` deb [trusted=yes arch=amd64] file:/PATH_TO_LOCAL_REPO focal main ``` + * On Ubuntu 22.04: + ``` + deb [trusted=yes arch=amd64] file:/PATH_TO_LOCAL_REPO jammy main + ``` + * On Debian 10: + ``` + deb [trusted=yes arch=amd64] file:/PATH_TO_LOCAL_REPO buster main + ``` After that, you need to update the apt: - * On Ubuntu 18.04 and Ubuntu 20.04: ``` $ sudo apt update ``` - - To build local RPM package repository, enter the following command: +- To build local RPM package repository, enter the following command: ``` $ make rpm_local_repo ``` @@ -291,16 +321,24 @@ You can find the tools and libraries generated in the `build/linux` directory. **Note**: The above command builds the local package repository. If you want to use it, you need to add it to the system repository configuration. Since the local package repository is not signed with GPG, you should ignore the gpgcheck when installing the packages. - - To add the local RPM package repository to the system repository configuration, you can use the following command. You need to replace PATH_TO_LOCAL_REPO with the proper path on your system: - * On Red Hat Enterprise Linux 8.4 and CentOS Stream 8: +- To add the local RPM package repository to the system repository configuration, you can use the following command. You need to replace PATH_TO_LOCAL_REPO with the proper path on your system: + * On Red Hat Enterprise Linux 8.6, CentOS Stream 8, CentOS 8.3, Anolis OS 8.6: ``` $ sudo yum-config-manager --add-repo file://PATH_TO_LOCAL_REPO ``` - - To ignore the gpgcheck when you install the package, enter the following command: - * On Red Hat Enterprise Linux 8.4 and CentOS Stream 8: + * On SUSE Linux Enterprise Server 15.4, you need to replace LOCAL_REPO_ALIAS with proper alias name for the local repo: + ``` + $ sudo zypper addrepo PATH_TO_LOCAL_REPO LOCAL_REPO_ALIAS + ``` +- To ignore the gpgcheck when you install the package, enter the following command: + * On Red Hat Enterprise Linux 8.6, CentOS Stream 8, CentOS 8.3, Anolis OS 8.6: ``` $ sudo yum --nogpgcheck install ``` + * On SUSE Linux Enterprise Server 15.5: + ``` + $ sudo zypper --no-gpg-checks install + ``` Install the Intel(R) SGX SDK ------------------------ @@ -310,19 +348,33 @@ Install the Intel(R) SGX SDK * Ubuntu\* 18.04 LTS Server 64bits * Ubuntu\* 20.04 LTS Desktop 64bits * Ubuntu\* 20.04 LTS Server 64bits - * Red Hat Enterprise Linux Server release 8.4 64bits + * Ubuntu\* 22.04 LTS Server 64bits + * Red Hat Enterprise Linux Server release 8.6 64bits * CentOS Stream 8 64bits + * CentOS 8.3 64bits + * SUSE Linux Enterprise Server 15.4 64bits + * Anolis OS 8.6 64bits + * Debian 10 64bits - Use the following command to install the required tool to use Intel(R) SGX SDK: - * On Ubuntu 18.04 and Ubuntu 20.04: + * On Ubuntu 18.04, Ubuntu 20.04 and Debian 10: ``` $ sudo apt-get install build-essential python ``` - * On Red Hat Enterprise Linux 8.4 and CentOS Stream 8: + * On Ubuntu 22.04: + ``` + $ sudo apt-get install build-essential python2 + ``` + * On Red Hat Enterprise Linux 8.6, CentOS Stream 8, CentOS 8.3 and Anolis OS 8.6: ``` $ sudo yum groupinstall 'Development Tools' $ sudo yum install python2 $ sudo alternatives --set python /usr/bin/python2 ``` + * On SUSE Linux Enterprise Server 15.4: + ``` + $ sudo zypper install --type pattern devel_basis + $ sudo zypper install python + ``` ### Install the Intel(R) SGX SDK To install the Intel(R) SGX SDK, invoke the installer, as follows: @@ -374,37 +426,50 @@ Install the Intel(R) SGX PSW * Ubuntu\* 18.04 LTS Server 64bits * Ubuntu\* 20.04 LTS Desktop 64bits * Ubuntu\* 20.04 LTS Server 64bits - * Red Hat Enterprise Linux Server release 8.4 64bits + * Ubuntu\* 22.04 LTS Server 64bits + * Red Hat Enterprise Linux Server release 8.6 64bits * CentOS Stream 8 64bits + * CentOS 8.3 64bits + * SUSE Linux Enterprise Server 15.4 64bits + * Anolis OS 8.6 64bits + * Debian 10 64bits - Ensure that you have a system with the following required hardware: * 6th Generation Intel(R) Core(TM) Processor or newer - Configure the system with the **Intel SGX hardware enabled** option and install Intel(R) SGX driver in advance. See the earlier topic, *Build and Install the Intel(R) SGX Driver*, for information on how to install the Intel(R) SGX driver. - Install the library using the following command: - * On Ubuntu 18.04 and Ubuntu 20.04: + * On Ubuntu 18.04, Ubuntu 20.04, Ubuntu 22.04 and Debian 10: ``` $ sudo apt-get install libssl-dev libcurl4-openssl-dev libprotobuf-dev ``` - * On Red Hat Enterprise Linux 8.4: + * On Red Hat Enterprise Linux 8.6: ``` $ sudo yum install openssl-devel libcurl-devel protobuf-devel ``` - * On CentOS Stream 8: + * On CentOS Stream 8 and CentOS 8.3: + ``` + $ sudo dnf --enablerepo=powertools install libcurl-devel protobuf-devel + ``` + * On Anolis OS 8.6: ``` $ sudo dnf --enablerepo=PowerTools install libcurl-devel protobuf-devel ``` + * On SUSE Linux Enterprise Server 15.4: + ``` + $ sudo zypper install libopenssl-devel libcurl-devel protobuf-devel + ``` ### Install the Intel(R) SGX PSW The SGX PSW provides 3 services: launch, EPID-based attestation, and algorithm agnostic attestation. Starting with the 2.8 release, the SGX PSW is split into smaller packages and the user can choose which features and services to install. There are 2 methods to install the required packages: Using individual packages or using the local repo generated by the build system. Using the local repo is recommended since the system will resolve the dependencies automatically. Currently, we support .deb and .rpm based repos. #### Using the local repo(recommended) -| |Ubuntu 18.04 and Ubuntu 20.04|Red Hat Enterprise Linux 8.4, CentOS Stream 8| -| ------------ | ------------ | ------------ | -|launch service |apt-get install libsgx-launch libsgx-urts|yum install libsgx-launch libsgx-urts| -|EPID-based attestation service|apt-get install libsgx-epid libsgx-urts|yum install libsgx-epid libsgx-urts| -|algorithm agnostic attestation service|apt-get install libsgx-quote-ex libsgx-urts|yum install libsgx-quote-ex libsgx-urts| -|DCAP ECDSA-based service |apt-get install libsgx-dcap-ql|yum install libsgx-dcap-ql| +| |Ubuntu 18.04, Ubuntu 20.04, Ubuntu 22.04 and Debian 10|Red Hat Enterprise Linux 8.6, CentOS Stream 8 and CentOS 8.3| SUSE Linux Enterprise Server 15| +| ------------ | ------------ | ------------ | ------------ | +|launch service |apt-get install libsgx-launch libsgx-urts|yum install libsgx-launch libsgx-urts|zypper install libsgx-launch libsgx-urts| +|EPID-based attestation service|apt-get install libsgx-epid libsgx-urts|yum install libsgx-epid libsgx-urts|zypper install libsgx-epid libsgx-urts| +|algorithm agnostic attestation service|apt-get install libsgx-quote-ex libsgx-urts|yum install libsgx-quote-ex libsgx-urts|zypper install libsgx-quote-ex libsgx-urts| +|DCAP ECDSA-based service |apt-get install libsgx-dcap-ql|yum install libsgx-dcap-ql|zypper install libsgx-dcap-ql| Optionally, you can install *-dbgsym or *-debuginfo packages to get the debug symbols, and install *-dev or *-devel packages to get the header files for development. @@ -420,14 +485,18 @@ apt-get dist-upgrade -o Dpkg::Options::="--force-overwrite" ``` #### Configure the installation Some packages are configured with recommended dependency on other packages that are not required for certain usage. For instance, the background daemon is not required for container usage. It will be installed by default, but you can drop it by using the additional option during the installation. -* On Ubuntu 18.04 and Ubuntu 20.04: +* On Ubuntu 18.04, Ubuntu 20.04, Ubuntu 22.04 and Debian 10: ``` --no-install-recommends ``` -* On Red Hat Enterprise Linux 8.4 and CentOS Stream 8: +* On Red Hat Enterprise Linux 8.6, CentOS Stream 8, CentOS 8.3 and Anolis OS 8.6: ``` --setopt=install_weak_deps=False ``` +* On SUSE Linux Enterprise Server 15.4: +``` + --no-recommends +``` ### ECDSA attestation To enable ECDSA attestation diff --git a/SampleCode/Cxx11SGXDemo/Enclave/Enclave_private_test.pem b/SampleCode/Cxx11SGXDemo/Enclave/Enclave_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/Cxx11SGXDemo/Enclave/Enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIG4gIBAAKCAYEAroOogvsj/fZDZY8XFdkl6dJmky0lRvnWMmpeH41Bla6U1qLZ -AmZuyIF+mQC/cgojIsrBMzBxb1kKqzATF4+XwPwgKz7fmiddmHyYz2WDJfAjIveJ -ZjdMjM4+EytGlkkJ52T8V8ds0/L2qKexJ+NBLxkeQLfV8n1mIk7zX7jguwbCG1Pr -nEMdJ3Sew20vnje+RsngAzdPChoJpVsWi/K7cettX/tbnre1DL02GXc5qJoQYk7b -3zkmhz31TgFrd9VVtmUGyFXAysuSAb3EN+5VnHGr0xKkeg8utErea2FNtNIgua8H -ONfm9Eiyaav1SVKzPHlyqLtcdxH3I8Wg7yqMsaprZ1n5A1v/levxnL8+It02KseD -5HqV4rf/cImSlCt3lpRg8U5E1pyFQ2IVEC/XTDMiI3c+AR+w2jSRB3Bwn9zJtFlW -KHG3m1xGI4ck+Lci1JvWWLXQagQSPtZTsubxTQNx1gsgZhgv1JHVZMdbVlAbbRMC -1nSuJNl7KPAS/VfzAgEDAoIBgHRXxaynbVP5gkO0ug6Qw/E27wzIw4SmjsxG6Wpe -K7kfDeRskKxESdsA/xCrKkwGwhcx1iIgS5+Qscd1Yg+1D9X9asd/P7waPmWoZd+Z -AhlKwhdPsO7PiF3e1AzHhGQwsUTt/Y/aSI1MpHBvy2/s1h9mFCslOUxTmWw0oj/Q -ldIEgWeNR72CE2+jFIJIyml6ftnb6qzPiga8Bm48ubKh0kvySOqnkmnPzgh+JBD6 -JnBmtZbfPT97bwTT+N6rnPqOOApvfHPf15kWI8yDbprG1l4OCUaIUH1AszxLd826 -5IPM+8gINLRDP1MA6azECPjTyHXhtnSIBZCyWSVkc05vYmNXYUNiXWMajcxW9M02 -wKzFELO8NCEAkaTPxwo4SCyIjUxiK1LbQ9h8PSy4c1+gGP4LAMR8xqP4QKg6zdu9 -osUGG/xRe/uufgTBFkcjqBHtK5L5VI0jeNIUAgW/6iNbYXjBMJ0GfauLs+g1VsOm -WfdgXzsb9DYdMa0OXXHypmV4GwKBwQDUwQj8RKJ6c8cT4vcWCoJvJF00+RFL+P3i -Gx2DLERxRrDa8AVGfqaCjsR+3vLgG8V/py+z+dxZYSqeB80Qeo6PDITcRKoeAYh9 -xlT3LJOS+k1cJcEmlbbO2IjLkTmzSwa80fWexKu8/Xv6vv15gpqYl1ngYoqJM3pd -vzmTIOi7MKSZ0WmEQavrZj8zK4endE3v0eAEeQ55j1GImbypSf7Idh7wOXtjZ7WD -Dg6yWDrri+AP/L3gClMj8wsAxMV4ZR8CgcEA0fzDHkFa6raVOxWnObmRoDhAtE0a -cjUj976NM5yyfdf2MrKy4/RhdTiPZ6b08/lBC/+xRfV3xKVGzacm6QjqjZrUpgHC -0LKiZaMtccCJjLtPwQd0jGQEnKfMFaPsnhOc5y8qVkCzVOSthY5qhz0XNotHHFmJ -gffVgB0iqrMTvSL7IA2yqqpOqNRlhaYhNl8TiFP3gIeMtVa9rZy31JPgT2uJ+kfo -gV7sdTPEjPWZd7OshGxWpT6QfVDj/T9T7L6tAoHBAI3WBf2DFvxNL2KXT2QHAZ9t -k3imC4f7U+wSE6zILaDZyzygA4RUbwG0gv8/TJVn2P/Eynf76DuWHGlaiLWnCbSz -Az2DHBQBBaku409zDQym3j1ugMRjzzSQWzJg0SIyBH3hTmnYcn3+Uqcp/lEBvGW6 -O+rsXFt3pukqJmIV8HzLGGaLm62BHUeZf3dyWm+i3p/hQAL7Xvu04QW70xuGqdr5 -afV7p5eaeQIJXyGQJ0eylV/90+qxjMKiB1XYg6WYvwKBwQCL/ddpgOdHJGN8uRom -e7Zq0Csi3hGheMKlKbN3vcxT5U7MdyHtTZZOJbTvxKNNUNYH/8uD+PqDGNneb29G -BfGzvI3EASyLIcGZF3OhKwZd0jUrWk2y7Vhob91jwp2+t73vdMbkKyI4mHOuXvGv -fg95si9oO7EBT+Oqvhccd2J+F1IVXncccYnF4u5ZGWt5lLewN/pVr7MjjykeaHqN -t+rfnQam2psA6fL4zS2zTmZPzR2tnY8Y1GBTi0Ko1OKd1HMCgcAb5cB/7/AQlhP9 -yQa04PLH9ygQkKKptZp7dy5WcWRx0K/hAHRoi2aw1wZqfm7VBNu2SLcs90kCCCxp -6C5sfJi6b8NpNbIPC+sc9wsFr7pGo9SFzQ78UlcWYK2Gu2FxlMjonhka5hvo4zvg -WxlpXKEkaFt3gLd92m/dMqBrHfafH7VwOJY2zT3WIpjwuk0ZzmRg5p0pG/svVQEH -NZmwRwlopysbR69B/n1nefJ84UO50fLh5s5Zr3gBRwbWNZyzhXk= ------END RSA PRIVATE KEY----- diff --git a/SampleCode/Cxx11SGXDemo/Makefile b/SampleCode/Cxx11SGXDemo/Makefile index 3ff689ad..be048aa7 100644 --- a/SampleCode/Cxx11SGXDemo/Makefile +++ b/SampleCode/Cxx11SGXDemo/Makefile @@ -156,6 +156,7 @@ Enclave_Cpp_Objects := $(Enclave_Cpp_Files:.cpp=.o) Enclave_Name := enclave.so Signed_Enclave_Name := enclave.signed.so Enclave_Config_File := Enclave/Enclave.config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) @@ -256,7 +257,12 @@ $(Enclave_Name): Enclave/Enclave_t.o $(Enclave_Cpp_Objects) @echo "LINK => $@" $(Signed_Enclave_Name): $(Enclave_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave/Enclave_private_test.pem -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) @echo "SIGN => $@" .PHONY: clean diff --git a/SampleCode/Cxx11SGXDemo/README.txt b/SampleCode/Cxx11SGXDemo/README.txt index 13a921a1..e417b772 100644 --- a/SampleCode/Cxx11SGXDemo/README.txt +++ b/SampleCode/Cxx11SGXDemo/README.txt @@ -26,9 +26,12 @@ The project demonstrates serveral C++11 features inside the Enclave: How to Build/Execute the C++11 sample program --------------------------------------------- 1. Install Intel(R) Software Guard Extensions (Intel(R) SGX) SDK for Linux* OS -2. Make sure your environment is set: +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to and put it under the folder. +3. Make sure your environment is set: $ source ${sgx-sdk-install-path}/environment -3. Build the project with the prepared Makefile: +4. Build the project with the prepared Makefile: a. Hardware Mode, Debug build: $ make b. Hardware Mode, Pre-release build: @@ -41,9 +44,9 @@ How to Build/Execute the C++11 sample program $ make SGX_MODE=SIM SGX_PRERELEASE=1 SGX_DEBUG=0 f. Simulation Mode, Release build: $ make SGX_MODE=SIM SGX_DEBUG=0 -4. Execute the binary directly: +5. Execute the binary directly: $ ./app -5. Remember to "make clean" before switching build mode +6. Remember to "make clean" before switching build mode ------------------------------------------------- Launch token initialization diff --git a/SampleCode/Cxx14SGXDemo/Enclave/Enclave_private_test.pem b/SampleCode/Cxx14SGXDemo/Enclave/Enclave_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/Cxx14SGXDemo/Enclave/Enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/Cxx14SGXDemo/Makefile b/SampleCode/Cxx14SGXDemo/Makefile index 4f9be8d9..e0bfba4b 100644 --- a/SampleCode/Cxx14SGXDemo/Makefile +++ b/SampleCode/Cxx14SGXDemo/Makefile @@ -156,6 +156,7 @@ Enclave_Cpp_Objects := $(Enclave_Cpp_Files:.cpp=.o) Enclave_Name := enclave.so Signed_Enclave_Name := enclave.signed.so Enclave_Config_File := Enclave/Enclave.config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) @@ -256,7 +257,12 @@ $(Enclave_Name): Enclave/Enclave_t.o $(Enclave_Cpp_Objects) @echo "LINK => $@" $(Signed_Enclave_Name): $(Enclave_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave/Enclave_private_test.pem -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) @echo "SIGN => $@" .PHONY: clean diff --git a/SampleCode/Cxx14SGXDemo/README.txt b/SampleCode/Cxx14SGXDemo/README.txt index f7c1dfeb..f7518bff 100644 --- a/SampleCode/Cxx14SGXDemo/README.txt +++ b/SampleCode/Cxx14SGXDemo/README.txt @@ -29,9 +29,12 @@ The project demonstrates several C++14 features inside the Enclave: How to Build/Execute the C++14 sample program --------------------------------------------- 1. Install Intel(R) Software Guard Extensions (Intel(R) SGX) SDK for Linux* OS -2. Make sure your environment is set: +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to and put it under the folder. +3. Make sure your environment is set: $ source ${sgx-sdk-install-path}/environment -3. Build the project with the prepared Makefile: +4. Build the project with the prepared Makefile: a. Hardware Mode, Debug build: $ make b. Hardware Mode, Pre-release build: @@ -44,9 +47,9 @@ How to Build/Execute the C++14 sample program $ make SGX_MODE=SIM SGX_PRERELEASE=1 SGX_DEBUG=0 f. Simulation Mode, Release build: $ make SGX_MODE=SIM SGX_DEBUG=0 -4. Execute the binary directly: +5. Execute the binary directly: $ ./app -5. Remember to "make clean" before switching build mode +6. Remember to "make clean" before switching build mode ------------------------------------------------- Launch token initialization diff --git a/SampleCode/Cxx17SGXDemo/App/App.cpp b/SampleCode/Cxx17SGXDemo/App/App.cpp new file mode 100644 index 00000000..817c837d --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/App/App.cpp @@ -0,0 +1,216 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include + +# include +# include +# define MAX_PATH FILENAME_MAX + +#include "sgx_urts.h" +#include "App.h" +#include "Enclave_u.h" + +/* Global EID shared by multiple threads */ +sgx_enclave_id_t global_eid = 0; + +typedef struct _sgx_errlist_t { + sgx_status_t err; + const char *msg; + const char *sug; /* Suggestion */ +} sgx_errlist_t; + +/* Error code returned by sgx_create_enclave */ +static sgx_errlist_t sgx_errlist[] = { + { + SGX_ERROR_UNEXPECTED, + "Unexpected error occurred.", + NULL + }, + { + SGX_ERROR_INVALID_PARAMETER, + "Invalid parameter.", + NULL + }, + { + SGX_ERROR_OUT_OF_MEMORY, + "Out of memory.", + NULL + }, + { + SGX_ERROR_ENCLAVE_LOST, + "Power transition occurred.", + "Please refer to the sample \"PowerTransition\" for details." + }, + { + SGX_ERROR_INVALID_ENCLAVE, + "Invalid enclave image.", + NULL + }, + { + SGX_ERROR_INVALID_ENCLAVE_ID, + "Invalid enclave identification.", + NULL + }, + { + SGX_ERROR_INVALID_SIGNATURE, + "Invalid enclave signature.", + NULL + }, + { + SGX_ERROR_OUT_OF_EPC, + "Out of EPC memory.", + NULL + }, + { + SGX_ERROR_NO_DEVICE, + "Invalid SGX device.", + "Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards." + }, + { + SGX_ERROR_MEMORY_MAP_CONFLICT, + "Memory map conflicted.", + NULL + }, + { + SGX_ERROR_INVALID_METADATA, + "Invalid enclave metadata.", + NULL + }, + { + SGX_ERROR_DEVICE_BUSY, + "SGX device was busy.", + NULL + }, + { + SGX_ERROR_INVALID_VERSION, + "Enclave version was invalid.", + NULL + }, + { + SGX_ERROR_INVALID_ATTRIBUTE, + "Enclave was not authorized.", + NULL + }, + { + SGX_ERROR_ENCLAVE_FILE_ACCESS, + "Can't open enclave file.", + NULL + }, + { + SGX_ERROR_NDEBUG_ENCLAVE, + "The enclave is signed as product enclave, and can not be created as debuggable enclave.", + NULL + }, + { + SGX_ERROR_MEMORY_MAP_FAILURE, + "Failed to reserve memory for the enclave.", + NULL + }, +}; + +/* Check error conditions for loading enclave */ +void print_error_message(sgx_status_t ret) +{ + size_t idx = 0; + size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0]; + + for (idx = 0; idx < ttl; idx++) { + if(ret == sgx_errlist[idx].err) { + if(NULL != sgx_errlist[idx].sug) + printf("Info: %s\n", sgx_errlist[idx].sug); + printf("Error: %s\n", sgx_errlist[idx].msg); + break; + } + } + + if (idx == ttl) + printf("Error: Unexpected error occurred.\n"); +} + +/* Initialize the enclave: + * Call sgx_create_enclave to initialize an enclave instance + */ +int initialize_enclave(void) +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + + /* Call sgx_create_enclave to initialize an enclave instance */ + /* Debug Support: set 2nd parameter to 1 */ + ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, NULL, NULL, &global_eid, NULL); + if (ret != SGX_SUCCESS) { + print_error_message(ret); + return -1; + } + + return 0; +} + +/* OCall functions */ +void ocall_print_string(const char *str) +{ + /* Proxy/Bridge will check the length and null-terminate + * the input string to prevent buffer overflow. + */ + printf("%s", str); +} + + +/* Application entry */ +int SGX_CDECL main(int argc, char *argv[]) +{ + (void)(argc); + (void)(argv); + + + /* Initialize the enclave */ + if(initialize_enclave() < 0){ + printf("Enter a character before exit ...\n"); + getchar(); + return -1; + } + + + /* Utilize trusted libraries */ + ecall_libcxx_functions(); + + /* Destroy the enclave */ + sgx_destroy_enclave(global_eid); + + printf("Info: Cxx17DemoEnclave successfully returned.\n"); + + //printf("Enter a character before exit ...\n"); + //getchar(); + return 0; +} + diff --git a/SampleCode/Cxx17SGXDemo/App/App.h b/SampleCode/Cxx17SGXDemo/App/App.h new file mode 100644 index 00000000..9c0ac2e8 --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/App/App.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef _APP_H_ +#define _APP_H_ + +#include +#include +#include +#include + +#include "sgx_error.h" /* sgx_status_t */ +#include "sgx_eid.h" /* sgx_enclave_id_t */ + +#ifndef TRUE +# define TRUE 1 +#endif + +#ifndef FALSE +# define FALSE 0 +#endif + +#if defined(__GNUC__) +# define TOKEN_FILENAME "enclave.token" +# define ENCLAVE_FILENAME "enclave.signed.so" +#endif + +extern sgx_enclave_id_t global_eid; /* global enclave id */ + +#if defined(__cplusplus) +extern "C" { +#endif + +void ecall_libcxx_functions(void); + + +#if defined(__cplusplus) +} +#endif + +#endif /* !_APP_H_ */ diff --git a/SampleCode/Cxx17SGXDemo/App/TrustedLibrary/Libcxx.cpp b/SampleCode/Cxx17SGXDemo/App/TrustedLibrary/Libcxx.cpp new file mode 100644 index 00000000..b14cb026 --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/App/TrustedLibrary/Libcxx.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ +#include +#include + +#include "../App.h" +#include "Enclave_u.h" + +typedef sgx_status_t(*ecall_cxx17_func)(sgx_enclave_id_t); + +ecall_cxx17_func functions_to_test[] = { + ecall_cxx17_static_assert, + ecall_cxx17_template_parameter, + ecall_cxx17_auto_deduction_from_braced_init_list, + ecall_cxx17_nested_namespace, + ecall_cxx17_u8_character_literals, + ecall_cxx17_hexadecimal_floating_point_literals, + ecall_cxx17_structured_binding, + ecall_cxx17_fold_expression, + ecall_cxx17_compile_time_if, + ecall_cxx17_initializer_in_if_switch, + ecall_cxx17_CTAD, + ecall_cxx17_inline_variable, + ecall_cxx17_lambda_capture_this_by_value, + ecall_cxx17_constexpr_lambda, + ecall_cxx17_uncaught_exceptions, + ecall_cxx17_invoke, + ecall_cxx17_reference, + ecall_cxx17_uninitialized_memory_algorithms, + ecall_cxx17_aligned_alloc, + ecall_cxx17_owner_less, + ecall_cxx17_shared_ptr_for_array, + ecall_cxx17_std_byte, + ecall_cxx17_std_conjunction_disjunction_negation, + ecall_cxx17_is_aggregate, + ecall_cxx17_is_swappable, + ecall_cxx17_searchers, + ecall_cxx17_std_has_unique_object_representations, + ecall_cxx17_clamp, + ecall_cxx17_reduce, + ecall_cxx17_inclusive_exclusive_scan, + ecall_cxx17_gcd_lcm, + ecall_cxx17_map_extract_merge, + ecall_cxx17_map_try_emplace_insert_or_assign, + ecall_cxx17_std_size_empty_data, + ecall_cxx17_std_as_const, + ecall_cxx17_optional, + ecall_cxx17_make_from_tuple, + ecall_cxx17_tuple_deduction_guides, + ecall_cxx17_any, + ecall_cxx17_variant, + ecall_cxx17_apply, + ecall_cxx17_align_new_delete, + ecall_cxx17_has_include, + ecall_cxx17_string_view, +}; + +void demo_cond_var_run() +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + ret = ecall_condition_variable_run(global_eid); + if (ret != SGX_SUCCESS) + abort(); +} + +void demo_cond_var_load() +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + ret = ecall_condition_variable_load(global_eid); + if (ret != SGX_SUCCESS) + abort(); +} + +// Examples for C++17 library and compiler features +void ecall_libcxx_functions(void) +{ + for (auto f : functions_to_test) { + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + ret = f(global_eid); + if (ret != SGX_SUCCESS) + abort(); + } + + std::thread th1(demo_cond_var_run); + std::thread th2(demo_cond_var_load); + th2.join(); + th1.join(); +} diff --git a/SampleCode/Cxx17SGXDemo/Enclave/Enclave.config.xml b/SampleCode/Cxx17SGXDemo/Enclave/Enclave.config.xml new file mode 100644 index 00000000..a94d12f0 --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/Enclave/Enclave.config.xml @@ -0,0 +1,12 @@ + + + 0 + 0 + 0x40000 + 0x100000 + 10 + 1 + 0 + 0 + 0xFFFFFFFF + diff --git a/SampleCode/Cxx17SGXDemo/Enclave/Enclave.cpp b/SampleCode/Cxx17SGXDemo/Enclave/Enclave.cpp new file mode 100644 index 00000000..a76eb6e8 --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/Enclave/Enclave.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include /* vsnprintf */ + +#include "Enclave.h" +#include "Enclave_t.h" /* print_string */ + +/* + * printf: + * Invokes OCALL to display the enclave buffer to the terminal. + */ +int printf(const char *fmt, ...) +{ + char buf[BUFSIZ] = {'\0'}; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, BUFSIZ, fmt, ap); + va_end(ap); + ocall_print_string(buf); + return 0; +} diff --git a/SampleCode/Cxx17SGXDemo/Enclave/Enclave.edl b/SampleCode/Cxx17SGXDemo/Enclave/Enclave.edl new file mode 100644 index 00000000..7b8b7882 --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/Enclave/Enclave.edl @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* Enclave.edl - Top EDL file. */ + +enclave { + + + /* Import ECALL/OCALL from sub-directory EDLs. + * [from]: specifies the location of EDL file. + * [import]: specifies the functions to import, + * [*]: implies to import all functions. + */ + + from "TrustedLibrary/Libcxx.edl" import *; + from "sgx_tstdc.edl" import *; + + /* + * ocall_print_string - invokes OCALL to display string buffer inside the enclave. + * [in]: copy the string buffer to App outside. + * [string]: specifies 'str' is a NULL terminated buffer. + */ + untrusted { + void ocall_print_string([in, string] const char *str); + }; + +}; diff --git a/psw/urts/linux/urts_trim.h b/SampleCode/Cxx17SGXDemo/Enclave/Enclave.h similarity index 82% rename from psw/urts/linux/urts_trim.h rename to SampleCode/Cxx17SGXDemo/Enclave/Enclave.h index 11a9fa9f..290bb7ed 100644 --- a/psw/urts/linux/urts_trim.h +++ b/SampleCode/Cxx17SGXDemo/Enclave/Enclave.h @@ -29,30 +29,22 @@ * */ -#ifndef _URTS_TRIM_H_ -#define _URTS_TRIM_H_ +#ifndef _ENCLAVE_H_ +#define _ENCLAVE_H_ -#include -#include -#include -#include "sgx_urts.h" +#include +#include - -#define SGX_CAST(type, item) ((type)(item)) - -#ifdef __cplusplus +#if defined(__cplusplus) extern "C" { #endif +int printf(const char *fmt, ...); +inline const char message[] = "inline variable from Cxx17"; -sgx_status_t SGX_CDECL ocall_trim_range(void* pms); - -sgx_status_t SGX_CDECL ocall_trim_accept(void* pms); - - -#ifdef __cplusplus +#if defined(__cplusplus) } -#endif /* __cplusplus */ - #endif + +#endif /* !_ENCLAVE_H_ */ diff --git a/SampleCode/Cxx17SGXDemo/Enclave/Enclave.lds b/SampleCode/Cxx17SGXDemo/Enclave/Enclave.lds new file mode 100644 index 00000000..e3d9d0ee --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/Enclave/Enclave.lds @@ -0,0 +1,9 @@ +enclave.so +{ + global: + g_global_data_sim; + g_global_data; + enclave_entry; + local: + *; +}; diff --git a/SampleCode/Cxx17SGXDemo/Enclave/Enclave_debug.lds b/SampleCode/Cxx17SGXDemo/Enclave/Enclave_debug.lds new file mode 100644 index 00000000..0d5614f5 --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/Enclave/Enclave_debug.lds @@ -0,0 +1,11 @@ +enclave.so +{ + global: + g_global_data_sim; + g_global_data; + enclave_entry; + g_peak_heap_used; + g_peak_rsrv_mem_committed; + local: + *; +}; diff --git a/SampleCode/Cxx17SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp b/SampleCode/Cxx17SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp new file mode 100644 index 00000000..547d3d00 --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp @@ -0,0 +1,1029 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Enclave.h" +#include "Enclave_t.h" + +using namespace std::literals; + +// Examples for new language and library features introduced by C++17: + +// New language features: +// fold-expressions +// class template argument deduction +// non-type template parameters declared with auto +// compile-time if constexpr +// inline variables +// structured bindings +// initializers for if and switch +// u8 character literal +// simplified nested namespaces +// using-declaration declaring multiple names +// made noexcept part of type system +// new order of evaluation rules +// guaranteed copy elision +// temporary materialization +// lambda capture of *this +// constexpr lambda +// attribute namespaces don't have to repeat +// new attributes: +// [[fallthrough]] +// [[maybe_unused]] +// [[nodiscard]] +// __has_include + +// New library features: +// Utility types +// std::tuple: +// std::apply +// std::make_from_tuple +// std::any +// std::optional +// std::variant +// searchers +// std::as_const +// std::not_fn + +// Memory management +// uninitialized memory algorithms +// std::destroy_at +// std::destroy +// std::destroy_n +// std::uninitialized_move +// std::uninitialized_value_construct +// weak_from_this +// std::aligned_alloc +// transparent std::owner_less +// array support for std::shared_ptr +// allocation functions with explicit alignment + +// Compile-time programming +// std::byte +// std::conjunction/std::disjunction/std::negation +// type trait variable templates (xxx_+v) +// std::is_swappable +// is_invocable +// is_aggregate +// std::has_unique_object_representations + +// Algorithms +// std::clamp +// std::reduce +// std::inclusive_scan +// std::exclusive_scan +// std::gcd +// std::lcm + +// Iterators and containers +// map/set extract and map/set merge +// map/unordered_map try_emplace and insert_or_assign +// contiguous iterators (LegacyContiguousIterator) +// non-member std::size/std::empty/std::data + +// Other +// std::launder +// std::uncaught_exceptions + + +// Fold expressions, for variadic templates +template +int sum(Args&&... args) +{ + return (args + ...); +} +void ecall_cxx17_fold_expression() { + printf("sum of 1, 2, 3, 4 is %d\n", sum(1, 2, 3, 4)); +} + +void ecall_cxx17_CTAD() { + std::pair p(2, 4.5); + auto [p1, p2] = p; + printf("std::pair <%d, %.1f>\n", p1, p2); + + std::tuple t(4, 3, 2.5); + auto [t1, t2, t3] = t; + printf("std::tuple (%d, %d, %.1f)\n", t1, t2, t3); +} + +template +class my_array {}; +// two type template parameters and one template template parameter: +template typename C = my_array> +class Map +{ +public: + Map() { + printf("Map instance constructed\n"); + } + + C key; + C value; +}; +// Use of `auto` as the type for a non-type template parameter +template +struct B {}; +void ecall_cxx17_template_parameter() { + // Allow typename (as an alternative to class) in a template template parameter + [[maybe_unused]] auto myMap = Map{}; + + // A non-type template parameter with a placeholder type + [[maybe_unused]] B<5> b1; // OK: non-type template parameter type is int + [[maybe_unused]] B<'a'> b2; // OK: non-type template parameter type is char +} + +// compile-time static `if` +template +auto get_value(T t) +{ + if constexpr (std::is_pointer_v) + return *t; // deduces return type to int for T = int* + else + return t; // deduces return type to int for T = int +} +void ecall_cxx17_compile_time_if() { + int v = 1234; + assert(get_value(&v) == get_value(v)); +} + +void ecall_cxx17_inline_variable() { + printf("inline variable: %s\n", message); +} + +void ecall_cxx17_structured_binding() { + std::set myset{"hello"}; + std::stringstream ss; + for (int i{2}; i; --i) { + ss.str(""); + if (auto [iter, success] = myset.insert("Hello"); success) { + ss << std::quoted(*iter); + printf("Insert is successful. The value is %s\n", ss.str().c_str()); + } else { + ss << std::quoted(*iter); + printf("The value %s already exists in the set.\n", ss.str().c_str()); + } + } +} + +void ecall_cxx17_initializer_in_if_switch() { + struct Device + { + enum State { SLEEP, READY, BAD }; + auto state() const { return m_state; } + private: + State m_state{}; + }; + + switch (auto dev = Device{}; dev.state()) + { + case Device::SLEEP: + printf("device state: SLEEP\n"); + break; + case Device::READY: + printf("device state: READY\n"); + break; + case Device::BAD: + printf("device state: BAD\n"); + break; + } + + std::map m{{0, "Intel"}, {1, "SGX"}, {2, "SDK"}}; + if (auto it = m.find(1); it != m.end()) { + printf("%s\n", it->second.c_str()); + } else { + printf("Not found\n"); + } + +} + +void ecall_cxx17_u8_character_literals() { + printf("UTF-8 character literals: u8'a' is decimal %d\n", u8'a'); +} + +namespace Intel::SGX::SDK { + void cxx17_nested_namespace() { + printf("Hello from nested namespace\n"); + } +} +void ecall_cxx17_nested_namespace() { + Intel::SGX::SDK::cxx17_nested_namespace(); +} + +struct LambdaCapture { + int accu = 0, incre = 0; + LambdaCapture(int a, int b):accu(a), incre(b) {} + LambdaCapture &increment() { + accu += incre; + return *this; + } + void show() const { + [*this]() { + printf("accu: %d, incre: %d\n", accu, incre); + }(); + } +}; +void ecall_cxx17_lambda_capture_this_by_value() { + auto lc = LambdaCapture(10, 5); + lc.increment().increment(); + lc.show(); +} + +void ecall_cxx17_constexpr_lambda() { + auto Fwd = [](int(*fp)(int), auto a){ return fp(a); }; + auto C = [](auto a){ return a; }; + static_assert(Fwd(C, 3) == 3); +} + +void g(){} +void h(){} +void i(){} +void cxx17_fallthrough(int n) { + switch (n) { + case 1: + case 2: + g(); + [[fallthrough]]; + case 3: // no warning on fallthrough + h(); + case 4: // compiler may warn on fallthrough + if(n < 3) { + i(); + [[fallthrough]]; // OK + } + else { + return; + } + case 5: + while (false) { + [[fallthrough]]; // ill-formed: next statement is not part of the same iteration + } + case 6: + [[fallthrough]]; // ill-formed, no subsequent case or default label + } +} + +struct [[nodiscard]] error_info {}; +error_info enable_missile_safety_mode() {return {};} +void cxx17_nodiscard() { + enable_missile_safety_mode(); // compiler may warn on discarding a nodiscard value +} + +#if __has_include() +# include +# define has_optional 1 + template using optional_t = std::optional; +#elif __has_include() +# include +# define has_optional -1 + template using optional_t = std::experimental::optional; +#else +# define has_optional 0 +# include + +template +class optional_t +{ + V v_{}; bool has_{false}; +public: + optional_t() = default; + optional_t(V&& v) : v_(v), has_{true} {} + V value_or(V&& alt) const& { return has_ ? v_ : alt; } + /*...*/ +}; +#endif +void ecall_cxx17_has_include() { + if (has_optional > 0) + printf(" is present\n"); + else if (has_optional < 0) + printf(" is present\n"); + else + printf(" is not present\n"); + + optional_t op; + printf("op = %d\n", op.value_or(-1)); + op = 42; + printf("op = %d\n", op.value_or(-1)); +} + +int add(int first, int second) { return first + second; } +void ecall_cxx17_apply() { + printf("sum of the pair elements: %d\n", std::apply(add, std::pair(1, 2))); +} + +struct FromTuple { + FromTuple(int first, float second, int third) { + printf("%d, %.2f, %d\n", first, second, third); + } +}; +void ecall_cxx17_make_from_tuple() { + auto tuple = std::make_tuple(42, 3.14f, 0); + std::make_from_tuple(std::move(tuple)); +} + +void ecall_cxx17_tuple_deduction_guides() { +#if !defined(__cpp_deduction_guides) || __cpp_deduction_guides < 201611 + // not supported + return; +#else + int a[2], b[3], c[4]; + std::tuple t1{a, b, c}; +#endif +} + +void ecall_cxx17_any() { + std::any a = 1; + printf("%s:%d\n", a.type().name(), std::any_cast(a)); + a = 3.14; + printf("%s:%f\n", a.type().name(), std::any_cast(a)); + a = true; + printf("%s:%d\n", a.type().name(), std::any_cast(a)); + + try + { + a = 1; + printf("%f\n", std::any_cast(a)); + } + catch (const std::bad_any_cast& e) + { + printf("%s\n", e.what()); + } + + a = 2; + if (a.has_value()) + { + printf("%s:%d\n", a.type().name(), std::any_cast(a)); + } + + a.reset(); + if (!a.has_value()) + { + printf("no value\n"); + } + + a = 3; + int* ia = std::any_cast(&a); + printf("%d\n", *ia); +} + +// optional can be used as the return type of a factory that may fail +std::optional create(bool b) { + if (b) + return "Godzilla"; + return {}; +} +// std::nullopt can be used to create any (empty) std::optional +auto create2(bool b) { + return b ? std::optional{"Godzilla"} : std::nullopt; +} +// std::reference_wrapper may be used to return a reference +auto create_ref(bool b) { + static std::string value = "Godzilla"; + return b ? std::optional>{value} + : std::nullopt; +} +void ecall_cxx17_optional() { + printf("create(false) returned %s\n", create(false).value_or("empty").c_str()); + + // optional-returning factory functions are usable as conditions of while and if + if (auto str = create2(true)) { + printf("create2(true) returned %s\n", (*str).c_str()); + } + + if (auto str = create_ref(true)) { + // using get() to access the reference_wrapper's value + printf("create_ref(true) returned %s\n", str->get().c_str()); + str->get() = "Mothra"; + printf("modifying it changed it to %s\n", str->get().c_str()); + } +} + +void ecall_cxx17_variant() { + std::variant v, w; + v = 42; // v contains int + int i = std::get(v); + assert(42 == i); // succeeds + w = std::get(v); + w = std::get<0>(v); // same effect as the previous line + w = v; // same effect as the previous line + + // std::get(v); // error: no double in [int, float] + // std::get<3>(v); // error: valid index values are 0 and 1 + + try { + std::get(w); // w contains int, not float: will throw + } + catch (const std::bad_variant_access& ex) { + printf("%s\n", ex.what()); + } + + std::variant x("abc"); + // converting constructors work when unambiguous + x = "def"; // converting assignment also works when unambiguous + + std::variant y("abc"); + // casts to void const * when passed a char const * + assert(std::holds_alternative(y)); + y = "xyz"s; + assert(std::holds_alternative(y)); +} + +#include +void ecall_cxx17_searchers() { + std::string haystack = "Lorem ipsum dolor sit amet, consectetur adipiscing elit," + " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"; + std::string needle = "pisci"; + + printf("Using std::default_searcher\n"); + // default_searcher + auto it = std::search(haystack.begin(), haystack.end(), + std::default_searcher( + needle.begin(), needle.end())); + if(it != haystack.end()) + printf("The string %s found at offset %d\n", needle.c_str(), it - haystack.begin()); + else + printf("The string %s not found\n", needle.c_str()); + + printf("Using std::boyer_moore_searcher\n"); + if (const auto it = std::search(haystack.begin(), haystack.end(), + std::experimental::fundamentals_v1::boyer_moore_searcher(needle.begin(), needle.end())); + it != haystack.end() + ) { + printf("The string %s found at offset %d\n", needle.c_str(), it - haystack.begin()); + } else { + printf("The string %s not found\n", needle.c_str()); + } + + printf("Using std::boyer_moore_searcher\n"); + if (const auto it = std::search(haystack.begin(), haystack.end(), + std::experimental::fundamentals_v1::boyer_moore_horspool_searcher(needle.begin(), needle.end())); + it != haystack.end() + ) { + printf("The string %s found at offset %d\n", needle.c_str(), it - haystack.begin()); + } else { + printf("The string %s not found\n", needle.c_str()); + } +} + +void ecall_cxx17_std_as_const() { + std::string mutableString = "Hello World!"; + auto&& constRef = std::as_const(mutableString); + // mutableString.clear(); // OK + // constRef.clear(); // error: 'constRef' is 'const' qualified but 'clear' is not marked const + assert( &constRef == &mutableString ); +} + +static void print(std::string rem, auto first, auto last) { + printf("%s", rem.c_str()); + for (; first != last; ++first) + printf("%s ", (*first).c_str()); + printf("\n"); +} +void ecall_cxx17_uninitialized_memory_algorithms() { + struct Tracer { + int value; + ~Tracer() { printf("%d destructed\n", value); } + }; + + alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 3]; + + for (int i = 0; i < 3; ++i) + new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects + + auto ptr = std::launder(reinterpret_cast(buffer)); + + for (int i = 0; i < 3; ++i) + std::destroy_at(ptr + i); + + + for (int i = 0; i < 3; ++i) + new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects + + auto ptr2 = std::launder(reinterpret_cast(buffer)); + + std::destroy(ptr2, ptr2 + 3); + + + for (int i = 0; i < 3; ++i) + new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects + + auto ptr3 = std::launder(reinterpret_cast(buffer)); + + std::destroy_n(ptr3, 3); + + struct S { std::string m{ "Default value" }; }; + + constexpr int n {3}; + alignas(alignof(S)) unsigned char mem[n * sizeof(S)]; + + try + { + auto first {reinterpret_cast(mem)}; + auto last {first + n}; + + std::uninitialized_value_construct(first, last); + + for (auto it {first}; it != last; ++it) { + printf("%s\n", it->m.c_str()); + } + + std::destroy(first, last); + } + catch(...) + { + printf("Exception!\n"); + } + + // Notice that for "trivial types" the uninitialized_value_construct + // zero-fills the given uninitialized memory area. + int v[] { 1, 2, 3, 4 }; + for (const int i : v) { printf("%d ", i); } + printf("\n"); + std::uninitialized_value_construct(std::begin(v), std::end(v)); + for (const int i : v) { printf("%d ", i); } + printf("\n"); + + std::string in[] { "Home", "Work!" }; + print("initially, in: ", std::begin(in), std::end(in)); + + constexpr auto sz = std::size(in); + alignas(alignof(std::string)) unsigned char out[sizeof(std::string) * sz]; + try { + auto first {reinterpret_cast(out)}; + auto last {first + sz}; + std::uninitialized_move(std::begin(in), std::end(in), first); + + print("after move, in: ", std::begin(in), std::end(in)); + print("after move, out: ", first, last); + + std::destroy(first, last); + } + catch (...) { + printf("Exception!\n"); + } +} + +void ecall_cxx17_aligned_alloc() { + int* p = static_cast(std::aligned_alloc(1024, 1024)); + printf("1024-byte aligned address: %p\n", static_cast(p)); + free(p); +} + +void ecall_cxx17_owner_less() { + int * p = new int (10); + + std::shared_ptr a (new int (20)); + std::shared_ptr b (a,p); + + // standard set container: cannot contain duplicates. + std::set < std::shared_ptr > value_based; + std::set < std::shared_ptr, std::owner_less> > owner_based; + + value_based.insert (a); + value_based.insert (b); + + owner_based.insert (a); + owner_based.insert (b); // overwrites (same owned pointer) + + printf("value_based.size() is %d\n", value_based.size()); + printf("owner_based.size() is %d\n", owner_based.size()); + + delete p; +} + +void ecall_cxx17_shared_ptr_for_array() { + const std::size_t arr_size = 10; + std::shared_ptr pis(new int[10]{0,1,2,3,4,5,6,7,8,9}); + for (std::size_t i = 0; i < arr_size; i++){ + printf("%d ", pis[i]); + } + printf("\n"); +} + +class alignas(64) Vec3d { + double x, y, z; +}; +void ecall_cxx17_align_new_delete() { + printf("sizeof(Vec3d) is %u\n", sizeof(Vec3d)); + printf("alignof(Vec3d) is %u\n", alignof(Vec3d)); + + auto vec3d = Vec3d{}; + auto pVec = new Vec3d[10]; + + if(reinterpret_cast(&vec3d) % alignof(Vec3d) == 0) + printf("vec3d is aligned to alignof(Vec3d)!\n"); + else + printf("vec3d is not aligned to alignof(Vec3d)!\n"); + + if(reinterpret_cast(pVec) % alignof(Vec3d) == 0) + printf("pVec is aligned to alignof(Vec3d)!\n"); + else + printf("pVec is not aligned to alignof(Vec3d)!\n"); + + delete[] pVec; +} + +void ecall_cxx17_std_byte() { + std::byte b{0b10100101}; + printf("1. %d\n", std::to_integer(b)); + + b <<= 1; + printf("2. %d\n", std::to_integer(b)); + + printf("3. %d\n", std::to_integer(b>>1)); + printf("4. %d\n", std::to_integer(b<<1)); + + b |= std::byte{0b11110000}; + printf("5. %d\n", std::to_integer(b)); + + b &= std::byte{0b11110000}; + printf("6. %d\n", std::to_integer(b)); + + b ^= std::byte{0b11111111}; + printf("7. %d\n", std::to_integer(b)); +} + +// func is enabled if all Ts... have the same type as T +template +std::enable_if_t...>> +func(T, Ts...) { + printf("all types in pack are T\n"); +} +// otherwise +template +std::enable_if_t...>> +func(T, Ts...) { + printf("not all types in pack are T\n"); +} +// values_equal::value is true if and only if a == b. +template +struct values_equal : std::bool_constant { + using type = T; +}; +// default_type::value is always true +template +struct default_type : std::true_type { + using type = T; +}; +// Now we can use disjunction like a switch statement: +template +using int_of_size = typename std::disjunction< // + values_equal, // + values_equal, // + values_equal, // + values_equal, // + default_type // must be last! + >::type; + +void ecall_cxx17_std_conjunction_disjunction_negation() { + func(1, 2, 3); + func(1, 2, "hello!"); + + static_assert(sizeof(int_of_size<1>) == 1); + static_assert(sizeof(int_of_size<2>) == 2); + static_assert(sizeof(int_of_size<4>) == 4); + static_assert(sizeof(int_of_size<8>) == 8); + static_assert(std::is_same_v, void>); + + static_assert( + std::is_same_v< + std::bool_constant, + typename std::negation>::type>, + ""); + + static_assert( + std::is_same_v< + std::bool_constant, + typename std::negation>::type>, + ""); +} + +auto func2(char) -> int (*)() { return nullptr; } +void ecall_cxx17_invoke() { + static_assert( std::is_invocable_v ); + static_assert( not std::is_invocable_v ); + static_assert( std::is_invocable_r_v ); + static_assert( not std::is_invocable_r_v ); + static_assert( std::is_invocable_r_v ); + static_assert( not std::is_invocable_r_v ); + static_assert( std::is_invocable_r_v ); + static_assert( not std::is_invocable_r_v ); + + auto add1 = [](int a) -> int { return a + 1; }; + static_assert(std::is_invocable_r_v); + static_assert(__cpp_lib_invoke); + assert(std::invoke(add1, 2) == 3); + + static_assert(std::negation_v>); +} + +// constructs a T at the uninitialized memory pointed to by p +// using list-initialization for aggregates and non-list initialization otherwise +template +T* construct(T* p, Args&&... args) { + if constexpr(std::is_aggregate_v) { + return ::new (static_cast(p)) T{std::forward(args)...}; + } + else { + return ::new (static_cast(p)) T(std::forward(args)...); + } +} +struct A { int x, y; }; +struct Na { Na(int, const char*) { } }; + +void ecall_cxx17_is_aggregate() { + std::aligned_union_t<1, A, Na> storage; + [[maybe_unused]] A* a = construct(reinterpret_cast(&storage), 1, 2); + [[maybe_unused]] Na* b = construct(reinterpret_cast(&storage), 1, "hello"); +} + +void ecall_cxx17_is_swappable() { + printf("std::is_swappable::value: %s\n", std::is_swappable::value ? "true" : "false"); +} + +void ecall_cxx17_std_has_unique_object_representations() { + printf("A has unique object representation: %d\n", std::has_unique_object_representations_v); + printf("Na has unique object representation: %d\n", std::has_unique_object_representations_v); +} + +void ecall_cxx17_clamp() { + static_assert(std::clamp(1, 2, 10) == 2); + static_assert(std::clamp(3, 2, 10) == 3); + static_assert(std::clamp(12, 2, 10) == 10); +} + +void ecall_cxx17_reduce() { + const std::vector v(100000, 0.1); + auto sum = std::reduce(v.cbegin(), v.cend()); + printf("sum: %.2f\n", sum); +} + +void ecall_cxx17_inclusive_exclusive_scan() { + std::vector data {3, 1, 4, 1, 5, 9, 2, 6}; + decltype(data) ret; + + printf("exclusive sum: "); + std::exclusive_scan(data.begin(), data.end(), + std::back_inserter(ret), + 0); + for (auto e : ret) { + printf("%d ", e); + } + printf("\n"); + + ret.clear(); + printf("inclusive product: "); + std::inclusive_scan(data.begin(), data.end(), + std::back_inserter(ret), + std::multiplies<>{}); + for (auto e : ret) { + printf("%d ", e); + } + printf("\n"); +} + +void ecall_cxx17_gcd_lcm() { + constexpr int p {2 * 2 * 3}; + constexpr int q {2 * 3 * 3}; + static_assert(2 * 3 == std::gcd(p, q)); + static_assert(2 * 2 * 3 * 3 == std::lcm(p, q)); +} + +void print_map(std::string_view comment, const auto& data) +{ + printf("%s", comment); + for (auto [k, v] : data) + printf(" %d(%c)", k, v); + printf("\n"); +} +void ecall_cxx17_map_extract_merge() { + std::map cont{{1, 'a'}, {2, 'b'}, {3, 'c'}}; + + print_map("Start:", cont); + + // Extract node handle and change key + auto nh = cont.extract(1); + nh.key() = 4; + + print_map("After extract and before insert:", cont); + + // Insert node handle back + cont.insert(std::move(nh)); + + print_map("End:", cont); + + std::map ma {{1, "apple"}, {5, "pear"}, {10, "banana"}}; + std::map mb {{2, "zorro"}, {4, "batman"}, {5, "X"}, {8, "alpaca"}}; + std::map u; + u.merge(ma); + printf("ma.size(): %d\n", ma.size()); + u.merge(mb); + printf("mb.size(): %d\n", mb.size()); + printf("mb.at(5): %s\n", mb.at(5).c_str()); + for(auto const &kv: u) + printf("%d, %s\n", kv.first, kv.second.c_str()); +} + +auto print_node = [](const auto &node) { + printf("[%s] = %s\n", node.first.c_str(), node.second.c_str()); +}; +auto print_result_emplace = [](auto const &pair) { + printf("%s", (pair.second ? "inserted: " : "ignored: ")); + print_node(*pair.first); +}; +auto print_result_insert = [](auto const &pair) { + printf("%s", (pair.second ? "inserted: " : "assigned: ")); + print_node(*pair.first); +}; +void ecall_cxx17_map_try_emplace_insert_or_assign() { + using namespace std::literals; + std::map m; + print_result_emplace( m.try_emplace("a", "a"s) ); + print_result_emplace( m.try_emplace("b", "abcd") ); + print_result_emplace( m.try_emplace("c", 10, 'c') ); + print_result_emplace( m.try_emplace("c", "Won't be inserted") ); + for (const auto &p : m) { print_node(p); } + + std::map myMap; + print_result_insert( myMap.insert_or_assign("a", "apple" ) ); + print_result_insert( myMap.insert_or_assign("b", "banana" ) ); + print_result_insert( myMap.insert_or_assign("c", "cherry" ) ); + print_result_insert( myMap.insert_or_assign("c", "clementine") ); + for (const auto &node : myMap) { print_node(node); } +} + +void ecall_cxx17_std_size_empty_data() { + std::vector v = { 3, 1, 4 }; + printf("size of vector: %d, empty? %s\n", std::size(v), std::empty(v) ? "true" : "false"); + int a[] = { -5, 10, 15 }; + printf("size of array: %d, empty? %s\n", std::size(a), std::empty(v) ? "true" : "false"); + + std::string s {"Hello SGX!\n"}; + char cstr[20]; + std::strncpy(cstr, std::data(s), std::size(s)+1); + printf("%s", cstr); +} + +struct Foo { + int count = std::uncaught_exceptions(); + ~Foo() { + printf("%s\n", count == std::uncaught_exceptions() + ? "~Foo() called normally" + : "~Foo() called during stack unwinding"); + } +}; +void ecall_cxx17_uncaught_exceptions() { + Foo f; + try { + Foo f; + printf("Exception thrown\n"); + throw std::runtime_error("test exception"); + } catch (const std::exception& e) { + printf("Exception caught: %s\n", e.what()); + } +} + +void ecall_cxx17_reference() { + static_assert(std::is_reference_v); + static_assert(std::is_lvalue_reference_v); + static_assert(std::is_rvalue_reference_v); + +} + +void ecall_cxx17_static_assert() { + static_assert(03746 == 2022); // since C++17 the message string is optional +} + +void ecall_cxx17_auto_deduction_from_braced_init_list() { + auto s = std::string{"Hello C++17"}; + printf("%s\n", s.c_str()); +} + +void ecall_cxx17_hexadecimal_floating_point_literals() { + printf("Hexadecimal floating literals:\n"); + printf(" 0x10.1p0 is %f\n", 0x10.1p0); + printf(" 0x1p5 is %f\n", 0x1p5); +} + +void ecall_cxx17_string_view() { + constexpr std::string_view unicode[] { + "▀▄─", "▄▀─", "▀─▄", "▄─▀" + }; + + for (int y{}, p{}; y != 3; ++y, p = ((p + 1) % 4)) { + for (int x{}; x != 16; ++x) + printf("%s", unicode[p]); + printf("\n"); + } +} + +class DemoConditionVariable +{ + std::mutex mtx; + std::condition_variable cond_var; + bool data_loaded; +public: + DemoConditionVariable() + { + data_loaded = false; + } + void load_data() + { + //Simulating loading of the data + printf("[condition_variable] Loading Data...\n"); + { + // Locking the data structure + std::scoped_lock guard(mtx); + // Setting the flag to true to signal load data completion + data_loaded = true; + } + // Notify to unblock the waiting thread + cond_var.notify_one(); + } + bool is_data_loaded() + { + return data_loaded; + } + void main_task() + { + printf("\n"); + printf("[condition_variable] Running condition variable demo.\n"); + + // Acquire the lock + std::unique_lock lck(mtx); + + printf("[condition_variable] Waiting for the data to be loaded in the other thread.\n"); + cond_var.wait(lck, std::bind(&DemoConditionVariable::is_data_loaded, this)); + printf("[condition_variable] Processing the loaded data.\n"); + printf("[condition_variable] Done.\n"); + } +}; + +DemoConditionVariable app; + +//E-call used by condition_variable demo - processing thread +void ecall_condition_variable_run() +{ + app.main_task(); +} + +//E-call used by condifion_variable demo - loader thread +void ecall_condition_variable_load() +{ + app.load_data(); +} diff --git a/SampleCode/Cxx17SGXDemo/Enclave/TrustedLibrary/Libcxx.edl b/SampleCode/Cxx17SGXDemo/Enclave/TrustedLibrary/Libcxx.edl new file mode 100644 index 00000000..c12ff0b3 --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/Enclave/TrustedLibrary/Libcxx.edl @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* Libcxx.edl - EDL sample for trusted C++ library. */ + +enclave { + + /* + * A subset of the C++14 standard is supported. + */ + + trusted { + public void ecall_cxx17_static_assert(void); + public void ecall_cxx17_template_parameter(void); + public void ecall_cxx17_auto_deduction_from_braced_init_list(void); + public void ecall_cxx17_nested_namespace(void); + public void ecall_cxx17_u8_character_literals(void); + public void ecall_cxx17_hexadecimal_floating_point_literals(void); + public void ecall_cxx17_fold_expression(void); + public void ecall_cxx17_compile_time_if(void); + public void ecall_cxx17_structured_binding(void); + public void ecall_cxx17_initializer_in_if_switch(void); + public void ecall_cxx17_CTAD(void); + public void ecall_cxx17_inline_variable(void); + public void ecall_cxx17_lambda_capture_this_by_value(void); + public void ecall_cxx17_constexpr_lambda(void); + public void ecall_cxx17_uncaught_exceptions(void); + public void ecall_cxx17_invoke(void); + public void ecall_cxx17_uninitialized_memory_algorithms(void); + public void ecall_cxx17_aligned_alloc(void); + public void ecall_cxx17_owner_less(void); + public void ecall_cxx17_shared_ptr_for_array(void); + public void ecall_cxx17_std_byte(void); + public void ecall_cxx17_std_conjunction_disjunction_negation(void); + public void ecall_cxx17_reference(void); + public void ecall_cxx17_is_aggregate(void); + public void ecall_cxx17_is_swappable(void); + public void ecall_cxx17_searchers(void); + public void ecall_cxx17_std_as_const(void); + public void ecall_cxx17_std_has_unique_object_representations(void); + public void ecall_cxx17_clamp(void); + public void ecall_cxx17_reduce(void); + public void ecall_cxx17_inclusive_exclusive_scan(void); + public void ecall_cxx17_gcd_lcm(void); + public void ecall_cxx17_map_extract_merge(void); + public void ecall_cxx17_map_try_emplace_insert_or_assign(void); + public void ecall_cxx17_std_size_empty_data(void); + public void ecall_cxx17_string_view(void); + public void ecall_cxx17_optional(void); + public void ecall_cxx17_any(void); + public void ecall_cxx17_make_from_tuple(void); + public void ecall_cxx17_tuple_deduction_guides(void); + public void ecall_cxx17_variant(void); + public void ecall_cxx17_align_new_delete(void); + public void ecall_cxx17_has_include(void); + public void ecall_cxx17_apply(void); + public void ecall_condition_variable_run(void); + public void ecall_condition_variable_load(void); + }; +}; diff --git a/SampleCode/Cxx17SGXDemo/Makefile b/SampleCode/Cxx17SGXDemo/Makefile new file mode 100644 index 00000000..e3772662 --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/Makefile @@ -0,0 +1,271 @@ +# +# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# + +######## SGX SDK Settings ######## + +SGX_SDK ?= /opt/intel/sgxsdk +SGX_MODE ?= HW +SGX_ARCH ?= x64 +SGX_DEBUG ?= 1 + +ifeq ($(shell getconf LONG_BIT), 32) + SGX_ARCH := x86 +else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) + SGX_ARCH := x86 +endif + +ifeq ($(SGX_ARCH), x86) + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r +else + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r +endif + +ifeq ($(SGX_DEBUG), 1) +ifeq ($(SGX_PRERELEASE), 1) +$(error Cannot set SGX_DEBUG and SGX_PRERELEASE at the same time!!) +endif +endif + +ifeq ($(SGX_DEBUG), 1) + SGX_COMMON_FLAGS += -O0 -g +else + SGX_COMMON_FLAGS += -O2 +endif + +SGX_COMMON_FLAGS += -Wall -Wextra -Winit-self -Wpointer-arith -Wreturn-type \ + -Waddress -Wsequence-point -Wformat-security \ + -Wmissing-include-dirs -Wfloat-equal -Wundef -Wshadow \ + -Wcast-align -Wcast-qual -Wconversion -Wredundant-decls +SGX_COMMON_CFLAGS := $(SGX_COMMON_FLAGS) -Wjump-misses-init -Wstrict-prototypes -Wunsuffixed-float-constants +SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++17 + +######## App Settings ######## + +ifneq ($(SGX_MODE), HW) + Urts_Library_Name := sgx_urts_sim +else + Urts_Library_Name := sgx_urts +endif + +App_Cpp_Files := App/App.cpp $(wildcard App/TrustedLibrary/*.cpp) +App_Include_Paths := -IApp -I$(SGX_SDK)/include + +App_C_Flags := -fPIC -Wno-attributes $(App_Include_Paths) + +# Three configuration modes - Debug, prerelease, release +# Debug - Macro DEBUG enabled. +# Prerelease - Macro NDEBUG and EDEBUG enabled. +# Release - Macro NDEBUG enabled. +ifeq ($(SGX_DEBUG), 1) + App_C_Flags += -DDEBUG -UNDEBUG -UEDEBUG +else ifeq ($(SGX_PRERELEASE), 1) + App_C_Flags += -DNDEBUG -DEDEBUG -UDEBUG +else + App_C_Flags += -DNDEBUG -UEDEBUG -UDEBUG +endif + +App_Cpp_Flags := $(App_C_Flags) +App_Link_Flags := -L$(SGX_LIBRARY_PATH) -l$(Urts_Library_Name) -lpthread + +App_Cpp_Objects := $(App_Cpp_Files:.cpp=.o) + +App_Name := app + +######## Enclave Settings ######## + +Enclave_Version_Script := Enclave/Enclave_debug.lds +ifeq ($(SGX_MODE), HW) +ifneq ($(SGX_DEBUG), 1) +ifneq ($(SGX_PRERELEASE), 1) + # Choose to use 'Enclave.lds' for HW release mode + Enclave_Version_Script = Enclave/Enclave.lds +endif +endif +endif + +ifneq ($(SGX_MODE), HW) + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim +else + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice +endif +Crypto_Library_Name := sgx_tcrypto + +Enclave_Cpp_Files := Enclave/Enclave.cpp $(wildcard Enclave/TrustedLibrary/*.cpp) +Enclave_Include_Paths := -IEnclave -I$(SGX_SDK)/include -I$(SGX_SDK)/include/libcxx -I$(SGX_SDK)/include/tlibc + +Enclave_C_Flags := -nostdinc -fvisibility=hidden -fpie -fstack-protector -fno-builtin-printf $(Enclave_Include_Paths) +Enclave_Cpp_Flags := $(Enclave_C_Flags) -nostdinc++ + +# Enable the security flags +Enclave_Security_Link_Flags := -Wl,-z,relro,-z,now,-z,noexecstack + +# To generate a proper enclave, it is recommended to follow below guideline to link the trusted libraries: +# 1. Link sgx_trts with the `--whole-archive' and `--no-whole-archive' options, +# so that the whole content of trts is included in the enclave. +# 2. For other libraries, you just need to pull the required symbols. +# Use `--start-group' and `--end-group' to link these libraries. +# Do NOT move the libraries linked with `--start-group' and `--end-group' within `--whole-archive' and `--no-whole-archive' options. +# Otherwise, you may get some undesirable errors. +Enclave_Link_Flags := $(Enclave_Security_Link_Flags) \ + -Wl,--no-undefined -nostdlib -nodefaultlibs -nostartfiles -L$(SGX_LIBRARY_PATH) \ + -Wl,--whole-archive -l$(Trts_Library_Name) -Wl,--no-whole-archive \ + -Wl,--start-group -lsgx_tstdc -lsgx_tcxx -l$(Crypto_Library_Name) -l$(Service_Library_Name) -Wl,--end-group \ + -Wl,-Bstatic -Wl,-Bsymbolic -Wl,--no-undefined \ + -Wl,-pie,-eenclave_entry -Wl,--export-dynamic \ + -Wl,--defsym,__ImageBase=0 \ + -Wl,--version-script=$(Enclave_Version_Script) + +Enclave_Cpp_Objects := $(Enclave_Cpp_Files:.cpp=.o) + +Enclave_Name := enclave.so +Signed_Enclave_Name := enclave.signed.so +Enclave_Config_File := Enclave/Enclave.config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem + +ifeq ($(SGX_MODE), HW) +ifeq ($(SGX_DEBUG), 1) + Build_Mode = HW_DEBUG +else ifeq ($(SGX_PRERELEASE), 1) + Build_Mode = HW_PRERELEASE +else + Build_Mode = HW_RELEASE +endif +else +ifeq ($(SGX_DEBUG), 1) + Build_Mode = SIM_DEBUG +else ifeq ($(SGX_PRERELEASE), 1) + Build_Mode = SIM_PRERELEASE +else + Build_Mode = SIM_RELEASE +endif +endif + + +.PHONY: all run target +all: .config_$(Build_Mode)_$(SGX_ARCH) + @$(MAKE) target + +ifeq ($(Build_Mode), HW_RELEASE) +target: $(App_Name) $(Enclave_Name) + @echo "The project has been built in release hardware mode." + @echo "Please sign the $(Enclave_Name) first with your signing key before you run the $(App_Name) to launch and access the enclave." + @echo "To sign the enclave use the command:" + @echo " $(SGX_ENCLAVE_SIGNER) sign -key -enclave $(Enclave_Name) -out <$(Signed_Enclave_Name)> -config $(Enclave_Config_File)" + @echo "You can also sign the enclave using an external signing tool." + @echo "To build the project in simulation mode set SGX_MODE=SIM. To build the project in prerelease mode set SGX_PRERELEASE=1 and SGX_MODE=HW." +else +target: $(App_Name) $(Signed_Enclave_Name) +ifeq ($(Build_Mode), HW_DEBUG) + @echo "The project has been built in debug hardware mode." +else ifeq ($(Build_Mode), SIM_DEBUG) + @echo "The project has been built in debug simulation mode." +else ifeq ($(Build_Mode), HW_PRERELEASE) + @echo "The project has been built in pre-release hardware mode." +else ifeq ($(Build_Mode), SIM_PRERELEASE) + @echo "The project has been built in pre-release simulation mode." +else + @echo "The project has been built in release simulation mode." +endif +endif + +run: all +ifneq ($(Build_Mode), HW_RELEASE) + @$(CURDIR)/$(App_Name) + @echo "RUN => $(App_Name) [$(SGX_MODE)|$(SGX_ARCH), OK]" +endif + +.config_$(Build_Mode)_$(SGX_ARCH): + @rm -f .config_* $(App_Name) $(Enclave_Name) $(Signed_Enclave_Name) $(App_Cpp_Objects) App/Enclave_u.* $(Enclave_Cpp_Objects) Enclave/Enclave_t.* + @touch .config_$(Build_Mode)_$(SGX_ARCH) + +######## App Objects ######## + +App/Enclave_u.h: $(SGX_EDGER8R) Enclave/Enclave.edl + @cd App && $(SGX_EDGER8R) --untrusted ../Enclave/Enclave.edl --search-path ../Enclave --search-path $(SGX_SDK)/include + @echo "GEN => $@" + +App/Enclave_u.c: App/Enclave_u.h + +App/Enclave_u.o: App/Enclave_u.c + @$(CC) $(SGX_COMMON_CFLAGS) $(App_C_Flags) -c $< -o $@ + @echo "CC <= $<" + +App/%.o: App/%.cpp App/Enclave_u.h + @$(CXX) $(SGX_COMMON_CXXFLAGS) $(App_Cpp_Flags) -c $< -o $@ + @echo "CXX <= $<" + +$(App_Name): App/Enclave_u.o $(App_Cpp_Objects) + @$(CXX) $^ -o $@ $(App_Link_Flags) + @echo "LINK => $@" + +######## Enclave Objects ######## + +Enclave/Enclave_t.h: $(SGX_EDGER8R) Enclave/Enclave.edl + @cd Enclave && $(SGX_EDGER8R) --trusted ../Enclave/Enclave.edl --search-path ../Enclave --search-path $(SGX_SDK)/include + @echo "GEN => $@" + +Enclave/Enclave_t.c: Enclave/Enclave_t.h + +Enclave/Enclave_t.o: Enclave/Enclave_t.c + @$(CC) $(SGX_COMMON_CFLAGS) $(Enclave_C_Flags) -c $< -o $@ + @echo "CC <= $<" + +Enclave/%.o: Enclave/%.cpp + @$(CXX) $(SGX_COMMON_CXXFLAGS) $(Enclave_Cpp_Flags) -c $< -o $@ + @echo "CXX <= $<" + +$(Enclave_Cpp_Objects): Enclave/Enclave_t.h + +$(Enclave_Name): Enclave/Enclave_t.o $(Enclave_Cpp_Objects) + @$(CXX) $^ -o $@ $(Enclave_Link_Flags) + @echo "LINK => $@" + +$(Signed_Enclave_Name): $(Enclave_Name) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) + @echo "SIGN => $@" + +.PHONY: clean + +clean: + @rm -f .config_* $(App_Name) $(Enclave_Name) $(Signed_Enclave_Name) $(App_Cpp_Objects) App/Enclave_u.* $(Enclave_Cpp_Objects) Enclave/Enclave_t.* $(Enclave_Test_Key) diff --git a/SampleCode/Cxx17SGXDemo/README.txt b/SampleCode/Cxx17SGXDemo/README.txt new file mode 100644 index 00000000..f6ddf26b --- /dev/null +++ b/SampleCode/Cxx17SGXDemo/README.txt @@ -0,0 +1,112 @@ +----------------------- +Purpose of Cxx17SGXDemo +----------------------- + +The project demonstrates several C++17 features inside the Enclave: + +- New language features: +- fold-expressions +- class template argument deduction +- non-type template parameters declared with auto +- compile-time if constexpr +- inline variables +- structured bindings +- initializers for if and switch +- u8 character literal +- simplified nested namespaces +- using-declaration declaring multiple names +- made noexcept part of type system +- new order of evaluation rules +- guaranteed copy elision +- temporary materialization +- lambda capture of *this +- constexpr lambda +- attribute namespaces don't have to repeat +- new attributes: +- [[fallthrough]] +- [[maybe_unused]] +- [[nodiscard]] +- __has_include +- +- New library features: +- Utility types +- std::tuple: +- std::apply +- std::make_from_tuple +- std::any +- std::optional +- std::variant +- searchers +- std::as_const +- std::not_fn +- +- Memory management +- uninitialized memory algorithms +- std::destroy_at +- std::destroy +- std::destroy_n +- std::uninitialized_move +- std::uninitialized_value_construct +- weak_from_this +- std::aligned_alloc +- transparent std::owner_less +- array support for std::shared_ptr +- allocation functions with explicit alignment +- +- Compile-time programming +- std::byte +- std::conjunction/std::disjunction/std::negation +- type trait variable templates (xxx_+v) +- std::is_swappable +- is_invocable +- is_aggregate +- std::has_unique_object_representations +- +- Algorithms +- std::clamp +- std::reduce +- std::inclusive_scan +- std::exclusive_scan +- std::gcd +- std::lcm +- +- Iterators and containers +- map/set extract and map/set merge +- map/unordered_map try_emplace and insert_or_assign +- contiguous iterators (LegacyContiguousIterator) +- non-member std::size/std::empty/std::data +- +- Other +- std::launder +- std::uncaught_exceptions + +--------------------------------------------- +How to Build/Execute the C++17 sample program +--------------------------------------------- +1. Install Intel(R) Software Guard Extensions (Intel(R) SGX) SDK for Linux* OS +2. Make sure your environment is set: + $ source ${sgx-sdk-install-path}/environment +3. Build the project with the prepared Makefile: + a. Hardware Mode, Debug build: + $ make + b. Hardware Mode, Pre-release build: + $ make SGX_PRERELEASE=1 SGX_DEBUG=0 + c. Hardware Mode, Release build: + $ make SGX_DEBUG=0 + d. Simulation Mode, Debug build: + $ make SGX_MODE=SIM + e. Simulation Mode, Pre-release build: + $ make SGX_MODE=SIM SGX_PRERELEASE=1 SGX_DEBUG=0 + f. Simulation Mode, Release build: + $ make SGX_MODE=SIM SGX_DEBUG=0 +4. Execute the binary directly: + $ ./app +5. Remember to "make clean" before switching build mode + +------------------------------------------------- +Launch token initialization +------------------------------------------------- +If using libsgx-enclave-common or sgxpsw under version 2.4, an initialized variable launch_token needs to be passed as the 3rd parameter of API sgx_create_enclave. For example, + +sgx_launch_token_t launch_token = {0}; +sgx_create_enclave(ENCLAVE_F7LENAME, SGX_DEBUG_FLAG, launch_token, NULL, &global_eid, NULL); diff --git a/SampleCode/LocalAttestation/App/Makefile b/SampleCode/LocalAttestation/App/Makefile index 1f193869..b205778c 100644 --- a/SampleCode/LocalAttestation/App/Makefile +++ b/SampleCode/LocalAttestation/App/Makefile @@ -37,14 +37,12 @@ RM = rm -f ifneq ($(SGX_MODE), HW) URTS_LIB_NAME := sgx_urts_sim - UAE_SERVICE_LIB := sgx_uae_service_sim else URTS_LIB_NAME := sgx_urts - UAE_SERVICE_LIB := sgx_uae_service endif INC:=-I$(SGX_SDK)/include -I../Include -LIB := -l$(URTS_LIB_NAME) -l$(UAE_SERVICE_LIB) -L$(SGX_SDK)/lib64 -lpthread +LIB := -l$(URTS_LIB_NAME) -L$(SGX_SDK)/lib64 -lpthread CXXFLAGS += $(INC) $(LIB) CFLAGS += $(INC) $(LIB) diff --git a/SampleCode/LocalAttestation/AppInitiator/Makefile b/SampleCode/LocalAttestation/AppInitiator/Makefile index 364da247..47f2d27b 100644 --- a/SampleCode/LocalAttestation/AppInitiator/Makefile +++ b/SampleCode/LocalAttestation/AppInitiator/Makefile @@ -37,14 +37,12 @@ RM = rm -f ifneq ($(SGX_MODE), HW) URTS_LIB_NAME := sgx_urts_sim - UAE_SERVICE_LIB := sgx_uae_service_sim else URTS_LIB_NAME := sgx_urts - UAE_SERVICE_LIB := sgx_uae_service endif INC:=-I$(SGX_SDK)/include -I../Include -LIB := -l$(URTS_LIB_NAME) -l$(UAE_SERVICE_LIB) -L$(SGX_SDK)/lib64 -lpthread +LIB := -l$(URTS_LIB_NAME) -L$(SGX_SDK)/lib64 -lpthread CXXFLAGS += $(INC) $(LIB) CFLAGS += $(INC) $(LIB) diff --git a/SampleCode/LocalAttestation/AppResponder/Makefile b/SampleCode/LocalAttestation/AppResponder/Makefile index 6c3fd56c..78b98b60 100644 --- a/SampleCode/LocalAttestation/AppResponder/Makefile +++ b/SampleCode/LocalAttestation/AppResponder/Makefile @@ -37,14 +37,12 @@ RM = rm -f ifneq ($(SGX_MODE), HW) URTS_LIB_NAME := sgx_urts_sim - UAE_SERVICE_LIB := sgx_uae_service_sim else URTS_LIB_NAME := sgx_urts - UAE_SERVICE_LIB := sgx_uae_service endif INC:=-I$(SGX_SDK)/include -I../Include -LIB := -l$(URTS_LIB_NAME) -l$(UAE_SERVICE_LIB) -L$(SGX_SDK)/lib64 -lpthread +LIB := -l$(URTS_LIB_NAME) -L$(SGX_SDK)/lib64 -lpthread CXXFLAGS += $(INC) $(LIB) CFLAGS += $(INC) $(LIB) diff --git a/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator.cpp b/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator.cpp index 80362530..1b075c8f 100644 --- a/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator.cpp +++ b/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator.cpp @@ -49,10 +49,13 @@ std::mapg_src_session_info_map; dh_session_t g_session; // This is hardcoded responder enclave's MRSIGNER for demonstration purpose. The content aligns to responder enclave's signing key +//Please replace with your project responder enclave's MRSIGNER in your project!!! +//The command to get your signed enclave's MRSIGNER: /bin/x64/sgx_sign dump -enclave -dumpfile mrsigner.txt +//Find the signed enclave's MRSIGNER in the mrsigner.txt(mrsigner->value:), then replace blow value sgx_measurement_t g_responder_mrsigner = { { - 0x83, 0xd7, 0x19, 0xe7, 0x7d, 0xea, 0xca, 0x14, 0x70, 0xf6, 0xba, 0xf6, 0x2a, 0x4d, 0x77, 0x43, - 0x03, 0xc8, 0x99, 0xdb, 0x69, 0x02, 0x0f, 0x9c, 0x70, 0xee, 0x1d, 0xfc, 0x08, 0xc7, 0xce, 0x9e + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } }; @@ -144,9 +147,11 @@ extern "C" uint32_t verify_peer_enclave_trust(sgx_dh_session_enclave_identity_t* return INVALID_PARAMETER_ERROR; // check peer enclave's MRSIGNER + // Please enable blow check in your own project!!! + /* if (memcmp((uint8_t *)&peer_enclave_identity->mr_signer, (uint8_t*)&g_responder_mrsigner, sizeof(sgx_measurement_t))) return ENCLAVE_TRUST_ERROR; - + */ // check peer enclave's product ID and enclave attribute (should be INITIALIZED'ed) if (peer_enclave_identity->isv_prod_id != RESPONDER_PRODID || !(peer_enclave_identity->attributes.flags & SGX_FLAGS_INITTED)) return ENCLAVE_TRUST_ERROR; diff --git a/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator_private_test.pem b/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator_private_test.pem deleted file mode 100644 index 75d7f88c..00000000 --- a/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/LocalAttestation/EnclaveInitiator/Makefile b/SampleCode/LocalAttestation/EnclaveInitiator/Makefile index 0dd1878a..cb52847f 100644 --- a/SampleCode/LocalAttestation/EnclaveInitiator/Makefile +++ b/SampleCode/LocalAttestation/EnclaveInitiator/Makefile @@ -43,9 +43,15 @@ Crypto_Library_Name := sgx_tcrypto ENCLAVE_NAME := libenclave_initiator.so SIGNED_ENCLAVE_NAME := libenclave_initiator.signed.so +Enclave_Test_Key := EnclaveInitiator_private_test.pem $(SIGNED_ENCLAVE_NAME) : $(ENCLAVE_NAME) - @$(SGX_ENCLAVE_SIGNER) sign -key EnclaveInitiator_private_test.pem -enclave $(ENCLAVE_NAME) -out $@ -config EnclaveInitiator.config.xml +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(ENCLAVE_NAME) -out $@ -config EnclaveInitiator.config.xml @cp $(SIGNED_ENCLAVE_NAME) $(TOPDIR)/$(OUTDIR)/ @echo "SIGN => $@" diff --git a/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder.cpp b/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder.cpp index 667cf544..3793f4d0 100644 --- a/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder.cpp +++ b/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder.cpp @@ -45,11 +45,14 @@ std::mapg_src_session_info_map; // this is expected initiator's MRSIGNER for demonstration purpose +//Please replace with your project responder enclave's MRSIGNER in your project!!! +//The command to get your signed enclave's MRSIGNER: /bin/x64/sgx_sign dump -enclave -dumpfile mrsigner.txt +//Find the signed enclave's MRSIGNER in the mrsigner.txtvalue:>, then replace blow value sgx_measurement_t g_initiator_mrsigner = { - { - 0xc3, 0x04, 0x46, 0xb4, 0xbe, 0x9b, 0xaf, 0x0f, 0x69, 0x72, 0x84, 0x23, 0xea, 0x61, 0x3e, 0xf8, - 0x1a, 0x63, 0xe7, 0x2a, 0xcf, 0x74, 0x39, 0xfa, 0x05, 0x49, 0x00, 0x1f, 0xd5, 0x48, 0x28, 0x35 - } + { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff + } }; /* Function Description: @@ -65,9 +68,11 @@ extern "C" uint32_t verify_peer_enclave_trust(sgx_dh_session_enclave_identity_t* return INVALID_PARAMETER_ERROR; // check peer enclave's MRSIGNER + // Please enable blow check in your project!!! + /* if (memcmp((uint8_t *)&peer_enclave_identity->mr_signer, (uint8_t*)&g_initiator_mrsigner, sizeof(sgx_measurement_t))) return ENCLAVE_TRUST_ERROR; - + */ if(peer_enclave_identity->isv_prod_id != 0 || !(peer_enclave_identity->attributes.flags & SGX_FLAGS_INITTED)) return ENCLAVE_TRUST_ERROR; diff --git a/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder_private_test.pem b/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/LocalAttestation/EnclaveResponder/Makefile b/SampleCode/LocalAttestation/EnclaveResponder/Makefile index c077c734..89ae202e 100644 --- a/SampleCode/LocalAttestation/EnclaveResponder/Makefile +++ b/SampleCode/LocalAttestation/EnclaveResponder/Makefile @@ -43,9 +43,15 @@ Crypto_Library_Name := sgx_tcrypto ENCLAVE_NAME := libenclave_responder.so SIGNED_ENCLAVE_NAME := libenclave_responder.signed.so +Enclave_Test_Key := EnclaveResponder_private_test.pem $(SIGNED_ENCLAVE_NAME) : $(ENCLAVE_NAME) - @$(SGX_ENCLAVE_SIGNER) sign -key EnclaveResponder_private_test.pem -enclave $(ENCLAVE_NAME) -out $@ -config EnclaveResponder.config.xml +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(ENCLAVE_NAME) -out $@ -config EnclaveResponder.config.xml @cp $(SIGNED_ENCLAVE_NAME) $(TOPDIR)/$(OUTDIR)/ @echo "SIGN => $@" diff --git a/SampleCode/LocalAttestation/README.txt b/SampleCode/LocalAttestation/README.txt index dce9f9a8..ff26a15f 100644 --- a/SampleCode/LocalAttestation/README.txt +++ b/SampleCode/LocalAttestation/README.txt @@ -5,7 +5,10 @@ The project aims to demo SGX local attestation flow. How to Build the Sample Code ------------------------------------ 1. Install Intel(R) Software Guard Extensions (Intel(R) SGX) SDK for Linux* OS -2. Build the project with the prepared Makefile: +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key/ automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to / and put it under the / folder. +3. Build the project with the prepared Makefile: a. Hardware Mode, Debug build: $ make b. Hardware Mode, Pre-release build: @@ -35,3 +38,11 @@ How to Execute the Sample Code b. run "./appinitiator" It would launch a process to act as local attestation initator. 3. If you want to try local attestation flow from one process, you can goto "bin" sub-folder and run "./app" + +------------------------------------ +How to Get Signed Enclave's MRSIGNER +------------------------------------ +1. Install Intel(R) Software Guard Extensions (Intel(R) SGX) SDK for Linux* OS +2. Execute blow command to get your signed enclave's MRSIGNER: + /bin/x64/sgx_sign dump -enclave -dumpfile mrsigner.txt +3. Find the signed enclave's MRSIGNER in the mrsigner.txt(mrsigner->value:) diff --git a/SampleCode/PowerTransition/Enclave/Enclave_private_test.pem b/SampleCode/PowerTransition/Enclave/Enclave_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/PowerTransition/Enclave/Enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/PowerTransition/Makefile b/SampleCode/PowerTransition/Makefile index 1e1cfdb0..780f7e5b 100644 --- a/SampleCode/PowerTransition/Makefile +++ b/SampleCode/PowerTransition/Makefile @@ -158,6 +158,7 @@ Enclave_Objects := $(Gen_Trusted_Object) $(Enclave_Cpp_Files:.cpp=.o) Enclave_Name := libenclave.so Signed_Enclave_Name := libenclave.signed.so Enclave_Config_File := Enclave/Enclave.config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) @@ -250,7 +251,12 @@ $(Enclave_Name): $(Enclave_Objects) @echo "LINK => $@" $(Signed_Enclave_Name): $(Enclave_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave/Enclave_private_test.pem -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) @echo "SIGN => $@" diff --git a/SampleCode/PowerTransition/README.txt b/SampleCode/PowerTransition/README.txt index 643b132e..1094d984 100644 --- a/SampleCode/PowerTransition/README.txt +++ b/SampleCode/PowerTransition/README.txt @@ -8,9 +8,12 @@ Software Guard Extensions projects development. How to Build/Execute the Sample Code ------------------------------------ 1. Install Intel(R) Software Guard Extensions (Intel(R) SGX) SDK for Linux* OS -2. Make sure your environment is set: +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to and put it under the folder. +3. Make sure your environment is set: $ source ${sgx-sdk-install-path}/environment -3. Build the project with the prepared Makefile: +4. Build the project with the prepared Makefile: a. Hardware Mode, Debug build: $ make b. Hardware Mode, Pre-release build: @@ -23,9 +26,9 @@ How to Build/Execute the Sample Code $ make SGX_MODE=SIM SGX_PRERELEASE=1 SGX_DEBUG=0 f. Simulation Mode, Release build: $ make SGX_MODE=SIM SGX_DEBUG=0 -4. Execute the binary directly: +5. Execute the binary directly: $ ./app -5. Remember to "make clean" before switching build mode +6. Remember to "make clean" before switching build mode ------------------------------------------------- Launch token initialization diff --git a/SampleCode/ProtobufSGXDemo/Enclave/Enclave_private_test.pem b/SampleCode/ProtobufSGXDemo/Enclave/Enclave_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/ProtobufSGXDemo/Enclave/Enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/ProtobufSGXDemo/Makefile b/SampleCode/ProtobufSGXDemo/Makefile index f6f2e97b..bb22dfa9 100644 --- a/SampleCode/ProtobufSGXDemo/Makefile +++ b/SampleCode/ProtobufSGXDemo/Makefile @@ -158,6 +158,7 @@ Enclave_Cpp_Objects := $(Enclave_Cpp_Files:.cpp=.o) Enclave_Name := enclave.so Signed_Enclave_Name := enclave.signed.so Enclave_Config_File := Enclave/Enclave.config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) @@ -268,7 +269,12 @@ $(Enclave_Name): Enclave/Enclave_t.o $(Enclave_Cpp_Objects) Enclave/person.pb.o @echo "LINK => $@" $(Signed_Enclave_Name): $(Enclave_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave/Enclave_private_test.pem -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) @echo "SIGN => $@" .PHONY: clean diff --git a/SampleCode/RemoteAttestation/Makefile b/SampleCode/RemoteAttestation/Makefile index ee86c43f..9b9f5aae 100644 --- a/SampleCode/RemoteAttestation/Makefile +++ b/SampleCode/RemoteAttestation/Makefile @@ -173,6 +173,7 @@ Enclave_Cpp_Objects := $(Enclave_Cpp_Files:.cpp=.o) Enclave_Name := isv_enclave.so Signed_Enclave_Name := isv_enclave.signed.so Enclave_Config_File := isv_enclave/isv_enclave.config.xml +Enclave_Test_Key := isv_enclave/isv_enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) @@ -283,7 +284,12 @@ $(Enclave_Name): isv_enclave/isv_enclave_t.o $(Enclave_Cpp_Objects) @echo "LINK => $@" $(Signed_Enclave_Name): $(Enclave_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key isv_enclave/isv_enclave_private_test.pem -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) @echo "SIGN => $@" .PHONY: clean diff --git a/SampleCode/RemoteAttestation/README.txt b/SampleCode/RemoteAttestation/README.txt index 79fc636a..2e1d07c9 100644 --- a/SampleCode/RemoteAttestation/README.txt +++ b/SampleCode/RemoteAttestation/README.txt @@ -9,9 +9,12 @@ The project demonstrates: How to Build/Execute the Sample Code ------------------------------------ 1. Install Intel(R) Software Guard Extensions (Intel(R) SGX) SDK for Linux* OS -2. Make sure your environment is set: +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to and put it under the folder. +3. Make sure your environment is set: $ source ${sgx-sdk-install-path}/environment -3. Build the project with the prepared Makefile: +4. Build the project with the prepared Makefile: a. Hardware Mode, Debug build: $ make b. Hardware Mode, Pre-release build: @@ -24,9 +27,9 @@ How to Build/Execute the Sample Code $ make SGX_MODE=SIM SGX_PRERELEASE=1 SGX_DEBUG=0 f. Simulation Mode, Release build: $ make SGX_MODE=SIM SGX_DEBUG=0 -4. Execute the binary directly: +5. Execute the binary directly: $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD/sample_libcrypto ./app -5. Remember to "make clean" before switching build mode +6. Remember to "make clean" before switching build mode ------------------------------------------------- Launch token initialization diff --git a/SampleCode/RemoteAttestation/isv_enclave/isv_enclave_private_test.pem b/SampleCode/RemoteAttestation/isv_enclave/isv_enclave_private_test.pem deleted file mode 100644 index b8ace89e..00000000 --- a/SampleCode/RemoteAttestation/isv_enclave/isv_enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/SampleAttestedTLS/Makefile b/SampleCode/SampleAttestedTLS/Makefile index 26b2b49e..b354653d 100644 --- a/SampleCode/SampleAttestedTLS/Makefile +++ b/SampleCode/SampleAttestedTLS/Makefile @@ -51,10 +51,14 @@ build: $(SGXSSL_HEADER_CHECK) $(MAKE) -C client $(MAKE) -C non_enc_client +tdx: $(SGXSSL_HEADER_CHECK) + $(MAKE) -C server_tdx + clean: $(MAKE) -C server clean $(MAKE) -C client clean $(MAKE) -C non_enc_client clean + $(MAKE) -C server_tdx clean run: echo "Launch processes to establish an Attested TLS between two enclaves" diff --git a/SampleCode/SampleAttestedTLS/README.md b/SampleCode/SampleAttestedTLS/README.md index 1e0b0b95..ccf454b1 100644 --- a/SampleCode/SampleAttestedTLS/README.md +++ b/SampleCode/SampleAttestedTLS/README.md @@ -2,6 +2,7 @@ The audience is assumed to be familiar: [What is an Attested TLS channel](AttestedTLSREADME.md#what-is-an-attested-tls-channel) + The `QuoteGenerationSample` and `QuoteVerificationSample` can be run successfully on server and client machines. (`tdx-quote-generation-sample` and `tdx-quote-verification-sample` for TDX) # The Attested TLS sample It has the following properties: @@ -39,7 +40,7 @@ Note: Both of them can run on the same machine or separate machines. - Host part (tls_server_host) - Instantiate an enclave before transitioning the control into the enclave via an ecall. - Enclave (tls_server_enclave.signed.so) - - Call tee_get_certificate_with_evidence to generate an certificate + - Call tee_get_certificate_with_evidence to generate a certificate - Use SgxSSL API to configure a TLS server using the generated certificate - Launch a TLS server and wait for client connection request - Read client payload and reply with server payload @@ -72,6 +73,36 @@ Note: Both of them can run on the same machine or separate machines. ./non_enc_client/tls_non_enc_client -server:localhost -port:12341 ``` +## TDX Sample Configration + +The sample supports creating attested TLS channel between: +- two TD-guests +- TD-guest and SGX enclave +- TD-guest and non TEE environment + +> **Note**: +> In order to connect to the port on guest TD from host or other machihnes, port forwarding needs to be set using QEMU command when starting the guest TD. +Use the following QEMU command: +>``` +>hostfwd=tcp::HOSTPORT-:GUESTPORT +>``` + +### TDX server application + + - Call tee_get_certificate_with_evidence to generate a certificate + - Use OpenSSL API to configure a TLS server using the generated certificate + - Launch a TLS server and wait for client connection request + - Read client payload and reply with server payload + - To run TDX server application, copy `./server_tdx/tls_server` to TD-guest and run the following command: + + ``` +./tls_server -port:12341 + ``` + +### TDX client application + +The TDX client applicaiton is the same as non-enclave client application, except that it is running in guest TD. + ## Build and run ```bash make diff --git a/SampleCode/SampleAttestedTLS/client/enc/Makefile b/SampleCode/SampleAttestedTLS/client/enc/Makefile index ed6a666e..30c53c7a 100644 --- a/SampleCode/SampleAttestedTLS/client/enc/Makefile +++ b/SampleCode/SampleAttestedTLS/client/enc/Makefile @@ -66,6 +66,7 @@ SOCKETINCDIR = $(SOCKET_DIR)/include #socket EDL search path SSLINCDIR = $(SGXSSL_PKG_PATH)/include ENC_TLS_CLIENT_Name := tls_client_enclave.so Signed_ENC_TLS_CLIENT_Name := tls_client_enclave.signed.so +Enclave_Test_Key := private_test_key.pem .PHONY: all build clean run @@ -89,7 +90,12 @@ build: $(CXX) -o $(ENC_TLS_CLIENT_Name) $(OBJ_FILES) $(Enclave_Link_Flags) sign: - $(SGX_ENCLAVE_SIGNER) sign -key private_test_key.pem -enclave $(ENC_TLS_CLIENT_Name) \ +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + $(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(ENC_TLS_CLIENT_Name) \ -out $(Signed_ENC_TLS_CLIENT_Name) -config client_enc.config.xml clean: diff --git a/SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem b/SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem deleted file mode 100644 index 59d0c167..00000000 --- a/SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/SampleAttestedTLS/common/common.h b/SampleCode/SampleAttestedTLS/common/common.h index b630eb55..3d262ef0 100644 --- a/SampleCode/SampleAttestedTLS/common/common.h +++ b/SampleCode/SampleAttestedTLS/common/common.h @@ -41,7 +41,7 @@ // put common files here in a definition of Macro to reduce // redundancy code -#ifdef CLIENT_UNTRUSTED +#ifdef CLIENT_USE_QVL #include "sgx_utls.h" #define PRINT printf #define GETCURRTIME time @@ -49,9 +49,18 @@ #define FREE_SUPDATA tee_free_supplemental_data_host #else #include "sgx_ttls.h" -extern void t_print(const char* fmt, ...); -#define PRINT t_print -#define GETCURRTIME t_time +#define PRINT T_PRINT +#define GETCURRTIME T_TIME #define VERIFY_CALLBACK tee_verify_certificate_with_evidence #define FREE_SUPDATA tee_free_supplemental_data #endif + +#ifdef TDX_ENV +#define T_PRINT printf +#define T_TIME time +#else +extern void t_print(const char* fmt, ...); +extern void t_time(time_t *c_time); +#define T_PRINT t_print +#define T_TIME t_time +#endif diff --git a/SampleCode/SampleAttestedTLS/common/openssl_utility.cpp b/SampleCode/SampleAttestedTLS/common/openssl_utility.cpp index e2db8bc2..9370eeb7 100644 --- a/SampleCode/SampleAttestedTLS/common/openssl_utility.cpp +++ b/SampleCode/SampleAttestedTLS/common/openssl_utility.cpp @@ -41,11 +41,11 @@ sgx_status_t generate_certificate_and_pkey(X509*& certificate, EVP_PKEY*& pkey) int key_type = RSA_TYPE; if (key_type) { - t_print(" generating keys by EC P-384\n"); + PRINT(" generating keys by EC P-384\n"); } else { - t_print(" generating keys by RSA 3072\n"); + PRINT(" generating keys by RSA 3072\n"); } result = generate_key_pair( key_type, &public_key_buffer, @@ -54,14 +54,14 @@ sgx_status_t generate_certificate_and_pkey(X509*& certificate, EVP_PKEY*& pkey) &private_key_buffer_size); if (result != SGX_SUCCESS) { - t_print(" failed to generate RSA key pair\n"); + PRINT(" failed to generate RSA key pair\n"); goto done; } - t_print("public_key_buf_size:[%ld]\n", public_key_buffer_size); - t_print("%s\n", public_key_buffer); - t_print("private_key_buf_size:[%ld]\n", private_key_buffer_size); - t_print("%s\n", private_key_buffer); + PRINT("public_key_buf_size:[%ld]\n", public_key_buffer_size); + PRINT("%s\n", public_key_buffer); + PRINT("private_key_buf_size:[%ld]\n", private_key_buffer_size); + PRINT("%s\n", private_key_buffer); qresult = tee_get_certificate_with_evidence( certificate_subject_name, private_key_buffer, @@ -74,7 +74,7 @@ sgx_status_t generate_certificate_and_pkey(X509*& certificate, EVP_PKEY*& pkey) if (qresult != SGX_QL_SUCCESS || output_certificate == nullptr) { if (output_certificate == nullptr) - t_print(" null certificate\n"); + PRINT(" null certificate\n"); p_sgx_tls_qe_err_msg(qresult); goto done; } @@ -91,18 +91,18 @@ sgx_status_t generate_certificate_and_pkey(X509*& certificate, EVP_PKEY*& pkey) &certificate_buffer_ptr, (long)output_certificate_size)) == nullptr) { - t_print("Failed to convert DER format certificate to X509 structure\n"); + PRINT("Failed to convert DER format certificate to X509 structure\n"); goto done; } mem = BIO_new_mem_buf((void*)private_key_buffer, -1); if (!mem) { - t_print("Failed to convert private key buf into BIO_mem\n"); + PRINT("Failed to convert private key buf into BIO_mem\n"); goto done; } if ((pkey = PEM_read_bio_PrivateKey(mem, nullptr, 0, nullptr)) == nullptr) { - t_print("Failed to convert private key buffer into EVP_KEY format\n"); + PRINT("Failed to convert private key buffer into EVP_KEY format\n"); goto done; } @@ -130,32 +130,32 @@ sgx_status_t load_tls_certificates_and_keys( if (generate_certificate_and_pkey(certificate, pkey) != SGX_SUCCESS) { - t_print("Cannot generate certificate and pkey\n"); + PRINT("Cannot generate certificate and pkey\n"); goto exit; } if (certificate == nullptr) { - t_print("null cert\n"); + PRINT("null cert\n"); goto exit; } if (!SSL_CTX_use_certificate(ctx, certificate)) { - t_print("Cannot load certificate on the server\n"); + PRINT("Cannot load certificate on the server\n"); goto exit; } if (!SSL_CTX_use_PrivateKey(ctx, pkey)) { - t_print("Cannot load private key on the server\n"); + PRINT("Cannot load private key on the server\n"); goto exit; } /* verify private key */ if (!SSL_CTX_check_private_key(ctx)) { - t_print("Private key does not match the public certificate\n"); + PRINT("Private key does not match the public certificate\n"); goto exit; } result = SGX_SUCCESS; @@ -185,7 +185,7 @@ sgx_status_t initalize_ssl_context(SSL_CONF_CTX*& ssl_conf_ctx, SSL_CTX*& ctx) if ((ssl_conf_return_value = SSL_CONF_cmd(ssl_conf_ctx, "MinProtocol", "TLSv1.2")) < 0) { - t_print( + PRINT( "Setting MinProtocol for ssl context configuration failed with " "error %d \n", ssl_conf_return_value); @@ -194,7 +194,7 @@ sgx_status_t initalize_ssl_context(SSL_CONF_CTX*& ssl_conf_ctx, SSL_CTX*& ctx) if ((ssl_conf_return_value = SSL_CONF_cmd(ssl_conf_ctx, "MaxProtocol", "TLSv1.3")) < 0) { - t_print( + PRINT( "Setting MaxProtocol for ssl context configuration failed with " "error %d \n", ssl_conf_return_value); @@ -203,7 +203,7 @@ sgx_status_t initalize_ssl_context(SSL_CONF_CTX*& ssl_conf_ctx, SSL_CTX*& ctx) if ((ssl_conf_return_value = SSL_CONF_cmd( ssl_conf_ctx, "CipherString", cipher_list_tlsv12_below)) < 0) { - t_print( + PRINT( "Setting CipherString for ssl context configuration failed with " "error %d \n", ssl_conf_return_value); @@ -212,7 +212,7 @@ sgx_status_t initalize_ssl_context(SSL_CONF_CTX*& ssl_conf_ctx, SSL_CTX*& ctx) if ((ssl_conf_return_value = SSL_CONF_cmd( ssl_conf_ctx, "Ciphersuites", cipher_list_tlsv13)) < 0) { - t_print( + PRINT( "Setting Ciphersuites for ssl context configuration failed with " "error %d \n", ssl_conf_return_value); @@ -221,7 +221,7 @@ sgx_status_t initalize_ssl_context(SSL_CONF_CTX*& ssl_conf_ctx, SSL_CTX*& ctx) if ((ssl_conf_return_value = SSL_CONF_cmd(ssl_conf_ctx, "Curves", supported_curves)) < 0) { - t_print( + PRINT( "Setting Curves for ssl context configuration failed with error %d " "\n", ssl_conf_return_value); @@ -229,7 +229,7 @@ sgx_status_t initalize_ssl_context(SSL_CONF_CTX*& ssl_conf_ctx, SSL_CTX*& ctx) } if (!SSL_CONF_CTX_finish(ssl_conf_ctx)) { - t_print("Error finishing ssl context configuration \n"); + PRINT("Error finishing ssl context configuration \n"); goto exit; } ret = SGX_SUCCESS; @@ -258,18 +258,18 @@ int read_from_session_peer( if (error == SSL_ERROR_WANT_READ) continue; - t_print("Failed! SSL_read returned error=%d\n", error); + PRINT("Failed! SSL_read returned error=%d\n", error); ret = bytes_read; break; } - t_print(" %d bytes read from session peer\n", bytes_read); + PRINT(" %d bytes read from session peer\n", bytes_read); // check to see if received payload is expected if ((bytes_read != payload_length) || (memcmp(payload, buffer, bytes_read) != 0)) { - t_print( + PRINT( "ERROR: expected reading %lu bytes but only " "received %d bytes\n", payload_length, @@ -279,7 +279,7 @@ int read_from_session_peer( } else { - t_print(" received all the expected data from the session peer\n\n"); + PRINT(" received all the expected data from the session peer\n\n"); ret = 0; break; } @@ -303,12 +303,12 @@ int write_to_session_peer( int error = SSL_get_error(ssl_session, bytes_written); if (error == SSL_ERROR_WANT_WRITE) continue; - t_print("Failed! SSL_write returned %d\n", error); + PRINT("Failed! SSL_write returned %d\n", error); ret = bytes_written; goto exit; } - t_print("%lu bytes written to session peer\n\n", payload_length); + PRINT("%lu bytes written to session peer\n\n", payload_length); exit: return ret; } diff --git a/SampleCode/SampleAttestedTLS/common/utility.cpp b/SampleCode/SampleAttestedTLS/common/utility.cpp index c3850b06..fd144eb9 100644 --- a/SampleCode/SampleAttestedTLS/common/utility.cpp +++ b/SampleCode/SampleAttestedTLS/common/utility.cpp @@ -52,19 +52,19 @@ int get_pkey_by_rsa(EVP_PKEY *pk) e = BN_new(); if (!e) { - t_print("BN_new failed\n"); + PRINT("BN_new failed\n"); return res; } res = BN_set_word(e, (BN_ULONG)RSA_F4); if (!res) { - t_print("BN_set_word failed (%d)\n", res); + PRINT("BN_set_word failed (%d)\n", res); return res; } rsa = RSA_new(); if (!rsa) { - t_print("RSA_new failed\n"); + PRINT("RSA_new failed\n"); res = -1; return res; } @@ -78,7 +78,7 @@ int get_pkey_by_rsa(EVP_PKEY *pk) if (!res) { - t_print("RSA_generate_key failed (%d)\n", res); + PRINT("RSA_generate_key failed (%d)\n", res); return res; } @@ -99,14 +99,14 @@ int get_pkey_by_ec(EVP_PKEY *pk) res = EVP_PKEY_keygen_init(ctx); if (res <= 0) { - t_print("EC_generate_key failed (%d)\n", res); + PRINT("EC_generate_key failed (%d)\n", res); return res; } res = EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, NID_secp384r1); if (res <= 0) { - t_print("EC_generate_key failed (%d)\n", res); + PRINT("EC_generate_key failed (%d)\n", res); return res; } @@ -114,7 +114,7 @@ int get_pkey_by_ec(EVP_PKEY *pk) res = EVP_PKEY_keygen(ctx, &pk); if (res <= 0) { - t_print("EC_generate_key failed (%d)\n", res); + PRINT("EC_generate_key failed (%d)\n", res); return res; } @@ -141,7 +141,7 @@ sgx_status_t generate_key_pair( pkey = EVP_PKEY_new(); if (!pkey) { - t_print("EVP_PKEY_new failed\n"); + PRINT("EVP_PKEY_new failed\n"); result = SGX_ERROR_UNEXPECTED; goto done; } @@ -163,7 +163,7 @@ sgx_status_t generate_key_pair( if (res <= 0) { - t_print("get_pkey failed (%d)\n", res); + PRINT("get_pkey failed (%d)\n", res); result = SGX_ERROR_UNEXPECTED; goto done; } @@ -172,7 +172,7 @@ sgx_status_t generate_key_pair( local_public_key = (uint8_t*)malloc(RSA_3072_PUBLIC_KEY_SIZE); if (!local_public_key) { - t_print("out-of-memory:calloc(local_public_key failed\n"); + PRINT("out-of-memory:calloc(local_public_key failed\n"); result = SGX_ERROR_OUT_OF_EPC; goto done; } @@ -181,7 +181,7 @@ sgx_status_t generate_key_pair( local_private_key = (uint8_t*)malloc(RSA_3072_PRIVATE_KEY_SIZE); if (!local_private_key) { - t_print("out-of-memory: calloc(local_private_key) failed\n"); + PRINT("out-of-memory: calloc(local_private_key) failed\n"); result = SGX_ERROR_OUT_OF_EPC; goto done; } @@ -192,21 +192,21 @@ sgx_status_t generate_key_pair( bio = BIO_new(BIO_s_mem()); if (!bio) { - t_print("BIO_new for local_public_key failed\n"); + PRINT("BIO_new for local_public_key failed\n"); goto done; } res = PEM_write_bio_PUBKEY(bio, pkey); if (!res) { - t_print("PEM_write_bio_PUBKEY failed (%d)\n", res); + PRINT("PEM_write_bio_PUBKEY failed (%d)\n", res); goto done; } res = BIO_read(bio, local_public_key, RSA_3072_PUBLIC_KEY_SIZE); if (!res) { - t_print("BIO_read public key failed (%d)\n", res); + PRINT("BIO_read public key failed (%d)\n", res); goto done; } BIO_free(bio); @@ -215,7 +215,7 @@ sgx_status_t generate_key_pair( bio = BIO_new(BIO_s_mem()); if (!bio) { - t_print("BIO_new for local_public_key failed\n"); + PRINT("BIO_new for local_public_key failed\n"); goto done; } @@ -223,14 +223,14 @@ sgx_status_t generate_key_pair( bio, pkey, nullptr, nullptr, 0, nullptr, nullptr); if (!res) { - t_print("PEM_write_bio_PrivateKey failed (%d)\n", res); + PRINT("PEM_write_bio_PrivateKey failed (%d)\n", res); goto done; } res = BIO_read(bio, local_private_key, RSA_3072_PRIVATE_KEY_SIZE); if (!res) { - t_print("BIO_read private key failed (%d)\n", res); + PRINT("BIO_read private key failed (%d)\n", res); goto done; } @@ -243,7 +243,7 @@ sgx_status_t generate_key_pair( *public_key_size = strlen(reinterpret_cast(local_public_key)) + 1; *private_key_size = strlen(reinterpret_cast(local_private_key)) + 1; - t_print("public_key_size %d, private_key_size %d\n", *public_key_size, *private_key_size); + PRINT("public_key_size %d, private_key_size %d\n", *public_key_size, *private_key_size); result = SGX_SUCCESS; done: diff --git a/SampleCode/SampleAttestedTLS/common/utility.h b/SampleCode/SampleAttestedTLS/common/utility.h index d2feb244..b2c3e81d 100644 --- a/SampleCode/SampleAttestedTLS/common/utility.h +++ b/SampleCode/SampleAttestedTLS/common/utility.h @@ -47,10 +47,6 @@ const unsigned char certificate_subject_name[] = "CN=Intel SGX Enclave, O=Intel Corporation,C=US"; -void t_time(time_t *c_time); - -void t_print(const char* fmt, ...); - sgx_status_t generate_key_pair( int type, uint8_t** public_key, diff --git a/SampleCode/SampleAttestedTLS/non_enc_client/Makefile b/SampleCode/SampleAttestedTLS/non_enc_client/Makefile index b0ba4cb1..9729ba17 100644 --- a/SampleCode/SampleAttestedTLS/non_enc_client/Makefile +++ b/SampleCode/SampleAttestedTLS/non_enc_client/Makefile @@ -32,7 +32,7 @@ include ../sgxenv.mk Client_Include_Path := -I. -I$(SGX_SDK)/include -I/usr/include/openssl -Client_Cpp_Flags := -DCLIENT_UNTRUSTED $(SGX_COMMON_CFLAGS) -fPIC -Wno-attributes $(Client_Include_Path) +Client_Cpp_Flags := -DCLIENT_USE_QVL $(SGX_COMMON_CFLAGS) -fPIC -Wno-attributes $(Client_Include_Path) ifeq ($(SGX_DEBUG), 1) Client_Cpp_Flags += -DDEBUG -UNDEBUG -UEDEBUG diff --git a/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh b/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh index 6cb56053..bbbe064d 100755 --- a/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh +++ b/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh @@ -35,9 +35,9 @@ project_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" echo "project_dir is $project_dir" sgxssl_dir=$project_dir/sgxssl openssl_out_dir=$sgxssl_dir/openssl_source -openssl_ver_name=openssl-1.1.1m +openssl_ver_name=openssl-1.1.1q sgxssl_github_archive=https://github.com/01org/intel-sgx-ssl/archive -sgxssl_file_name=support_tls_lin_1.1.1m +sgxssl_file_name=support_tls_lin_1.1.1q build_script=$sgxssl_dir/Linux/build_openssl.sh server_url_path=https://www.openssl.org/source full_openssl_url=$server_url_path/$openssl_ver_name.tar.gz @@ -56,8 +56,8 @@ if [ $debug == true ] ; then read -n 1 -p "download souce code only, because we need to build ourselves" fi -openssl_chksum=f89199be8b23ca45fc7cb9f1d8d3ee67312318286ad030f5316aca6462db6c96 -sgxssl_chksum=e645b5e9b0d81da4470d454b7f7d838cc310dd72427bd343bfe744c82493b39e +openssl_chksum=d7939ce614029cdff0b6c20f0e2e5703158a489a72b2507b8bd51bf8c8fd10ca +sgxssl_chksum=0ab6f62bda33e760422d502ba4812d058e50516ebb82e6c7713c78f580a7d622 rm -f check_sum_openssl.txt check_sum_sgxssl.txt if [ ! -f $build_script ]; then wget $sgxssl_github_archive/$sgxssl_file_name.zip -P $sgxssl_dir/ || exit 1 diff --git a/SampleCode/SampleAttestedTLS/server/enc/Makefile b/SampleCode/SampleAttestedTLS/server/enc/Makefile index b0d740cf..530ecbef 100644 --- a/SampleCode/SampleAttestedTLS/server/enc/Makefile +++ b/SampleCode/SampleAttestedTLS/server/enc/Makefile @@ -34,6 +34,7 @@ include ../../sgxenv.mk INCDIR := $(SGX_SDK)/include ENC_TLS_SERVER_Name := tls_server_enclave.so Signed_ENC_TLS_SERVER_Name := tls_server_enclave.signed.so +Enclave_Test_Key := private_test_key.pem .PHONY: all build clean run @@ -59,7 +60,12 @@ build: $(CXX) -o $(ENC_TLS_SERVER_Name) $(OBJ_FILES) $(Enclave_Link_Flags) sign: - $(SGX_ENCLAVE_SIGNER) sign -key private_test_key.pem -enclave $(ENC_TLS_SERVER_Name) \ +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + $(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(ENC_TLS_SERVER_Name) \ -out $(Signed_ENC_TLS_SERVER_Name) -config server_enc.config.xml clean: diff --git a/SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem b/SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem deleted file mode 100644 index 38c002ab..00000000 --- a/SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIG5AIBAAKCAYEA3G5Wa4v6OPqaboH5qO/g8Hg0NCkAIRAN3dCepNPjtjY/Uanr -mMu99GZn/L/+SzMjawYhudUmtHkh3m3nHKJqp0HMVgXV0k1BK00fnlUHYP2bNr5R -tV0LvpGH6Iy4b7t0/WRCZrxVdbJfaCnR8f7n9AJZ9xsnuuIiRL1dppH1lfijHuaj -aH2VBbOrrzkhS3LQQloG278KO3Yy0VeVCbm7ljO06QXv+V2I4jExVRtiiWAPnb0x -54b6AKkD+K4r+9LvYofZPVig+aQ9y54H3wJw3PWOlTOgkJPONIDhxkP+sTbaAlOD -NSE3XtPdMkGIH3RxMSkg8NWEa9tYhNOIfNUAN/ECT1Qe6UhMS5MVH2bCru/TijbA -IIWUwypWpt8UBs420RF8aJ69mivLsiEeJm3ODwa70h+1e2Da6Kgp6kpG9ZOm3wQ7 -WK9ywxiG1HR9Yd+wu8bBMfW1HBCjdpH2wQFOTsC5qy1FqIAU9a5r3tXn6CbMJnev -Sg2NAwd5UTADBOVhAgEDAoIBgQCS9DmdB/wl/Gb0VqZwn+tK+s14G1VrYAk+ixRt -4pfOztThG/Jl3SlNmZqof/7czMJHWWvROMR4UME+8+9obEcaK92Oro6MM4DHiL++ -41pAqRIkfuEjk10ptlqbCHr1J6NTmCxEfY5OdupFcTahVJqirDv6Ehp8lsGDKOkZ -tqO5UGy/RGzwU7iud8fKJhYyTIrW5q89KgbSTsyLj7ixJn0OzSNGA/VQ6QXsIMuO -EkGw6rUT03aaWfwAcK1QdB1SjJ5aOTLATtFPs3WKA40dBv4yNs7seywMqFq2rE1c -TxgbittaId28nCqNWH0dgJrq75qnYc8BucrvOd36tQwAYjs0Sr03/8TkyiWkC8mf -C0LT+aqD90bcF+S5hYr+grhBO9SzWYNWwvlWy2j3N6W/gCgmJbgEB+oke7NAR5Sd -Vy8wHiJshGKQ8xDBBAzFikZ2+rqHcHsuNjxNcp0qDbMaNrC4AxEKkL1mw6znD61F -IFQkKUdeAM5L+FnnyLU2qAw82qsCgcEA8lN0PU+sb5e2t1A92iswTyHcPktMmINM -OtnvJcAV4FWf3pM9kUKFyeT3HeWZ/+jEyI+tDvoyNcg8mjzE8JmIfzaM/7NhsJ6k -hACK7G6YW1yEt7kvbLY9h8B2MaH8BObVwJu0luSAaTnZU323t2yakiGmlLdgYPSl -0zxWdUzNu0Tn/rBVPTkNzK0T8Lq935KXvHU/OECvQPrDZCVAPFBgng7qH40SIyp1 -hMKVbWTKb6GDmn0O2mgSsT0jTRl0mj0hAoHBAOjemN+SupJ/VsVIdllMw0KBe/Qv -keUT+eekfpYNRKeQ8RyNeQj0ccDqKmgbBb8kRG2GvV9Eoc88TvKHMYuoHupKWXuh -FeF6b1GA28RnRhWczwyKpmmrgCUhj/d5A6ANogNvgs+Vxy7A1OvP7c/A90OsgTdc -deOyqDUAdIj6snIhiz2NUkIJy9TlX7tqVc/VATQoyTRjq2bp9FNYKd1e5JytNfvH -F2swHBZUUonAn0JHXX75av2w83YdRjIafA9gQQKBwQChjPgo38hKZSR6NX6RciA0 -wT1+3N27AjLR5p9ugA6VjmqUYikLga6GmKS+mRFVRdiFtR4J/CF5MChm0y31u7BU -zwiqd5Z1vxhYAFydnxA86Fh6e3TzJCkFKvl2a/1YmePVvSMPQwBGJpDiU8/Pnbxh -a8RjJOrrTcPiKDmjiIkng0VUdY4o0LPdyLf10dPqYbp9o3961corUdeYGNV9iusU -CfFqXgwXcaOt1w5I7dxKa60RqLSRmrcg02zeEPhm02sCgcEAmz8QlQx8Yao52Nr5 -kN3Xgaun+B+2mLf778L/DrODGmCgvbOmBfhL1fFxmryuf22C868o6i3BNNLfTFoh -B8Vp8YbmUmtj66b04QCSgu+EDmiKCFxu8R0AGMEKpPtXwAkWrPUB37kvdICN8oqe -ioCk18hWJOhOl8xwI1WjBfx29sEHfl421rEyje4/0kbj3+NWIsXbeEJyRJv4N5Ab -6OntvcjOp9oPnMq9ZDg3BoBqLC+TqfucqSCiTr4uzBGoCkArAoHBANdEojnkFjyw -cdoU54SQ0/JXLP38C2tibMg/kLEuAKIw6fWasEdf/SQ08Z0+mXomQDMhjBj98Tc8 -aEbkEqhwWLW2py3djDLPifSxMx+taog930SMubKquefyztX+jzajElCahwmt4XmK -l8tZTFVQPWqdRmtUvFCrHRGi+Rw5FApSDQqHgFANXuSx8mSNQKiMWQIO65cYT/Vi -490OqpNhUA5lXTxywdQmyg7RdCiV2xAYy+NE1EAIBYUdlNPG1WbAHA== ------END RSA PRIVATE KEY----- diff --git a/SampleCode/SampleDNNL/Enclave/Enclave_private_test.pem b/SampleCode/SampleDNNL/Enclave/Enclave_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/SampleDNNL/Enclave/Enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/SampleDNNL/Makefile b/SampleCode/SampleDNNL/Makefile index 8f740bb8..dc46173a 100644 --- a/SampleCode/SampleDNNL/Makefile +++ b/SampleCode/SampleDNNL/Makefile @@ -93,12 +93,6 @@ endif App_Compile_CXXFlags := $(App_Compile_CFlags) App_Link_Flags := -L$(SGX_LIBRARY_PATH) -l$(Urts_Library_Name) -lpthread -ifneq ($(SGX_MODE), HW) - App_Link_Flags += -lsgx_uae_service_sim -else - App_Link_Flags += -lsgx_uae_service -endif - Gen_Untrusted_Source := App/Enclave_u.c Gen_Untrusted_Object := App/Enclave_u.o @@ -162,6 +156,7 @@ Enclave_Objects := $(Gen_Trusted_Object) $(Enclave_C_Files:.c=.o) $(Enclave_Cpp_ Enclave_Name := libenclave.so Signed_Enclave_Name := libenclave.signed.so Enclave_Config_File := Enclave/Enclave.config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) @@ -262,7 +257,12 @@ $(Enclave_Name): $(Enclave_Objects) @echo "LINK => $@" $(Signed_Enclave_Name): $(Enclave_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave/Enclave_private_test.pem -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) @echo "SIGN => $@" diff --git a/SampleCode/SampleDNNL/README.txt b/SampleCode/SampleDNNL/README.txt index 97968b23..6e169952 100644 --- a/SampleCode/SampleDNNL/README.txt +++ b/SampleCode/SampleDNNL/README.txt @@ -7,21 +7,23 @@ The project demonstrates Intel(R) Deep Neural Network Library (DNNL) functions i How to Build/Execute the Sample Code ------------------------------------ 1. Install Intel(R) Software Guard Extensions (Intel(R) SGX) SDK for Linux* OS - -2. Build Intel(R) SGX DNNL library. +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to and put it under the folder. +3. Build Intel(R) SGX DNNL library. a. Download Intel(R) SGX source codes from: https://github.com/intel/linux-sgx b. Build the library. $ cd ./external/dnnl $ make -3. Install Intel(R) SGX DNNL library and header files. +4. Install Intel(R) SGX DNNL library and header files. a. Copy Intel(R) SGX DNNL lib to the Intel(R) SGX SDK installation directory. $ cp "./sgx_dnnl/lib/libsgx_dnnl.a" "$(SGX_SDK)/lib64" b. Copy Intel(R) SGX DNNL header files to the Intel(R) SGX SDK header file directory. $ cp "./sgx_dnnl/include/*" "$(SGX_SDK)/include" -4. Make sure your environment is set: +5. Make sure your environment is set: $ source ${sgx-sdk-install-path}/environment -5. Build the project with the prepared Makefile: +6. Build the project with the prepared Makefile: a. Hardware Mode, Debug build: $ make b. Hardware Mode, Pre-release build: @@ -34,7 +36,7 @@ How to Build/Execute the Sample Code $ make SGX_MODE=SIM SGX_PRERELEASE=1 SGX_DEBUG=0 f. Simulation Mode, Release build: $ make SGX_MODE=SIM SGX_DEBUG=0 -6. Execute the binary directly: +7. Execute the binary directly: $ ./app -7. Remember to "make clean" before switching build mode +8. Remember to "make clean" before switching build mode diff --git a/SampleCode/SampleEnclave/Enclave/Enclave_private_test.pem b/SampleCode/SampleEnclave/Enclave/Enclave_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/SampleEnclave/Enclave/Enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/SampleEnclave/Enclave/config.05.xml b/SampleCode/SampleEnclave/Enclave/config.05.xml new file mode 100644 index 00000000..8ffe35ea --- /dev/null +++ b/SampleCode/SampleEnclave/Enclave/config.05.xml @@ -0,0 +1,20 @@ + + 0 + 0 + 1 + 5 + 1 + 13 + 0x4000 + 0x2000 + 0x5000 + + 0x50000 + + 0 + + 1 + 0xFFFFFFFF + diff --git a/SampleCode/SampleEnclave/Makefile b/SampleCode/SampleEnclave/Makefile index f3e1591b..f7b0af37 100644 --- a/SampleCode/SampleEnclave/Makefile +++ b/SampleCode/SampleEnclave/Makefile @@ -155,6 +155,7 @@ Enclave_Cpp_Objects := $(sort $(Enclave_Cpp_Files:.cpp=.o)) Enclave_Name := enclave.so Signed_Enclave_Name := enclave.signed.so Enclave_Config_File := Enclave/Enclave.config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) @@ -256,10 +257,15 @@ $(Enclave_Name): Enclave/Enclave_t.o $(Enclave_Cpp_Objects) @echo "LINK => $@" $(Signed_Enclave_Name): $(Enclave_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave/Enclave_private_test.pem -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) @echo "SIGN => $@" .PHONY: clean clean: - @rm -f .config_* $(App_Name) $(Enclave_Name) $(Signed_Enclave_Name) $(App_Cpp_Objects) App/Enclave_u.* $(Enclave_Cpp_Objects) Enclave/Enclave_t.* + @rm -f .config_* $(App_Name) $(Enclave_Name) $(Signed_Enclave_Name) $(App_Cpp_Objects) App/Enclave_u.* $(Enclave_Cpp_Objects) Enclave/Enclave_t.* $(Enclave_Test_Key) diff --git a/SampleCode/SampleEnclave/README.txt b/SampleCode/SampleEnclave/README.txt index 923de7b1..c8873918 100644 --- a/SampleCode/SampleEnclave/README.txt +++ b/SampleCode/SampleEnclave/README.txt @@ -11,9 +11,12 @@ Extensions (Intel(R) SGX) SDK: How to Build/Execute the Sample Code ------------------------------------ 1. Install Intel(R) SGX SDK for Linux* OS -2. Make sure your environment is set: +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to and put it under the folder. +3. Make sure your environment is set: $ source ${sgx-sdk-install-path}/environment -3. Build the project with the prepared Makefile: +4. Build the project with the prepared Makefile: a. Hardware Mode, Debug build: 1) Enclave with no mitigation: $ make @@ -41,9 +44,9 @@ How to Build/Execute the Sample Code $ make SGX_MODE=SIM SGX_PRERELEASE=1 SGX_DEBUG=0 f. Simulation Mode, Release build: $ make SGX_MODE=SIM SGX_DEBUG=0 -4. Execute the binary directly: +5. Execute the binary directly: $ ./app -5. Remember to "make clean" before switching build mode +6. Remember to "make clean" before switching build mode ------------------------------------------ Explanation about Configuration Parameters diff --git a/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave_private_test.pem b/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/SampleEnclaveGMIPP/Makefile b/SampleCode/SampleEnclaveGMIPP/Makefile index fbada4f1..1235c360 100644 --- a/SampleCode/SampleEnclaveGMIPP/Makefile +++ b/SampleCode/SampleEnclaveGMIPP/Makefile @@ -155,6 +155,7 @@ Enclave_Cpp_Objects := $(sort $(Enclave_Cpp_Files:.cpp=.o)) Enclave_Name := enclave.so Signed_Enclave_Name := enclave.signed.so Enclave_Config_File := Enclave/Enclave.config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) @@ -256,7 +257,12 @@ $(Enclave_Name): Enclave/Enclave_t.o $(Enclave_Cpp_Objects) @echo "LINK => $@" $(Signed_Enclave_Name): $(Enclave_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave/Enclave_private_test.pem -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) @echo "SIGN => $@" .PHONY: clean diff --git a/SampleCode/SampleEnclaveGMIPP/README.txt b/SampleCode/SampleEnclaveGMIPP/README.txt index ca738685..0867f1fc 100644 --- a/SampleCode/SampleEnclaveGMIPP/README.txt +++ b/SampleCode/SampleEnclaveGMIPP/README.txt @@ -9,11 +9,14 @@ More details about GM SM2/SM3/SM4 functions in IPP, please refer to IPP official How to Build/Execute the Sample Code ------------------------------------ 1. Install Intel(R) SGX SDK for Linux* OS -2. Make sure your environment is set: +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to and put it under the folder. +3. Make sure your environment is set: $ source ${sgx-sdk-install-path}/environment -3. Ensure IPP header file folder is included in Makefile: +4. Ensure IPP header file folder is included in Makefile: Enclave_Include_Paths := [other Enclave_Include_Paths] -I$(SGX_SDK)/include/ipp -4. Build the project with the prepared Makefile: +5. Build the project with the prepared Makefile: a. Hardware Mode, Debug build: 1) Enclave with no mitigation: $ make @@ -41,6 +44,6 @@ How to Build/Execute the Sample Code $ make SGX_MODE=SIM SGX_PRERELEASE=1 SGX_DEBUG=0 f. Simulation Mode, Release build: $ make SGX_MODE=SIM SGX_DEBUG=0 -5. Execute the binary directly: +6. Execute the binary directly: $ ./app -6. Remember to "make clean" before switching build mode +7. Remember to "make clean" before switching build mode diff --git a/SampleCode/SampleEnclavePCL/Enclave/Enclave_private_test.pem b/SampleCode/SampleEnclavePCL/Enclave/Enclave_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/SampleEnclavePCL/Enclave/Enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIG4gIBAAKCAYEAroOogvsj/fZDZY8XFdkl6dJmky0lRvnWMmpeH41Bla6U1qLZ -AmZuyIF+mQC/cgojIsrBMzBxb1kKqzATF4+XwPwgKz7fmiddmHyYz2WDJfAjIveJ -ZjdMjM4+EytGlkkJ52T8V8ds0/L2qKexJ+NBLxkeQLfV8n1mIk7zX7jguwbCG1Pr -nEMdJ3Sew20vnje+RsngAzdPChoJpVsWi/K7cettX/tbnre1DL02GXc5qJoQYk7b -3zkmhz31TgFrd9VVtmUGyFXAysuSAb3EN+5VnHGr0xKkeg8utErea2FNtNIgua8H -ONfm9Eiyaav1SVKzPHlyqLtcdxH3I8Wg7yqMsaprZ1n5A1v/levxnL8+It02KseD -5HqV4rf/cImSlCt3lpRg8U5E1pyFQ2IVEC/XTDMiI3c+AR+w2jSRB3Bwn9zJtFlW -KHG3m1xGI4ck+Lci1JvWWLXQagQSPtZTsubxTQNx1gsgZhgv1JHVZMdbVlAbbRMC -1nSuJNl7KPAS/VfzAgEDAoIBgHRXxaynbVP5gkO0ug6Qw/E27wzIw4SmjsxG6Wpe -K7kfDeRskKxESdsA/xCrKkwGwhcx1iIgS5+Qscd1Yg+1D9X9asd/P7waPmWoZd+Z -AhlKwhdPsO7PiF3e1AzHhGQwsUTt/Y/aSI1MpHBvy2/s1h9mFCslOUxTmWw0oj/Q -ldIEgWeNR72CE2+jFIJIyml6ftnb6qzPiga8Bm48ubKh0kvySOqnkmnPzgh+JBD6 -JnBmtZbfPT97bwTT+N6rnPqOOApvfHPf15kWI8yDbprG1l4OCUaIUH1AszxLd826 -5IPM+8gINLRDP1MA6azECPjTyHXhtnSIBZCyWSVkc05vYmNXYUNiXWMajcxW9M02 -wKzFELO8NCEAkaTPxwo4SCyIjUxiK1LbQ9h8PSy4c1+gGP4LAMR8xqP4QKg6zdu9 -osUGG/xRe/uufgTBFkcjqBHtK5L5VI0jeNIUAgW/6iNbYXjBMJ0GfauLs+g1VsOm -WfdgXzsb9DYdMa0OXXHypmV4GwKBwQDUwQj8RKJ6c8cT4vcWCoJvJF00+RFL+P3i -Gx2DLERxRrDa8AVGfqaCjsR+3vLgG8V/py+z+dxZYSqeB80Qeo6PDITcRKoeAYh9 -xlT3LJOS+k1cJcEmlbbO2IjLkTmzSwa80fWexKu8/Xv6vv15gpqYl1ngYoqJM3pd -vzmTIOi7MKSZ0WmEQavrZj8zK4endE3v0eAEeQ55j1GImbypSf7Idh7wOXtjZ7WD -Dg6yWDrri+AP/L3gClMj8wsAxMV4ZR8CgcEA0fzDHkFa6raVOxWnObmRoDhAtE0a -cjUj976NM5yyfdf2MrKy4/RhdTiPZ6b08/lBC/+xRfV3xKVGzacm6QjqjZrUpgHC -0LKiZaMtccCJjLtPwQd0jGQEnKfMFaPsnhOc5y8qVkCzVOSthY5qhz0XNotHHFmJ -gffVgB0iqrMTvSL7IA2yqqpOqNRlhaYhNl8TiFP3gIeMtVa9rZy31JPgT2uJ+kfo -gV7sdTPEjPWZd7OshGxWpT6QfVDj/T9T7L6tAoHBAI3WBf2DFvxNL2KXT2QHAZ9t -k3imC4f7U+wSE6zILaDZyzygA4RUbwG0gv8/TJVn2P/Eynf76DuWHGlaiLWnCbSz -Az2DHBQBBaku409zDQym3j1ugMRjzzSQWzJg0SIyBH3hTmnYcn3+Uqcp/lEBvGW6 -O+rsXFt3pukqJmIV8HzLGGaLm62BHUeZf3dyWm+i3p/hQAL7Xvu04QW70xuGqdr5 -afV7p5eaeQIJXyGQJ0eylV/90+qxjMKiB1XYg6WYvwKBwQCL/ddpgOdHJGN8uRom -e7Zq0Csi3hGheMKlKbN3vcxT5U7MdyHtTZZOJbTvxKNNUNYH/8uD+PqDGNneb29G -BfGzvI3EASyLIcGZF3OhKwZd0jUrWk2y7Vhob91jwp2+t73vdMbkKyI4mHOuXvGv -fg95si9oO7EBT+Oqvhccd2J+F1IVXncccYnF4u5ZGWt5lLewN/pVr7MjjykeaHqN -t+rfnQam2psA6fL4zS2zTmZPzR2tnY8Y1GBTi0Ko1OKd1HMCgcAb5cB/7/AQlhP9 -yQa04PLH9ygQkKKptZp7dy5WcWRx0K/hAHRoi2aw1wZqfm7VBNu2SLcs90kCCCxp -6C5sfJi6b8NpNbIPC+sc9wsFr7pGo9SFzQ78UlcWYK2Gu2FxlMjonhka5hvo4zvg -WxlpXKEkaFt3gLd92m/dMqBrHfafH7VwOJY2zT3WIpjwuk0ZzmRg5p0pG/svVQEH -NZmwRwlopysbR69B/n1nefJ84UO50fLh5s5Zr3gBRwbWNZyzhXk= ------END RSA PRIVATE KEY----- diff --git a/SampleCode/SampleEnclavePCL/Makefile b/SampleCode/SampleEnclavePCL/Makefile index e2aadbe1..c660f004 100644 --- a/SampleCode/SampleEnclavePCL/Makefile +++ b/SampleCode/SampleEnclavePCL/Makefile @@ -166,6 +166,7 @@ Enclave_Cpp_Objects := $(Enclave_Cpp_Files:.cpp=.o) Enclave_Name := enclave.so Signed_Enclave_Name := enclave.signed.so Enclave_Config_File := Enclave/Enclave.config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem Unsigned_Enclave_Name := $(Enclave_Name) Encrypted_Enclave_Name := $(Enclave_Name).enc @@ -175,6 +176,7 @@ Signed_Seal_Enclave_Name := Seal.signed.so Seal_Enclave_Cpp_Files := Seal/Seal.cpp Seal_Enclave_Cpp_Objects := $(Seal_Enclave_Cpp_Files:.cpp=.o) Seal_Enclave_Config_File := Seal/Seal.config.xml +Seal_Enclave_Test_Key := Seal/Seal_private_test.pem PCL_LINK_FLAGS := @@ -319,7 +321,12 @@ $(Seal_Enclave_Name): Seal/Seal_t.o $(Seal_Enclave_Cpp_Objects) @echo "LINK => $@" $(Signed_Seal_Enclave_Name): $(Seal_Enclave_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Seal/Seal_private_test.pem -enclave $(Seal_Enclave_Name) -out $@ -config $(Seal_Enclave_Config_File) +ifeq ($(wildcard $(Seal_Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Seal_Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Seal_Enclave_Test_Key) -enclave $(Seal_Enclave_Name) -out $@ -config $(Seal_Enclave_Config_File) @echo "SIGN => $@" ######## Enclave Objects ######## @@ -356,7 +363,7 @@ $(Signed_Enclave_Name): $(Encrypted_Enclave_Name) else $(Signed_Enclave_Name): $(Enclave_Name) endif - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave/Enclave_private_test.pem -enclave $< -out $@ -config $(Enclave_Config_File) + @$(SGX_ENCLAVE_SIGNER) sign -key $(Seal_Enclave_Test_Key) -enclave $< -out $@ -config $(Enclave_Config_File) @echo "SIGN => $@" .PHONY: clean diff --git a/SampleCode/SampleEnclavePCL/README.md b/SampleCode/SampleEnclavePCL/README.md index ae07e155..dfaa2f0c 100644 --- a/SampleCode/SampleEnclavePCL/README.md +++ b/SampleCode/SampleEnclavePCL/README.md @@ -26,6 +26,9 @@ Enclave writers should compare SampleEnclave and SampleEnclavePCL. This demonstr Build and test the Intel(R) SGX PCL with the sample code -------------------------------------------------------- 1. Install Intel(R) Software Guard Extensions (Intel(R) SGX) SDK for Linux* OS +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key/ automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to / and put it under the / folder. 2. Make sure your environment is set: $ source ${sgx-sdk-install-path}/environment 3. Build the project with the prepared Makefile: diff --git a/SampleCode/SampleEnclavePCL/Seal/Seal_private_test.pem b/SampleCode/SampleEnclavePCL/Seal/Seal_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/SampleEnclavePCL/Seal/Seal_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/SealUnseal/Enclave_Seal/Enclave_private_test.pem b/SampleCode/SealUnseal/Enclave_Seal/Enclave_private_test.pem deleted file mode 100644 index d387d4f8..00000000 --- a/SampleCode/SealUnseal/Enclave_Seal/Enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- \ No newline at end of file diff --git a/SampleCode/SealUnseal/Makefile b/SampleCode/SealUnseal/Makefile index c07e3461..750ed39f 100644 --- a/SampleCode/SealUnseal/Makefile +++ b/SampleCode/SealUnseal/Makefile @@ -159,6 +159,7 @@ Enclave_Seal_Objects := $(Gen_Trusted_Object_Seal) $(Enclave_Seal_Cpp_Files:.cpp Enclave_Seal_Name := libenclave_seal.so Signed_Enclave_Seal_Name := libenclave_seal.signed.so Enclave_Seal_Config_File := Enclave_Seal/Enclave_Seal.config.xml +Enclave_Seal_Test_Key := Enclave_Seal/Enclave_private_test.pem Enclave_Seal_Link_Flags := $(Enclave_Link_Flags) -Wl,--version-script=Enclave_Seal/Enclave_Seal.lds # Enclave_Unseal @@ -274,7 +275,12 @@ $(Enclave_Seal_Name): $(Enclave_Seal_Objects) @echo "LINK => $@" $(Signed_Enclave_Seal_Name): $(Enclave_Seal_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave_Seal/Enclave_private_test.pem -enclave $(Enclave_Seal_Name) -out $@ -config $(Enclave_Seal_Config_File) +ifeq ($(wildcard $(Enclave_Seal_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Seal_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Seal_Test_Key) -enclave $(Enclave_Seal_Name) -out $@ -config $(Enclave_Seal_Config_File) @echo "SIGN => $@" @@ -298,7 +304,7 @@ $(Enclave_Unseal_Name): $(Enclave_Unseal_Objects) @echo "LINK => $@" $(Signed_Enclave_Unseal_Name): $(Enclave_Unseal_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave_Seal/Enclave_private_test.pem -enclave $(Enclave_Unseal_Name) -out $@ -config $(Enclave_Unseal_Config_File) + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Seal_Test_Key) -enclave $(Enclave_Unseal_Name) -out $@ -config $(Enclave_Unseal_Config_File) @echo "SIGN => $@" diff --git a/SampleCode/SealUnseal/README.txt b/SampleCode/SealUnseal/README.txt index 967dfbe1..c14b5b07 100644 --- a/SampleCode/SealUnseal/README.txt +++ b/SampleCode/SealUnseal/README.txt @@ -7,6 +7,9 @@ The project demonstrates sealing/unsealing data between two enclaves. How to Build/Execute the Sample Code ------------------------------------ 1. Install Intel(R) SGX SDK for Linux* OS +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to and put it under the folder. 2. Make sure your environment is set: $ source ${sgx-sdk-install-path}/environment 3. Build the project with the prepared Makefile: diff --git a/SampleCode/Switchless/Enclave/Enclave_private_test.pem b/SampleCode/Switchless/Enclave/Enclave_private_test.pem deleted file mode 100644 index 529d07be..00000000 --- a/SampleCode/Switchless/Enclave/Enclave_private_test.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -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 ------END RSA PRIVATE KEY----- diff --git a/SampleCode/Switchless/Makefile b/SampleCode/Switchless/Makefile index d66868f9..a08472ff 100644 --- a/SampleCode/Switchless/Makefile +++ b/SampleCode/Switchless/Makefile @@ -104,12 +104,6 @@ App_Link_Flags := -L$(SGX_LIBRARY_PATH) \ -Wl,--whole-archive -lsgx_uswitchless -Wl,--no-whole-archive \ -l$(Urts_Library_Name) -lpthread -ifneq ($(SGX_MODE), HW) - App_Link_Flags += -lsgx_uae_service_sim -else - App_Link_Flags += -lsgx_uae_service -endif - App_Cpp_Objects := $(App_Cpp_Files:.cpp=.o) App_Name := app @@ -163,6 +157,7 @@ Enclave_Cpp_Objects := $(Enclave_Cpp_Files:.cpp=.o) Enclave_Name := enclave.so Signed_Enclave_Name := enclave.signed.so Enclave_Config_File := Enclave/Enclave.config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifneq ($(SGX_DEBUG), 1) @@ -235,7 +230,12 @@ $(Enclave_Name): Enclave/Enclave_t.o $(Enclave_Cpp_Objects) @echo "LINK => $@" $(Signed_Enclave_Name): $(Enclave_Name) - @$(SGX_ENCLAVE_SIGNER) sign -key Enclave/Enclave_private_test.pem -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) @echo "SIGN => $@" .PHONY: clean diff --git a/SampleCode/Switchless/README.txt b/SampleCode/Switchless/README.txt index 19c8a7d0..589aba88 100644 --- a/SampleCode/Switchless/README.txt +++ b/SampleCode/Switchless/README.txt @@ -7,14 +7,19 @@ The project demonstrates how to use Fast OCalls provided by sgx_switchless. How to Build/Execute the Sample Code ------------------------------------ 1. Install Intel(R) SGX SDK for Linux* OS -2. Build the project with the prepared Makefile: +2. Enclave test key(two options): + a. Install openssl first, then the project will generate a test key automatically when you build the project. + b. Rename your test key(3072-bit RSA private key) to and put it under the folder. +3. Make sure your environment is set: + $ source ${sgx-sdk-install-path}/environment +4. Build the project with the prepared Makefile: a. Hardware Mode, Debug build: $ make SGX_MODE=HW SGX_DEBUG=1 b. Hardware Mode, Pre-release build: $ make SGX_MODE=HW SGX_PRERELEASE=1 c. Hardware Mode, Release build: $ make SGX_MODE=HW -3. Execute the binary directly: +5. Execute the binary directly: $ ./app ------------------------------------------------- diff --git a/buildenv.mk b/buildenv.mk index 51009c75..4b68593c 100644 --- a/buildenv.mk +++ b/buildenv.mk @@ -134,7 +134,7 @@ CFLAGS += -Wjump-misses-init -Wstrict-prototypes -Wunsuffixed-float-constants # additional warnings flags for C++ CXXFLAGS += -Wnon-virtual-dtor -CXXFLAGS += -std=c++14 +CXXFLAGS += -std=c++17 .DEFAULT_GOAL := all # this turns off the RCS / SCCS implicit rules of GNU Make @@ -218,13 +218,10 @@ endif ifneq ($(origin NIX_STORE), environment) BINUTILS_DIR ?= /usr/local/bin EXT_BINUTILS_DIR = $(ROOT_DIR)/external/toolset/$(DISTR_ID)$(DISTR_VER) -else -BINUTILS_DIR ?= $(ROOT_DIR)/external/toolset/nix/ -EXT_BINUTILS_DIR = $(ROOT_DIR)/external/toolset/nix/ -endif - # enable -B option for all the build MITIGATION_CFLAGS += -B$(BINUTILS_DIR) +endif + ifeq ($(MITIGATION_C), 1) ifeq ($(MITIGATION_INDIRECT), 1) diff --git a/common/inc/internal/arch.h b/common/inc/internal/arch.h index 54f31ded..8cfa683e 100644 --- a/common/inc/internal/arch.h +++ b/common/inc/internal/arch.h @@ -124,6 +124,8 @@ typedef struct _exit_info_t #define SE_VECTOR_BP 3 #define SE_VECTOR_BR 5 #define SE_VECTOR_UD 6 +#define SE_VECTOR_GP 13 +#define SE_VECTOR_PF 14 #define SE_VECTOR_MF 16 #define SE_VECTOR_AC 17 #define SE_VECTOR_XM 19 @@ -156,6 +158,15 @@ typedef struct _ssa_gpr_t uint64_t gs; /* (176) GS register */ } ssa_gpr_t; +typedef struct _misc_exinfo +{ + uint64_t maddr; // address for #PF, #GP. + uint32_t errcd; + uint32_t reserved; +} misc_exinfo_t; + +#define MISC_BYTE_SIZE sizeof(misc_exinfo_t) + typedef uint64_t si_flags_t; #define SI_FLAG_NONE 0x0 diff --git a/common/inc/internal/enclave_creator.h b/common/inc/internal/enclave_creator.h index 4b532805..58a05fe7 100644 --- a/common/inc/internal/enclave_creator.h +++ b/common/inc/internal/enclave_creator.h @@ -80,11 +80,6 @@ public: #ifdef SE_1P5_VERTICAL virtual uint32_t handle_page_fault(uint64_t pf_address) { UNUSED(pf_address); return (uint32_t)SGX_ERROR_UNEXPECTED; } #endif - virtual int emodpr(uint64_t addr, uint64_t size, uint64_t flag) = 0; - virtual int mktcs(uint64_t tcs_addr) = 0; - virtual int trim_range(uint64_t fromaddr, uint64_t toaddr) = 0; - virtual int trim_accept(uint64_t addr) = 0; - virtual int remove_range(uint64_t fromaddr, uint64_t numpages) = 0; // destructor virtual ~EnclaveCreator() {}; diff --git a/common/inc/internal/inst.h b/common/inc/internal/inst.h index 4f2b3575..84b7b226 100644 --- a/common/inc/internal/inst.h +++ b/common/inc/internal/inst.h @@ -46,6 +46,8 @@ typedef enum { SE_ERESUME, SE_EEXIT, SE_EACCEPT, + SE_EMODPE, + SE_EACCEPTCOPY, SE_EVERIFYREPORT2 = 0x8, SE_LAST_RING3, diff --git a/common/inc/internal/linux/linux-regs.h b/common/inc/internal/linux/linux-regs.h index 48a206d3..8741edc2 100644 --- a/common/inc/internal/linux/linux-regs.h +++ b/common/inc/internal/linux/linux-regs.h @@ -88,6 +88,7 @@ #define SE_EEXIT 4 #define SE_EACCEPT 5 #define SE_EMODPE 6 +#define SE_EACCEPTCOPY 7 #define SE_EVERIFYREPORT2 8 diff --git a/common/inc/internal/metadata.h b/common/inc/internal/metadata.h index ec121a73..31065856 100644 --- a/common/inc/internal/metadata.h +++ b/common/inc/internal/metadata.h @@ -37,10 +37,10 @@ #pragma pack(1) /* version of metadata */ -#define MAJOR_VERSION 2 //MAJOR_VERSION should not larger than 0ffffffff -#define MINOR_VERSION 4 //MINOR_VERSION should not larger than 0ffffffff +#define MAJOR_VERSION 3 //MAJOR_VERSION should not larger than 0ffffffff +#define MINOR_VERSION 0 //MINOR_VERSION should not larger than 0ffffffff -#define SGX_2_ELRANGE_MAJOR_VERSION 12 +#define SGX_2_ELRANGE_MAJOR_VERSION 13 #define SGX_1_ELRANGE_MAJOR_VERSION 11 #define SGX_MAJOR_VERSION_GAP 10 @@ -72,18 +72,17 @@ #define TCS_POLICY_BIND 0x00000000 /* If set, the TCS is bound to the application thread */ #define TCS_POLICY_UNBIND 0x00000001 -#define MAX_SAVE_BUF_SIZE 2632 - #define TCS_NUM_MIN 1 #define SSA_NUM_MIN 2 #define SSA_FRAME_SIZE_MIN 1 -#define SSA_FRAME_SIZE_MAX 2 +#define SSA_FRAME_SIZE_MAX 4 #define STACK_SIZE_MIN 0x0002000 /* 8 KB */ #define STACK_SIZE_MAX 0x0040000 /* 256 KB */ #define HEAP_SIZE_MIN 0x0001000 /* 4 KB */ #define HEAP_SIZE_MAX 0x1000000 /* 16 MB */ #define RSRV_SIZE_MIN 0x0000000 /* 0 KB */ #define RSRV_SIZE_MAX 0x0000000 /* 0 KB */ +#define USER_REGION_SIZE 0x0000000 /* 0 KB */ #define DEFAULT_MISC_SELECT 0 #define DEFAULT_MISC_MASK 0xFFFFFFFF #define ISVFAMILYID_MAX 0xFFFFFFFFFFFFFFFFULL @@ -128,6 +127,7 @@ typedef enum #define LAYOUT_ID_RSRV_MIN (20) #define LAYOUT_ID_RSRV_INIT (21) #define LAYOUT_ID_RSRV_MAX (22) +#define LAYOUT_ID_USER_REGION (23) extern const char * layout_id_str[]; diff --git a/common/inc/internal/rts.h b/common/inc/internal/rts.h index e94ad56b..612cd845 100644 --- a/common/inc/internal/rts.h +++ b/common/inc/internal/rts.h @@ -65,7 +65,8 @@ typedef enum SDK_VERSION_2_0, SDK_VERSION_2_1, SDK_VERSION_2_2, - SDK_VERSION_2_3 + SDK_VERSION_2_3, + SDK_VERSION_3_0, } sdk_version_t; typedef struct _system_features @@ -95,6 +96,8 @@ typedef struct _system_features #define BUILTIN_OCALL_2 -3 #define BUILTIN_OCALL_3 -4 #define BUILTIN_OCALL_4 -5 +#define BUILTIN_OCALL_5 -6 +#define BUILTIN_OCALL_6 -7 typedef enum { @@ -102,10 +105,12 @@ typedef enum EDMM_TRIM_COMMIT = BUILTIN_OCALL_2, EDMM_MODPR = BUILTIN_OCALL_3, EDMM_MPROTECT = BUILTIN_OCALL_4, + EDMM_ALLOC = BUILTIN_OCALL_5, + EDMM_MODIFY = BUILTIN_OCALL_6, }edmm_ocall_t; -#define is_builtin_ocall(ocall_val) (((int)ocall_val >= BUILTIN_OCALL_4) && ((int)ocall_val <= BUILTIN_OCALL_1)) +#define is_builtin_ocall(ocall_val) (((int)ocall_val >= BUILTIN_OCALL_6) && ((int)ocall_val <= BUILTIN_OCALL_1)) #pragma pack(pop) diff --git a/common/inc/internal/se_version.h b/common/inc/internal/se_version.h index e92553af..e2cca011 100644 --- a/common/inc/internal/se_version.h +++ b/common/inc/internal/se_version.h @@ -31,21 +31,21 @@ #ifndef _SE_VERSION_H_ #define _SE_VERSION_H_ -#define STRFILEVER "2.17.101.1" +#define STRFILEVER "2.18.100.3" #define SGX_MAJOR_VERSION 2 -#define SGX_MINOR_VERSION 17 -#define SGX_REVISION_VERSION 101 +#define SGX_MINOR_VERSION 18 +#define SGX_REVISION_VERSION 100 #define MAKE_VERSION_UINT(major,minor,rev) (((uint64_t)major)<<32 | ((uint64_t)minor) << 16 | rev) #define VERSION_UINT MAKE_VERSION_UINT(SGX_MAJOR_VERSION, SGX_MINOR_VERSION, SGX_REVISION_VERSION) #define COPYRIGHT "Copyright (C) 2022 Intel Corporation" -#define UAE_SERVICE_VERSION "2.3.216.1" -#define URTS_VERSION "1.1.120.1" -#define ENCLAVE_COMMON_VERSION "1.1.123.1" -#define LAUNCH_VERSION "1.0.118.1" -#define EPID_VERSION "1.0.118.1" -#define QUOTE_EX_VERSION "1.1.118.1" +#define UAE_SERVICE_VERSION "2.3.216.3" +#define URTS_VERSION "2.0.100.3" +#define ENCLAVE_COMMON_VERSION "1.2.100.3" +#define LAUNCH_VERSION "1.0.118.3" +#define EPID_VERSION "1.0.118.3" +#define QUOTE_EX_VERSION "1.1.118.3" #define PCE_VERSION "1.17.100.2" #define LE_VERSION "1.17.100.2" diff --git a/common/inc/internal/sethread_spinlock.h b/common/inc/internal/sethread_spinlock.h new file mode 100644 index 00000000..65a0607e --- /dev/null +++ b/common/inc/internal/sethread_spinlock.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef _SE_THREAD_SPINLOCK_H_ +#define _SE_THREAD_SPINLOCK_H_ +#include "sgx_thread.h" +/** a recursive spin lock */ +typedef struct _sgx_thread_spinlock_t +{ + size_t m_refcount; /* number of recursive calls */ + volatile uint32_t m_lock; /* use sgx_spinlock_t */ + sgx_thread_t m_owner; +} sgx_thread_spinlock_t; + +#define SGX_THREAD_RECURSIVE_SPINLOCK_INITIALIZER \ + {0, 0, SGX_THREAD_T_NULL} +#ifdef __cplusplus +extern "C" { +#endif + +int sgx_thread_spin_init(sgx_thread_spinlock_t *mutex); +int sgx_thread_spin_destroy(sgx_thread_spinlock_t *mutex); + +int sgx_thread_spin_trylock(sgx_thread_spinlock_t *mutex); +int sgx_thread_spin_unlock(sgx_thread_spinlock_t *mutex); +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/inc/internal/trts_inst.h b/common/inc/internal/trts_inst.h index 354148dc..ffb7f80a 100644 --- a/common/inc/internal/trts_inst.h +++ b/common/inc/internal/trts_inst.h @@ -74,17 +74,13 @@ struct ms_tcs extern "C" { #endif -int sgx_accept_forward(si_flags_t sfl, size_t lo, size_t hi); int do_ereport(const sgx_target_info_t *target_info, const sgx_report_data_t *report_data, sgx_report_t *report); int do_everifyreport2(const sgx_report2_mac_struct_t *report2_mac_struct); int do_egetkey(const sgx_key_request_t *key_request, sgx_key_128bit_t *key); uint32_t do_rdrand(uint32_t *rand); int do_eaccept(const sec_info_t *, size_t); +int do_eacceptcopy(const sec_info_t *, size_t, size_t); int do_emodpe(const sec_info_t*, size_t); -int apply_EPC_pages(void *start_address, size_t page_number); -int apply_pages_within_exception(void *start_address, size_t page_count); -int trim_EPC_pages(void *start_address, size_t page_number); -sgx_status_t SGXAPI trts_mprotect(size_t start, size_t size, uint64_t perms); sgx_status_t do_add_thread(void *ms); int is_dynamic_thread(void *tcs); int is_dynamic_thread_exist(void); diff --git a/common/inc/sgx_attributes.h b/common/inc/sgx_attributes.h index 4f5e1800..523d22eb 100644 --- a/common/inc/sgx_attributes.h +++ b/common/inc/sgx_attributes.h @@ -42,14 +42,17 @@ #define SGX_FLAGS_EINITTOKEN_KEY 0x0000000000000020ULL /* If set, then the enclave has access to EINITTOKEN key */ #define SGX_FLAGS_KSS 0x0000000000000080ULL /* If set enclave uses KSS */ +#define SGX_FLAGS_NON_CHECK_BITS 0x00FF000000000000ULL /* BIT[55-48] will not be checked */ + /* XSAVE Feature Request Mask */ #define SGX_XFRM_LEGACY 0x0000000000000003ULL /* Legacy XFRM which includes the basic feature bits required by SGX, x87 state(0x01) and SSE state(0x02) */ #define SGX_XFRM_AVX 0x0000000000000006ULL /* AVX XFRM which includes AVX state(0x04) and SSE state(0x02) required by AVX */ -#define SGX_XFRM_AVX512 0x00000000000000E6ULL /* AVX-512 XFRM - not supported */ +#define SGX_XFRM_AVX512 0x00000000000000E6ULL /* AVX-512 XFRM */ #define SGX_XFRM_MPX 0x0000000000000018ULL /* MPX XFRM - not supported */ #define SGX_XFRM_PKRU 0x0000000000000200ULL /* PKRU state */ +#define SGX_XFRM_AMX 0x0000000000060000ULL /* AMX XFRM, including XTILEDATA(0x40000) and XTILECFG(0x20000) */ -#define SGX_XFRM_RESERVED (~(SGX_XFRM_LEGACY | SGX_XFRM_AVX | SGX_XFRM_AVX512 | SGX_XFRM_PKRU)) +#define SGX_XFRM_RESERVED (~(SGX_XFRM_LEGACY | SGX_XFRM_AVX | SGX_XFRM_AVX512 | SGX_XFRM_PKRU | SGX_XFRM_AMX)) typedef struct _attributes_t { diff --git a/common/inc/sgx_tprotected_fs.h b/common/inc/sgx_tprotected_fs.h index dbd5abf9..3a37e28b 100644 --- a/common/inc/sgx_tprotected_fs.h +++ b/common/inc/sgx_tprotected_fs.h @@ -94,6 +94,29 @@ SGX_FILE* SGXAPI sgx_fopen(const char* filename, const char* mode, const sgx_key SGX_FILE* SGXAPI sgx_fopen_auto_key(const char* filename, const char* mode); +/* sgx_fopen_ex + * Purpose: Expert version of sgx_fopen/sgx_fopen_auto_key which is used if you want to control the internal `cache size`. + * The specified `cache size` must be page (4KB by default) aligned. + * Note that `sgx_fexport_auto_key` and `sgx_fimport_auto_key` don't support configuring `cache_size` right now + * + * Parameters: + * filename - [IN] the name of the file to open/create. + * mode - [IN] open mode. only supports 'r' or 'w' or 'a' (one and only one of them must be present), and optionally 'b' and/or '+'. + * key - [IN] encryption key that will be used for the file encryption. + * If it's NULL, we will swtich back to `sgx_fopen_auto_key and use enclave's seal key to protect the file + * NOTE - the key is actually used as a KDK (key derivation key) and only for the meta-data node, and not used directly for the encryption of any part of the file + * this is important in order to prevent hitting the key wear-out problem, and some other issues with GCM encryptions using the same key + * cache_size - [IN] Internal cache size in byte, which used to cache R/W data in enclave before flush to actual file + * It must larger than default cache size (192KB), and must be page (4KB by default) aligned + * a) Please make sure enclave heap is enough for the `cache`, e.g. Configure enough heap in enclave config file + * b) All the data in cache may lost after exeception, please try to call `sgx_fflush` explicitly to avoid data loss + * + * Return value: + * SGX_FILE* - pointer to the newly created file handle, NULL if an error occurred - check errno for the error code. +*/ +SGX_FILE* SGXAPI sgx_fopen_ex(const char* filename, const char* mode, const sgx_key_128bit_t *key, const uint64_t cache_size); + + /* sgx_fwrite * Purpose: write data to a file (see c++ fwrite documentation for more details). * diff --git a/common/inc/sgx_trts_exception.h b/common/inc/sgx_trts_exception.h index 3e04c325..bd66e5e4 100644 --- a/common/inc/sgx_trts_exception.h +++ b/common/inc/sgx_trts_exception.h @@ -54,6 +54,8 @@ typedef enum _sgx_exception_vector_t SGX_EXCEPTION_VECTOR_BP = 3, /* INT 3 instruction */ SGX_EXCEPTION_VECTOR_BR = 5, /* BOUND instruction */ SGX_EXCEPTION_VECTOR_UD = 6, /* UD2 instruction or reserved opcode */ + SGX_EXCEPTION_VECTOR_GP = 13, /* General Protection Fault */ + SGX_EXCEPTION_VECTOR_PF = 14, /* page fault */ SGX_EXCEPTION_VECTOR_MF = 16, /* x87 FPU floating-point or WAIT/FWAIT instruction */ SGX_EXCEPTION_VECTOR_AC = 17, /* Any data reference in memory */ SGX_EXCEPTION_VECTOR_XM = 19, /* SSE/SSE2/SSE3 floating-point instruction */ @@ -103,11 +105,19 @@ typedef struct _cpu_context_t } sgx_cpu_context_t; #endif +typedef struct _exinfo_t +{ + uint64_t faulting_address; + uint32_t error_code; + uint32_t reserved; +}sgx_misc_exinfo_t; + typedef struct _exception_info_t { sgx_cpu_context_t cpu_context; sgx_exception_vector_t exception_vector; sgx_exception_type_t exception_type; + sgx_misc_exinfo_t exinfo; } sgx_exception_info_t; typedef int (*sgx_exception_handler_t)(sgx_exception_info_t *info); diff --git a/common/inc/sgx_uswitchless.h b/common/inc/sgx_uswitchless.h index 3a4a99ff..73be13cd 100644 --- a/common/inc/sgx_uswitchless.h +++ b/common/inc/sgx_uswitchless.h @@ -121,17 +121,17 @@ typedef void (*sgx_uswitchless_worker_callback_t)( typedef struct { - uint32_t switchless_calls_pool_size_qwords; //number of qwords to use for outstanding calls. (actual number is x 64) + uint64_t switchless_calls_pool_size_qwords; //number of qwords to use for outstanding calls. (actual number is x 64) - uint32_t num_uworkers; //number of untrusted (for ocalls) worker threads + uint64_t num_uworkers; //number of untrusted (for ocalls) worker threads - uint32_t num_tworkers; //number of trusted (for ecalls) worker threads + uint64_t num_tworkers; //number of trusted (for ecalls) worker threads - uint32_t retries_before_fallback; //how many times to execute assembly pause instruction + uint64_t retries_before_fallback; //how many times to execute assembly pause instruction //while waiting for worker thread to start executing switchless call //before falling back to direct ECall/OCall. - uint32_t retries_before_sleep; //how many times a worker thread executes assembly pause instruction + uint64_t retries_before_sleep; //how many times a worker thread executes assembly pause instruction //while waiting for switchless call request //before going to sleep diff --git a/common/inc/stdc++/linux/exception b/common/inc/stdc++/linux/exception index afcb0fea..a3c81106 100644 --- a/common/inc/stdc++/linux/exception +++ b/common/inc/stdc++/linux/exception @@ -61,8 +61,16 @@ namespace std virtual const char* what() const throw(); }; +# if __cplusplus < 201103L bool uncaught_exception() throw(); - +# elif __cplusplus <= 201703L + bool uncaught_exception() noexcept; +# endif + +# if __cplusplus >= 201703L + int uncaught_exceptions() noexcept; +# endif + typedef void (*unexpected_handler)(); unexpected_handler set_unexpected(unexpected_handler) throw(); void unexpected(); diff --git a/common/inc/stdc++/new b/common/inc/stdc++/new index 545f46fb..6536db2a 100644 --- a/common/inc/stdc++/new +++ b/common/inc/stdc++/new @@ -35,6 +35,7 @@ #include #include #include +#include namespace std @@ -49,21 +50,45 @@ namespace std * handler and a bad allocation exception is thrown if an allocation fails. */ new_handler set_new_handler(new_handler handler); + + enum class align_val_t : size_t { }; + + inline void* __libcpp_aligned_alloc(size_t __alignment, size_t __size) { + void* __result = nullptr; + ::posix_memalign(&__result, __alignment, __size); + return __result; + } + + inline void __libcpp_aligned_free(void* __ptr) { + ::free(__ptr); + } }; void* SGXAPI operator new (size_t); +void* SGXAPI operator new (size_t, std::align_val_t); void* SGXAPI operator new[] (size_t); +void* SGXAPI operator new[] (size_t, std::align_val_t); void* SGXAPI operator new (size_t, const std::nothrow_t&); +void* SGXAPI operator new (size_t, std::align_val_t, const std::nothrow_t&); inline void* SGXAPI operator new (size_t, void* __p) {return __p;}; void* SGXAPI operator new[] (size_t, const std::nothrow_t&); +void* SGXAPI operator new[] (size_t, std::align_val_t, const std::nothrow_t&); inline void* SGXAPI operator new[] (size_t, void* __p) {return __p;}; void SGXAPI operator delete (void*); +void SGXAPI operator delete (void*, std::align_val_t); +void SGXAPI operator delete (void*, size_t); +void SGXAPI operator delete (void*, size_t, std::align_val_t); void SGXAPI operator delete (void*, const std::nothrow_t&); +void SGXAPI operator delete (void*, std::align_val_t, const std::nothrow_t&); inline void SGXAPI operator delete (void*, void*){}; void SGXAPI operator delete[] (void*); +void SGXAPI operator delete[] (void*, std::align_val_t); +void SGXAPI operator delete[] (void*, size_t); +void SGXAPI operator delete[] (void*, size_t, std::align_val_t); void SGXAPI operator delete[] (void*, const std::nothrow_t&); +void SGXAPI operator delete[] (void*, std::align_val_t, const std::nothrow_t&); inline void SGXAPI operator delete[] (void*, void*){}; #endif /* _NEW_ */ diff --git a/common/inc/tlibc/stdalign.h b/common/inc/tlibc/stdalign.h new file mode 100644 index 00000000..93b8f601 --- /dev/null +++ b/common/inc/tlibc/stdalign.h @@ -0,0 +1,15 @@ +#ifndef _STDALIGN_H +#define _STDALIGN_H +#ifndef __cplusplus +/* this whole header only works in C11 or with compiler extensions */ +#if __STDC_VERSION__ < 201112L && defined( __GNUC__) +#define _Alignas(t) __attribute__((__aligned__(t))) +#define _Alignof(t) __alignof__(t) +#endif +#define alignas _Alignas +#define alignof _Alignof +#endif +#define __alignas_is_defined 1 +#define __alignof_is_defined 1 +#endif + diff --git a/common/inc/tlibc/stdlib.h b/common/inc/tlibc/stdlib.h index f32b6d00..57d0b0bb 100644 --- a/common/inc/tlibc/stdlib.h +++ b/common/inc/tlibc/stdlib.h @@ -99,7 +99,12 @@ long _TLIBC_CDECL_ labs(long); ldiv_t _TLIBC_CDECL_ ldiv(long, long); void * _TLIBC_CDECL_ malloc(size_t); void * _TLIBC_CDECL_ memalign(size_t, size_t); -int _TLIBC_CDECL_ posix_memalign(void**, size_t, size_t); +#ifndef __cplusplus +int _TLIBC_CDECL_ posix_memalign(void **, size_t, size_t); +#else +int _TLIBC_CDECL_ posix_memalign(void **, size_t, size_t) throw (); +#endif +void * _TLIBC_CDECL_ aligned_alloc(size_t, size_t); void _TLIBC_CDECL_ qsort(void *, size_t, size_t, int (*)(const void *, const void *)); void * _TLIBC_CDECL_ realloc(void *, size_t); double _TLIBC_CDECL_ strtod(const char *, char **); diff --git a/docker/build/Dockerfile b/docker/build/Dockerfile index 79bac5bc..0e363f46 100644 --- a/docker/build/Dockerfile +++ b/docker/build/Dockerfile @@ -64,14 +64,14 @@ RUN make psw_install_pkg RUN make deb_local_repo -FROM ubuntu:18.04 as aesm +FROM ubuntu:18.04 as aesm RUN apt-get update && apt-get install -y \ libcurl4 \ libprotobuf10 \ libssl1.1 \ make \ module-init-tools - + WORKDIR /installer COPY --from=builder /linux-sgx/linux/installer/bin/*.bin ./ RUN ./sgx_linux_x64_psw*.bin --no-start-aesm @@ -149,4 +149,3 @@ RUN adduser -q --disabled-password --gecos "" --no-create-home sgxuser USER sgxuser CMD ./app - diff --git a/docker/build/README.md b/docker/build/README.md index 74d071b4..4875215d 100644 --- a/docker/build/README.md +++ b/docker/build/README.md @@ -60,3 +60,14 @@ The sample scripts and Compose files are compatible with the Flexible Launch Con **Note**: When you switch between drivers, make sure you uninstall the previous driver and reboot the system before installing the other one. **Note**: Earlier versions of the Flexible Launch Control driver and kernel patches may expose the SGX device as a single node at "/dev/sgx". + +## Experimental: Build and run TDX QGS in docker container +### Prerequisites +Besides the [Prerequisites](#prerequisites), you need to have docker version >= 20.04 to support host-gateway used in build_and_run_qgs_docker.sh. And Legacy Launch Control driver is not supported. + +### Run with Docker directly +This will start QGS on one terminal directly. +``` +$ ./build_and_run_qgs_docker.sh +``` +It will listen on docker volume /var/lib/docker/volumes/qgs-socket. In order to connect to QGS in this configuration, you need to run QEMU with `quote-generation-service=unix:/var/lib/docker/volumes/qgs-socket/_data/qgs.socket` option and use TDVMCall mode(which is the default mode if you installed with rpm/deb package) to get quote within TD guest. diff --git a/docker/build/build_and_run_aesm_deb_docker.sh b/docker/build/build_and_run_qgs_docker.sh similarity index 79% rename from docker/build/build_and_run_aesm_deb_docker.sh rename to docker/build/build_and_run_qgs_docker.sh index 2574adce..7acb3659 100755 --- a/docker/build/build_and_run_aesm_deb_docker.sh +++ b/docker/build/build_and_run_qgs_docker.sh @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright (C) 2022 Intel Corporation. All rights reserved. +# Copyright (C) 2020 Intel Corporation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions @@ -30,12 +30,12 @@ # set -e -docker build --target aesm_deb --build-arg https_proxy=$https_proxy \ - --build-arg http_proxy=$http_proxy -t sgx_aesm_deb -f ./Dockerfile ../../ +docker build --target qgs --build-arg https_proxy=$https_proxy \ + --build-arg http_proxy=$http_proxy -t tdx_qgs -f ./tdx-qgs.dockerfile ../../ -docker volume create --driver local --opt type=tmpfs --opt device=tmpfs --opt o=rw aesmd-socket +docker volume create --driver local --opt type=tmpfs --opt device=tmpfs --opt o=rw qgs-socket # If you use the Legacy Launch Control driver, replace /dev/sgx/enclave with /dev/isgx, and remove # --device=/dev/sgx/provision -docker run --env http_proxy --env https_proxy --device=/dev/sgx/enclave --device=/dev/sgx/provision -v /dev/log:/dev/log -v aesmd-socket:/var/run/aesmd -it sgx_aesm_deb +docker run --device=/dev/sgx/enclave --device=/dev/sgx/provision -v /dev/log:/dev/log -v qgs-socket:/var/run/tdx-qgs/ -it --add-host=host.docker.internal:host-gateway tdx_qgs /opt/intel/tdx-qgs/qgs --no-daemon diff --git a/docker/build/tdx-qgs.dockerfile b/docker/build/tdx-qgs.dockerfile new file mode 100644 index 00000000..35a57be2 --- /dev/null +++ b/docker/build/tdx-qgs.dockerfile @@ -0,0 +1,67 @@ +# Copyright (C) 2020 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + + +FROM quay.io/centos/centos:stream8 as qgs-builder + +RUN dnf -y groupinstall 'Development Tools' +RUN dnf -y install --enablerepo=powertools ocaml ocaml-ocamlbuild wget python2 \ + openssl-devel libcurl-devel protobuf-devel cmake createrepo yum-utils \ + dos2unix pkgconf boost-devel protobuf-c-compiler protobuf-c-devel \ + protobuf-lite-devel + +# We assume this docker file is invoked with root at the top of linux-sgx repo, see shell scripts for example. +WORKDIR /linux-sgx +COPY . . +RUN alternatives --set python /usr/bin/python2 +RUN make sdk_install_pkg_no_mitigation + +WORKDIR /opt/intel +RUN sh -c 'echo yes | /linux-sgx/linux/installer/bin/sgx_linux_x64_sdk_*.bin' + +WORKDIR /linux-sgx +RUN make rpm_local_repo + + +FROM quay.io/centos/centos:stream8 as qgs + +WORKDIR /installer + +COPY --from=qgs-builder /linux-sgx/linux/installer/rpm/sgx_rpm_local_repo/ . +RUN dnf config-manager --add-repo file:///installer +RUN dnf -y install --setopt=install_weak_deps=False --nogpgcheck tdx-qgs \ + libsgx-dcap-default-qpl +RUN mkdir -p /var/run/tdx-qgs/ +RUN sed -i "s/localhost:8081/host.docker.internal:8081/" /etc/sgx_default_qcnl.conf && \ + sed -i 's/"use_secure_cert": true/"use_secure_cert": false/' /etc/sgx_default_qcnl.conf && \ + sed -i "s/port = 4050//" /etc/qgs.conf + + +WORKDIR /opt/intel/tdx-qgs +CMD ./qgs --no-daemon diff --git a/download_prebuilt.sh b/download_prebuilt.sh index 677d47d3..a1b36b8b 100755 --- a/download_prebuilt.sh +++ b/download_prebuilt.sh @@ -33,11 +33,11 @@ top_dir=`dirname $0` out_dir=$top_dir -optlib_name=optimized_libs_2.17.tar.gz -ae_file_name=prebuilt_ae_2.17.tar.gz +optlib_name=optimized_libs_2.18.tar.gz +ae_file_name=prebuilt_ae_2.18.tar.gz binutils_file_name=as.ld.objdump.r4.tar.gz -checksum_file=SHA256SUM_prebuilt_2.17.cfg -server_url_path=https://download.01.org/intel-sgx/sgx-linux/2.17 +checksum_file=SHA256SUM_prebuilt_2.18.cfg +server_url_path=https://download.01.org/intel-sgx/sgx-linux/2.18 server_optlib_url=$server_url_path/$optlib_name server_ae_url=$server_url_path/$ae_file_name server_binutils_url=$server_url_path/$binutils_file_name diff --git a/external/dcap_source b/external/dcap_source index 68a77a85..85cf8bdd 160000 --- a/external/dcap_source +++ b/external/dcap_source @@ -1 +1 @@ -Subproject commit 68a77a852cd911a44a97733aec870e9bd93a3b86 +Subproject commit 85cf8bdd393ab273a308be3f41d2f7cc25c0ec0c diff --git a/external/dnnl/Makefile b/external/dnnl/Makefile index dc0e4040..1b385b52 100644 --- a/external/dnnl/Makefile +++ b/external/dnnl/Makefile @@ -89,7 +89,7 @@ else endif $(LIBDNNL):$(CHECK_SOURCE) - mkdir -p $(DNNL_DIR)/build && cd $(DNNL_DIR)/build && cmake -DCMAKE_CXX_ENCLAVE_FLAGS="$(CXX_ENCLAVE_FLAGS)" -DCMAKE_C_ENCLAVE_FLAGS="$(C_ENCLAVE_FLAGS)" $(DNNL_CONFIG) .. && make + mkdir -p $(DNNL_DIR)/build && cd $(DNNL_DIR)/build && cmake -DCMAKE_CXX_ENCLAVE_FLAGS="$(CXX_ENCLAVE_FLAGS)" -DCMAKE_C_ENCLAVE_FLAGS="$(C_ENCLAVE_FLAGS)" $(DNNL_CONFIG) .. && $(MAKE) .PHONY: clean clean: diff --git a/external/openmp/Makefile b/external/openmp/Makefile index 0d63fd8f..1c789daa 100644 --- a/external/openmp/Makefile +++ b/external/openmp/Makefile @@ -69,7 +69,7 @@ $(LIBOMP): $(CHECK_SOURCE) ifeq ("$(wildcard $(OMP_DIR)/final/runtime/src/sgx_stub.h)", "") cd openmp_code && git apply ../0001-Enable-OpenMP-in-SGX.patch && cd .. endif - $(MKDIR) openmp_code/final/build && cd openmp_code/final/build && cmake $(OMP_CONFIG) .. && make + $(MKDIR) openmp_code/final/build && cd openmp_code/final/build && cmake $(OMP_CONFIG) .. && $(MAKE) .PHONY: clean diff --git a/external/protobuf/Makefile b/external/protobuf/Makefile index b556b279..def52204 100644 --- a/external/protobuf/Makefile +++ b/external/protobuf/Makefile @@ -70,7 +70,7 @@ ifeq ($(shell git rev-parse --is-inside-work-tree), true) git submodule update -f --init $(PB_DIR) else $(RM) -r $(PB_DIR)/ - git clone https://github.com/protocolbuffers/protobuf.git -b 3.20.x --depth 1 $(PB_DIR) + git clone https://github.com/protocolbuffers/protobuf.git -b v3.20.1 --depth 1 $(PB_DIR) endif diff --git a/external/protobuf/protobuf_code b/external/protobuf/protobuf_code index 26d11fdb..21027a27 160000 --- a/external/protobuf/protobuf_code +++ b/external/protobuf/protobuf_code @@ -1 +1 @@ -Subproject commit 26d11fdba2fb6435ee4bef8a20fa011574397225 +Subproject commit 21027a27c4c2ec1000859ccbcfff46d83b16e1ed diff --git a/external/sgx-emm/Makefile b/external/sgx-emm/Makefile new file mode 100644 index 00000000..7ff92904 --- /dev/null +++ b/external/sgx-emm/Makefile @@ -0,0 +1,78 @@ +# Copyright (C) 2011-2022 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +include ../../buildenv.mk + +EMM_DIR = emm_src + +CPPFLAGS += -I$(EMM_DIR)/include \ + -I$(COMMON_DIR)/inc/tlibc \ + -Wno-missing-braces \ + -Wno-unused-parameter + +C_Files := $(EMM_DIR)/bit_array.c \ + $(EMM_DIR)/ema.c \ + $(EMM_DIR)/emalloc.c \ + $(EMM_DIR)/emm_private.c \ + $(EMM_DIR)/sgx_mm.c + +OBJS := $(C_Files:.c=.o) +OBJS := $(sort $(OBJS)) + +LIB_NAME := libsgx_mm.a + +CHECK_SOURCE := +ifeq ("$(wildcard $(EMM_DIR)/sgx_mm.c)", "") +CHECK_SOURCE := emm_code +endif + +.PHONY: all clean emm_code + +all: $(LIB_NAME) | $(BUILD_DIR) + $(CP) $(LIB_NAME) $| + +$(LIB_NAME): $(CHECK_SOURCE) $(OBJS) + $(AR) rcs $@ $(OBJS) + +$(OBJS): %.o: %.c + $(CC) -c $(COMMON_FLAGS) $(ENCLAVE_CFLAGS) $(CPPFLAGS) $< -o $@ + +$(BUILD_DIR): + @$(MKDIR) $@ + +emm_code: +ifeq ($(shell git rev-parse --is-inside-work-tree 2> /dev/null), true) + git submodule update -f --init --recursive -- $(EMM_DIR) +else + $(RM) -rf $(EMM_DIR) + git clone -b sgx-emm-1.0.0 https://github.com/intel/sgx-emm.git --depth 1 $(EMM_DIR) +endif + +clean: + @$(RM) $(LIB_NAME) $(OBJS) $(BUILD_DIR)/$(LIB_NAME) *.bak *~ + diff --git a/external/sgx-emm/api_tests/App/App.cpp b/external/sgx-emm/api_tests/App/App.cpp new file mode 100644 index 00000000..8f615e2f --- /dev/null +++ b/external/sgx-emm/api_tests/App/App.cpp @@ -0,0 +1,419 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include +#include +#include + +#include +#include +#include + +# include +# include +# define MAX_PATH FILENAME_MAX + +#include "sgx_urts.h" +#include "App.h" +#include "Enclave_u.h" +#include "../tcs.h" +using namespace std; + +/* Global EID shared by multiple threads */ +sgx_enclave_id_t global_eid = 0; + +typedef struct _sgx_errlist_t { + sgx_status_t err; + const char *msg; + const char *sug; /* Suggestion */ +} sgx_errlist_t; + +/* Error code returned by sgx_create_enclave */ +static sgx_errlist_t sgx_errlist[] = { + { + SGX_ERROR_UNEXPECTED, + "Unexpected error occurred.", + NULL + }, + { + SGX_ERROR_INVALID_PARAMETER, + "Invalid parameter.", + NULL + }, + { + SGX_ERROR_OUT_OF_MEMORY, + "Out of memory.", + NULL + }, + { + SGX_ERROR_ENCLAVE_LOST, + "Power transition occurred.", + "Please refer to the sample \"PowerTransition\" for details." + }, + { + SGX_ERROR_INVALID_ENCLAVE, + "Invalid enclave image.", + NULL + }, + { + SGX_ERROR_INVALID_ENCLAVE_ID, + "Invalid enclave identification.", + NULL + }, + { + SGX_ERROR_INVALID_SIGNATURE, + "Invalid enclave signature.", + NULL + }, + { + SGX_ERROR_OUT_OF_EPC, + "Out of EPC memory.", + NULL + }, + { + SGX_ERROR_NO_DEVICE, + "Invalid SGX device.", + "Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards." + }, + { + SGX_ERROR_MEMORY_MAP_CONFLICT, + "Memory map conflicted.", + NULL + }, + { + SGX_ERROR_INVALID_METADATA, + "Invalid enclave metadata.", + NULL + }, + { + SGX_ERROR_DEVICE_BUSY, + "SGX device was busy.", + NULL + }, + { + SGX_ERROR_INVALID_VERSION, + "Enclave version was invalid.", + NULL + }, + { + SGX_ERROR_INVALID_ATTRIBUTE, + "Enclave was not authorized.", + NULL + }, + { + SGX_ERROR_ENCLAVE_FILE_ACCESS, + "Can't open enclave file.", + NULL + }, +}; + +/* Check error conditions for loading enclave */ +void print_error_message(sgx_status_t ret) +{ + size_t idx = 0; + size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0]; + + for (idx = 0; idx < ttl; idx++) { + if(ret == sgx_errlist[idx].err) { + if(NULL != sgx_errlist[idx].sug) + printf("Info: %s\n", sgx_errlist[idx].sug); + printf("Error: %s\n", sgx_errlist[idx].msg); + break; + } + } + + if (idx == ttl) + printf("Error code is 0x%X. Please refer to the \"Intel SGX SDK Developer Reference\" for more details.\n", ret); +} + +/* Initialize the enclave: + * Call sgx_create_enclave to initialize an enclave instance + */ +int initialize_enclave(void) +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + + /* Call sgx_create_enclave to initialize an enclave instance */ + /* Debug Support: set 2nd parameter to 1 */ + ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, NULL, NULL, &global_eid, NULL); + if (ret != SGX_SUCCESS) { + print_error_message(ret); + return -1; + } + + return 0; +} + +/* OCall functions */ +void ocall_print_string(const char *str) +{ + /* Proxy/Bridge will check the length and null-terminate + * the input string to prevent buffer overflow. + */ + printf("%s", str); +} + +int test_tcs(); + +static atomic counter_failures; + +#include //rand +void driver(int sid) +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + int retval = 0; + do{ + usleep(rand()%11); + ret = ecall_test_sgx_mm(global_eid, &retval, sid); + if (ret == SGX_SUCCESS){ + printf("test_sgx_mm returned %d\n", retval); + counter_failures += retval; + }else if (ret == SGX_ERROR_OUT_OF_TCS){ + printf("!!! enclave out of TCS, retrying...\n"); + continue; + }else + { + abort(); + } + //test_tcs does its own retry + counter_failures += test_tcs(); + return; + }while(true); +} + + +int test_unsafe() +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + int retval = 0; + ret = ecall_test_sgx_mm_unsafe(global_eid, &retval); + if (ret == SGX_SUCCESS){ + if(retval) + printf("!!! test_sgx_mm_unsafe returned %d\n", retval); + else + printf("*** unsafe tests passed\n"); + return retval; + }else + abort(); +} + + +typedef struct ms_ecall_check_context_t { + int ms_retval; + size_t ms_tcs; +} ms_ecall_check_context_t; + +extern "C" { +#include "isgx_user.h" +} +vdso_sgx_enter_enclave_t vdso_sgx_enter_enclave; + +#define EENTER 2 + +int ecall_check_context_manual(int* retval, size_t tcs) +{ + ms_ecall_check_context_t ms; + ms.ms_tcs = tcs; + ms.ms_retval= -1; + struct sgx_enclave_run run; + memset(&run, 0, sizeof(run)); + run.tcs = (__u64)tcs; +/******** + !NOTE: hardcoded ecall number. Needs update if edl changes +*******/ + int ret = vdso_sgx_enter_enclave((unsigned long)3, (unsigned long)(&ms), 0, EENTER, + 0, 0, &run); + if (ret == 0) *retval = ms.ms_retval; + return ret; +} +#include +#include +void* get_vdso_sym(const char* vdso_func_name) +{ + char* dynstr = 0; + void *ret = NULL; + + uint8_t* vdso_addr = (uint8_t*)getauxval(AT_SYSINFO_EHDR); + Elf64_Ehdr* elf_header = (Elf64_Ehdr*)vdso_addr; + Elf64_Shdr* section_header = (Elf64_Shdr*)(vdso_addr + elf_header->e_shoff); + + for (int i = 0; i < elf_header->e_shnum; i++) { + auto& s = section_header[i]; + auto& ss_ = section_header[elf_header->e_shstrndx]; + auto name = (char*)(vdso_addr + ss_.sh_offset + s.sh_name); + if (strcmp(name, ".dynstr") == 0) { + dynstr = (char*)(vdso_addr + s.sh_offset); + break; + } + } + + for (int i = 0; i < elf_header->e_shnum; i++) { + auto& s = section_header[i]; + auto& ss_ = section_header[elf_header->e_shstrndx]; + auto name = (char*)(vdso_addr + ss_.sh_offset + s.sh_name); + if (strcmp(name, ".dynsym") == 0) { + for (unsigned int si = 0; si < (s.sh_size/s.sh_entsize); si++) { + auto &sym = ((Elf64_Sym*)(vdso_addr + s.sh_offset))[si]; + auto vdname = dynstr + sym.st_name; + if (strcmp(vdname, vdso_func_name) == 0) { + ret = (vdso_addr + sym.st_value); + break; + } + } + if (ret) break; + } + } + return ret; +} + +#define fastcall __attribute__((regparm(3),noinline,visibility("default"))) +//this function is used to notify GDB scripts +//GDB is supposed to have a breakpoint on urts_add_tcs to receive debug interupt +//once the breakpoint has been hit, GDB extracts the address of tcs and sets DBGOPTIN for the tcs +extern "C" void fastcall urts_add_tcs(tcs_t * const tcs) +{ + (void)(tcs); +} + +int test_tcs() +{ + if(vdso_sgx_enter_enclave == NULL) + return 0; //skip this test + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + size_t tcs = 0; + + do { + usleep(rand()%11); + ret = ecall_alloc_context(global_eid, &tcs); + if (ret == SGX_SUCCESS){ + if (tcs > 1) { + printf("*** test_alloc_context returned 0X%LX\n", tcs); + break; + } else { + printf("!!! alloc context failed\n"); + return 1; + } + }else if (ret == SGX_ERROR_OUT_OF_TCS){ + continue; + }else + abort(); + } while (true); + + urts_add_tcs((tcs_t*)tcs);//turn on sgx-gdb + int retval = 0; + int r = ecall_check_context_manual(&retval, tcs); + + if (r == 0){ + if (retval) { + printf("!!! check tcs returned %d\n", retval); + return 1; + } + else + printf("*** check tcs passed\n"); + }else + abort(); + + do { + usleep(rand()%11); + ret = ecall_dealloc_context(global_eid, &retval, tcs); + if (ret == SGX_SUCCESS) { + if(retval) { + printf("!!! test_deaalloc_context returned %d\n", retval); + return 1; + } + else{ + printf("*** dealloc context pass\n"); + return 0; + } + } else if (ret == SGX_ERROR_OUT_OF_TCS){ + continue; + }else + abort(); + } while (true); + return 0; +} + +/* ecall_thread_functions: + * Invokes thread functions including mutex, condition variable, etc. + */ +int test_sgx_mm_functions(int num_threads) +{ + vector threads; + for (int i=0; i< num_threads; i++) + threads.push_back(new thread(driver, i)); + + for (int i=0; i< num_threads; i++) + { + threads[i]->join(); + delete threads[i]; + } + + if(counter_failures) + { + printf("!!! Fail in %d threads\n", static_cast(counter_failures)); + }else + printf("*** All threads ran successfully.\n"); + return counter_failures; +} + + + +/* Application entry */ +int SGX_CDECL main(int argc, char *argv[]) +{ + (void)(argc); + (void)(argv); + + + vdso_sgx_enter_enclave = (vdso_sgx_enter_enclave_t)get_vdso_sym("__vdso_sgx_enter_enclave"); + /* Initialize the enclave */ + if(initialize_enclave() < 0){ + printf("Failed initialize enclave.\n"); + return -1; + } + //srand (time(NULL)); + srand ((3141596/1618)*271828); + int ret = 0; + + //50 threads for 100 iterations passed when this is checked in + ret += test_sgx_mm_functions(50); + ret += test_unsafe(); + + sgx_destroy_enclave(global_eid); + if (!ret) + printf("*** All tests pass.\n"); + else + printf("!!! %d test(s) failed.\n", ret); + + return ret; +} + diff --git a/external/sgx-emm/api_tests/App/App.h b/external/sgx-emm/api_tests/App/App.h new file mode 100644 index 00000000..485b4751 --- /dev/null +++ b/external/sgx-emm/api_tests/App/App.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#ifndef _APP_H_ +#define _APP_H_ + +#include +#include +#include +#include + +#include "sgx_error.h" /* sgx_status_t */ +#include "sgx_eid.h" /* sgx_enclave_id_t */ + +#ifndef TRUE +# define TRUE 1 +#endif + +#ifndef FALSE +# define FALSE 0 +#endif + +# define TOKEN_FILENAME "enclave.token" +# define ENCLAVE_FILENAME "enclave.signed.so" + +extern sgx_enclave_id_t global_eid; /* global enclave id */ + +#endif /* !_APP_H_ */ diff --git a/external/sgx-emm/api_tests/Enclave/Enclave.cpp b/external/sgx-emm/api_tests/Enclave/Enclave.cpp new file mode 100644 index 00000000..44c82dc7 --- /dev/null +++ b/external/sgx-emm/api_tests/Enclave/Enclave.cpp @@ -0,0 +1,925 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "Enclave.h" +#include "Enclave_t.h" /* print_string */ +#include +#include /* vsnprintf */ +#include +#include +#include "../../emm_src/include/sgx_mm.h" +#define SGX_PAGE_SIZE 4096 +#include "sgx_thread.h" +#include +#include "sgx_trts.h" +#include "../tcs.h" +using namespace std; +/* + * printf: + * Invokes OCALL to display the enclave buffer to the terminal. + */ +int printf(const char* fmt, ...) +{ + char buf[4096*2] = { '\0' }; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, BUFSIZ, fmt, ap); + va_end(ap); + ocall_print_string(buf); + return (int)strnlen(buf, BUFSIZ - 1) + 1; +} + +#define LOG(fmt, ...) do { \ + printf("[%s %s:%d] " fmt, __FUNCTION__, __FILE__, __LINE__, ##__VA_ARGS__); \ +}while(0) + + +#define EXPECT_EQ(a, b) \ + do { \ + if ((a) != (b)){ \ + LOG( #a " expected:" #b " got: %lu\n", (uint64_t)(a)); \ + return 1; \ + }\ + } while(0); + +#define EXPECT_NEQ(a, b) \ + do { \ + if ((a) == (b)) {\ + LOG( #a " not expected: " #b "\n" ); \ + return 1; \ + }\ + } while(0); + +const size_t ALLOC_SIZE = 0x2000; +vector allocated_blocks; +sgx_thread_mutex_t mutex = SGX_THREAD_MUTEX_INITIALIZER; + +int test_sgx_mm_alloc_dealloc() +{ + int ret = sgx_mm_dealloc(0, ALLOC_SIZE); + EXPECT_EQ(ret, EINVAL); + // we should be able to alloc, commit, uncommit + // in multiple threads without interference + void* addr = 0; + ret = sgx_mm_alloc(NULL, ALLOC_SIZE, + SGX_EMA_COMMIT_NOW, NULL, NULL, &addr); + + EXPECT_EQ(ret, 0); + EXPECT_NEQ(addr, NULL); + ret = sgx_mm_dealloc(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + return 0; +} + +int test_sgx_mm_alloc_commit_uncommit() +{ + int ret = sgx_mm_dealloc(0, ALLOC_SIZE); + EXPECT_EQ(ret, EINVAL); + // we should be able to alloc, commit, uncommit + // in multiple threads without interference + void* addr = 0; + ret = sgx_mm_alloc(NULL, ALLOC_SIZE, + SGX_EMA_COMMIT_NOW, NULL, NULL, &addr); + + EXPECT_EQ(ret, 0); + EXPECT_NEQ(addr, NULL); + + ret = sgx_mm_commit(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + void* addr1 = NULL; + ret = sgx_mm_alloc(addr, ALLOC_SIZE, + SGX_EMA_COMMIT_NOW | SGX_EMA_FIXED, NULL, NULL, &addr1); + + EXPECT_EQ(ret, EEXIST); + EXPECT_EQ(addr1, NULL); + ret = sgx_mm_uncommit(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + ret = sgx_mm_uncommit(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); //we do nothing if it's already uncommitted + + ret = sgx_mm_commit(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + //no longer use these areas, ready to be + // released by any thread + sgx_thread_mutex_lock(&mutex); + allocated_blocks.push_back(addr); + sgx_thread_mutex_unlock(&mutex); + return 0; +} + +int test_sgx_mm_types() +{ + int ret = sgx_mm_dealloc(0, ALLOC_SIZE); + EXPECT_EQ(ret, EINVAL); + void* addr = 0; + ret = sgx_mm_alloc(NULL, ALLOC_SIZE, + SGX_EMA_COMMIT_NOW, NULL, NULL, &addr); + EXPECT_EQ(ret, 0); + EXPECT_NEQ(addr, NULL); + ret = sgx_mm_modify_type(addr + SGX_PAGE_SIZE, SGX_PAGE_SIZE, + SGX_EMA_PAGE_TYPE_SS_FIRST); + EXPECT_EQ(ret, EPERM); + + ret = sgx_mm_modify_permissions(addr + SGX_PAGE_SIZE, SGX_PAGE_SIZE, + SGX_EMA_PROT_READ_EXEC); + EXPECT_EQ(ret, 0); + + ret = sgx_mm_modify_type(addr + SGX_PAGE_SIZE, SGX_PAGE_SIZE, + SGX_EMA_PAGE_TYPE_TCS); + EXPECT_EQ(ret, EACCES); + + ret = sgx_mm_modify_type(addr, SGX_PAGE_SIZE, SGX_EMA_PAGE_TYPE_TCS); + EXPECT_EQ(ret, 0); + + ret = sgx_mm_uncommit(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + ret = sgx_mm_modify_type(addr, SGX_PAGE_SIZE, SGX_EMA_PAGE_TYPE_TCS); + EXPECT_EQ(ret, EACCES); + + ret = sgx_mm_dealloc(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + return 0; +} + +/* + * Only release areas previously stored + * by other threads as ready to be released + */ +int test_sgx_mm_dealloc() +{ + int res = 0; + sgx_thread_mutex_lock(&mutex); + auto it = allocated_blocks.begin(); + while ( it!=allocated_blocks.end()){ + int ret = sgx_mm_dealloc(*it, ALLOC_SIZE); + if(ret){ + res ++; + LOG("!!! failed dealloc, errno = %d\n", ret); + it++; + }else + it = allocated_blocks.erase(it); + } + sgx_thread_mutex_unlock(&mutex); + return res; +} + +int test_sgx_mm_alloc_dealloc_unsafe1() +{ +// allocation, deallocation + int ret = sgx_mm_dealloc(0, ALLOC_SIZE); + EXPECT_EQ(ret, EINVAL); + + void* addr = 0; + ret = sgx_mm_alloc(NULL, ALLOC_SIZE, + SGX_EMA_COMMIT_NOW, NULL, NULL, &addr); + + EXPECT_EQ(ret, 0); + EXPECT_NEQ(addr, NULL); + + ret = sgx_mm_commit(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + void* addr1 = NULL; + ret = sgx_mm_alloc(addr, ALLOC_SIZE, + SGX_EMA_COMMIT_NOW|SGX_EMA_FIXED, NULL, NULL, &addr1); + + EXPECT_EQ(ret, EEXIST); + EXPECT_EQ(addr1, NULL); + + ret = sgx_mm_uncommit(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + ret = sgx_mm_uncommit(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); //we do nothing if it's already uncommitted + + ret = sgx_mm_commit(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + ret = sgx_mm_dealloc(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + ret = sgx_mm_dealloc(addr, ALLOC_SIZE); + EXPECT_EQ(ret, EINVAL); + + ret = sgx_mm_uncommit(addr, ALLOC_SIZE); + EXPECT_EQ(ret, EINVAL); // error if it's already deallocated + + void* addr2 = NULL; + ret = sgx_mm_alloc(addr, ALLOC_SIZE, + SGX_EMA_COMMIT_ON_DEMAND|SGX_EMA_FIXED, NULL, NULL, &addr2); + + EXPECT_EQ(ret, 0); + EXPECT_EQ(addr2, addr);//mm should realloc to the given addr + + ret = sgx_mm_dealloc(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + ret = sgx_mm_alloc(addr, ALLOC_SIZE, + SGX_EMA_COMMIT_ON_DEMAND|SGX_EMA_FIXED, NULL, NULL, &addr2); + + EXPECT_EQ(ret, 0); + EXPECT_EQ(addr, addr2); + + ret = sgx_mm_alloc(addr, ALLOC_SIZE, + SGX_EMA_COMMIT_ON_DEMAND, NULL, NULL, &addr2); + + EXPECT_EQ(ret, 0); + EXPECT_NEQ(addr, addr2); + + uint8_t *data= (uint8_t*)addr2; + data[0]=0xFF; + data[ALLOC_SIZE-1]=0xFF; + + ret = sgx_mm_dealloc(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + ret = sgx_mm_dealloc(addr2, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + + return 0; +} + +#include +typedef struct _pfdata +{ + sgx_pfinfo pf; + union { + int access; // access that triggers PF, R/W/X + int magic; + }; + void* addr_expected; + jmp_buf jbuf; // used for jmp_handler only +} pf_data_t; + +int jmp_handler(const sgx_pfinfo *pfinfo, void *private_data) +{ + pf_data_t* pd = (pf_data_t *) private_data; + memcpy(private_data, pfinfo, sizeof(*pfinfo)); + void* addr = (void*) pd->pf.maddr; + if (pd->pf.pfec.rw == 0 + && addr == pd->addr_expected) + { + int ret = sgx_mm_commit(addr, SGX_PAGE_SIZE); + if (ret) abort(); + memset(addr, pd->magic, SGX_PAGE_SIZE); + longjmp(pd->jbuf, 1); + abort(); //won't reach here + } + return SGX_MM_EXCEPTION_CONTINUE_SEARCH; +} + +int test_sgx_mm_alloc_jmp() +{ + + void* addr = 0; + pf_data_t pd; + memset((void*) &pd, 0, sizeof(pd)); + int ret = sgx_mm_alloc(NULL, ALLOC_SIZE, + SGX_EMA_COMMIT_ON_DEMAND, &jmp_handler, &pd, &addr); + + EXPECT_EQ(ret, 0); + EXPECT_NEQ(addr, NULL); + const int MAGIC = 0x55UL; + + uint8_t* data = (uint8_t*)addr; + pd.magic = MAGIC; + pd.addr_expected = addr; + if (0 == setjmp(pd.jbuf)) { + uint8_t d0 = 0; + d0 = data[0]; + EXPECT_NEQ (d0, 0); //should not come here + }else { + uint8_t d0 = data[0]; + + EXPECT_EQ (d0, MAGIC); + EXPECT_EQ (pd.pf.pfec.rw, 0); //Read caused PF + EXPECT_EQ (pd.pf.pfec.sgx, 1); // sgx bit set + } + + ret = sgx_mm_dealloc(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + return 0; +} + +int permissions_handler(const sgx_pfinfo *pfinfo, void *private_data) +{ + pf_data_t* pd = (pf_data_t *) private_data; + memcpy(private_data, pfinfo, sizeof(*pfinfo)); + void* addr = (void*) pd->pf.maddr; + if(pd->pf.pfec.rw == 1 && pd->access == SGX_EMA_PROT_WRITE){ + sgx_mm_modify_permissions(addr, SGX_PAGE_SIZE, SGX_EMA_PROT_WRITE | SGX_EMA_PROT_READ); + }else if (pd->pf.pfec.rw == 0 && (pd->access & SGX_EMA_PROT_READ )){//R or RX + sgx_mm_modify_permissions(addr, SGX_PAGE_SIZE, pd->access); + }else + abort(); + return SGX_MM_EXCEPTION_CONTINUE_EXECUTION; +} + +int commit_data_handler(const sgx_pfinfo *pfinfo, void *private_data) +{ + pf_data_t* pd = (pf_data_t *) private_data; + memcpy(private_data, pfinfo, sizeof(*pfinfo)); + void* addr = (void*) pd->pf.maddr; + + if (pd->access == SGX_EMA_PROT_WRITE + && pd->pf.pfec.rw == 1 + && addr == pd->addr_expected) + { + int ret = sgx_mm_modify_permissions(addr, SGX_PAGE_SIZE, SGX_EMA_PROT_WRITE | SGX_EMA_PROT_READ); + if(ret) abort(); + return SGX_MM_EXCEPTION_CONTINUE_EXECUTION; + } + + if (addr == pd->addr_expected) + { + void* data = 0; + int ret = sgx_mm_alloc(NULL, SGX_PAGE_SIZE, SGX_EMA_COMMIT_NOW, + NULL, NULL, &data); + if(ret) abort(); + assert(data!=0); + memset(data, pd->magic, SGX_PAGE_SIZE); + ret = sgx_mm_commit_data(addr, SGX_PAGE_SIZE, (uint8_t*)data, + SGX_EMA_PROT_READ); + if(ret) abort(); + ret = sgx_mm_dealloc((void*)data, SGX_PAGE_SIZE); + if(ret) abort(); + return SGX_MM_EXCEPTION_CONTINUE_EXECUTION; + }else + return SGX_MM_EXCEPTION_CONTINUE_SEARCH; +} + +static const int MAX_NESTED_HANDLER = 10; +int nested_handler(const sgx_pfinfo *pfinfo, void *private_data) +{ + pf_data_t* orig_pd = (pf_data_t *) private_data; + memcpy(private_data, pfinfo, sizeof(*pfinfo)); + void* addr = (void*) orig_pd->pf.maddr; + + if (addr == orig_pd->addr_expected) + { + void* data = 0; + if (orig_pd->magic == MAX_NESTED_HANDLER) + { + int ret = sgx_mm_alloc(NULL, SGX_PAGE_SIZE, SGX_EMA_COMMIT_NOW, + NULL, NULL, &data); + if (ret) abort(); + assert(data!=0); + memset(data, orig_pd->magic, SGX_PAGE_SIZE); + ret = sgx_mm_commit_data(addr, SGX_PAGE_SIZE, (uint8_t*)data, + SGX_EMA_PROT_READ); + if (ret) abort(); + } else + { + pf_data_t nested_pd; + memset((void*) &nested_pd, 0, sizeof(nested_pd)); + int ret = sgx_mm_alloc(NULL, SGX_PAGE_SIZE, + SGX_EMA_COMMIT_ON_DEMAND, + &nested_handler, + &nested_pd, &data); + + if (ret) abort(); + assert(data != 0); + nested_pd.addr_expected = data; + nested_pd.magic = orig_pd->magic + 1; + ret = sgx_mm_commit_data(addr, SGX_PAGE_SIZE, (uint8_t*)data, + SGX_EMA_PROT_READ); + if (ret) abort(); + if (nested_pd.pf.pfec.errcd == 0) abort(); //READ suceess with PF + if (nested_pd.pf.pfec.rw != 0) abort(); //READ indicated in PFEC + } + int ret = sgx_mm_dealloc((void*)data, SGX_PAGE_SIZE); + if (ret) abort(); + return SGX_MM_EXCEPTION_CONTINUE_EXECUTION; + }else + return SGX_MM_EXCEPTION_CONTINUE_SEARCH; +} + +int test_sgx_mm_permissions() +{ + + void* addr = 0; + pf_data_t pd; + memset((void*) &pd, 0, sizeof(pd)); + int ret = sgx_mm_alloc(NULL, ALLOC_SIZE, + SGX_EMA_COMMIT_NOW, &permissions_handler, &pd, &addr); + + EXPECT_EQ(ret, 0); + EXPECT_NEQ(addr, NULL); + + uint8_t* data = (uint8_t*)addr; + uint8_t d0 = data[0]; + EXPECT_EQ(d0, 0); + EXPECT_EQ (pd.pf.pfec.errcd, 0); //Read suceess without PF + data[0] = 0xFF; + EXPECT_EQ (pd.pf.pfec.errcd, 0); //WRITE suceess without PF + + // permissions reduction + ret = sgx_mm_modify_permissions(addr, ALLOC_SIZE/2, SGX_EMA_PROT_READ); + EXPECT_EQ(ret, 0); + + pd.access = SGX_EMA_PROT_READ; + d0 = data[0]; + EXPECT_EQ(d0, 0xFF); + EXPECT_EQ (pd.pf.pfec.errcd, 0); //Read suceess without PF + + pd.access = SGX_EMA_PROT_WRITE; + data[ALLOC_SIZE-1] = 0xFF; + EXPECT_EQ (pd.pf.pfec.errcd, 0); //WRITE suceess without PF + + pd.access = SGX_EMA_PROT_WRITE; + data[0] = 0xFF; + EXPECT_NEQ (pd.pf.pfec.errcd, 0); //WRITE suceess with PF + EXPECT_EQ (pd.pf.pfec.rw, 1); //WRITE indicated in PFEC + + // permissions reduction + ret = sgx_mm_modify_permissions(addr + ALLOC_SIZE/2, ALLOC_SIZE/2, SGX_EMA_PROT_NONE); + EXPECT_EQ(ret, 0); + + //no longer used, ready to be released by any thread + //we could dealloc here but to make it more interesting... + sgx_thread_mutex_lock(&mutex); + allocated_blocks.push_back(addr); + sgx_thread_mutex_unlock(&mutex); + + return 0; +} + +int test_sgx_mm_permissions_dealloc() +{ + void* addr = 0; + pf_data_t pd; + memset((void*) &pd, 0, sizeof(pd)); + int ret = sgx_mm_alloc(NULL, ALLOC_SIZE, + SGX_EMA_COMMIT_NOW, &permissions_handler, &pd, &addr); + + EXPECT_EQ(ret, 0); + EXPECT_NEQ(addr, NULL); + + uint8_t* data = (uint8_t*)addr; + uint8_t d0 = data[0]; + EXPECT_EQ(d0, 0); + EXPECT_EQ (pd.pf.pfec.errcd, 0); //Read suceess without PF + data[0] = 0xFF; + EXPECT_EQ (pd.pf.pfec.errcd, 0); //WRITE suceess without PF + + // permissions reduction + ret = sgx_mm_modify_permissions(addr, ALLOC_SIZE/2, SGX_EMA_PROT_READ); + EXPECT_EQ(ret, 0); + + pd.access = SGX_EMA_PROT_READ; + d0 = data[0]; + EXPECT_EQ(d0, 0xFF); + EXPECT_EQ (pd.pf.pfec.errcd, 0); //Read suceess without PF + + pd.access = SGX_EMA_PROT_WRITE; + data[ALLOC_SIZE-1] = 0xFF; + EXPECT_EQ (pd.pf.pfec.errcd, 0); //WRITE suceess without PF + + pd.access = SGX_EMA_PROT_WRITE; + data[0] = 0xFF; + EXPECT_NEQ (pd.pf.pfec.errcd, 0); //WRITE suceess with PF + EXPECT_EQ (pd.pf.pfec.rw, 1); //WRITE indicated in PFEC + + memset((void*) &pd, 0, sizeof(pd)); + pd.access = SGX_EMA_PROT_READ|SGX_EMA_PROT_EXEC; + + + ret = sgx_mm_dealloc(addr, ALLOC_SIZE); + EXPECT_EQ(ret, 0); + EXPECT_EQ (pd.pf.pfec.errcd, 0); // no PF + + return 0; +} + +int test_sgx_mm_commit_data() +{ + void* addr = 0; + const int MAGIC = 0x55UL; + pf_data_t pd; + memset((void*) &pd, 0, sizeof(pd)); + int ret = sgx_mm_alloc(NULL, ALLOC_SIZE, + SGX_EMA_COMMIT_ON_DEMAND, + &commit_data_handler, + &pd, &addr); + + EXPECT_EQ(ret, 0); + EXPECT_NEQ(addr, NULL); + + pd.addr_expected = addr; + pd.magic = MAGIC; + + uint8_t* data = (uint8_t*)addr; + for (int i =0; ioentry = (size_t)(&enclave_entry) - enclave_base; + tcs->cssa = 0; + tcs->nssa = 2; + tcs->ofs_limit = tcs->ogs_limit = (uint32_t)-1; + tcs->ossa = (size_t) ssa - enclave_base; + tcs->ofs_base = (size_t)tls - enclave_base; + tcs->ogs_base = (size_t)tls - enclave_base; + + ret =sgx_mm_modify_type(ptcs, SGX_PAGE_SIZE, SGX_EMA_PAGE_TYPE_TCS); + + EXPECT_EQ(ret, 0); + return (size_t) ptcs; +} + +int ecall_check_context(size_t tcs) +{ + return 0; +} + +int ecall_dealloc_context(size_t tcs) +{ + size_t base = tcs - 37*SGX_PAGE_SIZE; + size_t size = (16 * 3 + 5 + 1 + 2 + 1) * SGX_PAGE_SIZE; + + int ret = sgx_mm_dealloc ((void*)base, size); + + EXPECT_EQ(ret, 0); + + return 0; +} diff --git a/external/sgx-emm/api_tests/Enclave/Enclave.edl b/external/sgx-emm/api_tests/Enclave/Enclave.edl new file mode 100644 index 00000000..be3fc577 --- /dev/null +++ b/external/sgx-emm/api_tests/Enclave/Enclave.edl @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +enclave { + from "sgx_tstdc.edl" import sgx_thread_wait_untrusted_event_ocall, sgx_thread_set_untrusted_event_ocall; + trusted { + public int ecall_test_sgx_mm(int seq_id); + public int ecall_test_sgx_mm_unsafe(void); + public size_t ecall_alloc_context(void); + public int ecall_check_context(size_t tcs); + public int ecall_dealloc_context(size_t tcs); + }; + untrusted { + void ocall_print_string([in, string] const char *str); + }; + +}; diff --git a/sdk/trts/trts_trim.h b/external/sgx-emm/api_tests/Enclave/Enclave.h similarity index 79% rename from sdk/trts/trts_trim.h rename to external/sgx-emm/api_tests/Enclave/Enclave.h index 8adc959f..f6bb82b5 100644 --- a/sdk/trts/trts_trim.h +++ b/external/sgx-emm/api_tests/Enclave/Enclave.h @@ -29,29 +29,20 @@ * */ +#ifndef _ENCLAVE_H_ +#define _ENCLAVE_H_ -#ifndef TRIM_RANGE_T_H__ -#define TRIM_RANGE_T_H__ +#include +#include -#include -#include -#include -#include "sgx_edger8r.h" // for sgx_ocall etc. - - -#include // for size_t - -#define SGX_CAST(type, item) ((type)(item)) - -#ifdef __cplusplus +#if defined(__cplusplus) extern "C" { #endif -sgx_status_t SGXAPI trim_range_ocall(size_t fromaddr, size_t toaddr); -sgx_status_t SGXAPI trim_range_commit_ocall(size_t addr); +int printf(const char* fmt, ...); -#ifdef __cplusplus +#if defined(__cplusplus) } -#endif /* __cplusplus */ - #endif + +#endif /* !_ENCLAVE_H_ */ diff --git a/external/sgx-emm/api_tests/Enclave/Enclave.lds b/external/sgx-emm/api_tests/Enclave/Enclave.lds new file mode 100644 index 00000000..0d5614f5 --- /dev/null +++ b/external/sgx-emm/api_tests/Enclave/Enclave.lds @@ -0,0 +1,11 @@ +enclave.so +{ + global: + g_global_data_sim; + g_global_data; + enclave_entry; + g_peak_heap_used; + g_peak_rsrv_mem_committed; + local: + *; +}; diff --git a/external/sgx-emm/api_tests/Enclave/config.xml b/external/sgx-emm/api_tests/Enclave/config.xml new file mode 100644 index 00000000..5bc33da3 --- /dev/null +++ b/external/sgx-emm/api_tests/Enclave/config.xml @@ -0,0 +1,18 @@ + + 0 + 0 + 248 + 3 + 1 + 248 + + 0x10000 + 0x2000 + 0xF0000000 + 0x9000 + 0x08000 + 0x90000000 + 0 + 1 + 0xFFFFFFFF + diff --git a/external/sgx-emm/api_tests/Makefile b/external/sgx-emm/api_tests/Makefile new file mode 100644 index 00000000..1d192745 --- /dev/null +++ b/external/sgx-emm/api_tests/Makefile @@ -0,0 +1,271 @@ +# +# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# + +######## SGX SDK Settings ######## + +SGX_SDK ?= /opt/intel/sgxsdk +SGX_MODE ?= HW +SGX_ARCH ?= x64 +SGX_DEBUG ?= 1 + +include $(SGX_SDK)/buildenv.mk + +ifeq ($(shell getconf LONG_BIT), 32) + SGX_ARCH := x86 +else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) + SGX_ARCH := x86 +endif + +ifeq ($(SGX_ARCH), x86) + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r +else + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r +endif + +ifeq ($(SGX_DEBUG), 1) +ifeq ($(SGX_PRERELEASE), 1) +$(error Cannot set SGX_DEBUG and SGX_PRERELEASE at the same time!!) +endif +endif + +ifeq ($(SGX_DEBUG), 1) + SGX_COMMON_FLAGS += -O0 -g +else + SGX_COMMON_FLAGS += -O2 +endif + +SGX_COMMON_FLAGS += -Wall -Wextra -Winit-self -Wpointer-arith -Wreturn-type \ + -Waddress -Wsequence-point -Wformat-security \ + -Wmissing-include-dirs -Wfloat-equal -Wundef -Wshadow \ + -Wcast-align -Wcast-qual -Wconversion -Wredundant-decls +SGX_COMMON_CFLAGS := $(SGX_COMMON_FLAGS) -Wjump-misses-init -Wstrict-prototypes -Wunsuffixed-float-constants +SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++11 + +######## App Settings ######## + +ifneq ($(SGX_MODE), HW) + Urts_Library_Name := sgx_urts_sim +else + Urts_Library_Name := sgx_urts +endif + +App_Cpp_Files := App/App.cpp +App_Include_Paths := -IApp -I$(SGX_SDK)/include -I../../../psw/urts/linux + +App_C_Flags := -fPIC -Wno-attributes $(App_Include_Paths) + +# Three configuration modes - Debug, prerelease, release +# Debug - Macro DEBUG enabled. +# Prerelease - Macro NDEBUG and EDEBUG enabled. +# Release - Macro NDEBUG enabled. +ifeq ($(SGX_DEBUG), 1) + App_C_Flags += -DDEBUG -UNDEBUG -UEDEBUG +else ifeq ($(SGX_PRERELEASE), 1) + App_C_Flags += -DNDEBUG -DEDEBUG -UDEBUG +else + App_C_Flags += -DNDEBUG -UEDEBUG -UDEBUG +endif + +App_Cpp_Flags := $(App_C_Flags) +App_Link_Flags := -L$(SGX_LIBRARY_PATH) -l$(Urts_Library_Name) -lpthread + +App_Cpp_Objects := $(App_Cpp_Files:.cpp=.o) + +App_Name := test_mm_api + +######## Enclave Settings ######## + +ifneq ($(SGX_MODE), HW) + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim +else + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice +endif +Crypto_Library_Name := sgx_tcrypto + +Enclave_Cpp_Files := Enclave/Enclave.cpp +Enclave_Include_Paths := -IEnclave -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX_SDK)/include/libcxx + +Enclave_C_Flags := $(Enclave_Include_Paths) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections $(MITIGATION_CFLAGS) +CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") +ifeq ($(CC_BELOW_4_9), 1) + Enclave_C_Flags += -fstack-protector +else + Enclave_C_Flags += -fstack-protector-strong +endif + +Enclave_Cpp_Flags := $(Enclave_C_Flags) -nostdinc++ + +# Enable the security flags +Enclave_Security_Link_Flags := -Wl,-z,relro,-z,now,-z,noexecstack + +# To generate a proper enclave, it is recommended to follow below guideline to link the trusted libraries: +# 1. Link sgx_trts with the `--whole-archive' and `--no-whole-archive' options, +# so that the whole content of trts is included in the enclave. +# 2. For other libraries, you just need to pull the required symbols. +# Use `--start-group' and `--end-group' to link these libraries. +# Do NOT move the libraries linked with `--start-group' and `--end-group' within `--whole-archive' and `--no-whole-archive' options. +# Otherwise, you may get some undesirable errors. +Enclave_Link_Flags := $(MITIGATION_LDFLAGS) $(Enclave_Security_Link_Flags) \ + -Wl,--no-undefined -nostdlib -nodefaultlibs -nostartfiles -L$(SGX_TRUSTED_LIBRARY_PATH) \ + -Wl,--whole-archive -l$(Trts_Library_Name) -Wl,--no-whole-archive \ + -Wl,--start-group -lsgx_tstdc -lsgx_tcxx -l$(Crypto_Library_Name) -l$(Service_Library_Name) -Wl,--end-group \ + -Wl,-Bstatic -Wl,-Bsymbolic -Wl,--no-undefined \ + -Wl,-pie,-eenclave_entry -Wl,--export-dynamic \ + -Wl,--defsym,__ImageBase=0 -Wl,--gc-sections \ + -Wl,--version-script=Enclave/Enclave.lds + +Enclave_Cpp_Objects := $(sort $(Enclave_Cpp_Files:.cpp=.o)) + +Enclave_Name := enclave.so +Signed_Enclave_Name := enclave.signed.so +Enclave_Config_File := Enclave/config.xml +Enclave_Test_Key := Enclave/Enclave_private_test.pem + +ifeq ($(SGX_MODE), HW) +ifeq ($(SGX_DEBUG), 1) + Build_Mode = HW_DEBUG +else ifeq ($(SGX_PRERELEASE), 1) + Build_Mode = HW_PRERELEASE +else + Build_Mode = HW_RELEASE +endif +else +ifeq ($(SGX_DEBUG), 1) + Build_Mode = SIM_DEBUG +else ifeq ($(SGX_PRERELEASE), 1) + Build_Mode = SIM_PRERELEASE +else + Build_Mode = SIM_RELEASE +endif +endif + + +.PHONY: all target run +all: .config_$(Build_Mode)_$(SGX_ARCH) + @$(MAKE) target + +ifeq ($(Build_Mode), HW_RELEASE) +target: $(App_Name) $(Enclave_Name) + @echo "The project has been built in release hardware mode." + @echo "Please sign the $(Enclave_Name) first with your signing key before you run the $(App_Name) to launch and access the enclave." + @echo "To sign the enclave use the command:" + @echo " $(SGX_ENCLAVE_SIGNER) sign -key -enclave $(Enclave_Name) -out <$(Signed_Enclave_Name)> -config $(Enclave_Config_File)" + @echo "You can also sign the enclave using an external signing tool." + @echo "To build the project in simulation mode set SGX_MODE=SIM. To build the project in prerelease mode set SGX_PRERELEASE=1 and SGX_MODE=HW." + + +else +target: $(App_Name) $(Signed_Enclave_Name) +ifeq ($(Build_Mode), HW_DEBUG) + @echo "The project has been built in debug hardware mode." +else ifeq ($(Build_Mode), SIM_DEBUG) + @echo "The project has been built in debug simulation mode." +else ifeq ($(Build_Mode), HW_PRERELEASE) + @echo "The project has been built in pre-release hardware mode." +else ifeq ($(Build_Mode), SIM_PRERELEASE) + @echo "The project has been built in pre-release simulation mode." +else + @echo "The project has been built in release simulation mode." +endif + +endif + +run: all +ifneq ($(Build_Mode), HW_RELEASE) + @$(CURDIR)/$(App_Name) + @echo "RUN => $(App_Name) [$(SGX_MODE)|$(SGX_ARCH), OK]" +endif + +.config_$(Build_Mode)_$(SGX_ARCH): + @rm -f .config_* $(App_Name) $(Enclave_Name) $(Signed_Enclave_Name) $(App_Cpp_Objects) App/Enclave_u.* $(Enclave_Cpp_Objects) Enclave/Enclave_t.* + @touch .config_$(Build_Mode)_$(SGX_ARCH) + +######## App Objects ######## + +App/Enclave_u.h: $(SGX_EDGER8R) Enclave/Enclave.edl + @cd App && $(SGX_EDGER8R) --untrusted ../Enclave/Enclave.edl --search-path ../Enclave --search-path $(SGX_SDK)/include + @echo "GEN => $@" + +App/Enclave_u.c: App/Enclave_u.h + +App/Enclave_u.o: App/Enclave_u.c + @$(CC) $(SGX_COMMON_CFLAGS) $(App_C_Flags) -c $< -o $@ + @echo "CC <= $<" + +App/%.o: App/%.cpp App/Enclave_u.h + @$(CXX) $(SGX_COMMON_CXXFLAGS) $(App_Cpp_Flags) -c $< -o $@ + @echo "CXX <= $<" + +$(App_Name): App/Enclave_u.o $(App_Cpp_Objects) + @$(CXX) $^ -o $@ $(App_Link_Flags) + @echo "LINK => $@" + +######## Enclave Objects ######## + +Enclave/Enclave_t.h: $(SGX_EDGER8R) Enclave/Enclave.edl + @cd Enclave && $(SGX_EDGER8R) --trusted ../Enclave/Enclave.edl --search-path ../Enclave --search-path $(SGX_SDK)/include + @echo "GEN => $@" + +Enclave/Enclave_t.c: Enclave/Enclave_t.h + +Enclave/Enclave_t.o: Enclave/Enclave_t.c + @$(CC) $(SGX_COMMON_CFLAGS) $(Enclave_C_Flags) -c $< -o $@ + @echo "CC <= $<" + +Enclave/%.o: Enclave/%.cpp Enclave/Enclave_t.h + @$(CXX) $(SGX_COMMON_CXXFLAGS) $(Enclave_Cpp_Flags) -c $< -o $@ + @echo "CXX <= $<" + +$(Enclave_Name): Enclave/Enclave_t.o $(Enclave_Cpp_Objects) + @$(CXX) $^ -o $@ $(Enclave_Link_Flags) + @echo "LINK => $@" + +$(Signed_Enclave_Name): $(Enclave_Name) +ifeq ($(wildcard $(Enclave_Test_Key)),) + @echo "There is no enclave test key." + @echo "The project will generate a key for test." + @openssl genrsa -out $(Enclave_Test_Key) -3 3072 +endif + @$(SGX_ENCLAVE_SIGNER) sign -key $(Enclave_Test_Key) -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File) + @echo "SIGN => $@" + +.PHONY: clean + +clean: + @rm -f .config_* $(App_Name) $(Enclave_Name) $(Signed_Enclave_Name) $(App_Cpp_Objects) App/Enclave_u.* $(Enclave_Cpp_Objects) Enclave/Enclave_t.* $(Enclave_Test_Key) diff --git a/external/sgx-emm/api_tests/tcs.h b/external/sgx-emm/api_tests/tcs.h new file mode 100644 index 00000000..a6012e3a --- /dev/null +++ b/external/sgx-emm/api_tests/tcs.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef TCS_H_ +#define TCS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _tcs_t +{ + uint64_t reserved0; /* (0) */ + uint64_t flags; /* (8)bit 0: DBGOPTION */ + uint64_t ossa; /* (16)State Save Area */ + uint32_t cssa; /* (24)Current SSA slot */ + uint32_t nssa; /* (28)Number of SSA slots */ + uint64_t oentry; /* (32)Offset in enclave to which control is transferred on EENTER if enclave INACTIVE state */ + uint64_t reserved1; /* (40) */ + uint64_t ofs_base; /* (48)When added to the base address of the enclave, produces the base address FS segment inside the enclave */ + uint64_t ogs_base; /* (56)When added to the base address of the enclave, produces the base address GS segment inside the enclave */ + uint32_t ofs_limit; /* (64)Size to become the new FS limit in 32-bit mode */ + uint32_t ogs_limit; /* (68)Size to become the new GS limit in 32-bit mode */ +#define TCS_RESERVED_LENGTH 4024 + uint8_t reserved[TCS_RESERVED_LENGTH]; /* (72) */ +}tcs_t; + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/external/sgx-emm/api_tests/test_loop.sh b/external/sgx-emm/api_tests/test_loop.sh new file mode 100755 index 00000000..06904217 --- /dev/null +++ b/external/sgx-emm/api_tests/test_loop.sh @@ -0,0 +1,17 @@ +let fail=0 +for ((i=1;i<=$1;i++));do + time ./test_mm_api + if [ $? -eq 0 ] + then + echo "pass for iteration $i" + else + echo "fail for iteration $i" + let fail=fail+1 + fi +done +if [ $fail -eq 0 ] +then + echo "passed $1 iterations" + else + echo "$fail out of $1 iterations failed" +fi diff --git a/external/sgx-emm/create_symlink.sh b/external/sgx-emm/create_symlink.sh new file mode 100755 index 00000000..8a58ad65 --- /dev/null +++ b/external/sgx-emm/create_symlink.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# +# Copyright (C) 2011-2022 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# + +emm_src=external/sgx-emm/emm_src +common_inc=common/inc +common_internal=common/inc/internal + +ln -sf ../../$emm_src/include/sgx_mm.h $common_inc/sgx_mm.h +ln -sf ../../$emm_src/include/sgx_mm_primitives.h $common_inc/sgx_mm_primitives.h +ln -sf ../../$emm_src/include/sgx_mm_rt_abstraction.h $common_inc/sgx_mm_rt_abstraction.h + +ln -sf ../../../$emm_src/include/bit_array.h $common_internal/bit_array.h +ln -sf ../../../$emm_src/include/bit_array_imp.h $common_internal/bit_array_imp.h +ln -sf ../../../$emm_src/include/ema.h $common_internal/ema.h +ln -sf ../../../$emm_src/include/ema_imp.h $common_internal/ema_imp.h +ln -sf ../../../$emm_src/include/emm_private.h $common_internal/emm_private.h diff --git a/external/sgx-emm/emm_src b/external/sgx-emm/emm_src new file mode 160000 index 00000000..41a3ead0 --- /dev/null +++ b/external/sgx-emm/emm_src @@ -0,0 +1 @@ +Subproject commit 41a3ead0e350f255d82eb0f79a9f356816ea19ed diff --git a/external/sgx-emm/ut/Makefile b/external/sgx-emm/ut/Makefile new file mode 100644 index 00000000..bf67ad4e --- /dev/null +++ b/external/sgx-emm/ut/Makefile @@ -0,0 +1,55 @@ +# +# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# + +include ../../../buildenv.mk + +CPPFLAGS += -I$(COMMON_DIR)/inc \ + -I$(COMMON_DIR)/inc/internal \ + -DTEST=1 -g + +.PHONY: all clean + +all: test_bit_array test_ema test_public test_emm + +test_bit_array: test_bit_array.c ../bit_array.c + @$(CC) $(CPPFLAGS) $^ -o $@ + +test_ema: test_ema.c stub.c ../ema.c ../bit_array.c + @$(CC) $(CPPFLAGS) $^ -o $@ + +test_public: test_public.c stub.c ../sgx_mm.c ../ema.c ../bit_array.c + @$(CC) $(CPPFLAGS) $^ -o $@ + +test_emm: test_emm.c stub.c ../emm_private.c ../sgx_mm.c ../ema.c ../bit_array.c + @$(CC) $(CPPFLAGS) $^ -o $@ + +clean: + @$(RM) test_bit_array test_ema test_public test_emm diff --git a/external/sgx-emm/ut/stub.c b/external/sgx-emm/ut/stub.c new file mode 100644 index 00000000..d2839623 --- /dev/null +++ b/external/sgx-emm/ut/stub.c @@ -0,0 +1,100 @@ +/** + * + * INTEL CONFIDENTIAL + * Copyright(c) 2011-2017 Intel Corporation All Rights Reserved. + * + * The source code contained or described herein and all documents related to + * the source code ("Material") are owned by Intel Corporation or its suppliers + * or licensors. Title to the Material remains with Intel Corporation or its + * suppliers and licensors. The Material contains trade secrets and proprietary + * and confidential information of Intel or its suppliers and licensors. The + * Material is protected by worldwide copyright and trade secret laws and treaty + * provisions. No part of the Material may be used, copied, reproduced, modified, + * published, uploaded, posted, transmitted, distributed, or disclosed in any + * way without Intel's prior express written permission. + * + * No license under any patent, copyright, trade secret or other intellectual + * property right is granted to or conferred upon you by disclosure or delivery + * of the Materials, either expressly, by implication, inducement, estoppel or + * otherwise. Any license under such intellectual property rights must be + * express and approved by Intel(R) in writing. + * + */ + +#include "../sgx_mm_primitives.h" +#include "../sgx_mm_rt_abstraction.h" + +struct _sgx_mm_mutex { + void *impl; +} g_mm_lock; + +int do_eaccept(const sec_info_t* si, size_t addr) +{ + return 0; +} + +int do_eacceptcopy(const sec_info_t* si, size_t addr, size_t src) +{ + return 0; +} + +int do_emodpe(const sec_info_t* si, size_t addr) +{ + return 0; +} + +int sgx_mm_alloc_ocall(size_t addr, size_t length, int props, int flags) +{ + return 0; +} + +int sgx_mm_modify_ocall(size_t addr, size_t length, int flags_from, int flags_to) +{ + return 0; +} + +size_t get_rts_base() +{ + return 0; +} + +size_t get_rts_end() +{ + return 0x7FFFFF000000; +} + +size_t get_user_base() +{ + return 0x7FFFFF000000; +} + +size_t get_user_end() +{ + return 0x7FFFFFFFFFFF; +} +bool sgx_mm_is_within_enclave(const void *ptr, size_t size){ + return true; +} + + +sgx_mm_mutex* sgx_mm_mutex_create(void) +{ + return &g_mm_lock; +} +int sgx_mm_mutex_lock(sgx_mm_mutex *mutex) +{ + return 0; +} +int sgx_mm_mutex_unlock(sgx_mm_mutex *mutex) +{ + return 0; +} + +int sgx_mm_mutex_destroy(sgx_mm_mutex *mutex) +{ + return 0; +} +bool sgx_mm_register_pfhandler(sgx_mm_pfhandler_t pfhandler) +{ + return true; +} diff --git a/sdk/trts/trts_trim.cpp b/external/sgx-emm/ut/test_bit_array.c similarity index 53% rename from sdk/trts/trts_trim.cpp rename to external/sgx-emm/ut/test_bit_array.c index de447033..598cad8a 100644 --- a/sdk/trts/trts_trim.cpp +++ b/external/sgx-emm/ut/test_bit_array.c @@ -29,58 +29,51 @@ * */ +#include +#include "bit_array.h" -#include "trts_trim.h" -#include "sgx_trts.h" // for sgx_ocalloc, sgx_is_outside_enclave -#include "internal/rts.h" - -/* sgx_ocfree() just restores the original outside stack pointer. */ -#define OCALLOC(val, type, len) do { \ - void* __tmp = sgx_ocalloc(len); \ - if (__tmp == NULL) { \ - sgx_ocfree(); \ - return SGX_ERROR_UNEXPECTED;\ - } \ - (val) = (type)__tmp; \ -} while (0) - -typedef struct ms_trim_range_ocall_t { - size_t ms_fromaddr; - size_t ms_toaddr; -} ms_trim_range_ocall_t; - -typedef struct ms_trim_range_commit_ocall_t { - size_t ms_addr; -} ms_trim_range_commit_ocall_t; - -sgx_status_t SGXAPI trim_range_ocall(size_t fromaddr, size_t toaddr) +int main() { - sgx_status_t status = SGX_SUCCESS; + bit_array *ba = bit_array_new_set(31); + assert(bit_array_test(ba, 0) == true); + assert(bit_array_test(ba, 15) == true); + assert(bit_array_test(ba, 18) == true); + assert(bit_array_test(ba, 24) == true); + assert(bit_array_test(ba, 30) == true); + assert(bit_array_test_range(ba, 17, 10) == true); - ms_trim_range_ocall_t* ms; - OCALLOC(ms, ms_trim_range_ocall_t*, sizeof(*ms)); + bit_array_reset_range(ba, 17, 10); + assert(bit_array_test_range(ba, 17, 10) == false); + assert(bit_array_test(ba, 17) == false); + assert(bit_array_test(ba, 18) == false); + assert(bit_array_test(ba, 24) == false); + assert(bit_array_test(ba, 26) == false); + assert(bit_array_test(ba, 27) == true); + assert(bit_array_test(ba, 30) == false); - ms->ms_fromaddr = fromaddr; - ms->ms_toaddr = toaddr; - status = sgx_ocall(EDMM_TRIM, ms); + bit_array *lo = NULL, *hi = NULL; + int ret = bit_array_split(ba, 0, &lo, &hi); + assert(ret == 0); + assert(lo == NULL); + assert(hi == ba); + ret = bit_array_split(ba, 31, &lo, &hi); + assert(ret == 0); + assert(lo == ba); + assert(hi == NULL); - sgx_ocfree(); - return status; + ret = bit_array_split(ba, 17, &lo, &hi); + assert(lo == ba); + assert(ret == 0); + bit_array_delete(lo); + + bit_array *new_ba = NULL, *new_hi = NULL; + ret = bit_array_split(hi, 10, &new_ba, &new_hi); + assert(ret == 0); + assert(new_ba == hi); + assert(bit_array_test(new_hi, 3) == false); + + bit_array_delete(new_ba); + bit_array_delete(new_hi); + return 0; } - -sgx_status_t SGXAPI trim_range_commit_ocall(size_t addr) -{ - sgx_status_t status = SGX_SUCCESS; - - ms_trim_range_commit_ocall_t* ms; - OCALLOC(ms, ms_trim_range_commit_ocall_t*, sizeof(*ms)); - - ms->ms_addr = addr; - status = sgx_ocall(EDMM_TRIM_COMMIT, ms); - - - sgx_ocfree(); - return status; -} - diff --git a/external/sgx-emm/ut/test_ema.c b/external/sgx-emm/ut/test_ema.c new file mode 100644 index 00000000..7ceb6140 --- /dev/null +++ b/external/sgx-emm/ut/test_ema.c @@ -0,0 +1,192 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include "ema.h" + +extern ema_root_t g_user_ema_root; +extern ema_root_t g_rts_ema_root; +struct ema_root_ { + ema_t *guard; +}; + +int main() +{ + //make sure rts is inited. + ema_t *node0 = ema_new(0, 0xFFF00000, + SGX_EMA_COMMIT_NOW, + SGX_EMA_PROT_READ_WRITE | SGX_EMA_PAGE_TYPE_REG, + NULL, NULL, g_rts_ema_root.guard); + + assert(node0); + // find_build/insert node + size_t addr = 0; + ema_t *next_ema = NULL; + bool ret = find_free_region(&g_user_ema_root, + 0x2000, SGX_PAGE_SIZE, &addr, &next_ema); + + assert(ret == true); + assert(addr == 0xFFF00000); + assert(next_ema == g_user_ema_root.guard); + + node0 = ema_new(0xFFF00000, 0x2000, + SGX_EMA_COMMIT_ON_DEMAND, + SGX_EMA_PROT_READ_WRITE | SGX_EMA_PAGE_TYPE_REG, + NULL, NULL, next_ema); + + + // find at/build/push_back node + + ret = find_free_region_at(&g_user_ema_root, 0xFFF03000, + 0x1000, + &next_ema); + + assert(ret == true); + assert(next_ema == g_user_ema_root.guard); + + ema_t *node1 = ema_new(0xFFF03000, 0x1000, + SGX_EMA_COMMIT_NOW, + SGX_EMA_PROT_READ_WRITE | SGX_EMA_PAGE_TYPE_REG, + NULL, NULL, g_user_ema_root.guard); + + + // negative case for find_at + ret = find_free_region_at(&g_user_ema_root, + 0xFFF02000, 0x3000, &next_ema); + + assert(ret == false); + assert(next_ema == NULL); + + + // find_at/build/insert node + ret = find_free_region_at(&g_user_ema_root, + 0xFFF06000, 0x3000, &next_ema); + + assert(ret == true); + assert(next_ema == g_user_ema_root.guard); + + ema_t *node2 = ema_new(0xFFF06000, 0x3000, + SGX_EMA_COMMIT_ON_DEMAND, + SGX_EMA_PROT_READ_WRITE | SGX_EMA_PAGE_TYPE_REG, + NULL, NULL, next_ema); + + // dump current nodes on the root + dump_ema_root(&g_user_ema_root); + + ema_t *first = NULL, *last = NULL; + + // search_ema_range #1 + int r = search_ema_range(&g_user_ema_root, + 0xFFF00000, 0xFFF06000, + &first, &last); + assert(r == 0); + assert(first == node0); + assert(last == node2); + + + // search_ema_range #2 + r = search_ema_range(&g_user_ema_root, + 0xFFF02000, 0xFFF06000, + &first, &last); + assert(r == 0); + assert(first == node1); + assert(last == node2); + + + // search_ema_range #3 + r = search_ema_range(&g_user_ema_root, + 0xFFF02000, 0xFFF09000, + &first, &last); + assert(r == 0); + assert(first == node1); + assert(last == g_user_ema_root.guard); + + // search_ema_range #4 + r = search_ema_range(&g_user_ema_root, + 0xFFF01000, 0xFFF05000, + &first, &last); + assert(r == 0); + assert(first == node0); + assert(last == node2); + + // negative case, middle address region + r = search_ema_range(&g_user_ema_root, + 0xFFF04000, 0xFFF05000, + &first, &last); + assert(r == -1); + assert(first == NULL); + assert(last == NULL); + + // negative case, front address region + r = search_ema_range(&g_user_ema_root, + 0xFFE00000, 0xFFF00000, + &first, &last); + assert(r == -1); + assert(first == NULL); + assert(last == NULL); + + // negative case, rear address region + r = search_ema_range(&g_user_ema_root, + 0xFFF0A000, 0xFFF0B000, + &first, &last); + assert(r == -1); + assert(first == NULL); + assert(last == NULL); + + + // ema split: split point is out of range + ema_t *tmp_node = NULL; + r = ema_split(node0, 0xFFE00000, true, &tmp_node); + assert(tmp_node == NULL); + + // ema split: split point is out of range + tmp_node = NULL; + r = ema_split(node0, 0xFFF02000, false, &tmp_node); + assert(tmp_node == NULL); + + // ema split: split point is within range + size_t node0_base = ema_base(node0); + tmp_node = NULL; + ema_split(node0, 0xFFF01000, true, &tmp_node); + assert(ema_next(tmp_node) == node0); + assert(ema_base(tmp_node) == node0_base); + assert(ema_size(tmp_node) == 0x1000); + + tmp_node = NULL; + r = ema_split_ex(node2, 0xFFF07000, 0xFFF08000, &tmp_node); + assert(ema_base(tmp_node) == 0xFFF07000); + assert(ema_size(tmp_node) == 0x1000); + dump_ema_root(&g_user_ema_root); + destroy_ema_root(&g_user_ema_root); + + return 0; +} diff --git a/external/sgx-emm/ut/test_emm.c b/external/sgx-emm/ut/test_emm.c new file mode 100644 index 00000000..a82330d8 --- /dev/null +++ b/external/sgx-emm/ut/test_emm.c @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "emm_private.h" +#include "sgx_mm.h" + +int main() +{ + int ret = -1; + void* addr; + ret = mm_alloc((void *)0xFFFF0000, 0x10000, + SGX_EMA_COMMIT_NOW | SGX_EMA_GROWSUP, + NULL, NULL, &addr); + + return ret; +} diff --git a/external/sgx-emm/ut/test_public.c b/external/sgx-emm/ut/test_public.c new file mode 100644 index 00000000..64d15c24 --- /dev/null +++ b/external/sgx-emm/ut/test_public.c @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "sgx_mm.h" + +int main() +{ + int ret = -1; + + ret = sgx_mm_alloc((void *)0xFFFF0000, 0x10000, + SGX_EMA_COMMIT_NOW | SGX_EMA_GROWSUP, + NULL, NULL, NULL); + + return ret; +} diff --git a/external/sgxssl/prepare_sgxssl.sh b/external/sgxssl/prepare_sgxssl.sh index 1f68d58f..7c9872ec 100755 --- a/external/sgxssl/prepare_sgxssl.sh +++ b/external/sgxssl/prepare_sgxssl.sh @@ -32,16 +32,16 @@ top_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" openssl_out_dir=$top_dir/openssl_source -openssl_ver=1.1.1o +openssl_ver=1.1.1q openssl_ver_name=openssl-$openssl_ver sgxssl_github_archive=https://github.com/intel/intel-sgx-ssl/archive -sgxssl_file_name=lin_2.17_1.1.1o +sgxssl_file_name=lin_2.18_1.1.1q build_script=$top_dir/Linux/build_openssl.sh server_url_path=https://www.openssl.org/source full_openssl_url=$server_url_path/old/1.1.1/$openssl_ver_name.tar.gz -sgxssl_chksum=f0ed7bd37b45fd2350ec835a9c56b5590554e13b94471a38d3379054448a6d4b -openssl_chksum=9384a2b0570dd80358841464677115df785edb941c71211f75076d72fe6b438f +sgxssl_chksum=6c33d2178b6b01bdbb1f97804ae14aec13544b0cb45902a0906c20ef7b4032bc +openssl_chksum=d7939ce614029cdff0b6c20f0e2e5703158a489a72b2507b8bd51bf8c8fd10ca rm -f check_sum_sgxssl.txt check_sum_openssl.txt if [ ! -f $build_script ]; then wget $sgxssl_github_archive/$sgxssl_file_name.zip -P $top_dir || exit 1 diff --git a/linux/installer/bin/install-sgx-sdk.bin.tmpl b/linux/installer/bin/install-sgx-sdk.bin.tmpl index f286c255..63256555 100755 --- a/linux/installer/bin/install-sgx-sdk.bin.tmpl +++ b/linux/installer/bin/install-sgx-sdk.bin.tmpl @@ -180,7 +180,13 @@ export_the_simulation() ln -s ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/${LIB_DIR}/libsgx_quote_ex_sim.so ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/sdk_libs/ ln -s ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/${LIB_DIR}/libsgx_launch_sim.so ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/sdk_libs/ ln -s ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/${LIB_DIR}/libsgx_epid_sim.so ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/sdk_libs/ -} +} + +create_urts_soname_link() +{ + URTS_SONAME=`objdump -p ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/${LIB_DIR}/libsgx_urts.so | grep SONAME | awk '{print $2}'` + ln -fs ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/${LIB_DIR}/libsgx_urts.so ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/${LIB_DIR}/${URTS_SONAME} +} generate_environment_script() { @@ -198,6 +204,7 @@ EOF } export_the_simulation +create_urts_soname_link generate_environment_script echo """ diff --git a/linux/installer/common/libsgx-enclave-common/Makefile b/linux/installer/common/libsgx-enclave-common/Makefile index 3c939a3a..f850d3c5 100644 --- a/linux/installer/common/libsgx-enclave-common/Makefile +++ b/linux/installer/common/libsgx-enclave-common/Makefile @@ -37,7 +37,11 @@ PACKAGES=$(notdir $(wildcard $(PACKAGE_ROOT_FOLDER)/*)) USR_LIB_PATH=/usr/$(notdir $(shell gcc -print-multi-os-directory))/$(shell dpkg-architecture -qDEB_HOST_MULTIARCH 2> /dev/null) USR_INC_PATH=/usr/$(INC_DIR) -ifeq ($(shell LD_PRELOAD= stat -c "%G" /dev/sgx_enclave 2>/dev/null),sgx) +SYSTEMD_VERSION=$(or $(shell rpm -q --info systemd-libs 2> /dev/null | awk '/Version/ {print $$NF}' | awk -F[.-] '{print $$1}'), \ +$(shell rpm -q --info libsystemd0 2> /dev/null | awk '/Version/ {print $$NF}' | awk -F[.-] '{print $$1}'), \ +$(shell dpkg --status libsystemd0 2> /dev/null | awk '/Version/ {print $$NF}' | awk -F[.-] '{print $$1}'),0) + +ifeq ($(shell [ $(SYSTEMD_VERSION) -ge 248 ] && echo true),true) SGX_UDEV_RULE_DEL=/etc/udev/rules.d/91-sgx-enclave.rules else SGX_UDEV_RULE_DEL=/etc/udev/rules.d/94-sgx-enclave.rules diff --git a/linux/installer/common/psw-dcap/Makefile b/linux/installer/common/psw-dcap/Makefile index 4f05c94d..14f4c189 100644 --- a/linux/installer/common/psw-dcap/Makefile +++ b/linux/installer/common/psw-dcap/Makefile @@ -53,6 +53,8 @@ QE3_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,QE3_VERSION) QE3_MAJOR_VER:=$(word 1,$(subst ., ,$(QE3_FULL_VER))) QVE_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,QVE_VERSION) QVE_MAJOR_VER:=$(word 1,$(subst ., ,$(QVE_FULL_VER))) +PCE_LOGIC_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,PCE_WRAPPER_VERSION) +PCE_LOGIC_MAJOR_VER:=$(word 1,$(subst ., ,$(PCE_LOGIC_FULL_VER))) ECL_FULL_VER:= $(call ACQUIRE_PSW_VERSION,ENCLAVE_COMMON_VERSION) ECL_MAJOR_VER:=$(word 1,$(subst ., ,$(ECL_FULL_VER))) URTS_FULL_VER:= $(call ACQUIRE_PSW_VERSION,URTS_VERSION) @@ -281,6 +283,10 @@ install_ae: $(foreach PKG,$(AE_PKGS),post_$(PKG)) cd $(shell readlink -m $(DESTDIR)/$(AE_IDE_PACKAGE)/$(USR_LIB_PATH)) && \ mv libsgx_id_enclave.signed.so libsgx_id_enclave.signed.so.$(IDE_FULL_VER) && \ ln -fs libsgx_id_enclave.signed.so.$(IDE_FULL_VER) libsgx_id_enclave.signed.so.$(IDE_MAJOR_VER) + cd $(shell readlink -m $(DESTDIR)/$(PCE_LOGIC_PACKAGE)/$(USR_LIB_PATH)) && \ + mv libsgx_pce_logic.so libsgx_pce_logic.so.$(PCE_LOGIC_FULL_VER) && \ + ln -fs libsgx_pce_logic.so.$(PCE_LOGIC_FULL_VER) libsgx_pce_logic.so.$(PCE_LOGIC_MAJOR_VER) && \ + ln -fs libsgx_pce_logic.so.$(PCE_LOGIC_MAJOR_VER) libsgx_pce_logic.so PHONY+=install_dev_lib install_dev_lib: $(foreach PKG,$(DEV_LIB_PKGS),post_$(PKG)) diff --git a/linux/installer/common/psw-tdx/91-sgx-enclave.rules b/linux/installer/common/psw-tdx/91-sgx-enclave.rules new file mode 100644 index 00000000..223dd06b --- /dev/null +++ b/linux/installer/common/psw-tdx/91-sgx-enclave.rules @@ -0,0 +1,4 @@ +SUBSYSTEM=="misc",KERNEL=="sgx_enclave",MODE="0666",SYMLINK+="sgx/enclave" +SUBSYSTEM=="misc",KERNEL=="enclave",MODE="0666" +SUBSYSTEM=="sgx",KERNEL=="sgx/enclave",MODE="0666" + diff --git a/linux/installer/common/psw-tdx/92-sgx-provision.rules b/linux/installer/common/psw-tdx/92-sgx-provision.rules new file mode 100644 index 00000000..78ab76f3 --- /dev/null +++ b/linux/installer/common/psw-tdx/92-sgx-provision.rules @@ -0,0 +1,3 @@ +SUBSYSTEM=="misc",KERNEL=="sgx_provision",SYMLINK+="sgx/provision",GROUP="sgx_prv",MODE="0660" +SUBSYSTEM=="misc",KERNEL=="provision",GROUP="sgx_prv",MODE="0660" +SUBSYSTEM=="sgx",KERNEL=="sgx/provision",GROUP="sgx_prv",MODE="0660" diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-id-enclave.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-id-enclave.txt new file mode 100644 index 00000000..b450db4b --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-id-enclave.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_id_enclave.signed.so /lib/libsgx_id_enclave.signed.so 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-pce.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-pce.txt new file mode 100644 index 00000000..e0b172c5 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-pce.txt @@ -0,0 +1,3 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_pce.signed.so /lib/libsgx_pce.signed.so 0 main STP +/linux/installer/common/psw-tdx/92-sgx-provision.rules /etc/udev/rules.d/93-sgx-provision.rules 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-qve.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-qve.txt new file mode 100644 index 00000000..188d6b86 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-qve.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_qve.signed.so /lib/libsgx_qve.signed.so 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-tdqe.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-tdqe.txt new file mode 100644 index 00000000..18444a07 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-ae-tdqe.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_tdqe.signed.so /lib/libsgx_tdqe.signed.so 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-default-qpl-devel.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-default-qpl-devel.txt new file mode 100644 index 00000000..46a874bc --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-default-qpl-devel.txt @@ -0,0 +1 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-default-qpl.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-default-qpl.txt new file mode 100644 index 00000000..88197ec6 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-default-qpl.txt @@ -0,0 +1,4 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/build/linux/libdcap_quoteprov.so /lib/libdcap_quoteprov.so 0 main STP +/external/dcap_source/QuoteGeneration/build/linux/libsgx_default_qcnl_wrapper.so /lib/libsgx_default_qcnl_wrapper.so 0 main STP +/external/dcap_source/QuoteGeneration/qcnl/linux/sgx_default_qcnl.conf /etc/sgx_default_qcnl.conf 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-quote-verify-devel.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-quote-verify-devel.txt new file mode 100644 index 00000000..4b3363f6 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-quote-verify-devel.txt @@ -0,0 +1,3 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteVerification/dcap_quoteverify/inc/sgx_dcap_quoteverify.h /include/sgx_dcap_quoteverify.h 0 main STP +/external/dcap_source/QuoteVerification/QvE/Include/sgx_qve_header.h /include/sgx_qve_header.h 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-quote-verify.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-quote-verify.txt new file mode 100644 index 00000000..f46a51fa --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-dcap-quote-verify.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/build/linux/libsgx_dcap_quoteverify.so /lib/libsgx_dcap_quoteverify.so 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-enclave-common-devel.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-enclave-common-devel.txt new file mode 100644 index 00000000..e0c0e122 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-enclave-common-devel.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/psw/enclave_common/sgx_enclave_common.h /include/sgx_enclave_common.h 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-enclave-common.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-enclave-common.txt new file mode 100644 index 00000000..695886e9 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-enclave-common.txt @@ -0,0 +1,4 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_enclave_common.so /lib/libsgx_enclave_common.so 0 main STP +/linux/installer/common/psw-tdx/91-sgx-enclave.rules /etc/udev/rules.d/91-sgx-enclave.rules 0 main STP +/linux/installer/common/psw-tdx/remount-dev-exec.service /usr/lib/systemd/system/remount-dev-exec.service 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-headers.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-headers.txt new file mode 100644 index 00000000..a77cbcc3 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-headers.txt @@ -0,0 +1,13 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/common/inc/sgx_attributes.h /include/sgx_attributes.h 0 main STP +/common/inc/sgx_defs.h /include/sgx_defs.h 0 main STP +/common/inc/sgx_eid.h /include/sgx_eid.h 0 main STP +/common/inc/sgx_error.h /include/sgx_error.h 0 main STP +/common/inc/sgx_report.h /include/sgx_report.h main STP +/common/inc/sgx_key.h /include/sgx_key.h 0 main STP +/common/inc/sgx_quote.h /include/sgx_quote.h 0 main STP +/common/inc/sgx_urts.h /include/sgx_urts.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_ql_lib_common.h /include/sgx_ql_lib_common.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_quote_3.h /include/sgx_quote_3.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_ql_quote.h /include/sgx_ql_quote.h 0 main STP +/external/dcap_source/QuoteGeneration/pce_wrapper/inc/sgx_pce.h /include/sgx_pce.h 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-pce-logic.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-pce-logic.txt new file mode 100644 index 00000000..2abc37f1 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-pce-logic.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/build/linux/libsgx_pce_logic.so /lib/libsgx_pce_logic.so 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-network-devel.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-network-devel.txt new file mode 100644 index 00000000..a6866c11 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-network-devel.txt @@ -0,0 +1,4 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/SGXPlatformRegistration/include/MPNetwork.h /include/MPNetwork.h 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/include/MPNetworkDefs.h /include/MPNetworkDefs.h 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/include/c_wrapper/mp_network.h /include/mp_network.h 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-network.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-network.txt new file mode 100644 index 00000000..2f260bd5 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-network.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/SGXPlatformRegistration/build/lib64/libmpa_network.so /lib/libmpa_network.so 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-uefi-devel.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-uefi-devel.txt new file mode 100644 index 00000000..ce5aee6b --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-uefi-devel.txt @@ -0,0 +1,4 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/SGXPlatformRegistration/include/MPUefi.h /include/MPUefi.h 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/include/MultiPackageDefs.h /include/MultiPackageDefs.h 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/include/c_wrapper/mp_uefi.h /include/mp_uefi.h 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-uefi.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-uefi.txt new file mode 100644 index 00000000..63356491 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-ra-uefi.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/SGXPlatformRegistration/build/lib64/libmpa_uefi.so /lib/libmpa_uefi.so 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-tdx-logic-devel.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-tdx-logic-devel.txt new file mode 100644 index 00000000..f5b4de2a --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-tdx-logic-devel.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/quote_wrapper/tdx_quote/inc/td_ql_wrapper.h /include/td_ql_wrapper.h 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-tdx-logic.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-tdx-logic.txt new file mode 100644 index 00000000..122d7389 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-tdx-logic.txt @@ -0,0 +1,3 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/build/linux/libsgx_tdx_logic.so /lib/libsgx_tdx_logic.so 0 main STP + diff --git a/linux/installer/common/psw-tdx/BOM_install/libsgx-urts.txt b/linux/installer/common/psw-tdx/BOM_install/libsgx-urts.txt new file mode 100644 index 00000000..ad7c7c37 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libsgx-urts.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_urts.so /lib/libsgx_urts.so 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libtdx-attest-devel.txt b/linux/installer/common/psw-tdx/BOM_install/libtdx-attest-devel.txt new file mode 100644 index 00000000..e5f22c1b --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libtdx-attest-devel.txt @@ -0,0 +1,4 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/quote_wrapper/tdx_attest/tdx_attest.h /include/tdx_attest.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/tdx_attest/test_tdx_attest.c /sample/test_tdx_attest.c 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/tdx_attest/Makefile.sample /sample/Makefile 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/libtdx-attest.txt b/linux/installer/common/psw-tdx/BOM_install/libtdx-attest.txt new file mode 100644 index 00000000..93845c31 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/libtdx-attest.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/build/linux/libtdx_attest.so /lib/libtdx_attest.so 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/sgx-dcap-pccs.txt b/linux/installer/common/psw-tdx/BOM_install/sgx-dcap-pccs.txt new file mode 100644 index 00000000..d70745c9 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/sgx-dcap-pccs.txt @@ -0,0 +1,74 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/pccs/config/default.json /config/default.json 0 main STP +/external/dcap_source/QuoteGeneration/pccs/constants/index.js /constants/index.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/constants/pccs_status_code.js /constants/pccs_status_code.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/identityController.js /controllers/identityController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/index.js /controllers/index.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/pckcertController.js /controllers/pckcertController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/pckcrlController.js /controllers/pckcrlController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/platformCollateralController.js /controllers/platformCollateralController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/platformsController.js /controllers/platformsController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/refreshController.js /controllers/refreshController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/rootcacrlController.js /controllers/rootcacrlController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/tcbinfoController.js /controllers/tcbinfoController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/crlController.js /controllers/crlController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/fmspc_tcbs.js /dao/models/fmspc_tcbs.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/index.js /dao/models/index.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/pck_cert.js /dao/models/pck_cert.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/pck_certchain.js /dao/models/pck_certchain.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/pck_crl.js /dao/models/pck_crl.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/pcs_certificates.js /dao/models/pcs_certificates.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/pcs_version.js /dao/models/pcs_version.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/platform_tcbs.js /dao/models/platform_tcbs.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/platforms_registered.js /dao/models/platforms_registered.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/platforms.js /dao/models/platforms.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/enclave_identities.js /dao/models/enclave_identities.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/crl_cache.js /dao/models/crl_cache.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/fmspcTcbDao.js /dao/fmspcTcbDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/pckCertchainDao.js /dao/pckCertchainDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/pckcertDao.js /dao/pckcertDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/pckcrlDao.js /dao/pckcrlDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/pcsCertificatesDao.js /dao/pcsCertificatesDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/pcsVersionDao.js /dao/pcsVersionDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/platformsDao.js /dao/platformsDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/platformsRegDao.js /dao/platformsRegDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/platformTcbsDao.js /dao/platformTcbsDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/enclaveIdentityDao.js /dao/enclaveIdentityDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/crlCacheDao.js /dao/crlCacheDao.js 0 main STP +/external/dcap_source/tools/PCKCertSelection/out/libPCKCertSelection.so /lib/libPCKCertSelection.so 0 main STP +/external/dcap_source/QuoteGeneration/pccs/lib_wrapper/pcklib_wrapper.js /lib_wrapper/pcklib_wrapper.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/middleware/auth.js /middleware/auth.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/middleware/error.js /middleware/error.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/middleware/addRequestId.js /middleware/addRequestId.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/migrations/00_db_initialize.up.sql /migrations/00_db_initialize.up.sql 0 main STP +/external/dcap_source/QuoteGeneration/pccs/migrations/01_db_version_1.js /migrations/01_db_version_1.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/migrations/02_db_version_2.js /migrations/02_db_version_2.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/pcs_client/pcs_client.js /pcs_client/pcs_client.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/routes/index.js /routes/index.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/identityService.js /services/identityService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/index.js /services/index.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/pccs_schemas.js /services/pccs_schemas.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/pckcertService.js /services/pckcertService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/pckcrlService.js /services/pckcrlService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/platformCollateralService.js /services/platformCollateralService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/platformsRegService.js /services/platformsRegService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/platformsService.js /services/platformsService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/refreshService.js /services/refreshService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/rootcacrlService.js /services/rootcacrlService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/tcbinfoService.js /services/tcbinfoService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/crlService.js /services/crlService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/caching_modes/cachingMode.js /services/caching_modes/cachingMode.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/caching_modes/cachingModeManager.js /services/caching_modes/cachingModeManager.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/logic/commonCacheLogic.js /services/logic/commonCacheLogic.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/logic/qvCollateralLogic.js /services/logic/qvCollateralLogic.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/utils/Logger.js /utils/Logger.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/utils/PccsError.js /utils/PccsError.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/utils/apputil.js /utils/apputil.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/x509/x509.js /x509/x509.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/install.sh /install.sh 0 main STP +/external/dcap_source/QuoteGeneration/pccs/package.json /package.json 0 main STP +/external/dcap_source/QuoteGeneration/pccs/pccs_server.js /pccs_server.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/pccs.service /pccs.service 0 main STP +/external/dcap_source/QuoteGeneration/pccs/startup.sh /startup.sh 0 main STP +/external/dcap_source/QuoteGeneration/pccs/cleanup.sh /cleanup.sh 0 main STP +/external/dcap_source/QuoteGeneration/pccs/README.md /README.md 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/sgx-pck-id-retrieval-tool.txt b/linux/installer/common/psw-tdx/BOM_install/sgx-pck-id-retrieval-tool.txt new file mode 100644 index 00000000..600fe91a --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/sgx-pck-id-retrieval-tool.txt @@ -0,0 +1,5 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/PCKRetrievalTool/network_setting.conf /network_setting.conf 0 main STP +/external/dcap_source/tools/PCKRetrievalTool/PCKIDRetrievalTool /PCKIDRetrievalTool 0 main STP +/external/dcap_source/tools/PCKRetrievalTool/README.txt /README.txt 0 main STP +/external/dcap_source/tools/PCKRetrievalTool/License.txt /License.txt 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/sgx-ra-service.txt b/linux/installer/common/psw-tdx/BOM_install/sgx-ra-service.txt new file mode 100644 index 00000000..3521a03f --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/sgx-ra-service.txt @@ -0,0 +1,8 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/SGXPlatformRegistration/build/bin/mpa_manage /mpa_manage 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/package/mpa_registration /mpa_registration 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/package/mpa_registration_tool.service /mpa_registration_tool.service 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/package/mpa_registration_tool.conf /mpa_registration_tool.conf 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/config/mpa_registration.conf /conf/mpa_registration.conf 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/package/startup.sh /startup.sh 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/package/cleanup.sh /cleanup.sh 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_install/tdx-qgs.txt b/linux/installer/common/psw-tdx/BOM_install/tdx-qgs.txt new file mode 100644 index 00000000..2043a4bf --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_install/tdx-qgs.txt @@ -0,0 +1,8 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/quote_wrapper/qgs/qgsd.service /qgsd.service 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/qgs/qgsd.conf /qgsd.conf 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/qgs/qgs.conf /conf/qgs.conf 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/qgs/qgs /qgs 0 main STP +/external/dcap_source/QuoteGeneration/installer/linux/common/tdx-qgs/startup.sh /startup.sh 0 main STP +/external/dcap_source/QuoteGeneration/installer/linux/common/tdx-qgs/cleanup.sh /cleanup.sh 0 main STP +/external/dcap_source/QuoteGeneration/installer/linux/common/tdx-qgs/linksgx.sh /linksgx.sh 0 main STP diff --git a/linux/installer/common/psw-tdx/BOM_source/psw-tdx-tarball.txt b/linux/installer/common/psw-tdx/BOM_source/psw-tdx-tarball.txt new file mode 100644 index 00000000..fc735b36 --- /dev/null +++ b/linux/installer/common/psw-tdx/BOM_source/psw-tdx-tarball.txt @@ -0,0 +1,23 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/common /common 0 main STP +/external /external 0 main STP +/psw/enclave_common /psw/enclave_common 0 main STP +/psw/urts /psw/urts 0 main STP +/psw/ae/inc /psw/ae/inc 0 main STP +/psw/ae/common /psw/ae/common 0 main STP +/sdk /sdk 0 main STP +/SampleCode /SampleCode 0 main STP +/buildenv.mk /buildenv.mk 0 main STP +/Makefile.psw_tdx /Makefile 0 main STP +/License.txt /License.txt 0 main STP +/README.md /README.md 0 main STP +/linux/installer/common/psw-tdx /linux/installer/common/psw-tdx 0 main STP +/linux/installer/common/sdk /linux/installer/common/sdk 0 main STP +/linux/installer/common/gen_source /linux/installer/common/gen_source 0 main STP +/linux/installer/common/licenses /linux/installer/common/licenses 0 main STP +/linux/installer/bin/build-installpkg.sh /linux/installer/bin/build-installpkg.sh 0 main STP +/linux/installer/bin/install-sgx-sdk.bin.tmpl /linux/installer/bin/install-sgx-sdk.bin.tmpl 0 main STP +/linux/installer/rpm/psw-tdx/build.sh /linux/installer/rpm/psw-tdx/build.sh 0 main STP +/linux/installer/rpm/psw-tdx/clean.sh /linux/installer/rpm/psw-tdx/clean.sh 0 main STP +/linux/installer/rpm/psw-tdx/psw-tdx.spec.tmpl /linux/installer/rpm/psw-tdx/psw-tdx.spec.tmpl 0 main STP +/external/ippcp_internal/Makefile.psw_dcap /external/ippcp_internal/Makefile 0 main STP diff --git a/linux/installer/common/psw-tdx/Makefile b/linux/installer/common/psw-tdx/Makefile new file mode 100644 index 00000000..4f50ee49 --- /dev/null +++ b/linux/installer/common/psw-tdx/Makefile @@ -0,0 +1,307 @@ +# +# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# + +include installConfig + +ACQUIRE_PSW_VERSION = $(shell awk \ + '$$2 ~ /$1/ { print substr($$3, 2, length($$3) - 2); }' \ + $(SRCDIR)/common/inc/internal/se_version.h) + +ACQUIRE_DCAP_VERSION = $(shell awk \ + '$$2 ~ /$1/ { print substr($$3, 2, length($$3) - 2); }' \ + $(SRCDIR)/external/dcap_source/QuoteGeneration/common/inc/internal/se_version.h) + +PCE_FULL_VER:= $(call ACQUIRE_PSW_VERSION,PCE_VERSION) +PCE_MAJOR_VER:=$(word 1,$(subst ., ,$(PCE_FULL_VER))) +IDE_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,IDE_VERSION) +IDE_MAJOR_VER:=$(word 1,$(subst ., ,$(IDE_FULL_VER))) +TDQE_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,TDQE_VERSION) +TDQE_MAJOR_VER:=$(word 1,$(subst ., ,$(TDQE_FULL_VER))) +QVE_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,QVE_VERSION) +QVE_MAJOR_VER:=$(word 1,$(subst ., ,$(QVE_FULL_VER))) +URTS_FULL_VER:= $(call ACQUIRE_PSW_VERSION,URTS_VERSION) +URTS_MAJOR_VER:=$(word 1,$(subst ., ,$(URTS_FULL_VER))) +ECL_FULL_VER:= $(call ACQUIRE_PSW_VERSION,ENCLAVE_COMMON_VERSION) +ECL_MAJOR_VER:=$(word 1,$(subst ., ,$(ECL_FULL_VER))) +QPL_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,DEFAULT_QPL_VERSION) +QPL_MAJOR_VER:=$(word 1,$(subst ., ,$(QPL_FULL_VER))) +QCNL_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,DEFAULT_QPL_VERSION) +QCNL_MAJOR_VER:=$(word 1,$(subst ., ,$(QCNL_FULL_VER))) +QVL_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,QUOTE_VERIFIER_VERSION) +QVL_MAJOR_VER:=$(word 1,$(subst ., ,$(QVL_FULL_VER))) +PCE_LOGIC_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,PCE_WRAPPER_VERSION) +PCE_LOGIC_MAJOR_VER:=$(word 1,$(subst ., ,$(PCE_LOGIC_FULL_VER))) +TDX_LOGIC_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,TDQE_WRAPPER_VERSION) +TDX_LOGIC_MAJOR_VER:=$(word 1,$(subst ., ,$(TDX_LOGIC_FULL_VER))) +RAN_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,STRFILEVER) +RAN_MAJOR_VER:=$(word 1,$(subst ., ,$(RAN_FULL_VER))) +RAU_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,STRFILEVER) +RAU_MAJOR_VER:=$(word 1,$(subst ., ,$(RAU_FULL_VER))) + +CUR_PATH:=$(realpath $(dir $(lastword $(MAKEFILE_LIST)))) +BOM_PATH:=$(CUR_PATH)/BOM_install +GEN_SCRIPT:=$(realpath $(CUR_PATH)/../gen_source/copy_source.py) + +PACKAGE_ROOT_PATH:=$(SRCDIR)/build/pkgroot + +USR_LIB_PATH:=/usr/$(notdir $(shell gcc -print-multi-os-directory))/$(shell dpkg-architecture -qDEB_HOST_MULTIARCH 2> /dev/null) +USR_INC_PATH=/usr/$(INC_DIR) + +# Support systemd by default(for Fedora build environment) +QGSD_CONF=qgsd.service +QGSD_CONF_DEL=qgsd.conf +QGSD_CONF_PATH=$(if $(wildcard /lib/systemd/system/.),/lib/systemd/system,/usr/lib/systemd/system) + +PCCS_CONF=pccs.service +PCCS_CONF_PATH=$(if $(wildcard /lib/systemd/system/.),/lib/systemd/system,/usr/lib/systemd/system) + +RAD_CONF=mpa_registration_tool.service +RAD_CONF_DEL=mpa_registration_tool.conf +RAD_CONF_PATH=$(if $(wildcard /lib/systemd/system/.),/lib/systemd/system,/usr/lib/systemd/system) + +TEST_COPYABLE = \( -d $1 -a -n "$$(shell ls -A $1 2> /dev/null)" \) + +define PRE_INSTALL_TEMPLATE +pre_$(1): | $(PACKAGE_ROOT_PATH) + python $(GEN_SCRIPT) --bom-file $(BOM_PATH)/$(1).txt \ + --src-path $(SRCDIR) --dst-path $$|/$(1) +endef + +define INSTALL_AESM_SERVICE_TEMPLATE +$(1): pre_$(1) | $(PACKAGE_ROOT_PATH) + install -d $$(shell readlink -m $(DESTDIR)/$$@) + test $(call TEST_COPYABLE,$$|/$$@/$(LIB_DIR)) && ( \ + install -d $$(shell readlink -m $(DESTDIR)/$$@/$(USR_LIB_PATH)) && \ + install $$|/$$@/$(LIB_DIR)/* $(DESTDIR)/$$@/$(USR_LIB_PATH) && \ + rm -fr $$|/$$@/$(LIB_DIR) ) ||: + test $(call TEST_COPYABLE,$$|/$$@/$(ETC_DIR)) && ( \ + install -d $$(shell readlink -m $(DESTDIR)/$$@/$(ETC_DIR)) && \ + cp -fr $$|/$$@/$(ETC_DIR)/* $(DESTDIR)/$$@/$(ETC_DIR) && \ + rm -fr $$|/$$@/$(ETC_DIR) ) ||: + +post_$(1): $(1) | $(PACKAGE_ROOT_PATH) + test $(call TEST_COPYABLE,$$|/$$<) && ( \ + install -d $$(shell readlink -m $(DESTDIR)/$$ $(DESTDIR)/$(TDX_QGS_PACKAGE)/$(QGSD_CONF_PATH)/$(QGSD_CONF) + rm -f $(DESTDIR)/$(TDX_QGS_PACKAGE)/$(TDX_QGS_PACKAGE_PATH)/$(TDX_QGS_PACKAGE)/$(QGSD_CONF) + rm -f $(DESTDIR)/$(TDX_QGS_PACKAGE)/$(TDX_QGS_PACKAGE_PATH)/$(TDX_QGS_PACKAGE)/$(QGSD_CONF_DEL) + $(if $(shell grep '^ID=clear-linux-os' /usr/lib/os-release 2> /dev/null), \ + $(if $(wildcard $(DESTDIR)/$(TDX_QGS_PACKAGE_PATH)/$(TDX_QGS_PACKAGE)/conf/$(QGSD_CONF)), \ + mv $(DESTDIR)/$(TDX_QGS_PACKAGE)/$(TDX_QGS_PACKAGE_PATH)/$(TDX_QGS_PACKAGE)/conf/$(QGSD_CONF) \ + $(DESTDIR)/$(TDX_QGS_PACKAGE)/$(TDX_QGS_PACKAGE_PATH)/$(TDX_QGS_PACKAGE)/conf/$(QGSD_CONF).sample), \ + $(if $(wildcard $(DESTDIR)/$(TDX_QGS_PACKAGE)/$(TDX_QGS_PACKAGE_PATH)/$(TDX_QGS_PACKAGE)/conf/.*), \ + install -d $(shell readlink -m $(DESTDIR)/$(TDX_QGS_PACKAGE)/$(ETC_DIR)) && \ + cp -fr $(DESTDIR)/$(TDX_QGS_PACKAGE)/$(SGX_INSTALL_PATH)/$(TDX_QGS_PACKAGE)/conf/* \ + $(DESTDIR)/$(TDX_QGS_PACKAGE)/$(ETC_DIR) && \ + rm -fr $(DESTDIR)/$(TDX_QGS_PACKAGE)/$(SGX_INSTALL_PATH)/$(TDX_QGS_PACKAGE)/conf)) + +PHONY+=install_$(DCAP_PCCS_PACKAGE) +install_$(DCAP_PCCS_PACKAGE): pre_$(DCAP_PCCS_PACKAGE) | $(PACKAGE_ROOT_PATH) + install -d $(shell readlink -m $(DESTDIR)/$(DCAP_PCCS_PACKAGE)/$(PCCS_CONF_PATH)) && \ + cp -f $|/$(DCAP_PCCS_PACKAGE)/$(PCCS_CONF) $(DESTDIR)/$(DCAP_PCCS_PACKAGE)/$(PCCS_CONF_PATH) && \ + rm -f $|/$(DCAP_PCCS_PACKAGE)/$(PCCS_CONF) + install -d $(shell readlink -m $(DESTDIR)/$(DCAP_PCCS_PACKAGE)/$(SGX_INSTALL_PATH)/$(DCAP_PCCS_PACKAGE)) && \ + cp -fr $|/$(DCAP_PCCS_PACKAGE)/* $(DESTDIR)/$(DCAP_PCCS_PACKAGE)/$(SGX_INSTALL_PATH)/$(DCAP_PCCS_PACKAGE) + +PHONY+=$(RA_SERVICE_PACKAGE) +$(RA_SERVICE_PACKAGE): pre_$(RA_SERVICE_PACKAGE) | $(PACKAGE_ROOT_PATH) + install -d $(shell readlink -m $(DESTDIR)/$@/$(SGX_INSTALL_PATH)/$@) && \ + cp -fr $|/$@/* $(DESTDIR)/$@/$(SGX_INSTALL_PATH)/$@ + +PHONY+=install_$(RA_SERVICE_PACKAGE) +install_$(RA_SERVICE_PACKAGE): $(RA_SERVICE_PACKAGE) + install -d $(shell readlink -m $(DESTDIR)/$ $(DESTDIR)/$ /dev/null +elif [ -d /etc/init/ ]; then + initctl reload-configuration + initctl stop qgsd +fi + +# Remove qgsd user and group +userdel qgsd 2> /dev/null || true +groupdel qgsd 2> /dev/null || true + +exit 0 diff --git a/linux/installer/common/psw-tdx/installConfig b/linux/installer/common/psw-tdx/installConfig new file mode 100644 index 00000000..7129b71d --- /dev/null +++ b/linux/installer/common/psw-tdx/installConfig @@ -0,0 +1,31 @@ +SGX_HEADERS_PACKAGE=libsgx-headers +URTS_PACKAGE=libsgx-urts +ENCLAVE_COMMON_PACKAGE=libsgx-enclave-common +ENCLAVE_COMMON_DEV_PACKAGE=libsgx-enclave-common-devel +AE_PCE_PACKAGE=libsgx-ae-pce +TDX_QGS_PACKAGE=tdx-qgs +AE_IDE_PACKAGE=libsgx-ae-id-enclave +AE_TDQE_PACKAGE=libsgx-ae-tdqe +AE_QVE_PACKAGE=libsgx-ae-qve +TDX_LOGIC_PACKAGE=libsgx-tdx-logic +TDX_LOGIC_DEV_PACKAGE=libsgx-tdx-logic-devel +PCE_LOGIC_PACKAGE=libsgx-pce-logic +DCAP_QPL_PACKAGE=libsgx-dcap-default-qpl +DCAP_QPL_DEV_PACKAGE=libsgx-dcap-default-qpl-devel +TDX_ATTEST_PACKAGE=libtdx-attest +TDX_ATTEST_DEV_PACKAGE=libtdx-attest-devel +DCAP_QVL_PACKAGE=libsgx-dcap-quote-verify +DCAP_QVL_DEV_PACKAGE=libsgx-dcap-quote-verify-devel +DCAP_PCCS_PACKAGE=sgx-dcap-pccs +PCK_ID_RETRIEVAL_TOOL_PACKAGE=sgx-pck-id-retrieval-tool +RA_NETWORK_PACKAGE=libsgx-ra-network +RA_NETWORK_DEV_PACKAGE=libsgx-ra-network-devel +RA_UEFI_PACKAGE=libsgx-ra-uefi +RA_UEFI_DEV_PACKAGE=libsgx-ra-uefi-devel +RA_SERVICE_PACKAGE=sgx-ra-service + +SGX_INSTALL_PATH=/opt/intel +TDX_QGS_PACKAGE_PATH=/opt/intel +INC_DIR=include +LIB_DIR=lib +ETC_DIR=etc diff --git a/linux/installer/common/psw-tdx/remount-dev-exec.service b/linux/installer/common/psw-tdx/remount-dev-exec.service new file mode 100644 index 00000000..ed4b7123 --- /dev/null +++ b/linux/installer/common/psw-tdx/remount-dev-exec.service @@ -0,0 +1,11 @@ +[Unit] +Description=Remount /dev as exec to allow AESM service to boot and load enclaves into SGX +After=udev.service + +[Service] +Type=oneshot +ExecStart=/bin/mount -o remount,exec /dev +RemainAfterExit=true + +[Install] +WantedBy=multi-user.target diff --git a/linux/installer/common/psw-tdx/startup.sh b/linux/installer/common/psw-tdx/startup.sh new file mode 100644 index 00000000..31c564cf --- /dev/null +++ b/linux/installer/common/psw-tdx/startup.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# +# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# + + +set -e + +if test $(id -u) -ne 0; then + echo "Root privilege is required." + exit 1 +fi + +# Create user and group if not exist +id -u qgsd &> /dev/null || \ + useradd -r -U -c "User for qgsd" \ + -d /var/opt/qgsd -s /sbin/nologin qgsd + +# Start the QGSD service +if [ -d /run/systemd/system ]; then + systemctl enable qgsd + systemctl start qgsd +elif [ -d /etc/init/ ]; then + initctl reload-configuration + initctl start qgsd +fi + +exit 0 diff --git a/linux/installer/common/psw/BOMs/psw_base.txt b/linux/installer/common/psw/BOMs/psw_base.txt index 10f8087f..2a960a75 100644 --- a/linux/installer/common/psw/BOMs/psw_base.txt +++ b/linux/installer/common/psw/BOMs/psw_base.txt @@ -9,8 +9,8 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /build/linux/libsgx_default_qcnl_wrapper.so /package/aesm/libsgx_default_qcnl_wrapper.so 0 main STP /build/linux/liburts_internal.so /package/aesm/liburts_internal.so 0 main STP /build/linux/libCppMicroServices.so.4.0.0 /package/aesm/libCppMicroServices.so.4.0.0 0 main STP -/external/dcap_source/QuoteGeneration/build/linux/libsgx_pce_logic.so /package/aesm/libsgx_pce_logic.so 0 main STP -/external/dcap_source/QuoteGeneration/build/linux/libsgx_qe3_logic.so /package/aesm/libsgx_qe3_logic.so 0 main STP +/external/dcap_source/QuoteGeneration/build/linux/libsgx_pce_logic.so /package/aesm/libsgx_pce_logic.so.1 0 main STP +/external/dcap_source/QuoteGeneration/build/linux/libsgx_qe3_logic.so /package/aesm/libsgx_qe3_logic.so.1 0 main STP /build/linux/bundles/libepid_quote_service_bundle.so /package/aesm/bundles/libepid_quote_service_bundle.so 0 main STP /build/linux/bundles/lible_launch_service_bundle.so /package/aesm/bundles/lible_launch_service_bundle.so 0 main STP /build/linux/bundles/liblinux_network_service_bundle.so /package/aesm/bundles/liblinux_network_service_bundle.so 0 main STP diff --git a/linux/installer/common/sdk/BOMs/sdk_base.txt b/linux/installer/common/sdk/BOMs/sdk_base.txt index 49bd2eb6..ae2c2d92 100644 --- a/linux/installer/common/sdk/BOMs/sdk_base.txt +++ b/linux/installer/common/sdk/BOMs/sdk_base.txt @@ -59,6 +59,7 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /common/inc/tlibc/limits.h /package/include/tlibc/limits.h 0 main STP /common/inc/tlibc/math.h /package/include/tlibc/math.h 0 main STP /common/inc/tlibc/stdarg.h /package/include/tlibc/stdarg.h 0 main STP +/common/inc/tlibc/stdalign.h /package/include/tlibc/stdalign.h 0 main STP /common/inc/tlibc/stdbool.h /package/include/tlibc/stdbool.h 0 main STP /common/inc/tlibc/stddef.h /package/include/tlibc/stddef.h 0 main STP /common/inc/tlibc/stdint.h /package/include/tlibc/stdint.h 0 main STP @@ -112,6 +113,7 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /external/ippcp_internal/inc/ippcpdefs.h /package/include/ipp/ippcpdefs.h 0 main STP /external/ippcp_internal/inc/ippversion.h /package/include/ipp/ippversion.h 0 main STP /external/ippcp_internal/inc/sgx_ippcp.h /package/include/ipp/sgx_ippcp.h 0 main STP +/external/sgx-emm/emm_src/include/sgx_mm.h /package/include/sgx_mm.h 0 main STP /linux/installer/common/sdk/install.sh /scripts/install.sh 0 main STP /linux/installer/common/sdk/Makefile /Makefile 0 main STP /external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_ql_lib_common.h /package/include/./sgx_ql_lib_common.h 0 main STP @@ -147,7 +149,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator.cpp /package/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator.cpp 0 main STP /SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator.edl /package/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator.edl 0 main STP /SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator.lds /package/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator.lds 0 main STP -/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator_private_test.pem /package/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveInitiator_private_test.pem 0 main STP /SampleCode/LocalAttestation/EnclaveInitiator/EnclaveMessageExchange.cpp /package/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveMessageExchange.cpp 0 main STP /SampleCode/LocalAttestation/EnclaveInitiator/EnclaveMessageExchange.h /package/SampleCode/LocalAttestation/EnclaveInitiator/EnclaveMessageExchange.h 0 main STP /SampleCode/LocalAttestation/EnclaveInitiator/Makefile /package/SampleCode/LocalAttestation/EnclaveInitiator/Makefile 0 main STP @@ -161,7 +162,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder.cpp /package/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder.cpp 0 main STP /SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder.edl /package/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder.edl 0 main STP /SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder.lds /package/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder.lds 0 main STP -/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder_private_test.pem /package/SampleCode/LocalAttestation/EnclaveResponder/EnclaveResponder_private_test.pem 0 main STP /SampleCode/LocalAttestation/EnclaveResponder/Makefile /package/SampleCode/LocalAttestation/EnclaveResponder/Makefile 0 main STP /SampleCode/LocalAttestation/EnclaveResponder/ReadMe.txt /package/SampleCode/LocalAttestation/EnclaveResponder/ReadMe.txt 0 main STP /SampleCode/LocalAttestation/EnclaveResponder/Utility_E2.cpp /package/SampleCode/LocalAttestation/EnclaveResponder/Utility_E2.cpp 0 main STP @@ -186,7 +186,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/PowerTransition/Enclave/Enclave.cpp /package/SampleCode/PowerTransition/Enclave/Enclave.cpp 0 main STP /SampleCode/PowerTransition/Enclave/Enclave.edl /package/SampleCode/PowerTransition/Enclave/Enclave.edl 0 main STP /SampleCode/PowerTransition/Enclave/Enclave.lds /package/SampleCode/PowerTransition/Enclave/Enclave.lds 0 main STP -/SampleCode/PowerTransition/Enclave/Enclave_private_test.pem /package/SampleCode/PowerTransition/Enclave/Enclave_private_test.pem 0 main STP /SampleCode/PowerTransition/Makefile /package/SampleCode/PowerTransition/Makefile 0 main STP /SampleCode/PowerTransition/.project /package/SampleCode/PowerTransition/.project 0 main STP /SampleCode/PowerTransition/README.txt /package/SampleCode/PowerTransition/README.txt 0 main STP @@ -198,7 +197,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/RemoteAttestation/isv_enclave/isv_enclave.cpp /package/SampleCode/RemoteAttestation/isv_enclave/isv_enclave.cpp 0 main STP /SampleCode/RemoteAttestation/isv_enclave/isv_enclave.edl /package/SampleCode/RemoteAttestation/isv_enclave/isv_enclave.edl 0 main STP /SampleCode/RemoteAttestation/isv_enclave/isv_enclave.lds /package/SampleCode/RemoteAttestation/isv_enclave/isv_enclave.lds 0 main STP -/SampleCode/RemoteAttestation/isv_enclave/isv_enclave_private_test.pem /package/SampleCode/RemoteAttestation/isv_enclave/isv_enclave_private_test.pem 0 main STP /SampleCode/RemoteAttestation/Makefile /package/SampleCode/RemoteAttestation/Makefile 0 main STP /SampleCode/RemoteAttestation/README.txt /package/SampleCode/RemoteAttestation/README.txt 0 main STP /SampleCode/RemoteAttestation/.project /package/SampleCode/RemoteAttestation/.project 0 main STP @@ -235,11 +233,11 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/SampleEnclave/Enclave/config.02.xml /package/SampleCode/SampleEnclave/Enclave/config.02.xml 0 main STP /SampleCode/SampleEnclave/Enclave/config.03.xml /package/SampleCode/SampleEnclave/Enclave/config.03.xml 0 main STP /SampleCode/SampleEnclave/Enclave/config.04.xml /package/SampleCode/SampleEnclave/Enclave/config.04.xml 0 main STP +/SampleCode/SampleEnclave/Enclave/config.05.xml /package/SampleCode/SampleEnclave/Enclave/config.05.xml 0 main STP /SampleCode/SampleEnclave/Enclave/Enclave.cpp /package/SampleCode/SampleEnclave/Enclave/Enclave.cpp 0 main STP /SampleCode/SampleEnclave/Enclave/Enclave.edl /package/SampleCode/SampleEnclave/Enclave/Enclave.edl 0 main STP /SampleCode/SampleEnclave/Enclave/Enclave.h /package/SampleCode/SampleEnclave/Enclave/Enclave.h 0 main STP /SampleCode/SampleEnclave/Enclave/Enclave.lds /package/SampleCode/SampleEnclave/Enclave/Enclave.lds 0 main STP -/SampleCode/SampleEnclave/Enclave/Enclave_private_test.pem /package/SampleCode/SampleEnclave/Enclave/Enclave_private_test.pem 0 main STP /SampleCode/SampleEnclave/Enclave/TrustedLibrary/Libc.cpp /package/SampleCode/SampleEnclave/Enclave/TrustedLibrary/Libc.cpp 0 main STP /SampleCode/SampleEnclave/Enclave/TrustedLibrary/Libc.edl /package/SampleCode/SampleEnclave/Enclave/TrustedLibrary/Libc.edl 0 main STP /SampleCode/SampleEnclave/Enclave/TrustedLibrary/Libcxx.cpp /package/SampleCode/SampleEnclave/Enclave/TrustedLibrary/Libcxx.cpp 0 main STP @@ -257,7 +255,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.edl /package/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.edl 0 main STP /SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.h /package/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.h 0 main STP /SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.lds /package/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.lds 0 main STP -/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave_private_test.pem /package/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave_private_test.pem 0 main STP /SampleCode/SampleEnclaveGMIPP/Makefile /package/SampleCode/SampleEnclaveGMIPP/Makefile 0 main STP /SampleCode/SampleEnclaveGMIPP/README.txt /package/SampleCode/SampleEnclaveGMIPP/README.txt 0 main STP /SampleCode/SampleEnclavePCL/App/App.cpp /package/SampleCode/SampleEnclavePCL/App/App.cpp 0 main STP @@ -282,7 +279,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/SampleEnclavePCL/Enclave/Enclave.edl /package/SampleCode/SampleEnclavePCL/Enclave/Enclave.edl 0 main STP /SampleCode/SampleEnclavePCL/Enclave/Enclave.h /package/SampleCode/SampleEnclavePCL/Enclave/Enclave.h 0 main STP /SampleCode/SampleEnclavePCL/Enclave/Enclave.lds /package/SampleCode/SampleEnclavePCL/Enclave/Enclave.lds 0 main STP -/SampleCode/SampleEnclavePCL/Enclave/Enclave_private_test.pem /package/SampleCode/SampleEnclavePCL/Enclave/Enclave_private_test.pem 0 main STP /SampleCode/SampleEnclavePCL/Enclave/TrustedLibrary/Libc.cpp /package/SampleCode/SampleEnclavePCL/Enclave/TrustedLibrary/Libc.cpp 0 main STP /SampleCode/SampleEnclavePCL/Enclave/TrustedLibrary/Libc.edl /package/SampleCode/SampleEnclavePCL/Enclave/TrustedLibrary/Libc.edl 0 main STP /SampleCode/SampleEnclavePCL/Enclave/TrustedLibrary/Libcxx.cpp /package/SampleCode/SampleEnclavePCL/Enclave/TrustedLibrary/Libcxx.cpp 0 main STP @@ -297,7 +293,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/SampleEnclavePCL/Seal/Seal.cpp /package/SampleCode/SampleEnclavePCL/Seal/Seal.cpp 0 main STP /SampleCode/SampleEnclavePCL/Seal/Seal.edl /package/SampleCode/SampleEnclavePCL/Seal/Seal.edl 0 main STP /SampleCode/SampleEnclavePCL/Seal/Seal.lds /package/SampleCode/SampleEnclavePCL/Seal/Seal.lds 0 main STP -/SampleCode/SampleEnclavePCL/Seal/Seal_private_test.pem /package/SampleCode/SampleEnclavePCL/Seal/Seal_private_test.pem 0 main STP /SampleCode/SampleAttestedTLS/AttestedTLSREADME.md /package/SampleCode/SampleAttestedTLS/AttestedTLSREADME.md 0 main STP /SampleCode/SampleAttestedTLS/Makefile /package/SampleCode/SampleAttestedTLS/Makefile 0 main STP /SampleCode/SampleAttestedTLS/prepare_sgxssl.sh /package/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh 0 main STP @@ -321,7 +316,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/SampleAttestedTLS/server/enc/enclave.lds /package/SampleCode/SampleAttestedTLS/server/enc/enclave.lds 0 main STP /SampleCode/SampleAttestedTLS/server/enc/Makefile /package/SampleCode/SampleAttestedTLS/server/enc/Makefile 0 main STP /SampleCode/SampleAttestedTLS/server/enc/openssl_server.cpp /package/SampleCode/SampleAttestedTLS/server/enc/openssl_server.cpp 0 main STP -/SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem /package/SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem 0 main STP /SampleCode/SampleAttestedTLS/server/enc/server_enc.config.xml /package/SampleCode/SampleAttestedTLS/server/enc/server_enc.config.xml 0 main STP /SampleCode/SampleAttestedTLS/server/host/host.cpp /package/SampleCode/SampleAttestedTLS/server/host/host.cpp 0 main STP /SampleCode/SampleAttestedTLS/server/host/Makefile /package/SampleCode/SampleAttestedTLS/server/host/Makefile 0 main STP @@ -331,7 +325,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/SampleAttestedTLS/client/enc/Makefile /package/SampleCode/SampleAttestedTLS/client/enc/Makefile 0 main STP /SampleCode/SampleAttestedTLS/client/enc/enclave.lds /package/SampleCode/SampleAttestedTLS/client/enc/enclave.lds 0 main STP /SampleCode/SampleAttestedTLS/client/enc/openssl_client.cpp /package/SampleCode/SampleAttestedTLS/client/enc/openssl_client.cpp 0 main STP -/SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem /package/SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem 0 main STP /SampleCode/SampleAttestedTLS/client/host/host.cpp /package/SampleCode/SampleAttestedTLS/client/host/host.cpp 0 main STP /SampleCode/SampleAttestedTLS/client/host/Makefile /package/SampleCode/SampleAttestedTLS/client/host/Makefile 0 main STP /SampleCode/SampleAttestedTLS/non_enc_client/client.cpp /package/SampleCode/SampleAttestedTLS/non_enc_client/client.cpp 0 main STP @@ -355,7 +348,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/Cxx11SGXDemo/Enclave/Enclave.h /package/SampleCode/Cxx11SGXDemo/Enclave/Enclave.h 0 main STP /SampleCode/Cxx11SGXDemo/Enclave/Enclave_debug.lds /package/SampleCode/Cxx11SGXDemo/Enclave/Enclave_debug.lds 0 main STP /SampleCode/Cxx11SGXDemo/Enclave/Enclave.lds /package/SampleCode/Cxx11SGXDemo/Enclave/Enclave.lds 0 main STP -/SampleCode/Cxx11SGXDemo/Enclave/Enclave_private_test.pem /package/SampleCode/Cxx11SGXDemo/Enclave/Enclave_private_test.pem 0 main STP /SampleCode/Cxx11SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp /package/SampleCode/Cxx11SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp 0 main STP /SampleCode/Cxx11SGXDemo/Enclave/TrustedLibrary/Libcxx.edl /package/SampleCode/Cxx11SGXDemo/Enclave/TrustedLibrary/Libcxx.edl 0 main STP /SampleCode/Cxx11SGXDemo/Makefile /package/SampleCode/Cxx11SGXDemo/Makefile 0 main STP @@ -372,11 +364,23 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/Cxx14SGXDemo/Enclave/Enclave.h /package/SampleCode/Cxx14SGXDemo/Enclave/Enclave.h 0 main STP /SampleCode/Cxx14SGXDemo/Enclave/Enclave_debug.lds /package/SampleCode/Cxx14SGXDemo/Enclave/Enclave_debug.lds 0 main STP /SampleCode/Cxx14SGXDemo/Enclave/Enclave.lds /package/SampleCode/Cxx14SGXDemo/Enclave/Enclave.lds 0 main STP -/SampleCode/Cxx14SGXDemo/Enclave/Enclave_private_test.pem /package/SampleCode/Cxx14SGXDemo/Enclave/Enclave_private_test.pem 0 main STP /SampleCode/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp /package/SampleCode/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp 0 main STP /SampleCode/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.edl /package/SampleCode/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.edl 0 main STP /SampleCode/Cxx14SGXDemo/Makefile /package/SampleCode/Cxx14SGXDemo/Makefile 0 main STP /SampleCode/Cxx14SGXDemo/README.txt /package/SampleCode/Cxx14SGXDemo/README.txt 0 main STP +/SampleCode/Cxx17SGXDemo/App/App.cpp /package/SampleCode/Cxx17SGXDemo/App/App.cpp 0 main STP +/SampleCode/Cxx17SGXDemo/App/App.h /package/SampleCode/Cxx17SGXDemo/App/App.h 0 main STP +/SampleCode/Cxx17SGXDemo/App/TrustedLibrary/Libcxx.cpp /package/SampleCode/Cxx17SGXDemo/App/TrustedLibrary/Libcxx.cpp 0 main STP +/SampleCode/Cxx17SGXDemo/Enclave/Enclave.config.xml /package/SampleCode/Cxx17SGXDemo/Enclave/Enclave.config.xml 0 main STP +/SampleCode/Cxx17SGXDemo/Enclave/Enclave.cpp /package/SampleCode/Cxx17SGXDemo/Enclave/Enclave.cpp 0 main STP +/SampleCode/Cxx17SGXDemo/Enclave/Enclave.edl /package/SampleCode/Cxx17SGXDemo/Enclave/Enclave.edl 0 main STP +/SampleCode/Cxx17SGXDemo/Enclave/Enclave.h /package/SampleCode/Cxx17SGXDemo/Enclave/Enclave.h 0 main STP +/SampleCode/Cxx17SGXDemo/Enclave/Enclave.lds /package/SampleCode/Cxx17SGXDemo/Enclave/Enclave.lds 0 main STP +/SampleCode/Cxx17SGXDemo/Enclave/Enclave_debug.lds /package/SampleCode/Cxx17SGXDemo/Enclave/Enclave_debug.lds 0 main STP +/SampleCode/Cxx17SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp /package/SampleCode/Cxx17SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp 0 main STP +/SampleCode/Cxx17SGXDemo/Enclave/TrustedLibrary/Libcxx.edl /package/SampleCode/Cxx17SGXDemo/Enclave/TrustedLibrary/Libcxx.edl 0 main STP +/SampleCode/Cxx17SGXDemo/Makefile /package/SampleCode/Cxx17SGXDemo/Makefile 0 main STP +/SampleCode/Cxx17SGXDemo/README.txt /package/SampleCode/Cxx17SGXDemo/README.txt 0 main STP /SampleCode/Switchless/Makefile /package/SampleCode/Switchless/Makefile 0 N/A N/A /SampleCode/Switchless/README.txt /package/SampleCode/Switchless/README.txt 0 N/A N/A /SampleCode/Switchless/App/App.h /package/SampleCode/Switchless/App/App.h 0 N/A N/A @@ -386,7 +390,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/Switchless/Enclave/Enclave.edl /package/SampleCode/Switchless/Enclave/Enclave.edl 0 N/A N/A /SampleCode/Switchless/Enclave/Enclave.lds /package/SampleCode/Switchless/Enclave/Enclave.lds 0 N/A N/A /SampleCode/Switchless/Enclave/Enclave.config.xml /package/SampleCode/Switchless/Enclave/Enclave.config.xml 0 N/A N/A -/SampleCode/Switchless/Enclave/Enclave_private_test.pem /package/SampleCode/Switchless/Enclave/Enclave_private_test.pem 0 N/A N/A /SampleCode/SampleCommonLoader/Makefile /package/SampleCode/SampleCommonLoader/Makefile 0 N/A N/A /SampleCode/SampleCommonLoader/README.txt /package/SampleCode/SampleCommonLoader/README.txt 0 N/A N/A /SampleCode/SampleCommonLoader/App/enclave_entry.S /package/SampleCode/SampleCommonLoader/App/enclave_entry.S 0 N/A N/A @@ -400,7 +403,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/SealUnseal/App/App.cpp /package/SampleCode/SealUnseal/App/App.cpp 0 N/A N/A /SampleCode/SealUnseal/App/ErrorSupport.cpp /package/SampleCode/SealUnseal/App/ErrorSupport.cpp 0 N/A N/A /SampleCode/SealUnseal/App/ErrorSupport.h /package/SampleCode/SealUnseal/App/ErrorSupport.h 0 N/A N/A -/SampleCode/SealUnseal/Enclave_Seal/Enclave_private_test.pem /package/SampleCode/SealUnseal/Enclave_Seal/Enclave_private_test.pem 0 N/A N/A /SampleCode/SealUnseal/Enclave_Seal/Enclave_Seal.config.xml /package/SampleCode/SealUnseal/Enclave_Seal/Enclave_Seal.config.xml 0 N/A N/A /SampleCode/SealUnseal/Enclave_Seal/Enclave_Seal.cpp /package/SampleCode/SealUnseal/Enclave_Seal/Enclave_Seal.cpp 0 N/A N/A /SampleCode/SealUnseal/Enclave_Seal/Enclave_Seal.edl /package/SampleCode/SealUnseal/Enclave_Seal/Enclave_Seal.edl 0 N/A N/A @@ -417,23 +419,81 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/ProtobufSGXDemo/Enclave/Enclave.edl /package/SampleCode/ProtobufSGXDemo/Enclave/Enclave.edl 0 N/A N/A /SampleCode/ProtobufSGXDemo/Enclave/Enclave.h /package/SampleCode/ProtobufSGXDemo/Enclave/Enclave.h 0 N/A N/A /SampleCode/ProtobufSGXDemo/Enclave/Enclave.lds /package/SampleCode/ProtobufSGXDemo/Enclave/Enclave.lds 0 N/A N/A -/SampleCode/ProtobufSGXDemo/Enclave/Enclave_private_test.pem /package/SampleCode/ProtobufSGXDemo/Enclave/Enclave_private_test.pem 0 N/A N/A /SampleCode/ProtobufSGXDemo/Enclave/person.proto /package/SampleCode/ProtobufSGXDemo/Enclave/person.proto 0 N/A N/A /SampleCode/ProtobufSGXDemo/Makefile /package/SampleCode/ProtobufSGXDemo/Makefile 0 N/A N/A /build/linux/gdb-sgx-plugin/sgx-gdb /package/bin/sgx-gdb 0 main STP /sdk/sample_libcrypto/sample_libcrypto.h /package/SampleCode/RemoteAttestation/sample_libcrypto/sample_libcrypto.h 0 main STP +/sdk/tlibcxx/include/CMakeLists.txt /package/include/libcxx/CMakeLists.txt 0 main STP +/sdk/tlibcxx/include/__availability /package/include/libcxx/__availability 0 main STP +/sdk/tlibcxx/include/__bit_reference /package/include/libcxx/__bit_reference 0 main STP +/sdk/tlibcxx/include/__bits /package/include/libcxx/__bits 0 main STP +/sdk/tlibcxx/include/__bsd_locale_defaults.h /package/include/libcxx/__bsd_locale_defaults.h 0 main STP +/sdk/tlibcxx/include/__bsd_locale_fallbacks.h /package/include/libcxx/__bsd_locale_fallbacks.h 0 main STP +/sdk/tlibcxx/include/__config /package/include/libcxx/__config 0 main STP +/sdk/tlibcxx/include/__config_site.in /package/include/libcxx/__config_site.in 0 main STP +/sdk/tlibcxx/include/__debug /package/include/libcxx/__debug 0 main STP +/sdk/tlibcxx/include/__errc /package/include/libcxx/__errc 0 main STP +/sdk/tlibcxx/include/__functional_03 /package/include/libcxx/__functional_03 0 main STP +/sdk/tlibcxx/include/__functional_base /package/include/libcxx/__functional_base 0 main STP +/sdk/tlibcxx/include/__functional_base_03 /package/include/libcxx/__functional_base_03 0 main STP +/sdk/tlibcxx/include/__hash_table /package/include/libcxx/__hash_table 0 main STP +/sdk/tlibcxx/include/__libcpp_version /package/include/libcxx/__libcpp_version 0 main STP +/sdk/tlibcxx/include/__locale /package/include/libcxx/__locale 0 main STP +/sdk/tlibcxx/include/__memory/allocator_traits.h /package/include/libcxx/__memory/allocator_traits.h 0 main STP +/sdk/tlibcxx/include/__memory/base.h /package/include/libcxx/__memory/base.h 0 main STP +/sdk/tlibcxx/include/__memory/pointer_traits.h /package/include/libcxx/__memory/pointer_traits.h 0 main STP +/sdk/tlibcxx/include/__memory/utilities.h /package/include/libcxx/__memory/utilities.h 0 main STP +/sdk/tlibcxx/include/__mutex_base /package/include/libcxx/__mutex_base 0 main STP +/sdk/tlibcxx/include/__node_handle /package/include/libcxx/__node_handle 0 main STP +/sdk/tlibcxx/include/__nullptr /package/include/libcxx/__nullptr 0 main STP +/sdk/tlibcxx/include/__sgx /package/include/libcxx/__sgx 0 main STP +/sdk/tlibcxx/include/__split_buffer /package/include/libcxx/__split_buffer 0 main STP +/sdk/tlibcxx/include/__sso_allocator /package/include/libcxx/__sso_allocator 0 main STP +/sdk/tlibcxx/include/__std_stream /package/include/libcxx/__std_stream 0 main STP +/sdk/tlibcxx/include/__string /package/include/libcxx/__string 0 main STP +/sdk/tlibcxx/include/__support/android/locale_bionic.h /package/include/libcxx/__support/android/locale_bionic.h 0 main STP +/sdk/tlibcxx/include/__support/fuchsia/xlocale.h /package/include/libcxx/__support/fuchsia/xlocale.h 0 main STP +/sdk/tlibcxx/include/__support/ibm/limits.h /package/include/libcxx/__support/ibm/limits.h 0 main STP +/sdk/tlibcxx/include/__support/ibm/locale_mgmt_aix.h /package/include/libcxx/__support/ibm/locale_mgmt_aix.h 0 main STP +/sdk/tlibcxx/include/__support/ibm/nanosleep.h /package/include/libcxx/__support/ibm/nanosleep.h 0 main STP +/sdk/tlibcxx/include/__support/ibm/support.h /package/include/libcxx/__support/ibm/support.h 0 main STP +/sdk/tlibcxx/include/__support/ibm/xlocale.h /package/include/libcxx/__support/ibm/xlocale.h 0 main STP +/sdk/tlibcxx/include/__support/musl/xlocale.h /package/include/libcxx/__support/musl/xlocale.h 0 main STP +/sdk/tlibcxx/include/__support/newlib/xlocale.h /package/include/libcxx/__support/newlib/xlocale.h 0 main STP +/sdk/tlibcxx/include/__support/nuttx/xlocale.h /package/include/libcxx/__support/nuttx/xlocale.h 0 main STP +/sdk/tlibcxx/include/__support/openbsd/xlocale.h /package/include/libcxx/__support/openbsd/xlocale.h 0 main STP +/sdk/tlibcxx/include/__support/sgx/__sgx_mutex_base /package/include/libcxx/__support/sgx/__sgx_mutex_base 0 main STP +/sdk/tlibcxx/include/__support/sgx/sgx_condition_variable /package/include/libcxx/__support/sgx/sgx_condition_variable 0 main STP +/sdk/tlibcxx/include/__support/sgx/sgx_invoke /package/include/libcxx/__support/sgx/sgx_invoke 0 main STP +/sdk/tlibcxx/include/__support/sgx/sgx_mutex /package/include/libcxx/__support/sgx/sgx_mutex 0 main STP +/sdk/tlibcxx/include/__support/sgx/support.h /package/include/libcxx/__support/sgx/support.h 0 main STP +/sdk/tlibcxx/include/__support/sgx/xlocale.h /package/include/libcxx/__support/sgx/xlocale.h 0 main STP +/sdk/tlibcxx/include/__support/solaris/floatingpoint.h /package/include/libcxx/__support/solaris/floatingpoint.h 0 main STP +/sdk/tlibcxx/include/__support/solaris/wchar.h /package/include/libcxx/__support/solaris/wchar.h 0 main STP +/sdk/tlibcxx/include/__support/solaris/xlocale.h /package/include/libcxx/__support/solaris/xlocale.h 0 main STP +/sdk/tlibcxx/include/__support/win32/limits_msvc_win32.h /package/include/libcxx/__support/win32/limits_msvc_win32.h 0 main STP +/sdk/tlibcxx/include/__support/win32/locale_win32.h /package/include/libcxx/__support/win32/locale_win32.h 0 main STP +/sdk/tlibcxx/include/__support/xlocale/__nop_locale_mgmt.h /package/include/libcxx/__support/xlocale/__nop_locale_mgmt.h 0 main STP +/sdk/tlibcxx/include/__support/xlocale/__posix_l_fallback.h /package/include/libcxx/__support/xlocale/__posix_l_fallback.h 0 main STP +/sdk/tlibcxx/include/__support/xlocale/__strtonum_fallback.h /package/include/libcxx/__support/xlocale/__strtonum_fallback.h 0 main STP +/sdk/tlibcxx/include/__threading_support /package/include/libcxx/__threading_support 0 main STP +/sdk/tlibcxx/include/__tree /package/include/libcxx/__tree 0 main STP +/sdk/tlibcxx/include/__tuple /package/include/libcxx/__tuple 0 main STP +/sdk/tlibcxx/include/__undef_macros /package/include/libcxx/__undef_macros 0 main STP /sdk/tlibcxx/include/algorithm /package/include/libcxx/algorithm 0 main STP +/sdk/tlibcxx/include/any /package/include/libcxx/any 0 main STP /sdk/tlibcxx/include/array /package/include/libcxx/array 0 main STP /sdk/tlibcxx/include/atomic /package/include/libcxx/atomic 0 main STP -/sdk/tlibcxx/include/__bit_reference /package/include/libcxx/__bit_reference 0 main STP +/sdk/tlibcxx/include/barrier /package/include/libcxx/barrier 0 main STP +/sdk/tlibcxx/include/bit /package/include/libcxx/bit 0 main STP /sdk/tlibcxx/include/bitset /package/include/libcxx/bitset 0 main STP -/sdk/tlibcxx/include/__bsd_locale_fallbacks.h /package/include/libcxx/__bsd_locale_fallbacks.h 0 main STP /sdk/tlibcxx/include/cassert /package/include/libcxx/cassert 0 main STP /sdk/tlibcxx/include/ccomplex /package/include/libcxx/ccomplex 0 main STP /sdk/tlibcxx/include/cctype /package/include/libcxx/cctype 0 main STP /sdk/tlibcxx/include/cerrno /package/include/libcxx/cerrno 0 main STP /sdk/tlibcxx/include/cfenv /package/include/libcxx/cfenv 0 main STP /sdk/tlibcxx/include/cfloat /package/include/libcxx/cfloat 0 main STP +/sdk/tlibcxx/include/charconv /package/include/libcxx/charconv 0 main STP /sdk/tlibcxx/include/chrono /package/include/libcxx/chrono 0 main STP /sdk/tlibcxx/include/cinttypes /package/include/libcxx/cinttypes 0 main STP /sdk/tlibcxx/include/ciso646 /package/include/libcxx/ciso646 0 main STP @@ -441,10 +501,11 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /sdk/tlibcxx/include/clocale /package/include/libcxx/clocale 0 main STP /sdk/tlibcxx/include/cmath /package/include/libcxx/cmath 0 main STP /sdk/tlibcxx/include/codecvt /package/include/libcxx/codecvt 0 main STP +/sdk/tlibcxx/include/compare /package/include/libcxx/compare 0 main STP /sdk/tlibcxx/include/complex /package/include/libcxx/complex 0 main STP /sdk/tlibcxx/include/complex.h /package/include/libcxx/complex.h 0 main STP +/sdk/tlibcxx/include/concepts /package/include/libcxx/concepts 0 main STP /sdk/tlibcxx/include/condition_variable /package/include/libcxx/condition_variable 0 main STP -/sdk/tlibcxx/include/__config /package/include/libcxx/__config 0 main STP /sdk/tlibcxx/include/csetjmp /package/include/libcxx/csetjmp 0 main STP /sdk/tlibcxx/include/csignal /package/include/libcxx/csignal 0 main STP /sdk/tlibcxx/include/cstdarg /package/include/libcxx/cstdarg 0 main STP @@ -458,32 +519,26 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /sdk/tlibcxx/include/ctime /package/include/libcxx/ctime 0 main STP /sdk/tlibcxx/include/cwchar /package/include/libcxx/cwchar 0 main STP /sdk/tlibcxx/include/cwctype /package/include/libcxx/cwctype 0 main STP -/sdk/tlibcxx/include/__debug /package/include/libcxx/__debug 0 main STP /sdk/tlibcxx/include/deque /package/include/libcxx/deque 0 main STP /sdk/tlibcxx/include/exception /package/include/libcxx/exception 0 main STP -/sdk/tlibcxx/include/experimental/algorithm /package/include/libcxx/experimental/algorithm 0 main STP -/sdk/tlibcxx/include/experimental/any /package/include/libcxx/experimental/any 0 main STP -/sdk/tlibcxx/include/experimental/chrono /package/include/libcxx/experimental/chrono 0 main STP +/sdk/tlibcxx/include/execution /package/include/libcxx/execution 0 main STP /sdk/tlibcxx/include/experimental/__config /package/include/libcxx/experimental/__config 0 main STP +/sdk/tlibcxx/include/experimental/__memory /package/include/libcxx/experimental/__memory 0 main STP +/sdk/tlibcxx/include/experimental/algorithm /package/include/libcxx/experimental/algorithm 0 main STP +/sdk/tlibcxx/include/experimental/coroutine /package/include/libcxx/experimental/coroutine 0 main STP /sdk/tlibcxx/include/experimental/deque /package/include/libcxx/experimental/deque 0 main STP -/sdk/tlibcxx/include/experimental/dynarray /package/include/libcxx/experimental/dynarray 0 main STP /sdk/tlibcxx/include/experimental/filesystem /package/include/libcxx/experimental/filesystem 0 main STP /sdk/tlibcxx/include/experimental/forward_list /package/include/libcxx/experimental/forward_list 0 main STP /sdk/tlibcxx/include/experimental/functional /package/include/libcxx/experimental/functional 0 main STP /sdk/tlibcxx/include/experimental/iterator /package/include/libcxx/experimental/iterator 0 main STP /sdk/tlibcxx/include/experimental/list /package/include/libcxx/experimental/list 0 main STP /sdk/tlibcxx/include/experimental/map /package/include/libcxx/experimental/map 0 main STP -/sdk/tlibcxx/include/experimental/__memory /package/include/libcxx/experimental/__memory 0 main STP /sdk/tlibcxx/include/experimental/memory_resource /package/include/libcxx/experimental/memory_resource 0 main STP -/sdk/tlibcxx/include/experimental/optional /package/include/libcxx/experimental/optional 0 main STP /sdk/tlibcxx/include/experimental/propagate_const /package/include/libcxx/experimental/propagate_const 0 main STP -/sdk/tlibcxx/include/experimental/ratio /package/include/libcxx/experimental/ratio 0 main STP /sdk/tlibcxx/include/experimental/regex /package/include/libcxx/experimental/regex 0 main STP /sdk/tlibcxx/include/experimental/set /package/include/libcxx/experimental/set 0 main STP +/sdk/tlibcxx/include/experimental/simd /package/include/libcxx/experimental/simd 0 main STP /sdk/tlibcxx/include/experimental/string /package/include/libcxx/experimental/string 0 main STP -/sdk/tlibcxx/include/experimental/string_view /package/include/libcxx/experimental/string_view 0 main STP -/sdk/tlibcxx/include/experimental/system_error /package/include/libcxx/experimental/system_error 0 main STP -/sdk/tlibcxx/include/experimental/tuple /package/include/libcxx/experimental/tuple 0 main STP /sdk/tlibcxx/include/experimental/type_traits /package/include/libcxx/experimental/type_traits 0 main STP /sdk/tlibcxx/include/experimental/unordered_map /package/include/libcxx/experimental/unordered_map 0 main STP /sdk/tlibcxx/include/experimental/unordered_set /package/include/libcxx/experimental/unordered_set 0 main STP @@ -492,14 +547,12 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /sdk/tlibcxx/include/ext/__hash /package/include/libcxx/ext/__hash 0 main STP /sdk/tlibcxx/include/ext/hash_map /package/include/libcxx/ext/hash_map 0 main STP /sdk/tlibcxx/include/ext/hash_set /package/include/libcxx/ext/hash_set 0 main STP +/sdk/tlibcxx/include/fenv.h /package/include/libcxx/fenv.h 0 main STP +/sdk/tlibcxx/include/filesystem /package/include/libcxx/filesystem 0 main STP /sdk/tlibcxx/include/forward_list /package/include/libcxx/forward_list 0 main STP /sdk/tlibcxx/include/fstream /package/include/libcxx/fstream 0 main STP /sdk/tlibcxx/include/functional /package/include/libcxx/functional 0 main STP -/sdk/tlibcxx/include/__functional_03 /package/include/libcxx/__functional_03 0 main STP -/sdk/tlibcxx/include/__functional_base /package/include/libcxx/__functional_base 0 main STP -/sdk/tlibcxx/include/__functional_base_03 /package/include/libcxx/__functional_base_03 0 main STP /sdk/tlibcxx/include/future /package/include/libcxx/future 0 main STP -/sdk/tlibcxx/include/__hash_table /package/include/libcxx/__hash_table 0 main STP /sdk/tlibcxx/include/initializer_list /package/include/libcxx/initializer_list 0 main STP /sdk/tlibcxx/include/inttypes.h /package/include/libcxx/inttypes.h 0 main STP /sdk/tlibcxx/include/iomanip /package/include/libcxx/iomanip 0 main STP @@ -508,63 +561,52 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /sdk/tlibcxx/include/iostream /package/include/libcxx/iostream 0 main STP /sdk/tlibcxx/include/istream /package/include/libcxx/istream 0 main STP /sdk/tlibcxx/include/iterator /package/include/libcxx/iterator 0 main STP +/sdk/tlibcxx/include/latch /package/include/libcxx/latch 0 main STP /sdk/tlibcxx/include/limits /package/include/libcxx/limits 0 main STP /sdk/tlibcxx/include/list /package/include/libcxx/list 0 main STP /sdk/tlibcxx/include/locale /package/include/libcxx/locale 0 main STP -/sdk/tlibcxx/include/__locale /package/include/libcxx/__locale 0 main STP +/sdk/tlibcxx/include/locale.h /package/include/libcxx/locale.h 0 main STP /sdk/tlibcxx/include/map /package/include/libcxx/map 0 main STP /sdk/tlibcxx/include/memory /package/include/libcxx/memory 0 main STP +/sdk/tlibcxx/include/module.modulemap /package/include/libcxx/module.modulemap 0 main STP /sdk/tlibcxx/include/mutex /package/include/libcxx/mutex 0 main STP -/sdk/tlibcxx/include/__mutex_base /package/include/libcxx/__mutex_base 0 main STP /sdk/tlibcxx/include/new /package/include/libcxx/new 0 main STP -/sdk/tlibcxx/include/__nullptr /package/include/libcxx/__nullptr 0 main STP +/sdk/tlibcxx/include/numbers /package/include/libcxx/numbers 0 main STP /sdk/tlibcxx/include/numeric /package/include/libcxx/numeric 0 main STP +/sdk/tlibcxx/include/optional /package/include/libcxx/optional 0 main STP /sdk/tlibcxx/include/ostream /package/include/libcxx/ostream 0 main STP /sdk/tlibcxx/include/queue /package/include/libcxx/queue 0 main STP /sdk/tlibcxx/include/random /package/include/libcxx/random 0 main STP /sdk/tlibcxx/include/ratio /package/include/libcxx/ratio 0 main STP -/sdk/tlibcxx/include/__refstring /package/include/libcxx/__refstring 0 main STP /sdk/tlibcxx/include/regex /package/include/libcxx/regex 0 main STP /sdk/tlibcxx/include/scoped_allocator /package/include/libcxx/scoped_allocator 0 main STP +/sdk/tlibcxx/include/semaphore /package/include/libcxx/semaphore 0 main STP /sdk/tlibcxx/include/set /package/include/libcxx/set 0 main STP -/sdk/tlibcxx/include/__sgx /package/include/libcxx/__sgx 0 main STP /sdk/tlibcxx/include/shared_mutex /package/include/libcxx/shared_mutex 0 main STP -/sdk/tlibcxx/include/__split_buffer /package/include/libcxx/__split_buffer 0 main STP -/sdk/tlibcxx/include/__sso_allocator /package/include/libcxx/__sso_allocator 0 main STP +/sdk/tlibcxx/include/span /package/include/libcxx/span 0 main STP /sdk/tlibcxx/include/sstream /package/include/libcxx/sstream 0 main STP /sdk/tlibcxx/include/stack /package/include/libcxx/stack 0 main STP /sdk/tlibcxx/include/stdbool.h /package/include/libcxx/stdbool.h 0 main STP /sdk/tlibcxx/include/stdexcept /package/include/libcxx/stdexcept 0 main STP -/sdk/tlibcxx/include/__std_stream /package/include/libcxx/__std_stream 0 main STP +/sdk/tlibcxx/include/stdint.h /package/include/libcxx/stdint.h 0 main STP /sdk/tlibcxx/include/streambuf /package/include/libcxx/streambuf 0 main STP /sdk/tlibcxx/include/string /package/include/libcxx/string 0 main STP +/sdk/tlibcxx/include/string_view /package/include/libcxx/string_view 0 main STP /sdk/tlibcxx/include/strstream /package/include/libcxx/strstream 0 main STP -/sdk/tlibcxx/include/support/sgx/sgx_condition_variable /package/include/libcxx/support/sgx/sgx_condition_variable 0 main STP -/sdk/tlibcxx/include/support/sgx/sgx_invoke /package/include/libcxx/support/sgx/sgx_invoke 0 main STP -/sdk/tlibcxx/include/support/sgx/sgx_mutex /package/include/libcxx/support/sgx/sgx_mutex 0 main STP -/sdk/tlibcxx/include/support/sgx/__sgx_mutex_base /package/include/libcxx/support/sgx/__sgx_mutex_base 0 main STP -/sdk/tlibcxx/include/support/sgx/xlocale.h /package/include/libcxx/support/sgx/xlocale.h 0 main STP -/sdk/tlibcxx/include/support/sgx/support.h /package/include/libcxx/support/sgx/support.h 0 main STP -/sdk/tlibcxx/include/support/xlocale/__nop_locale_mgmt.h /package/include/libcxx/support/xlocale/__nop_locale_mgmt.h 0 main STP -/sdk/tlibcxx/include/support/xlocale/__posix_l_fallback.h /package/include/libcxx/support/xlocale/__posix_l_fallback.h 0 main STP -/sdk/tlibcxx/include/support/xlocale/__strtonum_fallback.h /package/include/libcxx/support/xlocale/__strtonum_fallback.h 0 main STP /sdk/tlibcxx/include/system_error /package/include/libcxx/system_error 0 main STP /sdk/tlibcxx/include/tgmath.h /package/include/libcxx/tgmath.h 0 main STP /sdk/tlibcxx/include/thread /package/include/libcxx/thread 0 main STP -/sdk/tlibcxx/include/__threading_support /package/include/libcxx/__threading_support 0 main STP -/sdk/tlibcxx/include/__tree /package/include/libcxx/__tree 0 main STP /sdk/tlibcxx/include/tuple /package/include/libcxx/tuple 0 main STP -/sdk/tlibcxx/include/__tuple /package/include/libcxx/__tuple 0 main STP +/sdk/tlibcxx/include/type_traits /package/include/libcxx/type_traits 0 main STP /sdk/tlibcxx/include/typeindex /package/include/libcxx/typeindex 0 main STP /sdk/tlibcxx/include/typeinfo /package/include/libcxx/typeinfo 0 main STP -/sdk/tlibcxx/include/type_traits /package/include/libcxx/type_traits 0 main STP -/sdk/tlibcxx/include/__undef___deallocate /package/include/libcxx/__undef___deallocate 0 main STP -/sdk/tlibcxx/include/__undef_min_max /package/include/libcxx/__undef_min_max 0 main STP /sdk/tlibcxx/include/unordered_map /package/include/libcxx/unordered_map 0 main STP /sdk/tlibcxx/include/unordered_set /package/include/libcxx/unordered_set 0 main STP /sdk/tlibcxx/include/utility /package/include/libcxx/utility 0 main STP /sdk/tlibcxx/include/valarray /package/include/libcxx/valarray 0 main STP +/sdk/tlibcxx/include/variant /package/include/libcxx/variant 0 main STP /sdk/tlibcxx/include/vector /package/include/libcxx/vector 0 main STP +/sdk/tlibcxx/include/version /package/include/libcxx/version 0 main STP /external/protobuf/protobuf_code/src/google/protobuf/arenaz_sampler.h /package/include/tprotobuf/google/protobuf/arenaz_sampler.h 0 main STP /external/protobuf/protobuf_code/src/google/protobuf/inlined_string_field.h /package/include/tprotobuf/google/protobuf/inlined_string_field.h 0 main STP /external/protobuf/protobuf_code/src/google/protobuf/repeated_ptr_field.h /package/include/tprotobuf/google/protobuf/repeated_ptr_field.h 0 main STP diff --git a/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_cf.txt b/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_cf.txt index 918220f7..865b6bf1 100644 --- a/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_cf.txt +++ b/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_cf.txt @@ -15,6 +15,7 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /build/linuxCF/libsgx_pthread.a /package/lib64/cve_2020_0551_cf/libsgx_pthread.a 0 main STP /build/linuxCF/libsgx_protobuf.a /package/lib64/cve_2020_0551_cf/libsgx_protobuf.a 0 main STP /build/linuxCF/libsgx_ttls.a /package/lib64/cve_2020_0551_cf/libsgx_ttls.a 0 main STP +/build/linuxCF/libtdx_tls.a /package/lib64/cve_2020_0551_cf/libtdx_tls.a 0 main STP /build/linuxCF/libsgx_utls.a /package/lib64/cve_2020_0551_cf/libsgx_utls.a 0 main STP /build/linuxCF/libsgx_z.a /package/lib64/cve_2020_0551_cf/libsgx_z.a 0 main STP /external/dcap_source/QuoteGeneration/build/linuxCF/libsgx_dcap_tvl.a /package/lib64/cve_2020_0551_cf/libsgx_dcap_tvl.a 0 main STP diff --git a/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_load.txt b/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_load.txt index f6ec4b27..b6f2a869 100644 --- a/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_load.txt +++ b/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_load.txt @@ -15,6 +15,7 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /build/linuxLOAD/libsgx_pthread.a /package/lib64/cve_2020_0551_load/libsgx_pthread.a 0 main STP /build/linuxLOAD/libsgx_protobuf.a /package/lib64/cve_2020_0551_load/libsgx_protobuf.a 0 main STP /build/linuxLOAD/libsgx_ttls.a /package/lib64/cve_2020_0551_load/libsgx_ttls.a 0 main STP +/build/linuxLOAD/libtdx_tls.a /package/lib64/cve_2020_0551_load/libtdx_tls.a 0 main STP /build/linuxLOAD/libsgx_utls.a /package/lib64/cve_2020_0551_load/libsgx_utls.a 0 main STP /build/linuxLOAD/libsgx_z.a /package/lib64/cve_2020_0551_load/libsgx_z.a 0 main STP /external/dcap_source/QuoteGeneration/build/linuxLOAD/libsgx_dcap_tvl.a /package/lib64/cve_2020_0551_load/libsgx_dcap_tvl.a 0 main STP diff --git a/linux/installer/common/sdk/BOMs/sdk_x64.txt b/linux/installer/common/sdk/BOMs/sdk_x64.txt index 474495cc..dbf14e71 100644 --- a/linux/installer/common/sdk/BOMs/sdk_x64.txt +++ b/linux/installer/common/sdk/BOMs/sdk_x64.txt @@ -46,6 +46,7 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /build/linux/libsgx_omp.a /package/lib64/libsgx_omp.a 0 main STP /build/linux/libsgx_protobuf.a /package/lib64/libsgx_protobuf.a 0 main STP /build/linux/libsgx_ttls.a /package/lib64/libsgx_ttls.a 0 main STP +/build/linux/libtdx_tls.a /package/lib64/libtdx_tls.a 0 main STP /build/linux/libsgx_utls.a /package/lib64/libsgx_utls.a 0 main STP /build/linux/libsgx_z.a /package/lib64/libsgx_z.a 0 main STP /external/dcap_source/QuoteGeneration/build/linux/libsgx_dcap_tvl.a /package/lib64/libsgx_dcap_tvl.a 0 main STP diff --git a/linux/installer/deb/libsgx-enclave-common/libsgx-enclave-common-1.0/debian/control b/linux/installer/deb/libsgx-enclave-common/libsgx-enclave-common-1.0/debian/control index d0e45043..80d6e54f 100644 --- a/linux/installer/deb/libsgx-enclave-common/libsgx-enclave-common-1.0/debian/control +++ b/linux/installer/deb/libsgx-enclave-common/libsgx-enclave-common-1.0/debian/control @@ -2,7 +2,7 @@ Source: libsgx-enclave-common Section: libs Priority: optional Maintainer: -Build-Depends: debhelper (>= 8.0.0) +Build-Depends: debhelper (>= 8.0.0), libsystemd0 Standards-Version: 3.9.4 Homepage: https://github.com/intel/linux-sgx diff --git a/linux/installer/deb/local_repo_tool/conf/distributions b/linux/installer/deb/local_repo_tool/conf/distributions index 2f9137fc..ace56a94 100644 --- a/linux/installer/deb/local_repo_tool/conf/distributions +++ b/linux/installer/deb/local_repo_tool/conf/distributions @@ -29,3 +29,19 @@ Architectures: amd64 Components: main Description: ubuntu/hirsute repository for SGX PSW DebIndices: Packages . + +Origin: Intel Corporation +Label: Intel Corporation +Codename: jammy +Architectures: amd64 +Components: main +Description: ubuntu/jammy repository for SGX PSW +DebIndices: Packages . + +Origin: Intel Corporation +Label: Intel Corporation +Codename: buster +Architectures: amd64 +Components: main +Description: debian/buster repository for SGX PSW +DebIndices: Packages . diff --git a/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/control b/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/control index 82a2768a..49948db4 100644 --- a/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/control +++ b/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/control @@ -37,12 +37,12 @@ Description: Unified Quote Plugin for Intel(R) Software Guard Extensions AESM Se Package: libsgx-aesm-ecdsa-plugin Architecture: amd64 -Depends: ${shlibs:Depends}, ${misc:Depends}, sgx-aesm-service(>= @dep_version@), libsgx-qe3-logic(>= 1.14), libsgx-aesm-pce-plugin(>= @dep_version@) +Depends: ${shlibs:Depends}, ${misc:Depends}, sgx-aesm-service(>= @dep_version@), libsgx-qe3-logic(>= 1.15), libsgx-aesm-pce-plugin(>= @dep_version@) Description: ECDSA Quote Plugin for Intel(R) Software Guard Extensions AESM Service Package: libsgx-aesm-pce-plugin Architecture: amd64 -Depends: ${shlibs:Depends}, ${misc:Depends}, sgx-aesm-service(>= @dep_version@), libsgx-pce-logic(>= 1.14), libsgx-ae-pce(>= @dep_version@) +Depends: ${shlibs:Depends}, ${misc:Depends}, sgx-aesm-service(>= @dep_version@), libsgx-pce-logic(>= 1.15), libsgx-ae-pce(>= @dep_version@) Description: PCE Plugin for Intel(R) Software Guard Extensions AESM Service Package: libsgx-ae-pce diff --git a/linux/installer/rpm/libsgx-enclave-common/libsgx-enclave-common.spec b/linux/installer/rpm/libsgx-enclave-common/libsgx-enclave-common.spec index ca7f7862..6d813f81 100644 --- a/linux/installer/rpm/libsgx-enclave-common/libsgx-enclave-common.spec +++ b/linux/installer/rpm/libsgx-enclave-common/libsgx-enclave-common.spec @@ -36,6 +36,11 @@ Version: @version@ Release: 1%{?dist} Summary: Intel(R) Software Guard Extensions Enclave Common Loader Group: Development/Libraries +%if 0%{?suse_version} +BuildRequires: libsystemd0 +%else +BuildRequires: systemd-libs +%endif Recommends: libsgx-launch >= %{version}-%{release} License: BSD License diff --git a/linux/installer/rpm/psw-dcap/psw-dcap.spec.tmpl b/linux/installer/rpm/psw-dcap/psw-dcap.spec.tmpl index 627ca3b3..c7ba4c12 100644 --- a/linux/installer/rpm/psw-dcap/psw-dcap.spec.tmpl +++ b/linux/installer/rpm/psw-dcap/psw-dcap.spec.tmpl @@ -1,37 +1,5 @@ -#!/usr/bin/env bash # -# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Intel Corporation nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# - -# -# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. +# Copyright (C) 2011-2022 Intel Corporation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions @@ -94,7 +62,7 @@ BuildRequires: openssl-devel BuildRequires: protobuf-compiler BuildRequires: protobuf-devel BuildRequires: libcurl-devel -BuildRequires: python +BuildRequires: python2 BuildRequires: perl BuildRequires: nasm @@ -473,19 +441,19 @@ make clean %files -n sgx-ra-service -f %{_specdir}/list-sgx-ra-service %files -n sgx-pck-id-retrieval-tool -f %{_specdir}/list-sgx-pck-id-retrieval-tool -%post +%posttrans if [ -x %{_aesm_service_path}/startup.sh ]; then %{_aesm_service_path}/startup.sh; fi %preun if [ -x %{_aesm_service_path}/cleanup.sh ]; then %{_aesm_service_path}/cleanup.sh; fi -%post -n sgx-dcap-pccs +%posttrans -n sgx-dcap-pccs if [ -x %{_dcap_pccs_path}/startup.sh ]; then %{_dcap_pccs_path}/startup.sh; fi %preun -n sgx-dcap-pccs if [ -x %{_dcap_pccs_path}/cleanup.sh ]; then %{_dcap_pccs_path}/cleanup.sh; fi -%post -n sgx-ra-service +%posttrans -n sgx-ra-service if [ -x %{_ra_service_path}/startup.sh ]; then %{_ra_service_path}/startup.sh; fi %preun -n sgx-ra-service diff --git a/linux/installer/rpm/psw-tdx/build.sh b/linux/installer/rpm/psw-tdx/build.sh new file mode 100755 index 00000000..f42d6bd2 --- /dev/null +++ b/linux/installer/rpm/psw-tdx/build.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# +# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# + + +set -e + +psw_tdx="psw-tdx" + +cur_dir=$(dirname "$0") +root_dir="${cur_dir}/../../../../" +dcap_dir="${root_dir}/external/dcap_source" +common_dir="${root_dir}/linux/installer/common" +common_psw_tdx_dir="${common_dir}/${psw_tdx}" + +psw_version=$(awk '/STRFILEVER/ {print substr($3, 2, length($3) - 2);}' \ + ${root_dir}/common/inc/internal/se_version.h) +dcap_version=$(awk '/STRFILEVER/ {print substr($3, 2, length($3) - 2);}' \ + ${dcap_dir}/QuoteGeneration/common/inc/internal/se_version.h) +rpm_build_dir=${psw_tdx}-${dcap_version} + +source ${common_psw_tdx_dir}/installConfig + +pre_build() { + rm -fr ${cur_dir}/${rpm_build_dir} + mkdir -p ${cur_dir}/${rpm_build_dir}/{BUILD,RPMS,SOURCES,SPECS,SRPMS} +} + +update_spec() { + local min_version="4.12" + local rpm_version=$(rpmbuild --version 2> /dev/null | awk '{print $NF}') + local cur_version=$(echo -e "${rpm_version}\n${min_version}" | sort -V | head -n 1) + + sed -e "s:@psw_version@:${psw_version}:" \ + -e "s:@dcap_version@:${dcap_version}:" \ + -e "s:@tdx_qgs_path@:${SGX_INSTALL_PATH}/${TDX_QGS_PACKAGE}:" \ + -e "s:@ra_service_path@:${SGX_INSTALL_PATH}/${RA_SERVICE_PACKAGE}:" \ + -e "s:@dcap_pccs_path@:${SGX_INSTALL_PATH}/${DCAP_PCCS_PACKAGE}:" \ + -e "s:@pck_id_retrieval_tool_path@:${SGX_INSTALL_PATH}/${PCK_ID_RETRIEVAL_TOOL_PACKAGE}:" \ + ${cur_dir}/${psw_tdx}.spec.tmpl > ${cur_dir}/${rpm_build_dir}/SPECS/${psw_tdx}.spec + + if [ "${min_version}" != "${cur_version}" ]; then + sed -i "s/^Recommends:/Requires: /" ${cur_dir}/${rpm_build_dir}/SPECS/${psw_tdx}.spec + fi +} + +create_upstream_tarball() { + tar -zcvf ${cur_dir}/${rpm_build_dir}/SOURCES/${psw_tdx}-${dcap_version}.tar.gz \ + --exclude=$(realpath --relative-to=${root_dir} ${cur_dir}) \ + --directory=${root_dir} $(ls ${root_dir}) +} + +build_package() { + pushd ${cur_dir}/${rpm_build_dir} &> /dev/null + rpmbuild --define="_topdir `pwd`" -ba SPECS/${psw_tdx}.spec + popd &> /dev/null +} + +post_build() { + cp -f ${cur_dir}/${rpm_build_dir}/RPMS/**/*.rpm ${cur_dir} + cp -f ${cur_dir}/${rpm_build_dir}/SRPMS/*.rpm ${cur_dir} + cp -f ${cur_dir}/${rpm_build_dir}/SOURCES/*.tar.gz ${cur_dir} + cp -f ${cur_dir}/${rpm_build_dir}/SPECS/${psw_tdx}.spec ${cur_dir}/${psw_tdx}.spec.in + rm -fr ${cur_dir}/${rpm_build_dir} +} + +main() { + pre_build + update_spec + create_upstream_tarball + build_package + post_build +} + +main $@ diff --git a/docker/build/build_and_run_sample_deb_docker.sh b/linux/installer/rpm/psw-tdx/clean.sh similarity index 74% rename from docker/build/build_and_run_sample_deb_docker.sh rename to linux/installer/rpm/psw-tdx/clean.sh index 47819186..bf674ae4 100755 --- a/docker/build/build_and_run_sample_deb_docker.sh +++ b/linux/installer/rpm/psw-tdx/clean.sh @@ -1,6 +1,6 @@ -#!/bin/sh +#!/usr/bin/env bash # -# Copyright (C) 2022 Intel Corporation. All rights reserved. +# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions @@ -28,11 +28,9 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # +# + set -e -docker build --target sample_deb --build-arg https_proxy=$https_proxy \ - --build-arg http_proxy=$http_proxy -t sgx_sample_deb -f ./Dockerfile ../../ -# Another container should expose AESM and its socket in aesmd-socket volume. -# Replace /dev/sgx/enclave with /dev/isgx if you use the Legacy Launch Control driver -docker run --env http_proxy --env https_proxy --device=/dev/sgx/enclave -v aesmd-socket:/var/run/aesmd -it sgx_sample_deb +rm -f $(dirname "$0")/{*.rpm,*.tar.gz,*.spec.in} diff --git a/linux/installer/rpm/psw-tdx/psw-tdx.spec.tmpl b/linux/installer/rpm/psw-tdx/psw-tdx.spec.tmpl new file mode 100644 index 00000000..0dd5fd8c --- /dev/null +++ b/linux/installer/rpm/psw-tdx/psw-tdx.spec.tmpl @@ -0,0 +1,372 @@ +# +# Copyright (C) 2011-2022 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# + +%define _tdx_qgs_path @tdx_qgs_path@ +%define _ra_service_path @ra_service_path@ +%define _dcap_pccs_path @dcap_pccs_path@ +%define _pck_id_retrieval_tool_path @pck_id_retrieval_tool_path@ +%define _psw_version @psw_version@ +%define _dcap_version @dcap_version@ +%define _license_file COPYING + +Name: tdx-qgs +Version: %{_dcap_version} +Release: 1%{?dist} +Summary: Intel(R) TD Quoting Generation Service + +License: BSD and MIT and Apache and GPL and BSD/GPLv2 dual and zlib/libpng and Eclipse Public License-v1.0 and Open Source and OpenSSL +URL: https://github.com/intel/linux-sgx +Source0: psw-tdx-%{version}.tar.gz + +BuildRequires: autoconf +BuildRequires: automake +BuildRequires: binutils +BuildRequires: libtool +BuildRequires: gcc +BuildRequires: gcc-c++ +BuildRequires: make +BuildRequires: cmake +BuildRequires: ocaml +BuildRequires: ocaml-ocamlbuild +BuildRequires: redhat-rpm-config +BuildRequires: openssl +BuildRequires: openssl-devel +BuildRequires: protobuf-compiler +BuildRequires: protobuf-devel +BuildRequires: libcurl-devel +BuildRequires: python2 +BuildRequires: perl +BuildRequires: nasm + +%description +Intel(R) Intel(R) TD Quoting Generation Service + +%package -n libsgx-ae-pce +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions PCE + +%description -n libsgx-ae-pce +Intel(R) Software Guard Extensions PCE + +%package -n libsgx-headers +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Basic Headers + +%description -n libsgx-headers +Intel(R) Software Guard Extensions Basic Headers + +%package -n libsgx-urts +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions uRTS +Requires: libsgx-enclave-common >= %{version}-%{release} + +%description -n libsgx-urts +Intel(R) Software Guard Extensions uRTS + +%package -n libsgx-enclave-common +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Enclave Common Loader +Recommends: libsgx-launch >= %{version}-%{release} + +%description -n libsgx-enclave-common +Intel(R) Software Guard Extensions Enclave Common Loader + +%package -n libsgx-enclave-common-devel +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Enclave Common Loader for Developers +Requires: libsgx-enclave-common = %{version}-%{release} libsgx-headers >= %{version}-%{release} + +%description -n libsgx-enclave-common-devel +Intel(R) Software Guard Extensions Enclave Common Loader for Developers + +%package -n libsgx-ae-id-enclave +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions ID Enclave + +%description -n libsgx-ae-id-enclave +Intel(R) Software Guard Extensions ID Enclave + +%package -n libsgx-ae-tdqe +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions TDQE + +%description -n libsgx-ae-tdqe +Intel(R) Software Guard Extensions TDQE + +%package -n libsgx-ae-qve +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions QVE + +%description -n libsgx-ae-qve +Intel(R) Software Guard Extensions QVE + +%package -n libsgx-tdx-logic +Version: %{_dcap_version} +Summary: Intel(R) Trust Domain Extensions QE logic library +Requires: libsgx-urts >= %{_psw_version}-%{release} libsgx-ae-tdqe >= %{version}-%{release} libsgx-ae-id-enclave >= %{version}-%{release} libsgx-pce-logic >= %{version}-%{release} + +%description -n libsgx-tdx-logic +Intel(R) Trust Domain Extensions QE logic library + +%package -n libsgx-tdx-logic-devel +Version: %{_dcap_version} +Summary: Intel(R) Trust Domain Extensions QE logic library For Developers +Requires: libsgx-tdx-logic = %{version}-%{release} libsgx-headers >= %{_psw_version}-%{release} + +%description -n libsgx-tdx-logic-devel +Intel(R) Trust Domain Extensions QE logic library For Developers + +%package -n libsgx-pce-logic +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions PCE logic +Requires: libsgx-urts >= %{_psw_version}-%{release} libsgx-ae-pce >= %{_psw_version}-%{release} + +%description -n libsgx-pce-logic +Intel(R) Software Guard Extensions PCE logic + +%package -n libsgx-dcap-default-qpl +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Default Quote Provider Library + +%description -n libsgx-dcap-default-qpl +Intel(R) Software Guard Extensions Default Quote Provider Library + +%package -n libsgx-dcap-default-qpl-devel +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Default Quote Provider Library for Developers +Requires: libsgx-dcap-default-qpl = %{version}-%{release} + +%description -n libsgx-dcap-default-qpl-devel +Intel(R) Software Guard Extensions Default Quote Provider Library for Developers + +%package -n libtdx-attest +Version: %{_dcap_version} +Summary: Intel(R) Trust Domain Extensions Attestation library + +%description -n libtdx-attest +Intel(R) Trust Domain Extensions Attestation library + +%package -n libtdx-attest-devel +Version: %{_dcap_version} +Summary: Intel(R) Trust Domain Extensions Attestation library for Developers +Requires: libtdx-attest = %{version}-%{release} + +%description -n libtdx-attest-devel +Intel(R) Trust Domain Extensions Attestation library for Developers + +%package -n libsgx-dcap-quote-verify +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Verification Library +Recommends: libsgx-ae-qve >= %{version}-%{release} libsgx-urts >= %{_psw_version}-%{release} + +%description -n libsgx-dcap-quote-verify +Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Verification Library + +%package -n libsgx-dcap-quote-verify-devel +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Verification Library for Developers +Requires: libsgx-dcap-quote-verify = %{version}-%{release} libsgx-headers >= %{_psw_version}-%{release} + +%description -n libsgx-dcap-quote-verify-devel +Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Verification Library for Developers + +%package -n sgx-dcap-pccs +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions PCK Caching Service +Requires: gcc gcc-c++ make + +%description -n sgx-dcap-pccs +Intel(R) Software Guard Extensions PCK Caching Service + +%package -n libsgx-ra-network +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Registration Agent Network Library + +%description -n libsgx-ra-network +Intel(R) Software Guard Extensions Registration Agent Network Library + +%package -n libsgx-ra-network-devel +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Registration Agent Network Library for Developers +Requires: libsgx-ra-network = %{version}-%{release} + +%description -n libsgx-ra-network-devel +Intel(R) Software Guard Extensions Registration Agent Network Library for Developers + +%package -n libsgx-ra-uefi +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Registration Agent UEFI Library + +%description -n libsgx-ra-uefi +Intel(R) Software Guard Extensions Registration Agent UEFI Library + +%package -n libsgx-ra-uefi-devel +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Registration Agent UEFI Library for Developers +Requires: libsgx-ra-uefi = %{version}-%{release} + +%description -n libsgx-ra-uefi-devel +Intel(R) Software Guard Extensions Registration Agent UEFI Library for Developers + +%package -n sgx-ra-service +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Registration Agent Service +Requires: libsgx-ra-uefi >= %{version}-%{release} libsgx-ra-network >= %{version}-%{release} + +%description -n sgx-ra-service +Intel(R) Software Guard Extensions Registration Agent Service + +%package -n sgx-pck-id-retrieval-tool +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions PCK Certs Retrieve Tool +Recommends: libsgx-urts >= %{_psw_version} libsgx-ae-pce >= %{version}-%{release} libsgx-ae-id-enclave >= %{version}-%{release} libsgx-ra-uefi >= %{version}-%{release} + +%description -n sgx-pck-id-retrieval-tool +Intel(R) Software Guard Extensions:this tool is used to collect the platform information to retrieve the PCK certs from PCS(Provisioning Certification Server) + +%prep +%setup -qc + +%build +%undefine _auto_set_build_flags +make %{?_smp_mflags} build + +%install +make DESTDIR=%{?buildroot} install + +for pkg in $(ls -A %{?buildroot} 2> /dev/null |grep -v "license"); do + install -d %{?buildroot}/${pkg}/%{_docdir}/${pkg} + find %{?buildroot}/license -type f -print0 | \ + xargs -0 -n1 cat >> %{?buildroot}/${pkg}/%{_docdir}/${pkg}/%{_license_file} + find %{?buildroot}/${pkg} -type d -exec \ + sh -c '(ls -p "{}"|grep />/dev/null)||echo "{}"' \; | \ + sed -e "s#^%{?buildroot}/${pkg}##" | \ + grep -v "^%{_libdir}" | \ + grep -v "^%{_includedir}" | \ + grep -v "^%{_sysconfdir}" | \ + grep -v "^%{_tdx_qgs_path}" | \ + grep -v "^%{_dcap_pccs_path}" | \ + grep -v "^%{_ra_service_path}" | \ + grep -v "^%{_pck_id_retrieval_tool_path}" | \ + sed -e "s#^#%dir #" > %{_specdir}/list-${pkg} + for f in $(find %{?buildroot}/${pkg}); do + if [ -d ${f} ]; then + echo ${f} | sed -e "s#^%{?buildroot}/${pkg}##" | \ + grep -E "^%{_tdx_qgs_path}|^%{_dcap_pccs_path}|^%{_ra_service_path}|^%{_pck_id_retrieval_tool_path}" | \ + sed -e "s#^#%dir #" >> %{_specdir}/list-${pkg} + else + echo ${f} | \ + sed -e "s#^%{?buildroot}/${pkg}##" >> %{_specdir}/list-${pkg} + fi + done + cp -r %{?buildroot}/${pkg}/* %{?buildroot}/ + rm -fr %{?buildroot}/${pkg} + sed -i -e 's:^/etc/.*\.conf:%config &:' \ + -e 's:^%{_dcap_pccs_path}/config/default\.json:%config &:' %{_specdir}/list-${pkg} +done +rm -fr %{?buildroot}/license + +%clean +make clean + +%files -f %{_specdir}/list-%{name} +%files -n libsgx-ae-pce -f %{_specdir}/list-libsgx-ae-pce +%files -n libsgx-headers -f %{_specdir}/list-libsgx-headers +%files -n libsgx-urts -f %{_specdir}/list-libsgx-urts +%files -n libsgx-enclave-common -f %{_specdir}/list-libsgx-enclave-common +%files -n libsgx-enclave-common-devel -f %{_specdir}/list-libsgx-enclave-common-devel +%files -n libsgx-ae-id-enclave -f %{_specdir}/list-libsgx-ae-id-enclave +%files -n libsgx-ae-tdqe -f %{_specdir}/list-libsgx-ae-tdqe +%files -n libsgx-ae-qve -f %{_specdir}/list-libsgx-ae-qve +%files -n libsgx-tdx-logic -f %{_specdir}/list-libsgx-tdx-logic +%files -n libsgx-tdx-logic-devel -f %{_specdir}/list-libsgx-tdx-logic-devel +%files -n libsgx-pce-logic -f %{_specdir}/list-libsgx-pce-logic +%files -n libsgx-dcap-default-qpl -f %{_specdir}/list-libsgx-dcap-default-qpl +%files -n libsgx-dcap-default-qpl-devel -f %{_specdir}/list-libsgx-dcap-default-qpl-devel +%files -n libtdx-attest -f %{_specdir}/list-libtdx-attest +%files -n libtdx-attest-devel -f %{_specdir}/list-libtdx-attest-devel +%files -n libsgx-dcap-quote-verify -f %{_specdir}/list-libsgx-dcap-quote-verify +%files -n libsgx-dcap-quote-verify-devel -f %{_specdir}/list-libsgx-dcap-quote-verify-devel +%files -n sgx-dcap-pccs -f %{_specdir}/list-sgx-dcap-pccs +%files -n libsgx-ra-network -f %{_specdir}/list-libsgx-ra-network +%files -n libsgx-ra-network-devel -f %{_specdir}/list-libsgx-ra-network-devel +%files -n libsgx-ra-uefi -f %{_specdir}/list-libsgx-ra-uefi +%files -n libsgx-ra-uefi-devel -f %{_specdir}/list-libsgx-ra-uefi-devel +%files -n sgx-ra-service -f %{_specdir}/list-sgx-ra-service +%files -n sgx-pck-id-retrieval-tool -f %{_specdir}/list-sgx-pck-id-retrieval-tool + +%posttrans +if [ -x %{_tdx_qgs_path}/startup.sh ]; then %{_tdx_qgs_path}/startup.sh; fi + +%preun +if [ -x %{_tdx_qgs_path}/cleanup.sh ]; then %{_tdx_qgs_path}/cleanup.sh; fi + +%posttrans -n sgx-dcap-pccs +if [ -x %{_dcap_pccs_path}/startup.sh ]; then %{_dcap_pccs_path}/startup.sh; fi + +%preun -n sgx-dcap-pccs +if [ -x %{_dcap_pccs_path}/cleanup.sh ]; then %{_dcap_pccs_path}/cleanup.sh; fi + +%posttrans -n sgx-ra-service +if [ -x %{_ra_service_path}/startup.sh ]; then %{_ra_service_path}/startup.sh; fi + +%preun -n sgx-ra-service +if [ -x %{_ra_service_path}/cleanup.sh ]; then %{_ra_service_path}/cleanup.sh; fi + +%post -n libsgx-enclave-common +trigger_udev() { + if ! which udevadm &> /dev/null; then + return 0 + fi + udevadm control --reload || : + udevadm trigger || : +} + +trigger_udev + +%post -n libsgx-ae-pce +trigger_udev() { + if ! which udevadm &> /dev/null; then + return 0 + fi + udevadm control --reload || : + udevadm trigger || : +} + +# Add sgx_prv for in-kernel driver. +if [ -c /dev/sgx_provision -o -c /dev/sgx/provision ]; then + getent group sgx_prv &> /dev/null || groupadd sgx_prv + trigger_udev +fi + +%changelog +* Mon Sep 5 2022 SGX Team +- Initial Release diff --git a/linux/installer/rpm/psw-tdx/sanitize.sh b/linux/installer/rpm/psw-tdx/sanitize.sh new file mode 100755 index 00000000..83aeec19 --- /dev/null +++ b/linux/installer/rpm/psw-tdx/sanitize.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# +# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# + + +set -e + +tarball="linux-sgx" +psw_tdx="psw-tdx" + +cur_dir=$(dirname "$0") +root_dir="${cur_dir}/../../../../" +common_dir="${root_dir}/linux/installer/common" +common_psw_tdx_dir="${common_dir}/${psw_tdx}" +tarball_dir="${cur_dir}/${tarball}" + +make -C ${root_dir} preparation + +# Prepare ipp-crypto source +pushd ${root_dir}/external/ippcp_internal/ + +cd ipp-crypto && git apply ../0001-IPP-crypto-for-SGX_psw_dcap.patch >/dev/null 2>&1 || git apply ../0001-IPP-crypto-for-SGX_psw_dcap.patch --check -R + +popd + +python ${common_dir}/gen_source/copy_source.py \ + --bom-file ${common_psw_tdx_dir}/BOM_source/psw-tdx-tarball.txt \ + --src-path ${root_dir} \ + --dst-path ${tarball_dir} \ + --cleanup + +tar -zcvf ${tarball}.tar.gz -C ${cur_dir} ${tarball} +rm -fr ${tarball_dir} diff --git a/linux/installer/rpm/sgx-aesm-service/libsgx-ae-epid.spec b/linux/installer/rpm/sgx-aesm-service/libsgx-ae-epid.spec index e467f5c5..cbf6b88b 100644 --- a/linux/installer/rpm/sgx-aesm-service/libsgx-ae-epid.spec +++ b/linux/installer/rpm/sgx-aesm-service/libsgx-ae-epid.spec @@ -66,8 +66,6 @@ rm -fr %{?buildroot}/%{name} %files -f %{_specdir}/list-%{name} -%debug_package - %changelog * Mon Jul 29 2019 SGX Team - Initial Release diff --git a/linux/installer/rpm/sgx-aesm-service/libsgx-ae-le.spec b/linux/installer/rpm/sgx-aesm-service/libsgx-ae-le.spec index 65179770..a315a013 100644 --- a/linux/installer/rpm/sgx-aesm-service/libsgx-ae-le.spec +++ b/linux/installer/rpm/sgx-aesm-service/libsgx-ae-le.spec @@ -66,8 +66,6 @@ rm -fr %{?buildroot}/%{name} %files -f %{_specdir}/list-%{name} -%debug_package - %changelog * Mon Jul 29 2019 SGX Team - Initial Release diff --git a/linux/installer/rpm/sgx-aesm-service/libsgx-ae-pce.spec b/linux/installer/rpm/sgx-aesm-service/libsgx-ae-pce.spec index ebf1bc8a..6499adcf 100644 --- a/linux/installer/rpm/sgx-aesm-service/libsgx-ae-pce.spec +++ b/linux/installer/rpm/sgx-aesm-service/libsgx-ae-pce.spec @@ -67,8 +67,6 @@ rm -fr %{?buildroot}/%{name} %files -f %{_specdir}/list-%{name} -%debug_package - %post trigger_udev() { if ! which udevadm &> /dev/null; then diff --git a/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-ecdsa-plugin.spec b/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-ecdsa-plugin.spec index 506cceae..51bd9a2c 100644 --- a/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-ecdsa-plugin.spec +++ b/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-ecdsa-plugin.spec @@ -38,7 +38,7 @@ Version: @version@ Release: 1%{?dist} Summary: ECDSA Quote Plugin for Intel(R) Software Guard Extensions AESM Service Group: Development/System -Requires: sgx-aesm-service >= %{version}-%{release} libsgx-qe3-logic >= 1.14 libsgx-aesm-pce-plugin >= %{version}-%{release} +Requires: sgx-aesm-service >= %{version}-%{release} libsgx-qe3-logic >= 1.15 libsgx-aesm-pce-plugin >= %{version}-%{release} License: BSD License URL: https://github.com/intel/linux-sgx diff --git a/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-pce-plugin.spec b/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-pce-plugin.spec index d8fff8b9..b2233f6c 100644 --- a/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-pce-plugin.spec +++ b/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-pce-plugin.spec @@ -38,7 +38,7 @@ Version: @version@ Release: 1%{?dist} Summary: PCE Plugin for Intel(R) Software Guard Extensions AESM Service Group: Development/System -Requires: sgx-aesm-service >= %{version}-%{release} libsgx-pce-logic >= 1.14 +Requires: sgx-aesm-service >= %{version}-%{release} libsgx-pce-logic >= 1.15 License: BSD License URL: https://github.com/intel/linux-sgx diff --git a/linux/reproducibility/Dockerfile b/linux/reproducibility/Dockerfile index c8ee7f5c..99c554df 100644 --- a/linux/reproducibility/Dockerfile +++ b/linux/reproducibility/Dockerfile @@ -1,4 +1,4 @@ -FROM ubuntu:18.04 +FROM ubuntu:20.04 RUN apt-get update \ && apt-get install -y curl python perl git \ @@ -21,26 +21,22 @@ with pkgs; \n\ stdenvNoCC.mkDerivation { \n\ \tname = \"sgx-build-nix\"; \n\ \tbuildInputs = [ \n\ -\t\t/nix/store/raiq8qv61rc66arg3vzyfr9kw83s7dwv-autoconf-2.69 \n\ -\t\t/nix/store/7bsq9c4z657hddv60hpks48ws699y0fc-automake-1.16.1 \n\ -\t\t/nix/store/idj0yrdlk8x49f3gyl4sb8divwhfgjvp-libtool-2.4.6 \n\ -\t\t/nix/store/68yb6ams241kf5pjyxiwd7a98xxcbx0r-ocaml-4.06.1 \n\ +\t\t/nix/store/n0wh7aglap7fl8jfnmgnn1vdv71a9br9-autoconf-2.69 \n\ +\t\t/nix/store/laf3s9p2rsk2sz78v83ni7wvp4qsbii3-automake-1.16.5 \n\ +\t\t/nix/store/b7qjybcjdym24qi6yrcaf5kcxhq79gld-libtool-2.4.7 \n\ +\t\t/nix/store/sx7m5a7xwh76jzb05g07f3nbhl44qw4z-ocaml-4.13.1 \n\ \t\t/nix/store/ncqmw9iybd6iwxd4yk1x57gvs76k1sq4-ocamlbuild-0.12.0 \n\ -\t\t/nix/store/9dkhfaw1qsmvw4rv1z1fqgwhfpbdqrn0-file-5.35 \n\ -\t\t/nix/store/vs700jsqx2465qr0x78zcmgiii0890n3-cmake-3.15.5 \n\ -\t\t/nix/store/d0fv0g4vcv4s0ysa81pn9sf6fy4zzjcv-gnum4-1.4.18 \n\ -\t\t/nix/store/ljvpvjh36h9x2aaqzaby5clclq4mgdmc-openssl-1.1.1b \n\ -\t\t/nix/store/0klr6d4k2g0kabkamfivg185wpx8biqv-openssl-1.1.1b-dev \n\ -\t\t/nix/store/yg76yir7rkxkfz6p77w4vjasi3cgc0q6-gnumake-4.2.1 \n\ -\t\t/nix/store/5lyvydxv0w4f2s1ba84pjlbpvqkgn1ni-linux-headers-4.19.16 \n\ -\t\t/nix/store/681354n3k44r8z90m35hm8945vsp95h1-glibc-2.27 \n\ -\t\t/nix/store/1kl6ms8x56iyhylb2r83lq7j3jbnix7w-binutils-2.31.1 \n\ -\t\t/nix/store/lvwq3g3093injr86lm0kp0f61k5cbpay-gcc-wrapper-8.3.0 \n\ -\t\t/nix/store/dmxxhhl5yr92pbl17q1szvx34jcbzsy8-texinfo-6.5 \n\ -\t\t/nix/store/g6c80c9s2hmrk7jmkp9przi83jpcs8c6-bison-3.5.4 \n\ -\t\t/nix/store/qh2ppjlz4yq65cl0vs0m2h57x2cjlwm4-flex-2.6.4 \n\ -\t\t/nix/store/f2psw0phlmp7h7gk14rfsqdmjz4d1arb-gmp-6.2.1-dev \n\ -\t\t/nix/store/j6098x206440z8sbyqlibn95q6yhwdq7-nasm-2.15.05 \n\ +\t\t/nix/store/ja1iw47v9jkfgnj97l5cjivzn84160w2-file-5.41 \n\ +\t\t/nix/store/h2yqbmb203mb75rnqpg0x72w8fyw0vmz-cmake-3.22.3 \n\ +\t\t/nix/store/h3811zhzwfjzl3csh82xhr31hd5awaiz-gnum4-1.4.19 \n\ +\t\t/nix/store/cgvn7nmqbkkr4pzr02ypr6421z17mmgh-openssl-1.1.1o \n\ +\t\t/nix/store/nlbwsch1j3vcs1yixrrc6zw6nf3rjs64-openssl-1.1.1o-dev \n\ +\t\t/nix/store/0gz8dq0z6gx6lka4dbnmvbh47x1piri3-gnumake-4.2.1 \n\ +\t\t/nix/store/1j1i0x8p9xajqdlf0h0m38dpmb8ipxa6-linux-headers-5.17 \n\ +\t\t/nix/store/scd5n7xsn0hh0lvhhnycr9gx0h8xfzsl-glibc-2.34-210 \n\ +\t\t/nix/store/wp7kc5y840ldi5sd8j81fj4dabccff2d-binutils-wrapper-2.38 \n\ +\t\t/nix/store/n435g2xggqp22jl66ybfmjxc61d729v1-gcc-wrapper-8.5.0 \n\ +\t\t/nix/store/msf8mgq5i2v5yha67aykmnqf2rd00r4f-nasm-2.15.05 \n\ \t]; \n\ \n\ \tshellHook = '' \n\ @@ -51,32 +47,27 @@ stdenvNoCC.mkDerivation { \n\ #install the required software RUN touch .bash_profile \ -&& curl https://nixos.org/releases/nix/nix-2.2.1/install | sh \ +&& curl https://releases.nixos.org/nix/nix-2.9.0/install | sh \ && . /home/user/.nix-profile/etc/profile.d/nix.sh \ -&& nix-env -i /nix/store/raiq8qv61rc66arg3vzyfr9kw83s7dwv-autoconf-2.69 \ -&& nix-env -i /nix/store/7bsq9c4z657hddv60hpks48ws699y0fc-automake-1.16.1 \ -&& nix-env -i /nix/store/idj0yrdlk8x49f3gyl4sb8divwhfgjvp-libtool-2.4.6 \ -&& nix-env -i /nix/store/68yb6ams241kf5pjyxiwd7a98xxcbx0r-ocaml-4.06.1 \ +&& nix-env -i /nix/store/n0wh7aglap7fl8jfnmgnn1vdv71a9br9-autoconf-2.69 \ +&& nix-env -i /nix/store/laf3s9p2rsk2sz78v83ni7wvp4qsbii3-automake-1.16.5 \ +&& nix-env -i /nix/store/b7qjybcjdym24qi6yrcaf5kcxhq79gld-libtool-2.4.7 \ +&& nix-env -i /nix/store/sx7m5a7xwh76jzb05g07f3nbhl44qw4z-ocaml-4.13.1 \ && nix-env -i /nix/store/ncqmw9iybd6iwxd4yk1x57gvs76k1sq4-ocamlbuild-0.12.0 \ -&& nix-env -i /nix/store/9dkhfaw1qsmvw4rv1z1fqgwhfpbdqrn0-file-5.35 \ -&& nix-env -i /nix/store/vs700jsqx2465qr0x78zcmgiii0890n3-cmake-3.15.5 \ -&& nix-env -i /nix/store/d0fv0g4vcv4s0ysa81pn9sf6fy4zzjcv-gnum4-1.4.18 \ -&& nix-env -i /nix/store/ljvpvjh36h9x2aaqzaby5clclq4mgdmc-openssl-1.1.1b \ -&& nix-env -i /nix/store/0klr6d4k2g0kabkamfivg185wpx8biqv-openssl-1.1.1b-dev \ -&& nix-env -i /nix/store/yg76yir7rkxkfz6p77w4vjasi3cgc0q6-gnumake-4.2.1 \ -&& nix-env -i /nix/store/5lyvydxv0w4f2s1ba84pjlbpvqkgn1ni-linux-headers-4.19.16 \ -&& nix-env -i /nix/store/681354n3k44r8z90m35hm8945vsp95h1-glibc-2.27 \ -&& nix-env -i /nix/store/1kl6ms8x56iyhylb2r83lq7j3jbnix7w-binutils-2.31.1 \ -&& nix-env --set-flag priority 10 binutils-2.31.1 \ -&& nix-env -i /nix/store/lvwq3g3093injr86lm0kp0f61k5cbpay-gcc-wrapper-8.3.0 \ -&& nix-env -i /nix/store/dmxxhhl5yr92pbl17q1szvx34jcbzsy8-texinfo-6.5 \ -&& nix-env -i /nix/store/g6c80c9s2hmrk7jmkp9przi83jpcs8c6-bison-3.5.4 \ -&& nix-env -i /nix/store/qh2ppjlz4yq65cl0vs0m2h57x2cjlwm4-flex-2.6.4 \ -&& nix-env -i /nix/store/f2psw0phlmp7h7gk14rfsqdmjz4d1arb-gmp-6.2.1-dev \ -&& nix-env -i /nix/store/j6098x206440z8sbyqlibn95q6yhwdq7-nasm-2.15.05 +&& nix-env -i /nix/store/ja1iw47v9jkfgnj97l5cjivzn84160w2-file-5.41 \ +&& nix-env -i /nix/store/h2yqbmb203mb75rnqpg0x72w8fyw0vmz-cmake-3.22.3 \ +&& nix-env -i /nix/store/h3811zhzwfjzl3csh82xhr31hd5awaiz-gnum4-1.4.19 \ +&& nix-env -i /nix/store/cgvn7nmqbkkr4pzr02ypr6421z17mmgh-openssl-1.1.1o \ +&& nix-env -i /nix/store/nlbwsch1j3vcs1yixrrc6zw6nf3rjs64-openssl-1.1.1o-dev \ +&& nix-env -i /nix/store/0gz8dq0z6gx6lka4dbnmvbh47x1piri3-gnumake-4.2.1 \ +&& nix-env -i /nix/store/1j1i0x8p9xajqdlf0h0m38dpmb8ipxa6-linux-headers-5.17 \ +&& nix-env -i /nix/store/scd5n7xsn0hh0lvhhnycr9gx0h8xfzsl-glibc-2.34-210 \ +&& nix-env -i /nix/store/wp7kc5y840ldi5sd8j81fj4dabccff2d-binutils-wrapper-2.38 \ +&& nix-env --set-flag priority 10 binutils-wrapper-2.38 \ +&& nix-env -i /nix/store/n435g2xggqp22jl66ybfmjxc61d729v1-gcc-wrapper-8.5.0 \ +&& nix-env -i /nix/store/msf8mgq5i2v5yha67aykmnqf2rd00r4f-nasm-2.15.05 #config nix-shell RUN . /home/user/.nix-profile/etc/profile.d/nix.sh \ && nix-shell - diff --git a/linux/reproducibility/README.md b/linux/reproducibility/README.md index e4ffe265..7b777699 100644 --- a/linux/reproducibility/README.md +++ b/linux/reproducibility/README.md @@ -10,7 +10,6 @@ In order to reproduce the enclave build, there are three requirements:1. stable - The script [build_and_launch_docker.sh](./build_and_launch_docker.sh) is the interface to automate the reproducibility process for Intel(R) SGX. You can directly run this script in the host machine to verify the reproducibility. Currently below five reproducible types are supported: * sdk: specify this type if you want to verify the reproducibility for Intel(R) SGX SDK. The script will prepare the SDK code in the host machine and trigger SDK build in the launched container. * ipp: specify this type if you want to verify the reproducibility for the prebuilt IPP crypto. The script will prepare the IPP crypto code in the host machine and trigger the build in the launched container. - * binutils: specify this type if you want to verify the reproducibility for the prebuilt binutils. Th script will prepare the binutils code in the host machine and trigger the corresponding build in the launched container. * ae: specify this type if you want to verify the reproducibility for the prebuilt AEs. The script will prepare materials for AE reproducible build in the hose machine and trigger the corresponding build in the launched container. * all: specify this type if you want to verify all of the above components. The script will prepare materials for all the targets and trigger the build in the launched container. See `$ ./build_and_launch_docker.sh -h` for details diff --git a/linux/reproducibility/build_and_launch_docker.sh b/linux/reproducibility/build_and_launch_docker.sh index a99b306b..086e9ab0 100755 --- a/linux/reproducibility/build_and_launch_docker.sh +++ b/linux/reproducibility/build_and_launch_docker.sh @@ -42,7 +42,7 @@ # not specified, will use the same directory as the script location. # # -t, --reproduce-type: -# Specify the reproducibility type. Provided options: all|sdk|ae|ipp|binutils. +# Specify the reproducibility type. Provided options: all|sdk|ae|ipp. # If one type is provided, the corresponding code will be prepared. And the correponding # build steps will also be launched in the container automatically. # If no type is provided, all the code will be prepared. And the build steps will @@ -68,7 +68,6 @@ set -e script_dir="$( cd "$( dirname "$0" )" >> /dev/null 2>&1 && pwd )" code_dir="$script_dir/code_dir" sgx_repo="$code_dir/sgx" -binutils_repo="$code_dir/binutils" type="all" type_flag=0 mount_dir="/linux-sgx" @@ -76,8 +75,8 @@ mount_dir="/linux-sgx" sdk_installer="" sgx_src="" -default_sdk_installer=sgx_linux_x64_sdk_reproducible_2.17.100.1.bin -default_sdk_installer_url=https://download.01.org/intel-sgx/sgx-linux/2.17/distro/nix_reproducibility/$default_sdk_installer +default_sdk_installer=sgx_linux_x64_sdk_reproducible_2.18.100.1.bin +default_sdk_installer_url=https://download.01.org/intel-sgx/sgx-linux/2.18/distro/nix_reproducibility/$default_sdk_installer usage() @@ -94,7 +93,7 @@ usage() Specify the directory you want to prepare the code and share to the reproducible container. If this option is not specified, will use the same directory as the script location. -t, --reproduce-type: - Specify the reproducibility type. Provided options: all|sdk|ae|ipp|binutils. + Specify the reproducibility type. Provided options: all|sdk|ae|ipp. If one type is provided, the corresponding code will be prepared. And the correponding build steps will also be executed in the container automatically. If no type is provided, all the code will be prepared. And the build steps will not @@ -122,7 +121,7 @@ parse_cmd() -t | --reproduce-type ) shift type="$1" type_flag=1 - if [ "$type" != "all" ] && [ "$type" != "sdk" ] && [ "$type" != "ae" ] && [ "$type" != "ipp" ] && [ "$type" != "binutils" ]; then + if [ "$type" != "all" ] && [ "$type" != "sdk" ] && [ "$type" != "ae" ] && [ "$type" != "ipp" ]; then usage exit 1 fi @@ -163,7 +162,6 @@ parse_cmd() mkdir -p "$code_dir" | exit code_dir="$(realpath $code_dir)" sgx_repo="$code_dir/sgx" - binutils_repo="$code_dir/binutils" } prepare_sgx_src() @@ -179,7 +177,7 @@ prepare_sgx_src() if [ "$sgx_src" != "" ]; then mkdir -p "$sgx_repo" && cp -a "$sgx_src/." "$sgx_repo" else - git clone -b sgx_2.17_reproducible https://github.com/intel/linux-sgx.git $sgx_repo + git clone -b sgx_2.18_reproducible https://github.com/intel/linux-sgx.git $sgx_repo fi cd "$sgx_repo" && make preparation @@ -198,17 +196,6 @@ prepare_ipp_src() popd } -prepare_binutils_src() -{ - if [ -d $binutils_repo ]; then - echo "Removing existing repo $binutils_repo" - rm -rf $binutils_repo - fi - - git clone https://github.com/bminor/binutils-gdb.git --branch binutils-2_36_1 --depth 1 $binutils_repo - #git clone https://sourceware.org/git/binutils-gdb.git --branch binutils-2_36_1 --depth 1 $binutils_repo -} - prepare_sdk_installer() { @@ -243,11 +230,7 @@ EOF parse_cmd $@ case $type in - "binutils") - prepare_binutils_src - ;; "all") - prepare_binutils_src prepare_sgx_src prepare_ipp_src ;; @@ -281,6 +264,10 @@ if [ $? != 0 ]; then --build-arg http_proxy=$http_proxy -f $script_dir/Dockerfile . fi +# Allow 'w' permission for other users to the code_dir in case the uid in the container +# is different from the host uid. +chmod -R o+w $code_dir + if [ $type_flag = 0 ]; then docker run -v $code_dir:$mount_dir -it --network none --rm sgx.build.env else diff --git a/linux/reproducibility/start_build.sh.tmp b/linux/reproducibility/start_build.sh.tmp index 1dfe07ca..e0673af7 100644 --- a/linux/reproducibility/start_build.sh.tmp +++ b/linux/reproducibility/start_build.sh.tmp @@ -37,7 +37,6 @@ set -e script_dir="$( cd "$( dirname "$0" )" >> /dev/null 2>&1 && pwd )" sgx_repo="$script_dir/sgx" -binutils_repo="$script_dir/binutils" build_out="$script_dir/out" sdk_prefix="/linux-sgx/" @@ -56,14 +55,6 @@ clean_repo() if [ -f $sgx_repo/Makefile ]; then cd $sgx_repo/ && make clean fi - if [ -f $binutils_repo/Makefile ]; then - cd $binutils_repo && make clean - rm -f Makefile - fi - if [ -f $binutils_repo/gold/Makefile ]; then - cd $binutils_repo/gold && make clean - rm -f Makefile - fi # uninstall SDK installer if [ -x "$sdk_install_path/uninstall.sh" ]; then $sdk_install_path/uninstall.sh @@ -104,30 +95,20 @@ build_ae() { # Requires two input args: # $1: sdk installer path - # $2: binutils location - if [ $# != 2 ]; then + if [ $# != 1 ]; then echo "Invalid input parameter" exit 1 fi local sdk_installer="$1" - local toolset_dir="$2" if [ ! -f "$sdk_installer" ]; then echo "SDK installer is not found. $sdk_installer" exit 1 fi - if [ ! -d "$toolset_dir" ]; then - echo "LVI toolset is not found. $toolset_dir" - exit 1 - fi # Install sdk installer and source environment $sdk_installer --prefix=$sdk_prefix source $sdk_install_path/environment - # Current export MITIGATION_CFLAGS+=-B{toolset_dir} - # We can copy binutils to sdk installation folder - export MITIGATION_CFLAGS+=-B$toolset_dir - pushd . local ae_out="$build_out/ae" mkdir -p $ae_out @@ -150,22 +131,6 @@ build_ae() popd } -build_binutils() -{ - pushd . - cd $binutils_repo && ./configure --enable-deterministic-archives && make - local binutils_out="$script_dir/out/binutils" - mkdir -p $binutils_out - cp $binutils_repo/gas/as-new $binutils_out/as && strip $binutils_out/as - cp $binutils_repo/ld/ld-new $binutils_out/ld && strip $binutils_out/ld - cp $binutils_repo/binutils/objdump $binutils_out/ && strip $binutils_out/objdump - cp $binutils_repo/binutils/ar $binutils_out/ && strip $binutils_out/ar - cp $binutils_repo/binutils/objcopy $binutils_out/ && strip $binutils_out/objcopy - cp $binutils_repo/binutils/ranlib $binutils_out/ && strip $binutils_out/ranlib - popd - toolset_dir="$binutils_out" -} - usage() { echo " @@ -174,7 +139,7 @@ usage() Description: Automate the reproducible build in the container. The reproducibility TYPE - should be provied and could be one of [ all | sdk | ae | ipp | binutils ] + should be provied and could be one of [ all | sdk | ae | ipp ] " } @@ -183,12 +148,9 @@ usage() type="$1" if [ "$type" = "" ]; then echo "Invalid input parameter. Please input the reproducibility type. - Possible options: [ all | sdk | ae | ipp | binutils ]" + Possible options: [ all | sdk | ae | ipp ]" exit 1 -elif [ ! -d "$binutils_repo" -a "$type" = "binutils" ]; then - echo "No binutils source code." - exit 1 -elif [ ! -d "$sgx_repo" -a "$type" != "binutils" ]; then +elif [ ! -d "$sgx_repo" ]; then echo "No sgx source code." exit 1 fi @@ -197,33 +159,21 @@ clean_repo case "$type" in "all") - build_binutils - export PATH=$toolset_dir:$PATH build_ipp build_sdk - build_ae $sdk_installer $toolset_dir + build_ae $sdk_installer echo "All the targets are built out and could be found under $build_out" ;; - "binutils") - build_binutils - echo "The output binutils could be found under $toolset_dir" - ;; "ae") - toolset_dir="$script_dir/sgx/external/toolset/nix" - export PATH=$toolset_dir:$PATH sdk_installer=$(ls $script_dir/sgx_linux_x64_sdk_*.bin) - build_ae $sdk_installer $toolset_dir + build_ae $sdk_installer echo "The built out AEs could be found under $build_out/ae" ;; "sdk") - toolset_dir="$script_dir/sgx/external/toolset/nix" - export PATH=$toolset_dir:$PATH build_sdk echo "SGX SDK installer has been built out. $sdk_installer" ;; "ipp") - toolset_dir="$script_dir/sgx/external/toolset/nix" - export PATH=$toolset_dir:$PATH build_ipp echo "The built out IPP crypto libs could be found under $build_out/ipp" ;; diff --git a/psw/ae/aesm_service/source/qcnl/CMakeLists.txt b/psw/ae/aesm_service/source/qcnl/CMakeLists.txt index 7fdafc30..6ed7ad16 100644 --- a/psw/ae/aesm_service/source/qcnl/CMakeLists.txt +++ b/psw/ae/aesm_service/source/qcnl/CMakeLists.txt @@ -8,6 +8,10 @@ aux_source_directory(${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/Quot aux_source_directory(${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qcnl/linux _srcs) add_library(sgx_default_qcnl_wrapper SHARED ${_srcs}) +link_directories( + ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/prebuilt/openssl/lib/linux64 +) + target_include_directories(sgx_default_qcnl_wrapper PRIVATE ${SGX_HEADER_DIR} ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qcnl/inc @@ -15,6 +19,7 @@ target_include_directories(sgx_default_qcnl_wrapper PRIVATE ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/quote_wrapper/common/inc ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/common/inc/internal ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteVerification/QVL/Src/ThirdParty/rapidjson/include/rapidjson + ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/prebuilt/openssl/inc ) set_property(TARGET sgx_default_qcnl_wrapper APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-z,defs") @@ -23,6 +28,6 @@ set_property(TARGET sgx_default_qcnl_wrapper APPEND_STRING PROPERTY LINK_DEPENDS ) target_link_libraries(sgx_default_qcnl_wrapper - ${CURL_LIBRARIES} + ${CURL_LIBRARIES} crypto ) diff --git a/psw/enclave_common/Makefile b/psw/enclave_common/Makefile index 6627e99c..3e3151d8 100644 --- a/psw/enclave_common/Makefile +++ b/psw/enclave_common/Makefile @@ -77,10 +77,10 @@ ifndef DEBUG @$(CP) $(LIBSGX_ENCLAVE_COMMON_DEBUG) $| endif -$(LIBSGX_ENCLAVE_COMMON): $(OBJ) $(LIBWRAPPER) sgx_launch +$(LIBSGX_ENCLAVE_COMMON): $(OBJ) $(LIBWRAPPER) $(CXX) $(CXXFLAGS) -shared -Wl,-soname=$@.$(call SPLIT_VERSION,$(ECL_VER),1) $(LIB) -o $@ $(OBJ) $(LDFLAGS) -$(LIBSGX_ENCLAVE_COMMON_STATIC): $(OBJ) $(LIBWRAPPER) sgx_launch +$(LIBSGX_ENCLAVE_COMMON_STATIC): $(OBJ) $(LIBWRAPPER) $(CP) $(COMMON_DIR)/se_wrapper_psw/libwrapper.a $@ $(AR) rcs $@ $(OBJ) @@ -98,10 +98,6 @@ $(OBJ): %.o: %.cpp $(LIBWRAPPER): $(MAKE) -C $(COMMON_DIR)/se_wrapper_psw/ -.PHONY:sgx_launch -sgx_launch: - $(MAKE) -C $(LINUX_PSW_DIR)/uae_service/linux - $(BUILD_DIR): @$(MKDIR) $@ @@ -111,4 +107,3 @@ clean:: @$(RM) $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON) $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON_DEBUG) $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON_STATIC) @$(RM) $(LIBSGX_ENCLAVE_COMMON).orig $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON_DEBUG) $(MAKE) -C $(COMMON_DIR)/se_wrapper_psw/ clean - $(MAKE) -C $(LINUX_PSW_DIR)/uae_service/linux/ clean diff --git a/psw/enclave_common/sgx_enclave_common.cpp b/psw/enclave_common/sgx_enclave_common.cpp index 95e7eb4f..9662a277 100644 --- a/psw/enclave_common/sgx_enclave_common.cpp +++ b/psw/enclave_common/sgx_enclave_common.cpp @@ -29,6 +29,12 @@ * */ +#include +#include +#include +#include +#include +#include #include "sgx_enclave_common.h" #include "sgx_urts.h" #include "arch.h" @@ -40,13 +46,11 @@ #include "se_thread.h" #include "se_trace.h" #include "util.h" -#include -#include -#include -#include -#include #include "se_memcpy.h" #include "se_lock.hpp" +#include "sgx_mm.h" +#include "cpuid.h" + //ubuntu 18.04 use glibc 2.27, doesn't support MAP_FIXED_NOREPLACE #ifndef MAP_FIXED_NOREPLACE #define MAP_FIXED_NOREPLACE 0x100000 @@ -57,6 +61,7 @@ #define SGX_LAUNCH_SO "libsgx_launch.so.1" #define SGX_GET_LAUNCH_TOKEN "get_launch_token" +#define SGX_CPUID 0x12 func_get_launch_token_t get_launch_token_func = NULL; @@ -1313,3 +1318,495 @@ extern "C" bool COMM_API enclave_set_information( return false; } +uint32_t COMM_API enclave_get_features() +{ + int hFile = -1; + int driver_type = 0; + int a[4] = {0,0,0,0}; + uint32_t feature = ENCLAVE_FEATURE_NONE; + + __cpuid(a, 0); + if (a[0] < SGX_CPUID) + return feature; + + if (false == get_driver_type(&driver_type)) + return feature; + + __cpuidex(a, SGX_CPUID, 0); + if ((a[0] & 0x1)) + feature = ENCLAVE_FEATURE_SGX1; + + bool cpu_sgx2 = ((a[0] >> 1) & 0x1); + if ((!cpu_sgx2) || (driver_type != SGX_DRIVER_IN_KERNEL)) + return feature; + + open_se_device(SGX_DRIVER_IN_KERNEL, &hFile); + struct sgx_enclave_restrict_permissions ioc; + memset(&ioc, 0, sizeof(ioc)); + int ret = ioctl(hFile, SGX_IOC_ENCLAVE_RESTRICT_PERMISSIONS, &ioc); + close_file(&hFile); + + bool kernel_sgx2 = ((ret != -1) || (errno != ENOTTY)); + if (kernel_sgx2) + feature |= ENCLAVE_FEATURE_SGX2; + + return feature; +} + +using namespace std; +#define PROT_MASK (PROT_READ|PROT_WRITE|PROT_EXEC) + +uint32_t COMM_API enclave_alloc( + COMM_IN void* target_addr, + COMM_IN size_t target_size, + COMM_IN uint32_t data_properties, + COMM_IN uint32_t alloc_flags, + COMM_OUT_OPT uint32_t* enclave_error) +{ + UNUSED(data_properties); + UNUSED(alloc_flags); + + int ret = ENCLAVE_UNEXPECTED; + SE_TRACE(SE_TRACE_DEBUG, + "enclave_alloc for %p ( %llX ) with alloc flags = 0x%lX\n", + target_addr, target_size, alloc_flags); + + if (s_driver_type == SGX_DRIVER_DCAP) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_NOT_SUPPORTED; + return ENCLAVE_NOT_SUPPORTED; + } + if (s_driver_type == SGX_DRIVER_OUT_OF_TREE) + { + ret = mprotect(target_addr, target_size, PROT_WRITE | PROT_READ); + if (ret != 0) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_UNEXPECTED; + return ENCLAVE_UNEXPECTED; + } + return ENCLAVE_ERROR_SUCCESS; + } + int enclave_fd = get_file_handle_from_address(target_addr); + if (enclave_fd == -1) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_ADDRESS; + return ENCLAVE_INVALID_ADDRESS; + } + + // Future: support COMMIT_NOW when kernel supports + // Future: support CET + + int map_flags = MAP_SHARED | MAP_FIXED; + void *out = mmap(target_addr, target_size, PROT_WRITE | PROT_READ, map_flags, enclave_fd, 0); + if (out == MAP_FAILED) + { + ret = errno; + SE_TRACE(SE_TRACE_WARNING, "mmap failed, error = %d\n", ret); + ret = error_driver2api(-1, ret); + } + else + { + ret = ENCLAVE_ERROR_SUCCESS; + } + if (enclave_error != NULL) + *enclave_error = ret; + + return ret; +} + +uint64_t get_offset_for_address(uint64_t target_address) +{ + uint64_t enclave_base_addr = (uint64_t)get_enclave_base_address_from_address((void *)target_address); + assert(enclave_base_addr != 0); + assert(target_address >= enclave_base_addr); + enclave_elrange_t eelr; + if (get_elrange_from_base_address((void*)enclave_base_addr, &eelr)) + { + return (uint64_t)target_address - eelr.elrange_start_address; + } + + return (uint64_t)target_address - (uint64_t)enclave_base_addr; +} + +static int emodt(int fd, void *addr, size_t length, uint64_t type) +{ + struct sgx_enclave_modify_types ioc; + if (length == 0) + return EINVAL; + + SE_TRACE(SE_TRACE_DEBUG, + "MODT for %p ( %llX ), type: 0x%llX\n", + addr, length, type); + memset(&ioc, 0, sizeof(ioc)); + + ioc.page_type = type; + ioc.offset = get_offset_for_address((uint64_t)addr); + ioc.length = length; + do + { + int ret = ioctl(fd, SGX_IOC_ENCLAVE_MODIFY_TYPES, &ioc); + + if (ret && ioc.count == 0 && errno != EBUSY && errno != EAGAIN) + { //total failure + int err = errno; + SE_TRACE(SE_TRACE_WARNING, + "MODT failed, error = %d for %p ( %llX ), type: 0x%llX\n", + err, addr, length, type); + return err; + } + //for recoverable partial errors + length -= ioc.count; + ioc.offset += ioc.count; + ioc.result = 0; + ioc.count = 0; + } while (length != 0); + + return 0; +} + +static int trim(int fd, void *addr, size_t length) +{ + return emodt(fd, addr, length, (SGX_EMA_PAGE_TYPE_TRIM >> SGX_EMA_PAGE_TYPE_SHIFT)); +} +static int mktcs(int fd, void *addr, size_t length) +{ + + return emodt(fd, addr, length, (SGX_EMA_PAGE_TYPE_TCS >> SGX_EMA_PAGE_TYPE_SHIFT)); +} +static int trim_accept(int fd, void *addr, size_t length) +{ + struct sgx_enclave_remove_pages ioc; + memset(&ioc, 0, sizeof(ioc)); + + SE_TRACE(SE_TRACE_DEBUG, + "REMOVE for 0x%llX ( %llX )\n", + addr, length); + ioc.offset = get_offset_for_address((uint64_t)addr); + ioc.length = length; + int ret = 0; + do { + ret = ioctl(fd, SGX_IOC_ENCLAVE_REMOVE_PAGES, &ioc); + if(ret && ioc.count == 0 && errno != EBUSY && errno != EAGAIN ) + { //total failure + int err = errno; + SE_TRACE(SE_TRACE_WARNING, + "REMOVE failed, error = %d for 0x%llX ( %llX )\n", + err, addr, length); + return err; + } + ioc.length -= ioc.count; + ioc.offset += ioc.count; + ioc.count = 0; + } while (ioc.length != 0); + + return 0; +} +static int emodpr(int fd, void *addr, size_t length, uint64_t prot) +{ + struct sgx_enclave_restrict_permissions ioc; + if (length == 0) + return EINVAL; + + SE_TRACE(SE_TRACE_DEBUG, + "MODP for 0x%llX ( %llX ), prot: 0x%llX\n", + addr, length, prot); + memset(&ioc, 0, sizeof(ioc)); + + ioc.permissions = prot; + ioc.offset = get_offset_for_address((uint64_t)addr); + ioc.length = length; + + do + { + int ret = ioctl(fd, SGX_IOC_ENCLAVE_RESTRICT_PERMISSIONS, &ioc); + if (ret && ioc.count == 0 && errno != EBUSY && errno!=EAGAIN ) + { + int err = errno; + SE_TRACE(SE_TRACE_WARNING, + "MODP failed, error = %d for 0x%llX ( %llX ), prot: 0x%llX\n", + err, addr, length, prot); + return err; + } + ioc.length -= ioc.count; + ioc.offset += ioc.count; + ioc.result = 0; + ioc.count = 0; + } while (ioc.length != 0); + + return 0; +} + +// legacy support for EDMM + +static int trim_accept_legacy(int fd, void *addr, size_t len) +{ + sgx_range params; + memset(¶ms, 0, sizeof(sgx_range)); + params.start_addr = (unsigned long)addr; + params.nr_pages = (unsigned int)(len / SE_PAGE_SIZE); + + int ret = ioctl(fd, SGX_IOC_ENCLAVE_NOTIFY_ACCEPT, ¶ms); + + if (ret) + { + return errno; + } + + return SGX_SUCCESS; +} + +static int trim_legacy(int fd, void *fromaddr, uint64_t len) +{ + sgx_range params; + memset(¶ms, 0, sizeof(sgx_range)); + params.start_addr = (unsigned long)fromaddr; + params.nr_pages = (unsigned int)((len) / SE_PAGE_SIZE); + + int ret = ioctl(fd, SGX_IOC_ENCLAVE_TRIM, ¶ms); + if (ret) + { + return errno; + } + + return SGX_SUCCESS; +} + +static int mktcs_legacy(int fd, void *tcs_addr, size_t len) +{ + if (len != SE_PAGE_SIZE) + return EINVAL; + sgx_range params; + memset(¶ms, 0, sizeof(sgx_range)); + params.start_addr = (unsigned long)tcs_addr; + params.nr_pages = 1; + + int ret = ioctl(fd, SGX_IOC_ENCLAVE_MKTCS, ¶ms); + if (ret) + { + return errno; + } + return SGX_SUCCESS; +} + +static int emodpr_legacy(int fd, void *addr, uint64_t size, uint64_t flag) +{ + sgx_modification_param params; + memset(¶ms, 0, sizeof(sgx_modification_param)); + params.range.start_addr = (unsigned long)addr; + params.range.nr_pages = (unsigned int)(size / SE_PAGE_SIZE); + params.flags = (unsigned long)flag; + + int ret = ioctl(fd, SGX_IOC_ENCLAVE_EMODPR, ¶ms); + if (ret) + { + return errno; + } + + return SGX_SUCCESS; +} + +uint32_t COMM_API enclave_modify( + COMM_IN void* target_addr, + COMM_IN size_t target_size, + COMM_IN uint32_t from_data_properties, + COMM_IN uint32_t to_data_properties, + COMM_OUT_OPT uint32_t* enclave_error) +{ + int ret = ENCLAVE_UNEXPECTED; + SE_TRACE(SE_TRACE_DEBUG, + "enclave_modify for %p ( %llX ) from 0x%lX to %lX\n", + target_addr, target_size, from_data_properties, to_data_properties); + if (s_driver_type == SGX_DRIVER_DCAP) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_NOT_SUPPORTED; + return ENCLAVE_NOT_SUPPORTED; + } + uint64_t enclave_base = (uint64_t)get_enclave_base_address_from_address(target_addr); + if (enclave_base == 0) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_ADDRESS; + return ENCLAVE_INVALID_ADDRESS; + } + if (target_size % SE_PAGE_SIZE != 0) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_PARAMETER; + return ENCLAVE_INVALID_PARAMETER; + } + function _trim = trim; + function _trim_accept = trim_accept; + function _mktcs = mktcs; + function _emodpr = emodpr; + int fd = get_file_handle_from_address(target_addr); + if (s_driver_type == SGX_DRIVER_OUT_OF_TREE) + { + _trim = trim_legacy; + _trim_accept = trim_accept_legacy; + _mktcs = mktcs_legacy; + _emodpr = emodpr_legacy; + fd = s_hdevice; + } + if(fd == -1) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_ADDRESS; + return ENCLAVE_INVALID_ADDRESS; + } + + int type_to = (to_data_properties & SGX_EMA_PAGE_TYPE_MASK); + int type_from = (from_data_properties & SGX_EMA_PAGE_TYPE_MASK); + if (type_from == SGX_EMA_PAGE_TYPE_TRIM && type_to != SGX_EMA_PAGE_TYPE_TRIM) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_PARAMETER; + return ENCLAVE_INVALID_PARAMETER; + } + int prot_to = (to_data_properties & PROT_MASK); + int prot_from = (from_data_properties & PROT_MASK); + if ((prot_to != prot_from) && (type_to != type_from)) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_PARAMETER; + return ENCLAVE_INVALID_PARAMETER; + } + + if ((type_from & type_to & SGX_EMA_PAGE_TYPE_TRIM)) + { + //user space can only do EACCEPT for PT_TRIM type + ret = _trim_accept(fd, target_addr, target_size); + if (ret) + { + ret = error_driver2api(-1, ret); + if (enclave_error != NULL) + *enclave_error = ret; + return ret; + } + if (prot_to == PROT_NONE) + { + //EACCEPT done and notified. + //if user wants to remove permissions, + //only mprotect is needed + ret = mprotect(target_addr, target_size, prot_to); + if (ret == -1) + { + ret = error_driver2api(ret, errno); + if (enclave_error != NULL) + *enclave_error = ret; + return ret; + } + } + return ret; + } + + if (type_to == SGX_EMA_PAGE_TYPE_TRIM) + { + assert(type_from != SGX_EMA_PAGE_TYPE_TRIM); + if (prot_to != prot_from) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_PARAMETER; + return ENCLAVE_INVALID_PARAMETER; + } + ret = _trim(fd, target_addr, target_size); + if (ret) + { + ret = error_driver2api(-1, ret); + if (enclave_error != NULL) + *enclave_error = ret; + return ret; + } + return 0; + } + + if (type_to == SGX_EMA_PAGE_TYPE_TCS) + { + if (type_from != SGX_EMA_PAGE_TYPE_REG) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_PARAMETER; + return ENCLAVE_INVALID_PARAMETER; + } + if ((prot_from != (SGX_EMA_PROT_READ_WRITE)) && prot_to != prot_from) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_PARAMETER; + return ENCLAVE_INVALID_PARAMETER; + } + ret = _mktcs(fd, target_addr, target_size); + if (ret) + { + ret = error_driver2api(-1, ret); + if (enclave_error != NULL) + *enclave_error = ret; + return ret; + } + return 0; + } + + if (type_to != type_from) + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_PARAMETER; + return ENCLAVE_INVALID_PARAMETER; + } + // type_to == type_from + // this is for emodpr to epcm.NONE, enclave EACCEPT with pte.R + // separate mprotect is needed to change pte.R to pte.NONE + if (prot_to == prot_from && prot_to == PROT_NONE) + { + ret = mprotect((void *)target_addr, target_size, prot_to); + if (ret == -1) { + ret = errno; + ret = error_driver2api(-1, ret); + if (enclave_error != NULL) + *enclave_error = ret; + return ret; + } + } + + if (prot_to == prot_from) + { + ret = 0; //nothing to be done. + if (enclave_error != NULL) + *enclave_error = ret; + return ret; + } + // Permissions changes. Only do emodpr for PT_REG pages + if ((type_from & type_to & SGX_EMA_PAGE_TYPE_MASK) == SGX_EMA_PAGE_TYPE_REG) + { + ret = _emodpr(fd, target_addr, target_size, prot_to); + if (ret) + { + ret = error_driver2api(-1, ret); + if (enclave_error != NULL) + *enclave_error = ret; + return ret; + } + } + else + { + if (enclave_error != NULL) + *enclave_error = ENCLAVE_INVALID_PARAMETER; + return ENCLAVE_INVALID_PARAMETER; + } + //EACCEPT needs at least pte.R, PROT_NONE case done above. + if (prot_to != PROT_NONE) + { + ret = mprotect(target_addr, target_size, prot_to); + if (ret == -1) + { + ret = error_driver2api(ret, errno); + if (enclave_error != NULL) + *enclave_error = ret; + return ret; + } + } + if (enclave_error != NULL) + *enclave_error = ret; + return ret; +} diff --git a/psw/enclave_common/sgx_enclave_common.h b/psw/enclave_common/sgx_enclave_common.h index cdedbed9..b06379a5 100644 --- a/psw/enclave_common/sgx_enclave_common.h +++ b/psw/enclave_common/sgx_enclave_common.h @@ -50,6 +50,8 @@ extern "C" { #ifndef ENCLAVE_TYPE_SGX #define ENCLAVE_TYPE_SGX 0x00000001 /* An enclave for the Intel Software Guard Extensions (SGX) architecture version 1. */ +#endif +#ifndef ENCLAVE_TYPE_SGX2 #define ENCLAVE_TYPE_SGX2 0x00000002 /* An enclave for the Intel Software Guard Extensions (SGX) architecture version 2. */ #endif #define ENCLAVE_TYPE_SGX1 ENCLAVE_TYPE_SGX @@ -86,13 +88,42 @@ typedef enum { ENCLAVE_PAGE_WRITE = 1 << 1, /* Enables write access to the committed region of pages. */ ENCLAVE_PAGE_EXECUTE = 1 << 2, /* Enables execute access to the committed region of pages. */ ENCLAVE_PAGE_THREAD_CONTROL = 1 << 8, /* The page contains a thread control structure. */ + ENCLAVE_PAGE_REG = 2 << 8, /* The page contains a PT_REG page. */ + ENCLAVE_PAGE_TRIM = 4 << 8, /* The page is trimmed(PT_TRIM). This is for pages which will be trimmed (removed) from the enclave. */ + ENCLAVE_PAGE_SS_FIRST = 5 << 8, /* The page contains the first page of a Shadow Stack (future). */ + ENCLAVE_PAGE_SS_REST = 6 << 8, /* The page contains a non-first page of a Shadow Stack (future). */ ENCLAVE_PAGE_UNVALIDATED = 1 << 12, /* The page contents that you supply are excluded from measurement and content validation. */ } enclave_page_properties_t; +/* + * Hints to OS on how application may use the pages allocated with enclave_alloc. + */ +typedef enum { + ENCLAVE_EMA_NONE = 0, /* No suggestions provided. */ + ENCLAVE_EMA_RESERVE = 1, /* Suggest that the kernel should reserve the memory range and not immediately EAUG pages. */ + ENCLAVE_EMA_COMMIT_NOW = 2, /* Gives a hint that the kernel should EAUG pages immediately. */ + ENCLAVE_EMA_COMMIT_ON_DEMAND = 4, /* Gives a hint that the kernel can EAUG pages later. */ + ENCLAVE_EMA_GROWSDOWN = 16, /* Gives a hint to the kernel that the application will access pages above the + last accessed page. The kernel may want to EAUG pages from higher to lower addresses + with no gaps in addresses above the last committed page. */ + ENCLAVE_EMA_GROWSUP = 32, /* Gives a hint to the kernel that the application will access pages below the + last accessed page. The kernel may want to EAUG pages from lower to higher addresses + with no gaps in addresses below the last committed page. */ +} enclave_alloc_flags_t; + typedef enum { ENCLAVE_LAUNCH_TOKEN = 0x1 } enclave_info_type_t; +/** + * The enclave features flags describe additional enclave features + * which are supported by the platform. A value of 0 indicates no features are supported. + */ +typedef enum { + ENCLAVE_FEATURE_NONE = 0, + ENCLAVE_FEATURE_SGX1 = 0x00000001, /* The platform (HW and OS) supports SGX1 */ + ENCLAVE_FEATURE_SGX2 = 0x00000002, /* The platform (HW and OS) supports SGX2 */ +}enclave_features_t; #define ENCLAVE_CREATE_MAX_EX_FEATURES_COUNT 32 @@ -100,12 +131,12 @@ typedef enum { #define ENCLAVE_CREATE_EX_EL_RANGE (1 << ENCLAVE_CREATE_EX_EL_RANGE_BIT_IDX) // Reserve Bit 0 for the el_range config //update the following when adding new extended feature -#define _ENCLAVE_CREATE_LAST_EX_FEATURE_IDX_ ENCLAVE_CREATE_EX_EL_RANGE_BIT_IDX +#define _ENCLAVE_CREATE_LAST_EX_FEATURE_IDX_ ENCLAVE_CREATE_EX_EL_RANGE_BIT_IDX #define _ENCLAVE_CREATE_EX_FEATURES_MASK_ (((uint32_t)-1) >> (ENCLAVE_CREATE_MAX_EX_FEATURES_COUNT - 1 - _ENCLAVE_CREATE_LAST_EX_FEATURE_IDX_)) -typedef struct enclave_elrange{ +typedef struct enclave_elrange { uint64_t enclave_image_address; uint64_t elrange_start_address; uint64_t elrange_size; @@ -148,7 +179,7 @@ void* COMM_API enclave_create_ex( COMM_IN const uint32_t ex_features, COMM_IN const void* ex_features_p[32], COMM_OUT_OPT uint32_t* enclave_error); - + /* enclave_create() * Parameters: @@ -175,7 +206,7 @@ void* COMM_API enclave_create( /* enclave_load_data() * Parameters: * target_address [in] - The address in the enclave where you want to load the data. - * target_size [in] - The size of the range that you want to load in the enclave, in bytes. + * target_size [in] - The size of the range that you want to load in the enclave, in bytes. * source_buffer [in, optional] - An optional pointer to the data you want to load into the enclave. * data_properties [in] - The properties of the pages you want to add to the enclave. * enclave_error [out, optional] - An optional pointer to a variable that receives an enclave error code. @@ -193,7 +224,7 @@ size_t COMM_API enclave_load_data( /* enclave_initialize() * Parameters: * base_address [in] - The enclave base address as returned from the enclave_create API. - * info [in] - A pointer to the architecture-specific information to use to initialize the enclave. + * info [in] - A pointer to the architecture-specific information to use to initialize the enclave. * info_size [in] - The length of the structure that the info parameter points to, in bytes. * enclave_error [out, optional] - An optional pointer to a variable that receives an enclave error code. * Return Value: @@ -224,7 +255,7 @@ bool COMM_API enclave_delete( * info_type[in] - Identifies the type of information requested. initialized. * output_info[out] - Pointer to information returned by the API * output_info_size[in, out] - Size of the output_info buffer, in bytes. If the API succeeds, then this will return the number of bytes returned in output_info. If the API fails with, ENCLAVE_INVALID_SIZE, then this will return the required size - * enclave_error [out, optional] - An optional pointer to a variable that receives an enclave error code. + * enclave_error [out, optional] - An optional pointer to a variable that receives an enclave error code. */ bool COMM_API enclave_get_information( COMM_IN void* base_address, @@ -239,7 +270,7 @@ bool COMM_API enclave_get_information( * info_type[in] - Identifies the type of information requested. not been initialized. * input_info[in] - Pointer to information provided to the API * input_info_size[in] - Size of the information, in bytes, provided in input_info from the API. - * enclave_error [out, optional] - An optional pointer to a variable that receives an enclave error code. + * enclave_error [out, optional] - An optional pointer to a variable that receives an enclave error code. */ bool COMM_API enclave_set_information( COMM_IN void* base_address, @@ -247,6 +278,106 @@ bool COMM_API enclave_set_information( COMM_IN void* input_info, COMM_IN size_t input_info_size, COMM_OUT_OPT uint32_t* enclave_error); + +/* enclave_get_features() + * Parameters: + * None + * Return Value: + * Returns flags indicating enclave features which are supported on the platform. + */ +uint32_t COMM_API enclave_get_features(); + +/* enclave_alloc() + * Call OS to reserve region for EAUG, immediately or on-demand. + * + * Parameters + * targt_addr [in] - Desired page aligned start address. + * target_size [in] - Size of the region in bytes of multiples of page size. + * data_properties [in] - Page types to be allocated, must be one of these: + * - ENCLAVE_PAGE_REG: regular page type. This is the default if not specified. + * - ENCLAVE_PAGE_SS_FIRST: the first page in shadow stack. + * - ENCLAVE_PAGE_SS_REST: the rest page in shadow stack. + * alloc_flags [in] - A bitwise OR of flags describing committing mode, committing + * order, address preference, page type. The untrusted side. Implementation + * should always invoke mmap syscall with MAP_SHARED|MAP_FIXED_NOREPLACE, and + * translate following additional bits to proper parameters invoking mmap or + * other SGX specific syscall(s) provided by the kernel. The alloc_flags param + * of this interface should include exactly one of following for committing mode: + * - ENCLAVE_EMA_COMMIT_NOW: reserves memory range with ENCLAVE_PAGE_READ|SGX_EMA_PROT_WRITE, if supported, + * kernel is given a hint to EAUG EPC pages for the area as soon as possible. + * - ENCLAVE_EMA_COMMIT_ON_DEMAND: reserves memory range, EPC pages can be EAUGed upon #PF. + * ORed with zero or one of the committing order flags: + * - ENCLAVE_EMA_GROWSDOWN: if supported, a hint given for the kernel to EAUG pages from higher + * to lower addresses, no gaps in addresses above the last committed. + * - ENCLAVE_EMA_GROWSUP: if supported, a hint given for the kernel to EAUG pages from lower + * to higher addresses, no gaps in addresses below the last committed. + * enclave_error [out, optional] - An optional pointer to a variable that receives an enclave error code. + * + * Return Values: + * ENCLAVE_ERROR_SUCCESS(0): The operation was successful. + * ENCLAVE_NOT_SUPPORTED: Enavle feature is not supported by the system + * ENCLAVE_LOST: May be returned if the enclave has been removed or if it has not been initialized (via EINIT) + * ENCLAVE_INVALID_ADDRESS: The start address does not point to an enclave. + * ENCLAVE_INVALID_PARAMETER: An invalid combination of flags was provided. + * ENCLAVE_OUT_OF_MEMORY: No EPC left (some OSes like Linux), or system is out of memory for internal allocation by OS or this function. + * ENCLAVE_DEVICE_NO_MEMORY: NO EPC left (some OSes like Windows) + * ENCLAVE_INVALID_ADDRESS: Address does not point to an enclave or valid memory within the enclave + * ENCLAVE_NOT_INITIALIZED: May be returned if the enclave has not been initialized (via EINIT). + * Some configurations may give ENCLAVE_LOST if the enclave has not been initialized. + * ENCLAVE_UNEXPECTED: Unexpected error. + */ + +uint32_t COMM_API enclave_alloc ( + COMM_IN void* target_addr, + COMM_IN size_t target_size, + COMM_IN uint32_t data_properties, + COMM_IN uint32_t alloc_flags, + COMM_OUT_OPT uint32_t* enclave_error +); + +/* enclave_modify() + * Call OS to change permissions, type, or notify EACCEPT done after TRIM. + * + * Parameters: + * target_addr [in] - Start address of the memory to change protections. + * target_size [in] - Length of the area. This must be a multiple of the page size. + * from_data_properties [in] - The original EPCM flags of the EPC pages to be modified. + * Must be bitwise OR of following: + * ENCLAVE_PAGE_READ + * ENCLAVE_PAGE_WRITE + * ENCLAVE_PAGE_EXEC + * ENCLAVE_PAGE_REG: regular page, changeable to TRIM or TCS + * ENCLAVE_PAGE_TRIM: signal to the kernel EACCEPT is done for TRIM pages. + * to_data_properties [in] - The target EPCM flags. This must be bitwise OR of following: + * ENCLAVE_PAGE_READ + * ENCLAVE_PAGE_WRITE + * ENCLAVE_PAGE_EXEC + * ENCLAVE_PAGE_TRIM: change the page type to PT_TRIM. Note the address + * range for trimmed pages may still be reserved by enclave with + * proper permissions. + * ENCLAVE_PAGE_TCS: change the page type to PT_TCS + * + * Return Values: + * ENCLAVE_ERROR_SUCCESS(0): The operation was successful. + * ENCLAVE_NOT_SUPPORTED: Enclave feature is not supported by the system + * ENCLAVE_LOST: May be returned if the enclave has been removed or if it has not been initialized (via EINIT) + * ENCLAVE_INVALID_PARAMETER: An invalid combination of flags was provided. + * ENCLAVE_OUT_OF_MEMORY: No EPC left (some OSes like Linux), or system is out of memory for internal allocation by OS or this function. + * ENCLAVE_DEVICE_NO_MEMORY: NO EPC left (some OSes like Windows) + * ENCLAVE_INVALID_ADDRESS: Address does not point to an enclave or valid memory within the enclave + * ENCLAVE_NOT_INITIALIZED: May be returned if the enclave has not been initialized (via EINIT). + * Some configurations may give ENCLAVE_LOST if the enclave has not been initialized. + * ENCLAVE_UNEXPECTED: Unexpected error. + */ + +uint32_t COMM_API enclave_modify ( + COMM_IN void* target_addr, + COMM_IN size_t target_size, + COMM_IN uint32_t from_data_properties, + COMM_IN uint32_t to_data_properties, + COMM_OUT_OPT uint32_t* enclave_error +); + #ifdef __cplusplus } #endif diff --git a/psw/enclave_common/sgx_enclave_common.lds b/psw/enclave_common/sgx_enclave_common.lds index d76001f1..d10e4811 100644 --- a/psw/enclave_common/sgx_enclave_common.lds +++ b/psw/enclave_common/sgx_enclave_common.lds @@ -7,6 +7,9 @@ global: enclave_get_information; enclave_set_information; enclave_create_ex; + enclave_alloc; + enclave_modify; + enclave_get_features; local: *; }; diff --git a/psw/urts/create_param.h b/psw/urts/create_param.h index 6300d7da..235427e6 100644 --- a/psw/urts/create_param.h +++ b/psw/urts/create_param.h @@ -51,6 +51,8 @@ typedef struct _create_param_t uint64_t rsrv_init_size; uint64_t rsrv_offset; uint64_t rsrv_executable; + uint64_t user_region_offset; + uint64_t user_region_size; uint64_t first_ssa_gpr; uint64_t td_addr; uint64_t tls_addr; diff --git a/psw/urts/enclave.cpp b/psw/urts/enclave.cpp index b7fdc2af..d753b03a 100644 --- a/psw/urts/enclave.cpp +++ b/psw/urts/enclave.cpp @@ -38,8 +38,7 @@ #include "se_error_internal.h" #include "debugger_support.h" #include "se_memory.h" -#include "urts_trim.h" -#include "urts_emodpr.h" +#include "urts_emm.h" #include "rts_cmd.h" #include #include "rts.h" @@ -352,7 +351,7 @@ sgx_status_t CEnclave::ecall(const int proc, const void *ocall_table, void *ms, se_event_wake(m_new_thread_event); pthread_join(m_pthread_tid, NULL); } - ocall_table = m_ocall_table; + /*ocall_table = m_ocall_table; std::vector threads = m_thread_pool->get_thread_list(); for (unsigned idx = 0; idx < threads.size(); ++idx) @@ -381,7 +380,7 @@ sgx_status_t CEnclave::ecall(const int proc, const void *ocall_table, void *ms, return (sgx_status_t)ret; } } - } + }*/ } ret = do_ecall(proc, m_ocall_table, ms, trust_thread); @@ -412,14 +411,10 @@ int CEnclave::ocall(const unsigned int proc, const sgx_ocall_table_t *ocall_tabl if (is_builtin_ocall(proc)) { se_rdunlock(&m_rwlock); - if ((int)proc == EDMM_TRIM) - error = ocall_trim_range(ms); - else if ((int)proc == EDMM_TRIM_COMMIT) - error = ocall_trim_accept(ms); - else if ((int)proc == EDMM_MODPR) - error = ocall_emodpr(ms); - else if ((int)proc == EDMM_MPROTECT) - error = ocall_mprotect(ms); + if ((int)proc == EDMM_ALLOC) + error = ocall_emm_alloc(ms); + else if ((int)proc == EDMM_MODIFY) + error = ocall_emm_modify(ms); } else { diff --git a/psw/urts/enclave_creator_hw.h b/psw/urts/enclave_creator_hw.h index 15d02e20..48f36265 100644 --- a/psw/urts/enclave_creator_hw.h +++ b/psw/urts/enclave_creator_hw.h @@ -60,11 +60,6 @@ public: bool is_driver_compatible(); int get_misc_attr(sgx_misc_attribute_t *sgx_misc_attr, metadata_t *metadata, SGXLaunchToken * const lc, uint32_t flag); bool get_plat_cap(sgx_misc_attribute_t *se_attr); - int emodpr(uint64_t addr, uint64_t size, uint64_t flag); - int mktcs(uint64_t tcs_addr); - int trim_range(uint64_t fromaddr, uint64_t toaddr); - int trim_accept(uint64_t addr); - int remove_range(uint64_t fromaddr, uint64_t numpages); private: virtual bool open_device(); virtual void close_device(); diff --git a/psw/urts/enclave_creator_hw_com.cpp b/psw/urts/enclave_creator_hw_com.cpp index 534f7233..d5c9353f 100644 --- a/psw/urts/enclave_creator_hw_com.cpp +++ b/psw/urts/enclave_creator_hw_com.cpp @@ -39,9 +39,12 @@ #include "se_error_internal.h" #include "prd_css_util.h" #include "se_memcpy.h" +#include "se_detect.h" #include #define EDMM_ENABLE_BIT 0x1ULL +#define ARCH_REQ_XCOMP_PERM 0x1023 +extern "C" int arch_prctl(int code, unsigned long addr); bool EnclaveCreatorHW::use_se_hw() const { @@ -65,7 +68,7 @@ int EnclaveCreatorHW::initialize(sgx_enclave_id_t enclave_id) init_cpuinfo((uint32_t *)info.cpuinfo_table); info.system_feature_set[0] |= (1ULL << SYS_FEATURE_EXTEND); info.size = sizeof(system_features_t); - info.version = (sdk_version_t)MIN((uint32_t)SDK_VERSION_2_3, enclave->get_enclave_version()); + info.version = (sdk_version_t)MIN((uint32_t)SDK_VERSION_3_0, enclave->get_enclave_version()); info.sealed_key = enclave->get_sealed_key(); info.cpu_core_num = (uint32_t)sysconf(_SC_NPROCESSORS_ONLN); if (is_EDMM_supported(enclave_id)) @@ -153,6 +156,13 @@ int EnclaveCreatorHW::get_misc_attr(sgx_misc_attribute_t *sgx_misc_attr, metadat if(~(se_cap.misc_select) & (enclave_css->body.misc_select & enclave_css->body.misc_mask)) return SGX_ERROR_INVALID_MISC; + if(secs_attr->xfrm & (1 << AMX_TILEDATA_SHIFT)) + { + if(0 != arch_prctl(ARCH_REQ_XCOMP_PERM, AMX_TILEDATA_SHIFT)) + { + return SGX_ERROR_UNEXPECTED; + } + } // try to use maximum ablity of cpu sgx_misc_attr->misc_select = se_cap.misc_select & enclave_css->body.misc_select; diff --git a/psw/urts/linux/Makefile b/psw/urts/linux/Makefile index 529d7c2b..ef125ef6 100644 --- a/psw/urts/linux/Makefile +++ b/psw/urts/linux/Makefile @@ -31,6 +31,8 @@ include ../../../buildenv.mk +URTS_VER:= $(shell awk '$$2 ~ /URTS_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) + ifndef DEBUG CXXFLAGS += -DDISABLE_TRACE CFLAGS += -DDISABLE_TRACE @@ -95,8 +97,7 @@ OBJ2 := urts.o \ debugger_support.o \ get_thread_id.o \ prd_css_util.o \ - urts_emodpr.o \ - urts_trim.o \ + urts_emm.o \ edmm_utility.o OBJ3 := enter_enclave.o \ @@ -140,7 +141,7 @@ $(LIBURTS_INTERNAL): $(INTERNAL_OBJ) $(LIBWRAPPER) $(LIBSGX_ENCLAVE_COMMON) ittn @$(RM) -rf $(BUILD_DIR)/.sgx_enclave_common $(LIBURTS): $(URTS_OBJ) $(LIBWRAPPER) $(LIBSGX_ENCLAVE_COMMON) ittnotify - $(CXX) $(CXXFLAGS) -shared -Wl,-soname=$@ $(LIB) -o $@ $(URTS_OBJ) $(LDFLAGS) + $(CXX) $(CXXFLAGS) -shared -Wl,-soname=$@.$(call SPLIT_VERSION,$(URTS_VER),1) $(LIB) -o $@ $(URTS_OBJ) $(LDFLAGS) $(LIBURTS_DEBUG): $(LIBURTS) ifndef DEBUG diff --git a/psw/urts/linux/edmm_utility.cpp b/psw/urts/linux/edmm_utility.cpp index 69e701a6..1f6f9e42 100644 --- a/psw/urts/linux/edmm_utility.cpp +++ b/psw/urts/linux/edmm_utility.cpp @@ -41,7 +41,7 @@ #include #include #include - +#include #define SGX_URTS_CMD "for f in $(find /usr/$(basename $(gcc -print-multi-os-directory)) -name 'libsgx_urts.so' 2> /dev/null); do strings $f|grep 'SGX_URTS_VERSION_2'; done" #define SGX_CPUID 0x12 @@ -101,11 +101,6 @@ bool get_driver_type(int *driver_type) int hdev = open("/dev/sgx/enclave", O_RDWR); //attempt to open the in-kernel driver if (-1 == hdev) - { - //if /dev/sgx/enclave is not present, try to open /dev/sgx_enclave - hdev = open("/dev/sgx_enclave", O_RDWR); - } - if (-1 == hdev) { hdev = open("/dev/isgx", O_RDWR); //attempt to open the out-of-tree driver if (-1 == hdev) @@ -155,11 +150,6 @@ extern "C" bool open_se_device(int driver_type, int *hdevice) if (driver_type == SGX_DRIVER_IN_KERNEL) { *hdevice = open("/dev/sgx/enclave", O_RDWR); //attempt to open the in-kernel driver - //if /dev/sgx/enclave is not present, try to open /dev/sgx_enclave - if(-1 == *hdevice) - { - *hdevice = open("/dev/sgx_enclave", O_RDWR); - } } else if (driver_type == SGX_DRIVER_DCAP) { @@ -236,8 +226,17 @@ extern "C" bool is_cpu_support_edmm() */ extern "C" bool is_driver_support_edmm(int hdevice) { - if (-1 == hdevice) - return false; + if (-1 == hdevice){ + if(!open_se_device(SGX_DRIVER_IN_KERNEL, &hdevice)) + return false; + struct sgx_enclave_restrict_permissions ioc; + memset(&ioc, 0, sizeof(ioc)); + + int ret = ioctl(hdevice, SGX_IOC_ENCLAVE_RESTRICT_PERMISSIONS, &ioc); + bool supported = ret != -1 || (errno != ENOTTY); + close_se_device(&hdevice); + return supported; + } sgx_modification_param param; param.flags = 0; diff --git a/psw/urts/linux/enclave_creator_hw.cpp b/psw/urts/linux/enclave_creator_hw.cpp index d956e818..21bae2ff 100644 --- a/psw/urts/linux/enclave_creator_hw.cpp +++ b/psw/urts/linux/enclave_creator_hw.cpp @@ -49,7 +49,7 @@ #include #include #include - +#include "sgx_mm.h" #define POINTER_TO_U64(A) ((__u64)((uintptr_t)(A))) static EnclaveCreatorHW g_enclave_creator_hw; @@ -306,103 +306,11 @@ void EnclaveCreatorHW::close_device() m_hdevice = -1; } -int EnclaveCreatorHW::emodpr(uint64_t addr, uint64_t size, uint64_t flag) -{ - sgx_modification_param params; - memset(¶ms, 0 ,sizeof(sgx_modification_param)); - params.range.start_addr = (unsigned long)addr; - params.range.nr_pages = (unsigned int)(size/SE_PAGE_SIZE); - params.flags = (unsigned long)flag; - - int ret = ioctl(m_hdevice, SGX_IOC_ENCLAVE_EMODPR, ¶ms); - if (ret) - { - SE_TRACE(SE_TRACE_ERROR, "SGX_IOC_ENCLAVE_EMODPR failed %d\n", errno); - return error_driver2urts(ret, errno); - } - - return SGX_SUCCESS; -} - -int EnclaveCreatorHW::mktcs(uint64_t tcs_addr) -{ - sgx_range params; - memset(¶ms, 0 ,sizeof(sgx_range)); - params.start_addr = (unsigned long)tcs_addr; - params.nr_pages = 1; - - int ret = ioctl(m_hdevice, SGX_IOC_ENCLAVE_MKTCS, ¶ms); - if (ret) - { - SE_TRACE(SE_TRACE_ERROR, "MODIFY_TYPE failed %d\n", errno); - return error_driver2urts(ret, errno); - } - - return SGX_SUCCESS; -} - -int EnclaveCreatorHW::trim_range(uint64_t fromaddr, uint64_t toaddr) -{ - sgx_range params; - memset(¶ms, 0 ,sizeof(sgx_range)); - params.start_addr = (unsigned long)fromaddr; - params.nr_pages = (unsigned int)((toaddr - fromaddr)/SE_PAGE_SIZE); - - int ret= ioctl(m_hdevice, SGX_IOC_ENCLAVE_TRIM, ¶ms); - if (ret) - { - SE_TRACE(SE_TRACE_ERROR, "SGX_IOC_ENCLAVE_TRIM failed %d\n", errno); - return error_driver2urts(ret, errno); - } - - return SGX_SUCCESS; - -} - -int EnclaveCreatorHW::trim_accept(uint64_t addr) -{ - sgx_range params; - memset(¶ms, 0 ,sizeof(sgx_range)); - params.start_addr = (unsigned long)addr; - params.nr_pages = 1; - - int ret = ioctl(m_hdevice, SGX_IOC_ENCLAVE_NOTIFY_ACCEPT, ¶ms); - - - if (ret) - { - SE_TRACE(SE_TRACE_ERROR, "TRIM_RANGE_COMMIT failed %d\n", errno); - return error_driver2urts(ret, errno); - } - - return SGX_SUCCESS; -} - -int EnclaveCreatorHW::remove_range(uint64_t fromaddr, uint64_t numpages) -{ - int ret = -1; - uint64_t i; - unsigned long start; - - for (i = 0; i < numpages; i++) - { - start = (unsigned long)fromaddr + (unsigned long)(i << SE_PAGE_SHIFT); - ret = ioctl(m_hdevice, SGX_IOC_ENCLAVE_PAGE_REMOVE, &start); - if (ret) - { - SE_TRACE(SE_TRACE_ERROR, "PAGE_REMOVE failed %d\n", errno); - return error_driver2urts(ret, errno); - } - } - - return SGX_SUCCESS; -} - //EDMM is supported if and only if all of the following requirements are met: //1. We operate in HW mode //2. CPU has EDMM support //3. Driver has EDMM support -//4. Both the uRTS version and enclave (metadata) version are higher than 1.5 +//4. SDK version >= 3.0 bool EnclaveCreatorHW::is_EDMM_supported(sgx_enclave_id_t enclave_id) { bool supported = false, driver_supported = false, cpu_edmm = false; @@ -415,7 +323,7 @@ bool EnclaveCreatorHW::is_EDMM_supported(sgx_enclave_id_t enclave_id) driver_supported = is_driver_compatible(); //return value of get_enclave_version() considers the version of uRTS and enclave metadata - supported = use_se_hw() && cpu_edmm && driver_supported && (enclave->get_enclave_version() >= SDK_VERSION_2_0); + supported = use_se_hw() && cpu_edmm && driver_supported && (enclave->get_enclave_version() >= SDK_VERSION_3_0); return supported; } diff --git a/psw/urts/linux/isgx_user.h b/psw/urts/linux/isgx_user.h index 3c4dfdd0..177b5027 100644 --- a/psw/urts/linux/isgx_user.h +++ b/psw/urts/linux/isgx_user.h @@ -4,7 +4,7 @@ * * GPL LICENSE SUMMARY * - * Copyright(c) 2016 Intel Corporation. + * Copyright(c) 2016-2022 Intel Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as @@ -21,7 +21,7 @@ * * BSD LICENSE * - * Copyright(c) 2016 Intel Corporation. + * Copyright(c) 2016-2022 Intel Corporation. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -55,6 +55,7 @@ * Suresh Siddha * Serge Ayoun * Shay Katz-zamir + * Haitao Huang */ #ifndef _UAPI_ASM_X86_SGX_H @@ -108,16 +109,28 @@ enum sgx_page_flags { _IOW(SGX_MAGIC, 0x02, struct sgx_enclave_init) #define SGX_IOC_ENCLAVE_SET_ATTRIBUTE \ _IOW(SGX_MAGIC, 0x03, struct sgx_enclave_set_attribute) +#define SGX_IOC_VEPC_REMOVE_ALL \ + _IO(SGX_MAGIC, 0x04) +#define SGX_IOC_ENCLAVE_RESTRICT_PERMISSIONS \ + _IOWR(SGX_MAGIC, 0x05, struct sgx_enclave_restrict_permissions) +#define SGX_IOC_ENCLAVE_MODIFY_TYPES \ + _IOWR(SGX_MAGIC, 0x06, struct sgx_enclave_modify_types) +#define SGX_IOC_ENCLAVE_REMOVE_PAGES \ + _IOWR(SGX_MAGIC, 0x07, struct sgx_enclave_remove_pages) + + +/* Legacy OOT driver support for EDMM */ #define SGX_IOC_ENCLAVE_EMODPR \ _IOW(SGX_MAGIC, 0x09, struct sgx_modification_param) #define SGX_IOC_ENCLAVE_MKTCS \ _IOW(SGX_MAGIC, 0x0a, struct sgx_range) #define SGX_IOC_ENCLAVE_TRIM \ _IOW(SGX_MAGIC, 0x0b, struct sgx_range) + +//Legacy implementation to ensure EPC pages removed no later by this ioctl + #define SGX_IOC_ENCLAVE_NOTIFY_ACCEPT \ _IOW(SGX_MAGIC, 0x0c, struct sgx_range) -#define SGX_IOC_ENCLAVE_PAGE_REMOVE \ - _IOW(SGX_MAGIC, 0x0d, unsigned long) //Note: SGX_IOC_ENCLAVE_CREATE is the same for in-kernel except that it returns a file handle for in-kernel #define SGX_IOC_ENCLAVE_ADD_PAGES_IN_KERNEL \ @@ -267,7 +280,7 @@ struct sgx_enclave_destroy { /* - * SGX2.0 definitions + * SGX2.0 definitions for Legacy OOT driver */ #define SGX_GROW_UP_FLAG 1 @@ -284,6 +297,61 @@ struct sgx_modification_param { }; +/** + * struct sgx_enclave_restrict_permissions - parameters for ioctl + * %SGX_IOC_ENCLAVE_RESTRICT_PERMISSIONS + * @offset: starting page offset (page aligned relative to enclave base + * address defined in SECS) + * @length: length of memory (multiple of the page size) + * @permissions:new permission bits for pages in range described by @offset + * and @length + * @result: (output) SGX result code of ENCLS[EMODPR] function + * @count: (output) bytes successfully changed (multiple of page size) + */ +struct sgx_enclave_restrict_permissions { + __u64 offset; + __u64 length; + __u64 permissions; + __u64 result; + __u64 count; +}; + +/** + * struct sgx_enclave_modify_type - parameters for %SGX_IOC_ENCLAVE_MODIFY_TYPES + * @offset: starting page offset (page aligned relative to enclave base + * address defined in SECS) + * @length: length of memory (multiple of the page size) + * @page_type: new type for pages in range described by @offset and @length + * @result: (output) SGX result code of ENCLS[EMODT] function + * @count: (output) bytes successfully changed (multiple of page size) + */ +struct sgx_enclave_modify_types { + __u64 offset; + __u64 length; + __u64 page_type; + __u64 result; + __u64 count; +}; + +/** + * struct sgx_enclave_remove_pages - %SGX_IOC_ENCLAVE_REMOVE_PAGES parameters + * @offset: starting page offset (page aligned relative to enclave base + * address defined in SECS) + * @length: length of memory (multiple of the page size) + * @count: (output) bytes successfully changed (multiple of page size) + * + * Regular (PT_REG) or TCS (PT_TCS) can be removed from an initialized + * enclave if the system supports SGX2. First, the %SGX_IOC_ENCLAVE_MODIFY_TYPE + * ioctl() should be used to change the page type to PT_TRIM. After that + * succeeds ENCLU[EACCEPT] should be run from within the enclave and then + * %SGX_IOC_ENCLAVE_REMOVE_PAGES can be used to complete the page removal. + */ +struct sgx_enclave_remove_pages { + __u64 offset; + __u64 length; + __u64 count; +}; + struct sgx_enclave_run; @@ -363,7 +431,7 @@ struct sgx_enclave_run { * Most exceptions reported on ENCLU, including those that occur within the * enclave, are fixed up and reported synchronously instead of being delivered * via a standard signal. Debug Exceptions (#DB) and Breakpoints (#BP) are - * never fixed up and are always delivered via standard signals. On synchrously + * never fixed up and are always delivered via standard signals. On synchronously * reported exceptions, -EFAULT is returned and details about the exception are * recorded in @run.exception, the optional sgx_enclave_exception struct. * diff --git a/psw/urts/linux/sig_handler.cpp b/psw/urts/linux/sig_handler.cpp index b84d0a22..00cfd601 100644 --- a/psw/urts/linux/sig_handler.cpp +++ b/psw/urts/linux/sig_handler.cpp @@ -292,7 +292,6 @@ void* get_vdso_sym(const char* vdso_func_name) return ret; } - static int sgx_urts_vdso_handler(long rdi, long rsi, long rdx, long ursp, long r8, long r9, struct sgx_enclave_run *run) { @@ -304,15 +303,17 @@ static int sgx_urts_vdso_handler(long rdi, long rsi, long rdx, long ursp, long r { //need to handle exception here __u64 *user_data = (__u64*)run->user_data; - void *ocall_table = reinterpret_cast(user_data[0]); CTrustThread* trust_thread = reinterpret_cast(user_data[1]); - if(ocall_table == NULL || trust_thread == NULL) + if(trust_thread == NULL) { run->user_data = SGX_ERROR_UNEXPECTED; return 0; } + void *ocall_table = reinterpret_cast(user_data[0]); + //directly use the original tcs unsigned int ret = do_ecall(ECMD_EXCEPT, ocall_table, NULL, trust_thread); + if(SGX_SUCCESS == ret) { return SE_ERESUME; @@ -337,14 +338,14 @@ static int sgx_urts_vdso_handler(long rdi, long rsi, long rdx, long ursp, long r else { __u64 *user_data = (__u64*)run->user_data; - sgx_ocall_table_t *ocall_table = reinterpret_cast(user_data[0]); CTrustThread* trust_thread = reinterpret_cast(user_data[1]); - if(ocall_table == NULL || trust_thread == NULL) + if(trust_thread == NULL) { run->user_data = SGX_ERROR_UNEXPECTED; return 0; } + sgx_ocall_table_t *ocall_table = reinterpret_cast(user_data[0]); auto status = stack_sticker((unsigned int )rdi, ocall_table, (void *)rsi, trust_thread, trust_thread->get_tcs()); if(status == (int)SE_ERROR_READ_LOCK_FAIL) diff --git a/sdk/trts/trts_emodpr.cpp b/psw/urts/linux/urts_emm.cpp similarity index 60% rename from sdk/trts/trts_emodpr.cpp rename to psw/urts/linux/urts_emm.cpp index 79d85ebd..d390021b 100644 --- a/sdk/trts/trts_emodpr.cpp +++ b/psw/urts/linux/urts_emm.cpp @@ -29,51 +29,51 @@ * */ +#include "urts_emm.h" +#include "sgx_enclave_common.h" -#include "trts_emodpr.h" +#ifdef SE_SIM +#include "util.h" +#include +#endif -#include "sgx_trts.h" // for sgx_ocalloc, sgx_is_outside_enclave -#include "arch.h" -#include "sgx_edger8r.h" // for sgx_ocall etc. -#include "internal/rts.h" +typedef struct ms_alloc_ocall_t { + int32_t retval; + size_t addr; + size_t size; + uint32_t page_properties; + uint32_t alloc_flags; +} ms_emm_alloc_ocall_t; -/* sgx_ocfree() just restores the original outside stack pointer. */ -#define OCALLOC(val, type, len) do { \ - void* __tmp = sgx_ocalloc(len); \ - if (__tmp == NULL) { \ - sgx_ocfree(); \ - return SGX_ERROR_UNEXPECTED;\ - } \ - (val) = (type)__tmp; \ -} while (0) - -typedef struct ms_change_permissions_ocall_t { - size_t ms_addr; - size_t ms_size; - uint64_t ms_epcm_perms; -} ms_change_permissions_ocall_t; - -sgx_status_t SGXAPI change_permissions_ocall(size_t addr, size_t size, uint64_t epcm_perms, const int proc) +extern "C" sgx_status_t SGX_CDECL ocall_emm_alloc(void* pms) { #ifdef SE_SIM - (void)addr; - (void)size; - (void)epcm_perms; - (void)proc; - return SGX_SUCCESS; + UNUSED(pms); + return SGX_ERROR_FEATURE_NOT_SUPPORTED; #else - sgx_status_t status = SGX_SUCCESS; - - ms_change_permissions_ocall_t* ms; - OCALLOC(ms, ms_change_permissions_ocall_t*, sizeof(*ms)); - - ms->ms_addr = addr; - ms->ms_size = size; - ms->ms_epcm_perms = epcm_perms; - status = sgx_ocall(proc, ms); - - - sgx_ocfree(); - return status; + ms_emm_alloc_ocall_t* ms = SGX_CAST(ms_emm_alloc_ocall_t*, pms); + ms->retval = enclave_alloc((void *)ms->addr, ms->size,ms->page_properties, ms->alloc_flags, NULL); + return SGX_SUCCESS; +#endif +} + +typedef struct ms_modify_ocall_t { + int32_t retval; + size_t addr; + size_t size; + uint32_t flags_from; + uint32_t flags_to; +} ms_emm_modify_ocall_t; + + +extern "C" sgx_status_t SGX_CDECL ocall_emm_modify(void* pms) +{ +#ifdef SE_SIM + UNUSED(pms); + return SGX_ERROR_FEATURE_NOT_SUPPORTED; +#else + ms_emm_modify_ocall_t* ms = SGX_CAST(ms_emm_modify_ocall_t*, pms); + ms->retval = enclave_modify((void *)ms->addr, ms->size, ms->flags_from, ms->flags_to, NULL); + return SGX_SUCCESS; #endif } diff --git a/psw/urts/linux/urts_emodpr.h b/psw/urts/linux/urts_emm.h similarity index 92% rename from psw/urts/linux/urts_emodpr.h rename to psw/urts/linux/urts_emm.h index 12797b5f..74709445 100644 --- a/psw/urts/linux/urts_emodpr.h +++ b/psw/urts/linux/urts_emm.h @@ -29,8 +29,8 @@ * */ -#ifndef _URTS_EMODPR_H_ -#define _URTS_EMODPR_H_ +#ifndef _URTS_EMM_H_ +#define _URTS_EMM_H_ #include #include @@ -46,8 +46,8 @@ extern "C" { -sgx_status_t SGX_CDECL ocall_emodpr(void* pms); -sgx_status_t SGX_CDECL ocall_mprotect(void *pms); +sgx_status_t SGX_CDECL ocall_emm_alloc(void* pms); +sgx_status_t SGX_CDECL ocall_emm_modify(void *pms); #ifdef __cplusplus diff --git a/psw/urts/linux/urts_emodpr.cpp b/psw/urts/linux/urts_emodpr.cpp deleted file mode 100644 index 5696b21e..00000000 --- a/psw/urts/linux/urts_emodpr.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Intel Corporation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include "urts_emodpr.h" -#include "enclave_creator.h" -#include - -typedef struct ms_emodpr_ocall_t { - size_t ms_addr; - size_t ms_size; - uint64_t ms_epcm_perms; -} ms_trim_emodpr_ocall_t; - - - -sgx_status_t ocall_emodpr(void* pms) -{ - int ret = 0; - ms_trim_emodpr_ocall_t* ms = SGX_CAST(ms_trim_emodpr_ocall_t*, pms); - - if(ms->ms_epcm_perms < (SI_FLAG_R|SI_FLAG_W|SI_FLAG_X)) - { - EnclaveCreator *enclave_creator = get_enclave_creator(); - if(NULL == enclave_creator) - { - return SGX_ERROR_UNEXPECTED; - } - ret = enclave_creator->emodpr(ms->ms_addr, ms->ms_size, ms->ms_epcm_perms); - if(0 != ret) - { - return (sgx_status_t)ret; - } - } - if(ms->ms_epcm_perms != SI_FLAG_NONE) - { - ret = mprotect((void*)ms->ms_addr, ms->ms_size, (int)ms->ms_epcm_perms); - if(ret != 0) - { - return SGX_ERROR_UNEXPECTED; - } - } - - return SGX_SUCCESS; -} - -sgx_status_t ocall_mprotect(void *pms) -{ - int ret = 0; - ms_trim_emodpr_ocall_t* ms = SGX_CAST(ms_trim_emodpr_ocall_t*, pms); - if(ms->ms_epcm_perms & ~(SI_FLAG_R|SI_FLAG_W|SI_FLAG_X)) - { - return SGX_ERROR_INVALID_PARAMETER; - } - else - { - ret = mprotect((void*)ms->ms_addr, ms->ms_size, (int)ms->ms_epcm_perms); - if(ret != 0) - { - return SGX_ERROR_UNEXPECTED; - } - } - - return SGX_SUCCESS; -} diff --git a/psw/urts/linux/urts_trim.cpp b/psw/urts/linux/urts_trim.cpp deleted file mode 100644 index 75ac2c11..00000000 --- a/psw/urts/linux/urts_trim.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Intel Corporation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include "urts_trim.h" -#include "enclave_creator.h" - -typedef struct ms_trim_range_ocall_t { - size_t ms_fromaddr; - size_t ms_toaddr; -} ms_trim_range_ocall_t; - -typedef struct ms_trim_accept_ocall_t { - size_t ms_addr; -} ms_trim_accept_ocall_t; - -sgx_status_t ocall_trim_range(void* pms) -{ - int ret = 0; - ms_trim_range_ocall_t* ms = SGX_CAST(ms_trim_range_ocall_t*, pms); - - EnclaveCreator *enclave_creator = get_enclave_creator(); - if(NULL == enclave_creator) - { - return SGX_ERROR_UNEXPECTED; - } - ret = enclave_creator->trim_range(ms->ms_fromaddr, ms->ms_toaddr); - - return (sgx_status_t)ret; -} - -sgx_status_t ocall_trim_accept(void* pms) -{ - int ret = 0; - ms_trim_accept_ocall_t* ms = SGX_CAST(ms_trim_accept_ocall_t*, pms); - - EnclaveCreator *enclave_creator = get_enclave_creator(); - if(NULL == enclave_creator) - { - return SGX_ERROR_UNEXPECTED; - } - - ret = enclave_creator->trim_accept(ms->ms_addr); - - return (sgx_status_t)ret; - -} - - diff --git a/psw/urts/loader.cpp b/psw/urts/loader.cpp index 67eea74b..84d18257 100644 --- a/psw/urts/loader.cpp +++ b/psw/urts/loader.cpp @@ -320,65 +320,6 @@ int CLoader::build_pages(const uint64_t start_rva, const uint64_t size, const vo return SGX_SUCCESS; } -int CLoader::post_init_action(layout_t *layout_start, layout_t *layout_end, uint64_t delta) -{ - int ret = SGX_SUCCESS; - - for(layout_t *layout = layout_start; layout < layout_end; layout++) - { - if (!IS_GROUP_ID(layout->group.id) && (layout->entry.attributes & PAGE_ATTR_POST_REMOVE)) - { - uint64_t start_addr = layout->entry.rva + delta + (uint64_t)get_start_addr(); - uint64_t page_count = (uint64_t)layout->entry.page_count; - if (SGX_SUCCESS != (ret = get_enclave_creator()->trim_range(start_addr, start_addr + (page_count << SE_PAGE_SHIFT)))) - return ret; - - } - else if (IS_GROUP_ID(layout->group.id)) - { - uint64_t step = 0; - for(uint32_t j = 0; j < layout->group.load_times; j++) - { - step += layout->group.load_step; - if(SGX_SUCCESS != (ret = post_init_action(&layout[-layout->group.entry_count], layout, step))) - return ret; - } - } - } - return SGX_SUCCESS; -} - -int CLoader::post_init_action_commit(layout_t *layout_start, layout_t *layout_end, uint64_t delta) -{ - int ret = SGX_SUCCESS; - - for(layout_t *layout = layout_start; layout < layout_end; layout++) - { - if (!IS_GROUP_ID(layout->group.id) && (layout->entry.attributes & PAGE_ATTR_POST_REMOVE)) - { - uint64_t start_addr = layout->entry.rva + delta + (uint64_t)get_start_addr(); - uint64_t page_count = (uint64_t)layout->entry.page_count; - - for (uint64_t i = 0; i < page_count; i++) - { - if (SGX_SUCCESS != (ret = get_enclave_creator()->trim_accept(start_addr + (i << SE_PAGE_SHIFT)))) - return ret; - } - } - else if (IS_GROUP_ID(layout->group.id)) - { - uint64_t step = 0; - for(uint32_t j = 0; j < layout->group.load_times; j++) - { - step += layout->group.load_step; - if(SGX_SUCCESS != (ret = post_init_action_commit(&layout[-layout->group.entry_count], layout, step))) - return ret; - } - } - } - return SGX_SUCCESS; -} - int CLoader::build_context(const uint64_t start_rva, layout_entry_t *layout) { int ret = SGX_ERROR_UNEXPECTED; @@ -952,35 +893,6 @@ int CLoader::set_memory_protection() return SGX_ERROR_UNEXPECTED; } - if ((META_DATA_MAKE_VERSION(MAJOR_VERSION,MINOR_VERSION) <= m_metadata->version) && - get_enclave_creator()->is_EDMM_supported(get_enclave_id())) - { - std::vector> pages_to_protect; - m_parser.get_pages_to_protect((uint64_t)m_start_addr, pages_to_protect); - for (auto page : pages_to_protect) - { uint64_t start = 0, len = 0; - uint32_t perm = 0; - std::tie(start, len, perm) = page; - ret = get_enclave_creator()->emodpr(start, len, (uint64_t)perm); - if (ret != SGX_SUCCESS) - return SGX_ERROR_UNEXPECTED; - } - - //On EDMM supported platform, force set rsrv memory region's attribute to RW although it's was set to RWX by 1 - layout_t *layout_start = GET_PTR(layout_t, m_metadata, m_metadata->dirs[DIR_LAYOUT].offset); - layout_t *layout_end = GET_PTR(layout_t, m_metadata, m_metadata->dirs[DIR_LAYOUT].offset + m_metadata->dirs[DIR_LAYOUT].size); - for (layout_t *layout = layout_start; layout < layout_end; layout++) - { - if (layout->entry.id == LAYOUT_ID_RSRV_MIN && layout->entry.si_flags == SI_FLAGS_RWX && layout->entry.page_count > 0) - { - ret = get_enclave_creator()->emodpr((uint64_t)m_start_addr + layout->entry.rva, (uint64_t)layout->entry.page_count << SE_PAGE_SHIFT, (uint64_t)(SI_FLAG_R |SI_FLAG_W )); - if (ret != SGX_SUCCESS) - return SGX_ERROR_UNEXPECTED; - break; - } - } - } - //set memory protection for context ret = set_context_protection(GET_PTR(layout_t, m_metadata, m_metadata->dirs[DIR_LAYOUT].offset), GET_PTR(layout_t, m_metadata, m_metadata->dirs[DIR_LAYOUT].offset + m_metadata->dirs[DIR_LAYOUT].size), @@ -989,7 +901,6 @@ int CLoader::set_memory_protection() { return ret; } - return SGX_SUCCESS; } @@ -1028,10 +939,22 @@ int CLoader::set_context_protection(layout_t *layout_start, layout_t *layout_end } #endif } - - ret = mprotect(GET_PTR(void, m_start_addr, layout->entry.rva + delta), +#ifdef SE_SIM + ret = mprotect(GET_PTR(void, m_start_addr, layout->entry.rva + delta), (size_t)layout->entry.page_count << SE_PAGE_SHIFT, prot); +#else + ret = 0; + if((layout->entry.attributes&PAGE_ATTR_EADD)) + { + ret = mprotect(GET_PTR(void, m_start_addr, layout->entry.rva + delta), + (size_t)layout->entry.page_count << SE_PAGE_SHIFT, prot); + } + else if(prot!=PROT_NONE) + { + ret = 0; + } +#endif if(ret != 0) { SE_TRACE(SE_TRACE_WARNING, "mprotect(rva=%" PRIu64 ", len=%" PRIu64 ", flags=%d) failed\n", diff --git a/psw/urts/loader.h b/psw/urts/loader.h index 12e46f74..f4522801 100644 --- a/psw/urts/loader.h +++ b/psw/urts/loader.h @@ -68,8 +68,6 @@ public: const std::vector>& get_tcs_list() const; void* get_symbol_address(const char* const sym); int set_memory_protection(); - int post_init_action(layout_t *start, layout_t *end, uint64_t delta); - int post_init_action_commit(layout_t *start, layout_t *end, uint64_t delta); private: int build_mem_region(const section_info_t &sec_info); diff --git a/psw/urts/se_detect.cpp b/psw/urts/se_detect.cpp index 5528aa99..9def8d41 100644 --- a/psw/urts/se_detect.cpp +++ b/psw/urts/se_detect.cpp @@ -120,6 +120,14 @@ bool get_plat_cap_by_cpuid(sgx_misc_attribute_t *se_misc_attr) { se_misc_attr->secs_attr.xfrm &= ~(SGX_XFRM_PKRU); } + + // Check AMX + // XTILECFG and XTILEDATA should be set at the same time + if ((se_misc_attr->secs_attr.xfrm & SGX_XFRM_AMX) && + ((se_misc_attr->secs_attr.xfrm & SGX_XFRM_AMX) != SGX_XFRM_AMX)) + { + se_misc_attr->secs_attr.xfrm &= ~(SGX_XFRM_AMX); + } // use cpuid to get the misc_select __cpuidex(cpu_info, SE_LEAF, 0); se_misc_attr->misc_select = cpu_info[1]; diff --git a/psw/urts/se_detect.h b/psw/urts/se_detect.h index 2bb02b61..20166a11 100644 --- a/psw/urts/se_detect.h +++ b/psw/urts/se_detect.h @@ -43,6 +43,10 @@ // ECX[9] #define PKRU_SHIFT 9 +#define AMX_TILECFG_SHIFT 17 +#define AMX_TILEDATA_SHIFT 18 + + // CPUID function 1 // ECX[26] enums general support for XSAVE // ECX[27] enums XSAVE is enabled or not diff --git a/psw/urts/tcs.cpp b/psw/urts/tcs.cpp index fb482762..c98e5a37 100644 --- a/psw/urts/tcs.cpp +++ b/psw/urts/tcs.cpp @@ -433,7 +433,7 @@ CTrustThread * CTrustThreadPool::acquire_thread(int ecall_cmd) } if(is_special_ecall != true && - need_to_new_thread() == true) + need_to_new_thread() == true && NULL != m_utility_thread) { m_utility_thread->get_enclave()->fill_tcs_mini_pool_fn(); } @@ -473,12 +473,6 @@ bool CTrustThreadPool::need_to_new_thread() return true; } - -static int make_tcs(size_t tcs) -{ - return g_enclave_creator->mktcs(tcs); -} - struct ms_str { void * ms; @@ -506,16 +500,11 @@ sgx_status_t CTrustThreadPool::new_thread() return SGX_SUCCESS; } - size_t octbl_buf[ROUND_TO(sizeof(sgx_ocall_table_t) + sizeof(void*), sizeof(size_t)) / sizeof(size_t)]; - sgx_ocall_table_t *octbl = reinterpret_cast(octbl_buf); - octbl->count = 1; - void **ocalls = octbl->ocall; - *ocalls = reinterpret_cast(make_tcs); CTrustThread *trust_thread = m_unallocated_threads.back(); tcs_t *tcsp = trust_thread->get_tcs(); struct ms_str ms1; ms1.ms = tcsp; - ret = (sgx_status_t)do_ecall(ECMD_MKTCS, octbl, &ms1, m_utility_thread); + ret = (sgx_status_t)do_ecall(ECMD_MKTCS, NULL, &ms1, m_utility_thread); if (SGX_SUCCESS == ret ) { //add tcs to debug tcs info list diff --git a/psw/urts/urts_com.h b/psw/urts/urts_com.h index 40a1e0e4..b5a73c28 100644 --- a/psw/urts/urts_com.h +++ b/psw/urts/urts_com.h @@ -196,6 +196,14 @@ static sgx_status_t get_metadata(BinParser *parser, const int debug, metadata_t SE_TRACE(SE_TRACE_ERROR, "ERROR: metadata's size can't be zero.\n"); return SGX_ERROR_INVALID_METADATA; } + + // bypass metadata 2.x + if (MAJOR_VERSION_OF_METADATA((*metadata)->version)%SGX_MAJOR_VERSION_GAP == 2) + { + meta_rva += (*metadata)->size; + continue; + } + //check metadata version if(check_metadata_version(urts_version, (*metadata)->version) == true) { @@ -284,12 +292,7 @@ static int __create_enclave(BinParser &parser, if (MAJOR_VERSION_OF_METADATA(metadata->version) % SGX_MAJOR_VERSION_GAP == MAJOR_VERSION_OF_METADATA(urts_version)% SGX_MAJOR_VERSION_GAP && MINOR_VERSION_OF_METADATA(metadata->version) >= MINOR_VERSION_OF_METADATA(urts_version)) { - enclave_version = SDK_VERSION_2_3; - } - else if (MAJOR_VERSION_OF_METADATA(metadata->version) % SGX_MAJOR_VERSION_GAP == MAJOR_VERSION_OF_METADATA(urts_version)% SGX_MAJOR_VERSION_GAP && - MINOR_VERSION_OF_METADATA(metadata->version) < MINOR_VERSION_OF_METADATA(urts_version)) - { - enclave_version = SDK_VERSION_2_0; + enclave_version = SDK_VERSION_3_0; } // initialize the enclave object @@ -406,20 +409,6 @@ static int __create_enclave(BinParser &parser, //generate load debug event after EINIT generate_enclave_debug_event(URTS_EXCEPTION_POSTINITENCLAVE, debug_info); - if (get_enclave_creator()->is_EDMM_supported(loader.get_enclave_id())) - { - layout_t *layout_start = GET_PTR(layout_t, metadata, metadata->dirs[DIR_LAYOUT].offset); - layout_t *layout_end = GET_PTR(layout_t, metadata, metadata->dirs[DIR_LAYOUT].offset + metadata->dirs[DIR_LAYOUT].size); - if (SGX_SUCCESS != (ret = loader.post_init_action(layout_start, layout_end, 0))) - { - SE_TRACE(SE_TRACE_ERROR, "trim range error.\n"); - sgx_status_t status = SGX_SUCCESS; - generate_enclave_debug_event(URTS_EXCEPTION_PREREMOVEENCLAVE, debug_info); - CEnclavePool::instance()->remove_enclave(loader.get_enclave_id(), status); - goto fail; - } - } - //call trts to do some initialization if(SGX_SUCCESS != (ret = get_enclave_creator()->initialize(loader.get_enclave_id()))) { @@ -429,21 +418,6 @@ static int __create_enclave(BinParser &parser, goto fail; } - if (get_enclave_creator()->is_EDMM_supported(loader.get_enclave_id())) - { - - layout_t *layout_start = GET_PTR(layout_t, metadata, metadata->dirs[DIR_LAYOUT].offset); - layout_t *layout_end = GET_PTR(layout_t, metadata, metadata->dirs[DIR_LAYOUT].offset + metadata->dirs[DIR_LAYOUT].size); - if (SGX_SUCCESS != (ret = loader.post_init_action_commit(layout_start, layout_end, 0))) - { - SE_TRACE(SE_TRACE_ERROR, "trim page commit error.\n"); - sgx_status_t status = SGX_SUCCESS; - generate_enclave_debug_event(URTS_EXCEPTION_PREREMOVEENCLAVE, debug_info); - CEnclavePool::instance()->remove_enclave(loader.get_enclave_id(), status); - goto fail; - } - } - if(SGX_SUCCESS != (ret = loader.set_memory_protection())) { sgx_status_t status = SGX_SUCCESS; diff --git a/sdk/cpprt/linux/exception.cc b/sdk/cpprt/linux/exception.cc index ed16a0df..2223b8bb 100644 --- a/sdk/cpprt/linux/exception.cc +++ b/sdk/cpprt/linux/exception.cc @@ -1352,11 +1352,30 @@ namespace std * Returns whether there are any exceptions currently being thrown that * have not been caught. This can occur inside a nested catch statement. */ +#if __cplusplus <= 201703L +#if __cplusplus < 201103L bool uncaught_exception() throw() +#else + bool uncaught_exception() noexcept +#endif { __cxa_thread_info *info = thread_info(); return info->globals.uncaughtExceptions != 0; } +#endif + + /** + * Detects how many exceptions in the current thread have been thrown or rethrown + * and not yet entered their matching catch clauses. + */ +#if __cplusplus >= 201703L + int uncaught_exceptions() noexcept + { + __cxa_thread_info *info = thread_info(); + return info->globals.uncaughtExceptions; + } +#endif + /** * Returns the current unexpected handler. */ diff --git a/sdk/cpprt/memory_manage/delete10.cpp b/sdk/cpprt/memory_manage/delete10.cpp new file mode 100644 index 00000000..c1326be2 --- /dev/null +++ b/sdk/cpprt/memory_manage/delete10.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include +#include +#include "sgx_defs.h" +#include "sgx_trts.h" +#include "internal/util.h" + +SGX_WEAK void SGXAPI operator delete (void* ptr, std::align_val_t alignment, const std::nothrow_t&) +{ + ::operator delete(ptr, alignment); +} diff --git a/sdk/cpprt/memory_manage/delete11.cpp b/sdk/cpprt/memory_manage/delete11.cpp new file mode 100644 index 00000000..58a76d50 --- /dev/null +++ b/sdk/cpprt/memory_manage/delete11.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include +#include +#include "sgx_defs.h" +#include "sgx_trts.h" +#include "internal/se_cdefs.h" + +//Deallocate storage space of array +SGX_WEAK void SGXAPI operator delete[] (void* ptr, std::align_val_t alignment) +{ + ::operator delete(ptr, alignment); +} diff --git a/sdk/cpprt/memory_manage/delete12.cpp b/sdk/cpprt/memory_manage/delete12.cpp new file mode 100644 index 00000000..9c388f61 --- /dev/null +++ b/sdk/cpprt/memory_manage/delete12.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include +#include +#include "sgx_defs.h" +#include "sgx_trts.h" +#include "internal/se_cdefs.h" + +SGX_WEAK void SGXAPI operator delete[] (void* ptr, std::align_val_t alignment, const std::nothrow_t&) +{ + ::operator delete[](ptr, alignment); +} diff --git a/sdk/cpprt/memory_manage/delete13.cpp b/sdk/cpprt/memory_manage/delete13.cpp new file mode 100644 index 00000000..bb83e448 --- /dev/null +++ b/sdk/cpprt/memory_manage/delete13.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include +#include +#include "sgx_defs.h" +#include "sgx_trts.h" +#include "internal/util.h" + +SGX_WEAK void SGXAPI operator delete (void* ptr, size_t, std::align_val_t alignment) +{ + ::operator delete(ptr, alignment); +} diff --git a/sdk/cpprt/memory_manage/delete14.cpp b/sdk/cpprt/memory_manage/delete14.cpp new file mode 100644 index 00000000..f3ab4377 --- /dev/null +++ b/sdk/cpprt/memory_manage/delete14.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include +#include +#include "sgx_defs.h" +#include "sgx_trts.h" +#include "internal/util.h" + +SGX_WEAK void SGXAPI operator delete[] (void* ptr, size_t, std::align_val_t alignment) +{ + ::operator delete[](ptr, alignment); +} diff --git a/sdk/cpprt/memory_manage/delete9.cpp b/sdk/cpprt/memory_manage/delete9.cpp new file mode 100644 index 00000000..b6affc5a --- /dev/null +++ b/sdk/cpprt/memory_manage/delete9.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include +#include +#include "sgx_defs.h" +#include "sgx_trts.h" +#include "internal/se_cdefs.h" + +//deallocate the memory block pointed by ptr (if not-null) +SGX_WEAK void SGXAPI operator delete (void* ptr, std::align_val_t) +{ + //std::__libcpp_aligned_free(ptr); + free(ptr); +} diff --git a/sdk/cpprt/memory_manage/new10.cpp b/sdk/cpprt/memory_manage/new10.cpp new file mode 100644 index 00000000..5f8847b8 --- /dev/null +++ b/sdk/cpprt/memory_manage/new10.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include +#include +#include "sgx_defs.h" +#include "sgx_trts.h" +#include "internal/se_cdefs.h" + +SGX_WEAK void* SGXAPI operator new[] (size_t size, std::align_val_t alignment, const std::nothrow_t&) +{ + void* p = nullptr; + try + { + p = ::operator new[](size, alignment); + } + catch (...) + { + } + return p; +} diff --git a/sdk/cpprt/memory_manage/new7.cpp b/sdk/cpprt/memory_manage/new7.cpp new file mode 100644 index 00000000..b91ee301 --- /dev/null +++ b/sdk/cpprt/memory_manage/new7.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ +#include +#include +#include "sgx_defs.h" +#include "sgx_trts.h" +#include "internal/se_cdefs.h" +#include "internal/cpprt_internal.h" + +SGX_WEAK void* SGXAPI operator new(size_t size, std::align_val_t alignment) +{ + if (size == 0) + size = 1; + if (static_cast(alignment) < sizeof(void*)) + alignment = std::align_val_t(sizeof(void*)); + + // Try allocating memory. If allocation fails and there is a new_handler, + // call it to try free up memory, and try again until it succeeds, or until + // the new_handler decides to terminate. + // + // If allocation fails and there is no new_handler, we throw bad_alloc + // (or return nullptr if exceptions are disabled). + void* p; + while ((p = std::__libcpp_aligned_alloc(static_cast(alignment), size)) == nullptr) + { + if ( !call_newh() ){ + throw std::bad_alloc(); + } + } + return p; +} diff --git a/sdk/cpprt/memory_manage/new8.cpp b/sdk/cpprt/memory_manage/new8.cpp new file mode 100644 index 00000000..7e758a5b --- /dev/null +++ b/sdk/cpprt/memory_manage/new8.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ +#include +#include +#include "sgx_defs.h" +#include "sgx_trts.h" +#include "internal/util.h" +#include "internal/cpprt_internal.h" + +//nothrow version. +//on failure it returns a null pointer instead of throwing an exception. +SGX_WEAK void* SGXAPI operator new (size_t size, std::align_val_t alignment, const std::nothrow_t&) +{ + void* p = nullptr; + try + { + p = ::operator new(size, alignment); + } + catch (...) + { + } + return p; +} diff --git a/sdk/cpprt/memory_manage/new9.cpp b/sdk/cpprt/memory_manage/new9.cpp new file mode 100644 index 00000000..03d4d7d2 --- /dev/null +++ b/sdk/cpprt/memory_manage/new9.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include +#include +#include "sgx_defs.h" +#include "sgx_trts.h" +#include "internal/se_cdefs.h" + +//Allocate storage space for array +SGX_WEAK void* SGXAPI operator new[](size_t size, std::align_val_t alignment) +{ + return ::operator new(size, alignment); +} diff --git a/sdk/debugger_interface/linux/gdb-sgx-plugin/gdb_sgx_plugin.py b/sdk/debugger_interface/linux/gdb-sgx-plugin/gdb_sgx_plugin.py index be120d16..baf5aaa1 100755 --- a/sdk/debugger_interface/linux/gdb-sgx-plugin/gdb_sgx_plugin.py +++ b/sdk/debugger_interface/linux/gdb-sgx-plugin/gdb_sgx_plugin.py @@ -38,6 +38,7 @@ from ctypes import create_string_buffer import load_symbol_cmd import sgx_emmt import ctypes +import re # Calculate the bit mode of current debuggee project SIZE = gdb.parse_and_eval("sizeof(long)") @@ -523,7 +524,7 @@ def is_bp_in_urts(): try: ip = gdb.parse_and_eval("$pc") solib_name = gdb.solib_name(int(str(ip).split()[0], 16)) - if(solib_name.find("libsgx_urts.so") == -1 and solib_name.find("libsgx_urts_sim.so") == -1 and solib_name.find("libsgx_aesm_service.so") == -1): + if(re.match('libsgx_urts.so[.0-9]*', os.path.basename(solib_name)) == None and solib_name.find("libsgx_urts_sim.so") == -1 and solib_name.find("libsgx_aesm_service.so") == -1): return False else: return True @@ -716,7 +717,7 @@ def exit_handler(event): def newobj_handler(event): solib_name = os.path.basename(event.new_objfile.filename) - if solib_name == 'libsgx_urts.so' or solib_name == 'libsgx_urts_sim.so' or solib_name == 'libsgx_aesm_service.so': + if re.match('libsgx_urts.so[.0-9]*', solib_name) or solib_name == 'libsgx_urts_sim.so' or solib_name == 'libsgx_aesm_service.so': sgx_debugger_init() return diff --git a/sdk/debugger_interface/linux/se_ptrace.c b/sdk/debugger_interface/linux/se_ptrace.c index 11c7e3df..8e4e7600 100644 --- a/sdk/debugger_interface/linux/se_ptrace.c +++ b/sdk/debugger_interface/linux/se_ptrace.c @@ -159,8 +159,11 @@ static inline uint32_t get_ssa_frame_size(pid_t pid, thread_data_t* td) #endif //When debug trts, ssa_frame_size in TD is not initialized, so the value will be 0. - //It is a limitation to debug trts. As work around, the default size is 1 page, so - //we can debug enclave from the start of enclave_entry. + //It is a limitation to debug trts. As a workaround, set the default page to 1, so + //we can debug enclave from the start of enclave_entry. It works on most platforms + //except the enclave supports AMX. + //AMX makes the ssa_frame_size more than 1 page. If AMX is enabled, the debugger will + //only be workable after TD is initialized. if(0 == ssa_frame_size) ssa_frame_size = 1; diff --git a/sdk/encrypt_enclave/Makefile b/sdk/encrypt_enclave/Makefile index 798db18a..d388dc1d 100644 --- a/sdk/encrypt_enclave/Makefile +++ b/sdk/encrypt_enclave/Makefile @@ -31,8 +31,10 @@ include ../../buildenv.mk -ifndef $(VERBOSE) - VERBOSE := @ +ifndef VERBOSE + PCLVERBOSE := @ +else + PCLVERBOSE := endif INC_DIR := -I$(COMMON_DIR)/inc -I$(COMMON_DIR)/inc/internal -I. @@ -47,22 +49,22 @@ TOOL_NAME := sgx_encrypt .PHONY: all all: $(TOOL_NAME) | $(BUILD_DIR) - $(VERBOSE)$(CP) $< $| + $(PCLVERBOSE)$(CP) $< $| $(BUILD_DIR): @$(MKDIR) $@ $(OBJS): $(CPP_FILES) - $(VERBOSE)$(CXX) -c $< -o $@ $(CXXFLAGS) + $(PCLVERBOSE)$(CXX) -c $< -o $@ $(CXXFLAGS) @echo "CXX => $@" $(TOOL_NAME): $(OBJS) - $(VERBOSE)$(CXX) $^ -o $@ $(LINK_FLAGS) $(LDFLAGS) + $(PCLVERBOSE)$(CXX) $^ -o $@ $(LINK_FLAGS) $(LDFLAGS) @echo "LINK => $@" .PHONY: clean clean: - $(VERBOSE)$(RM) $(TOOL_NAME) $(OBJS) $(BUILD_DIR)/$(TOOL_NAME) + $(PCLVERBOSE)$(RM) $(TOOL_NAME) $(OBJS) $(BUILD_DIR)/$(TOOL_NAME) .PHONY: rebuild rebuild: diff --git a/sdk/gperftools/gperftools-2.7/src/libc_override_gcc_and_weak.h b/sdk/gperftools/gperftools-2.7/src/libc_override_gcc_and_weak.h index 25cf0483..e98ca9fb 100644 --- a/sdk/gperftools/gperftools-2.7/src/libc_override_gcc_and_weak.h +++ b/sdk/gperftools/gperftools-2.7/src/libc_override_gcc_and_weak.h @@ -69,8 +69,6 @@ void* operator new[](size_t size, const std::nothrow_t& nt) CPP_NOTHROW void operator delete(void* p, const std::nothrow_t& nt) CPP_NOTHROW ALIAS(tc_delete_nothrow); void operator delete[](void* p, const std::nothrow_t& nt) CPP_NOTHROW - ALIAS(tc_deletearray_nothrow); -#endif #if defined(ENABLE_SIZED_DELETE) @@ -209,6 +207,8 @@ void operator delete[](void *p, size_t size, std::align_val_t al) CPP_NOTHROW #endif /* defined(ENABLE_ALIGNED_NEW_DELETE) */ +#endif /* TCMALLOC_SGX */ + extern "C" { void* __attribute__((weak)) malloc(size_t size) __THROW ALIAS(tc_malloc); void __attribute__((weak)) free(void* ptr) __THROW ALIAS(tc_free); diff --git a/sdk/protected_code_loader/Makefile b/sdk/protected_code_loader/Makefile index 0b34b673..33564380 100644 --- a/sdk/protected_code_loader/Makefile +++ b/sdk/protected_code_loader/Makefile @@ -33,8 +33,10 @@ include ../../buildenv.mk -ifndef $(VERBOSE) - VERBOSE := @ +ifndef VERBOSE + PCLVERBOSE := @ +else + PCLVERBOSE := endif @@ -102,81 +104,81 @@ PCL_SIM_LIB_CPP_FLAGS := $(TCXXFLAGS) $(ENCLAVE_CXXFLAGS) -DSE_SIM=1 $(PCL_INCLU .PHONY: all all: | $(BUILD_DIR) - $(VERBOSE)$(MAKE) $(PCL_LIB) - $(VERBOSE)$(MAKE) $(PCL_SIM_LIB) - $(VERBOSE)$(CP) $(PCL_LIB) $| - $(VERBOSE)$(CP) $(PCL_SIM_LIB) $| + $(PCLVERBOSE)$(MAKE) $(PCL_LIB) + $(PCLVERBOSE)$(MAKE) $(PCL_SIM_LIB) + $(PCLVERBOSE)$(CP) $(PCL_LIB) $| + $(PCLVERBOSE)$(CP) $(PCL_SIM_LIB) $| $(BUILD_DIR): - $(VERBOSE)$(MKDIR) $@ + $(PCLVERBOSE)$(MKDIR) $@ .PHONY: $(PCL_LIB) $(PCL_LIB):$(PCL_CPP_OBJECTS) $(PCL_ASM_OBJECTS) $(PCL_C_OBJECTS) @echo "library build with DEBUG =" $(DEBUG) - $(VERBOSE)$(AR) -rc $@ $^ + $(PCLVERBOSE)$(AR) -rc $@ $^ @echo "AR <= $@" .PHONY: $(PCL_SIM_LIB) $(PCL_SIM_LIB):$(PCL_SIM_CPP_OBJECTS) $(PCL_ASM_OBJECTS) $(PCL_SIM_C_OBJECTS) @echo "library build with DEBUG =" $(DEBUG) - $(VERBOSE)$(AR) -rc $@ $^ + $(PCLVERBOSE)$(AR) -rc $@ $^ @echo "AR <= $@" %.o: %.s - $(VERBOSE)mkdir -p $(@D) - $(VERBOSE)$(CC) $(PCL_LIB_C_FLAGS) -c $< -o $@ - $(VERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) + $(PCLVERBOSE)mkdir -p $(@D) + $(PCLVERBOSE)$(CC) $(PCL_LIB_C_FLAGS) -c $< -o $@ + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) @echo "CC <= $<" %.o: %.c - $(VERBOSE)mkdir -p $(@D) - $(VERBOSE)$(CC) $(PCL_LIB_C_FLAGS) -c $< -o $@ - $(VERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) + $(PCLVERBOSE)mkdir -p $(@D) + $(PCLVERBOSE)$(CC) $(PCL_LIB_C_FLAGS) -c $< -o $@ + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) @echo "CC <= $<" %.o: %.cpp - $(VERBOSE)mkdir -p $(@D) - $(VERBOSE)$(CXX) $(PCL_LIB_CPP_FLAGS) -c $< -o $@ - $(VERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) + $(PCLVERBOSE)mkdir -p $(@D) + $(PCLVERBOSE)$(CXX) $(PCL_LIB_CPP_FLAGS) -c $< -o $@ + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) @echo "CXX <= $<" # Simulation objects $(SIM_OBJ_DIR)%.o: %.s - $(VERBOSE)mkdir -p $(@D) - $(VERBOSE)$(CC) $(PCL_SIM_LIB_C_FLAGS) -c $< -o $@ - $(VERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) + $(PCLVERBOSE)mkdir -p $(@D) + $(PCLVERBOSE)$(CC) $(PCL_SIM_LIB_C_FLAGS) -c $< -o $@ + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) @echo "CC <= $<" $(SIM_OBJ_DIR)%.o: %.c - $(VERBOSE)mkdir -p $(@D) - $(VERBOSE)$(CC) $(PCL_SIM_LIB_C_FLAGS) -c $< -o $@ - $(VERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) + $(PCLVERBOSE)mkdir -p $(@D) + $(PCLVERBOSE)$(CC) $(PCL_SIM_LIB_C_FLAGS) -c $< -o $@ + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) @echo "CC <= $<" $(SIM_OBJ_DIR)%.o: %.cpp - $(VERBOSE)mkdir -p $(@D) - $(VERBOSE)$(CXX) $(PCL_SIM_LIB_CPP_FLAGS) -c $< -o $@ - $(VERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) - $(VERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) + $(PCLVERBOSE)mkdir -p $(@D) + $(PCLVERBOSE)$(CXX) $(PCL_SIM_LIB_CPP_FLAGS) -c $< -o $@ + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .text=$(NIPX) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .data=$(NIPD) + $(PCLVERBOSE)$(OBJCOPY) $@ --rename-section .rodata=$(NIPRODT) @echo "CXX <= $<" .PHONY: clean clean: - $(VERBOSE)$(RM) $(PCL_LIB) $(PCL_SIM_LIB) $(PCL_CPP_OBJECTS) $(PCL_ASM_OBJECTS) $(PCL_C_OBJECTS) $(PCL_SIM_CPP_OBJECTS) $(PCL_SIM_C_OBJECTS) - $(VERBOSE)rm -rf $(SIM_DIR) $(BUILD_DIR)/$(PCL_LIB) $(BUILD_DIR)/$(PCL_SIM_LIB) + $(PCLVERBOSE)$(RM) $(PCL_LIB) $(PCL_SIM_LIB) $(PCL_CPP_OBJECTS) $(PCL_ASM_OBJECTS) $(PCL_C_OBJECTS) $(PCL_SIM_CPP_OBJECTS) $(PCL_SIM_C_OBJECTS) + $(PCLVERBOSE)rm -rf $(SIM_DIR) $(BUILD_DIR)/$(PCL_LIB) $(BUILD_DIR)/$(PCL_SIM_LIB) .PHONY: rebuild rebuild: diff --git a/sdk/protected_code_loader/crypto/pcl_gcm128.c b/sdk/protected_code_loader/crypto/pcl_gcm128.c index 974ff6fc..5667f696 100644 --- a/sdk/protected_code_loader/crypto/pcl_gcm128.c +++ b/sdk/protected_code_loader/crypto/pcl_gcm128.c @@ -93,7 +93,17 @@ #include #include #include -/* PCL UNUSED START +#if !defined(U64) + # if defined(_WIN64) && !defined(__MINGW32__) + # define U64(C) C##UI64 + # elif defined(__arch64__) + # define U64(C) C##UL + # else + # define U64(C) C##ULL + # endif +#endif + + /* PCL UNUSED START #if defined(BSWAP4) && defined(STRICT_ALIGNMENT) / * redefine, because alignment is ensured * / # undef GETU32 diff --git a/sdk/protected_fs/sgx_tprotected_fs/file_crypto.cpp b/sdk/protected_fs/sgx_tprotected_fs/file_crypto.cpp index ffef9931..b92fc4c8 100644 --- a/sdk/protected_fs/sgx_tprotected_fs/file_crypto.cpp +++ b/sdk/protected_fs/sgx_tprotected_fs/file_crypto.cpp @@ -283,5 +283,3 @@ bool protected_fs_file::restore_current_meta_data_key(const sgx_aes_gcm_128bit_k return true; } - - diff --git a/sdk/protected_fs/sgx_tprotected_fs/file_flush.cpp b/sdk/protected_fs/sgx_tprotected_fs/file_flush.cpp index cbfbbc8d..f0c37550 100644 --- a/sdk/protected_fs/sgx_tprotected_fs/file_flush.cpp +++ b/sdk/protected_fs/sgx_tprotected_fs/file_flush.cpp @@ -37,7 +37,7 @@ #include -bool protected_fs_file::flush(/*bool mc*/) +bool protected_fs_file::flush() { bool result = false; @@ -56,7 +56,7 @@ bool protected_fs_file::flush(/*bool mc*/) return false; } - result = internal_flush(/*mc,*/ true); + result = internal_flush(true); if (result == false) { assert(file_status != SGX_FILE_STATUS_OK); @@ -70,18 +70,11 @@ bool protected_fs_file::flush(/*bool mc*/) } -bool protected_fs_file::internal_flush(/*bool mc,*/ bool flush_to_disk) +bool protected_fs_file::internal_flush(bool flush_to_disk) { if (need_writing == false) // no changes at all return true; -/* - if (mc == true && encrypted_part_plain.mc_value > (UINT_MAX-2)) - { - last_error = SGX_ERROR_FILE_MONOTONIC_COUNTER_AT_MAX; - return false; - } -*/ if (encrypted_part_plain.size > MD_USER_DATA_SIZE && root_mht.need_writing == true) // otherwise it's just one write - the meta-data node { if (_RECOVERY_HOOK_(0) || write_recovery_file() != true) @@ -104,44 +97,17 @@ bool protected_fs_file::internal_flush(/*bool mc,*/ bool flush_to_disk) } } -/* - sgx_status_t status; - - if (mc == true) - { - // increase monotonic counter local value - only if everything is ok, we will increase the real counter - if (encrypted_part_plain.mc_value == 0) - { - // no monotonic counter so far, need to create a new one - status = sgx_create_monotonic_counter(&encrypted_part_plain.mc_uuid, &encrypted_part_plain.mc_value); - if (status != SGX_SUCCESS) - { - clear_update_flag(); - file_status = SGX_FILE_STATUS_FLUSH_ERROR; - last_error = status; - return false; - } - } - encrypted_part_plain.mc_value++; - } -*/ if (_RECOVERY_HOOK_(3) || update_meta_data_node() != true) { clear_update_flag(); - /* - if (mc == true) - encrypted_part_plain.mc_value--; // don't have to do this as the file cannot be fixed, but doing it anyway to prevent future errors - */ + file_status = SGX_FILE_STATUS_CRYPTO_ERROR; // this is something that shouldn't happen, can't fix this... return false; } if (_RECOVERY_HOOK_(4) || write_all_changes_to_disk(flush_to_disk) != true) { - //if (mc == false) - file_status = SGX_FILE_STATUS_WRITE_TO_DISK_FAILED; // special case, need only to repeat write_all_changes_to_disk in order to repair it - //else - //file_status = SGX_FILE_STATUS_WRITE_TO_DISK_FAILED_NEED_MC; // special case, need to repeat write_all_changes_to_disk AND increase the monotonic counter in order to repair it + file_status = SGX_FILE_STATUS_WRITE_TO_DISK_FAILED; // special case, need only to repeat write_all_changes_to_disk in order to repair it return false; } @@ -156,20 +122,7 @@ bool protected_fs_file::internal_flush(/*bool mc,*/ bool flush_to_disk) erase_recovery_file(); } */ -/* - if (mc == true) - { - uint32_t mc_value; - status = sgx_increment_monotonic_counter(&encrypted_part_plain.mc_uuid, &mc_value); - if (status != SGX_SUCCESS) - { - file_status = SGX_FILE_STATUS_MC_NOT_INCREMENTED; // special case - need only to increase the MC in order to repair it - last_error = status; - return false; - } - assert(mc_value == encrypted_part_plain.mc_value); - } -*/ + return true; } @@ -545,5 +498,3 @@ void protected_fs_file::erase_recovery_file() status = u_sgxprotectedfs_remove(&result32, recovery_filename); (void)status; // don't care if it succeeded or failed...just remove the warning } - - diff --git a/sdk/protected_fs/sgx_tprotected_fs/file_init.cpp b/sdk/protected_fs/sgx_tprotected_fs/file_init.cpp index a68e3639..60f19b36 100644 --- a/sdk/protected_fs/sgx_tprotected_fs/file_init.cpp +++ b/sdk/protected_fs/sgx_tprotected_fs/file_init.cpp @@ -67,15 +67,15 @@ bool protected_fs_file::cleanup_filename(const char* src, char* dest) } -protected_fs_file::protected_fs_file(const char* filename, const char* mode, const sgx_aes_gcm_128bit_key_t* import_key, const sgx_aes_gcm_128bit_key_t* kdk_key) +protected_fs_file::protected_fs_file(const char* filename, const char* mode, const sgx_aes_gcm_128bit_key_t* import_key, const sgx_aes_gcm_128bit_key_t* kdk_key, const uint32_t cache_page) { sgx_status_t status = SGX_SUCCESS; uint8_t result = 0; int32_t result32 = 0; - init_fields(); + init_fields(cache_page); - if (filename == NULL || mode == NULL || + if (filename == NULL || mode == NULL || strnlen(filename, 1) == 0 || strnlen(mode, 1) == 0) { last_error = EINVAL; @@ -247,7 +247,7 @@ protected_fs_file::protected_fs_file(const char* filename, const char* mode, con } -void protected_fs_file::init_fields() +void protected_fs_file::init_fields(const uint32_t cache_page) { meta_data_node_number = 0; memset(&file_meta_data, 0, sizeof(meta_data_node_t)); @@ -275,11 +275,14 @@ void protected_fs_file::init_fields() master_key_count = 0; recovery_filename[0] = '\0'; + + max_cache_page = cache_page; + + // set hash size + cache.rehash(max_cache_page); memset(&mutex, 0, sizeof(sgx_thread_mutex_t)); - // set hash size to fit MAX_PAGES_IN_CACHE - cache.rehash(MAX_PAGES_IN_CACHE); } @@ -460,51 +463,6 @@ bool protected_fs_file::init_existing_file(const char* filename, const char* cle return false; } -/* - sgx_mc_uuid_t empty_mc_uuid = {0}; - - // check if the file contains an active monotonic counter - if (consttime_memequal(&empty_mc_uuid, &encrypted_part_plain.mc_uuid, sizeof(sgx_mc_uuid_t)) == 0) - { - uint32_t mc_value = 0; - - status = sgx_read_monotonic_counter(&encrypted_part_plain.mc_uuid, &mc_value); - if (status != SGX_SUCCESS) - { - last_error = status; - return false; - } - - if (encrypted_part_plain.mc_value < mc_value) - { - last_error = SGX_ERROR_FILE_MONOTONIC_COUNTER_IS_BIGGER; - return false; - } - - if (encrypted_part_plain.mc_value == mc_value + 1) // can happen if AESM failed - file value stayed one higher - { - sgx_status_t status = sgx_increment_monotonic_counter(&encrypted_part_plain.mc_uuid, &mc_value); - if (status != SGX_SUCCESS) - { - file_status = SGX_FILE_STATUS_MC_NOT_INCREMENTED; - last_error = status; - return false; - } - } - - if (encrypted_part_plain.mc_value != mc_value) - { - file_status = SGX_FILE_STATUS_CORRUPTED; - last_error = SGX_ERROR_UNEXPECTED; - return false; - } - } - else - { - assert(encrypted_part_plain.mc_value == 0); - encrypted_part_plain.mc_value = 0; // do this anyway for release... - } -*/ if (encrypted_part_plain.size > MD_USER_DATA_SIZE) { // read the root node of the mht @@ -649,4 +607,3 @@ bool protected_fs_file::pre_close(sgx_key_128bit_t* key, bool import) return retval; } - diff --git a/sdk/protected_fs/sgx_tprotected_fs/file_other.cpp b/sdk/protected_fs/sgx_tprotected_fs/file_other.cpp index ea708687..e702a2d6 100644 --- a/sdk/protected_fs/sgx_tprotected_fs/file_other.cpp +++ b/sdk/protected_fs/sgx_tprotected_fs/file_other.cpp @@ -44,102 +44,6 @@ int32_t protected_fs_file::remove(const char* filename) { sgx_status_t status; int32_t result32 = 0; - -/* - void* file = NULL; - int64_t real_file_size = 0; - - if (filename == NULL) - return 1; - - meta_data_node_t* file_meta_data = NULL; - meta_data_encrypted_t* encrypted_part_plain = NULL; - - // if we have a problem in any of the stages, we simply jump to the end and try to remove the file... - do { - status = u_sgxprotectedfs_check_if_file_exists(&result, filename); - if (status != SGX_SUCCESS) - break; - - if (result == 0) - { - errno = EINVAL; - return 1; // no such file, or file locked so we can't delete it anyways - } - - try { - file_meta_data = new meta_data_node_t; - encrypted_part_plain = new meta_data_encrypted_t; - } - catch (std::bad_alloc e) { - break; - } - - status = u_sgxprotectedfs_exclusive_file_open(&file, filename, 1, &real_file_size, &result32); - if (status != SGX_SUCCESS || file == NULL) - break; - - if (real_file_size == 0 || real_file_size % NODE_SIZE != 0) - break; // empty file or not an SGX protected FS file - - // might be an SGX protected FS file - status = u_sgxprotectedfs_fread_node(&result32, file, 0, (uint8_t*)file_meta_data, NODE_SIZE); - if (status != SGX_SUCCESS || result32 != 0) - break; - - if (file_meta_data->plain_part.major_version != SGX_FILE_MAJOR_VERSION) - break; - - sgx_aes_gcm_128bit_key_t zero_key_id = {0}; - sgx_aes_gcm_128bit_key_t key = {0}; - if (consttime_memequal(&file_meta_data->plain_part.key_id, &zero_key_id, sizeof(sgx_aes_gcm_128bit_key_t)) == 1) - break; // shared file - no monotonic counter - - sgx_key_request_t key_request = {0}; - key_request.key_name = SGX_KEYSELECT_SEAL; - key_request.key_policy = SGX_KEYPOLICY_MRENCLAVE; - memcpy(&key_request.key_id, &file_meta_data->plain_part.key_id, sizeof(sgx_key_id_t)); - - status = sgx_get_key(&key_request, &key); - if (status != SGX_SUCCESS) - break; - - status = sgx_rijndael128GCM_decrypt(&key, - file_meta_data->encrypted_part, sizeof(meta_data_encrypted_blob_t), - (uint8_t*)encrypted_part_plain, - file_meta_data->plain_part.meta_data_iv, SGX_AESGCM_IV_SIZE, - NULL, 0, - &file_meta_data->plain_part.meta_data_gmac); - if (status != SGX_SUCCESS) - break; - - sgx_mc_uuid_t empty_mc_uuid = {0}; - if (consttime_memequal(&empty_mc_uuid, &encrypted_part_plain->mc_uuid, sizeof(sgx_mc_uuid_t)) == 0) - { - status = sgx_destroy_monotonic_counter(&encrypted_part_plain->mc_uuid); - if (status != SGX_SUCCESS) - break; - - // monotonic counter was deleted, mission accomplished!! - } - } - while (0); - - // cleanup - if (file_meta_data != NULL) - delete file_meta_data; - - if (encrypted_part_plain != NULL) - { - // scrub the encrypted part - memset_s(encrypted_part_plain, sizeof(meta_data_encrypted_t), 0, sizeof(meta_data_encrypted_t)); - delete encrypted_part_plain; - } - - if (file != NULL) - u_sgxprotectedfs_fclose(&result32, file); - -*/ // do the actual file removal status = u_sgxprotectedfs_remove(&result32, filename); @@ -197,13 +101,6 @@ int protected_fs_file::seek(int64_t new_offset, int origin) return -1; } - //if (open_mode.binary == 0 && origin != SEEK_SET && new_offset != 0) - //{ - // last_error = EINVAL; - // sgx_thread_mutex_unlock(&mutex); - // return -1; - //} - int result = -1; switch (origin) @@ -298,33 +195,6 @@ void protected_fs_file::clear_error() file_status = SGX_FILE_STATUS_OK; } } - -/* - if (file_status == SGX_FILE_STATUS_WRITE_TO_DISK_FAILED_NEED_MC) - { - if (write_all_changes_to_disk(true) == true) - { - need_writing = false; - file_status = SGX_FILE_STATUS_MC_NOT_INCREMENTED; // fall through...next 'if' should take care of this one - } - } - - if ((file_status == SGX_FILE_STATUS_MC_NOT_INCREMENTED) && - (encrypted_part_plain.mc_value <= (UINT_MAX-2))) - { - uint32_t mc_value; - sgx_status_t status = sgx_increment_monotonic_counter(&encrypted_part_plain.mc_uuid, &mc_value); - if (status == SGX_SUCCESS) - { - assert(mc_value == encrypted_part_plain.mc_value); - file_status = SGX_FILE_STATUS_OK; - } - else - { - last_error = status; - } - } -*/ if (file_status == SGX_FILE_STATUS_OK) { @@ -392,4 +262,3 @@ int32_t protected_fs_file::clear_cache() return 0; } - diff --git a/sdk/protected_fs/sgx_tprotected_fs/file_read_write.cpp b/sdk/protected_fs/sgx_tprotected_fs/file_read_write.cpp index 8d0c5f18..78860d98 100644 --- a/sdk/protected_fs/sgx_tprotected_fs/file_read_write.cpp +++ b/sdk/protected_fs/sgx_tprotected_fs/file_read_write.cpp @@ -312,7 +312,7 @@ void get_node_numbers(uint64_t offset, uint64_t* mht_node_number, uint64_t* data // node 1 - mht // nodes 2-97 - data (ATTACHED_DATA_NODES_COUNT == 96) // node 98 - mht - // node 99-195 - data + // node 99-194 - data // etc. uint64_t _mht_node_number; uint64_t _data_node_number; @@ -370,7 +370,7 @@ file_data_node_t* protected_fs_file::get_data_node() } // even if we didn't get the required data_node, we might have read other nodes in the process - while (cache.size() > MAX_PAGES_IN_CACHE) + while (cache.size() > max_cache_page) { void* data = cache.get_last(); assert(data != NULL); @@ -654,4 +654,3 @@ file_mht_node_t* protected_fs_file::read_mht_node(uint64_t mht_node_number) return file_mht_node; } - diff --git a/sdk/protected_fs/sgx_tprotected_fs/lru_cache.cpp b/sdk/protected_fs/sgx_tprotected_fs/lru_cache.cpp index 5b7918be..60626ec9 100644 --- a/sdk/protected_fs/sgx_tprotected_fs/lru_cache.cpp +++ b/sdk/protected_fs/sgx_tprotected_fs/lru_cache.cpp @@ -272,4 +272,3 @@ void lru_cache::remove_last() map.erase(key); delete map_node; } - diff --git a/sdk/protected_fs/sgx_tprotected_fs/protected_fs_file.h b/sdk/protected_fs/sgx_tprotected_fs/protected_fs_file.h index f02b208f..eebf481d 100644 --- a/sdk/protected_fs/sgx_tprotected_fs/protected_fs_file.h +++ b/sdk/protected_fs/sgx_tprotected_fs/protected_fs_file.h @@ -52,12 +52,15 @@ typedef enum SGX_FILE_STATUS_CRYPTO_ERROR, SGX_FILE_STATUS_CORRUPTED, SGX_FILE_STATUS_MEMORY_CORRUPTED, - //SGX_FILE_STATUS_WRITE_TO_DISK_FAILED_NEED_MC, - //SGX_FILE_STATUS_MC_NOT_INCREMENTED, SGX_FILE_STATUS_CLOSED, } protected_fs_status_e; +#ifndef SE_PAGE_SIZE +#define SE_PAGE_SIZE 0x1000 +#endif + #define MAX_PAGES_IN_CACHE 48 +#define DEFAULT_CACHE_SIZE (MAX_PAGES_IN_CACHE * SE_PAGE_SIZE) COMPILE_TIME_ASSERT(filename_length, FILENAME_MAX_LEN == FILENAME_MAX); @@ -152,9 +155,10 @@ private: uint8_t read_only; int64_t offset; // current file position (user's view) bool end_of_file; // flag + uint32_t max_cache_page; int64_t real_file_size; - + bool need_writing; // flag uint32_t last_error; // last operation error protected_fs_status_e file_status; @@ -176,7 +180,7 @@ private: sgx_iv_t empty_iv; sgx_report_t report; - void init_fields(); + void init_fields(const uint32_t cache_page); bool cleanup_filename(const char* src, char* dest); bool parse_mode(const char* mode); bool file_recovery(const char* filename); @@ -204,10 +208,10 @@ private: bool update_meta_data_node(); bool write_all_changes_to_disk(bool flush_to_disk); void erase_recovery_file(); - bool internal_flush(/*bool mc,*/ bool flush_to_disk); + bool internal_flush(bool flush_to_disk); public: - protected_fs_file(const char* filename, const char* mode, const sgx_aes_gcm_128bit_key_t* import_key, const sgx_aes_gcm_128bit_key_t* kdk_key); + protected_fs_file(const char* filename, const char* mode, const sgx_aes_gcm_128bit_key_t* import_key, const sgx_aes_gcm_128bit_key_t* kdk_key, const uint32_t cache_page); ~protected_fs_file(); size_t write(const void* ptr, size_t size, size_t count); @@ -218,7 +222,7 @@ public: uint32_t get_error(); void clear_error(); int32_t clear_cache(); - bool flush(/*bool mc*/); + bool flush(); bool pre_close(sgx_key_128bit_t* key, bool import); static int32_t remove(const char* filename); }; diff --git a/sdk/protected_fs/sgx_tprotected_fs/protected_fs_nodes.h b/sdk/protected_fs/sgx_tprotected_fs/protected_fs_nodes.h index e360cca7..ccd97e72 100644 --- a/sdk/protected_fs/sgx_tprotected_fs/protected_fs_nodes.h +++ b/sdk/protected_fs/sgx_tprotected_fs/protected_fs_nodes.h @@ -75,17 +75,10 @@ typedef struct _meta_data_plain #define MD_USER_DATA_SIZE (NODE_SIZE*3/4) // 3072 COMPILE_TIME_ASSERT(md_user_data_size, MD_USER_DATA_SIZE == 3072); -typedef struct _mc_uuid { - uint8_t mc_uuid[16]; -} sgx_mc_uuid_t; - typedef struct _meta_data_encrypted { char clean_filename[FILENAME_MAX_LEN]; int64_t size; - - sgx_mc_uuid_t mc_uuid; // not used - uint32_t mc_value; // not used sgx_aes_gcm_128bit_key_t mht_key; sgx_aes_gcm_128bit_tag_t mht_gmac; @@ -153,4 +146,3 @@ typedef struct _recovery_node #pragma pack(pop) #endif // _PROTECTED_FS_NODES_H_ - diff --git a/sdk/protected_fs/sgx_tprotected_fs/sgx_tprotected_fs.cpp b/sdk/protected_fs/sgx_tprotected_fs/sgx_tprotected_fs.cpp index fe8634ac..bcb93a3a 100644 --- a/sdk/protected_fs/sgx_tprotected_fs/sgx_tprotected_fs.cpp +++ b/sdk/protected_fs/sgx_tprotected_fs/sgx_tprotected_fs.cpp @@ -36,18 +36,24 @@ #include -static SGX_FILE* sgx_fopen_internal(const char* filename, const char* mode, const sgx_key_128bit_t *auto_key, const sgx_key_128bit_t *kdk_key) +static SGX_FILE* sgx_fopen_internal(const char* filename, const char* mode, const sgx_key_128bit_t *auto_key, const sgx_key_128bit_t *kdk_key, const uint64_t cache_size) { protected_fs_file* file = NULL; + uint32_t cache_page = 0; - if (filename == NULL || mode == NULL) + if (filename == NULL || mode == NULL || + cache_size < DEFAULT_CACHE_SIZE || cache_size % SE_PAGE_SIZE != 0 || + (cache_size / SE_PAGE_SIZE) > UINT_MAX) { errno = EINVAL; return NULL; } + // Internal page number should be smaller than UINT_MAX + cache_page = (uint32_t) (cache_size / SE_PAGE_SIZE); + try { - file = new protected_fs_file(filename, mode, auto_key, kdk_key); + file = new protected_fs_file(filename, mode, auto_key, kdk_key, cache_page); } catch (std::bad_alloc& e) { (void)e; // remove warning @@ -68,13 +74,19 @@ static SGX_FILE* sgx_fopen_internal(const char* filename, const char* mode, cons SGX_FILE* sgx_fopen_auto_key(const char* filename, const char* mode) { - return sgx_fopen_internal(filename, mode, NULL, NULL); + return sgx_fopen_internal(filename, mode, NULL, NULL, DEFAULT_CACHE_SIZE); } SGX_FILE* sgx_fopen(const char* filename, const char* mode, const sgx_key_128bit_t *key) { - return sgx_fopen_internal(filename, mode, NULL, key); + return sgx_fopen_internal(filename, mode, NULL, key, DEFAULT_CACHE_SIZE); +} + + +SGX_FILE* SGXAPI sgx_fopen_ex(const char* filename, const char* mode, const sgx_key_128bit_t *key, const uint64_t cache_size) +{ + return sgx_fopen_internal(filename, mode, NULL, key, cache_size); } @@ -133,30 +145,6 @@ int32_t sgx_fflush(SGX_FILE* stream) } -/* sgx_fflush_and_increment_mc - * Purpose: force actual write of all the cached data to the disk (see c++ fflush documentation for more details). - * in addition, in the first time this function is called, it adds a monotonic counter to the file - * in subsequent calls, the monotonic counter is incremented by one every time this function is called - * the monotonic counter is a limited resource, please read the SGX documentation for more details - * - * Parameters: - * stream - [IN] the file handle (opened with sgx_fopen or sgx_fopen_auto_key) - * - * Return value: - * int32_t - result, 0 on success, 1 in case of an error - check sgx_ferror for error code - * -int32_t sgx_fflush_and_increment_mc(SGX_FILE* stream) -{ - if (stream == NULL) - return 1; - - protected_fs_file* file = (protected_fs_file*)stream; - - return file->flush(true) == true ? 0 : 1; -} -*/ - - int32_t sgx_ferror(SGX_FILE* stream) { if (stream == NULL) @@ -222,7 +210,7 @@ int32_t sgx_remove(const char* filename) int32_t sgx_fexport_auto_key(const char* filename, sgx_key_128bit_t *key) { - SGX_FILE* stream = sgx_fopen_internal(filename, "r", NULL, NULL); + SGX_FILE* stream = sgx_fopen_internal(filename, "r", NULL, NULL, DEFAULT_CACHE_SIZE); if (stream == NULL) return 1; @@ -232,7 +220,7 @@ int32_t sgx_fexport_auto_key(const char* filename, sgx_key_128bit_t *key) int32_t sgx_fimport_auto_key(const char* filename, const sgx_key_128bit_t *key) { - SGX_FILE* stream = sgx_fopen_internal(filename, "r+", key, NULL); + SGX_FILE* stream = sgx_fopen_internal(filename, "r+", key, NULL, DEFAULT_CACHE_SIZE); if (stream == NULL) return 1; @@ -249,6 +237,3 @@ int32_t sgx_fclear_cache(SGX_FILE* stream) return file->clear_cache(); } - - - diff --git a/sdk/pthread/pthread.cpp b/sdk/pthread/pthread.cpp index 1b6c97d6..083a26af 100644 --- a/sdk/pthread/pthread.cpp +++ b/sdk/pthread/pthread.cpp @@ -364,7 +364,12 @@ int pthread_join(pthread_t thread, void **retval) */ __attribute__((weak)) pthread_t pthread_self(void) { - return (pthread_t)(pthread_info_tls.m_pthread); + pthread_t t = (pthread_t)(pthread_info_tls.m_pthread); + // For threads that are created outside enclave t value is NULL + if (!t) { + return (pthread_t)(sgx_thread_self()); + } + return t; } /* diff --git a/sdk/sign_tool/SignTool/enclave_creator_sign.cpp b/sdk/sign_tool/SignTool/enclave_creator_sign.cpp index b1585a4b..21a66245 100644 --- a/sdk/sign_tool/SignTool/enclave_creator_sign.cpp +++ b/sdk/sign_tool/SignTool/enclave_creator_sign.cpp @@ -305,46 +305,5 @@ int EnclaveCreatorST::get_enclave_info(uint8_t *hash, int size, uint64_t *quota) return SGX_SUCCESS; } -int EnclaveCreatorST::emodpr(uint64_t addr, uint64_t size, uint64_t flag) -{ - UNUSED(addr); - UNUSED(size); - UNUSED(flag); - - return SGX_SUCCESS; -} - -int EnclaveCreatorST::mktcs(uint64_t tcs_addr) -{ - UNUSED(tcs_addr); - - return SGX_SUCCESS; -} - -int EnclaveCreatorST::trim_range(uint64_t fromaddr, uint64_t toaddr) -{ - UNUSED(fromaddr); - UNUSED(toaddr); - - return SGX_SUCCESS; - -} - -int EnclaveCreatorST::trim_accept(uint64_t addr) -{ - UNUSED(addr); - - return SGX_SUCCESS; -} - -int EnclaveCreatorST::remove_range(uint64_t fromaddr, uint64_t numpages) -{ - UNUSED(fromaddr); - UNUSED(numpages); - - return SGX_SUCCESS; -} - - static EnclaveCreatorST g_enclave_creator_st; EnclaveCreator* g_enclave_creator = &g_enclave_creator_st; diff --git a/sdk/sign_tool/SignTool/enclave_creator_sign.h b/sdk/sign_tool/SignTool/enclave_creator_sign.h index dd23c83e..fde053d7 100644 --- a/sdk/sign_tool/SignTool/enclave_creator_sign.h +++ b/sdk/sign_tool/SignTool/enclave_creator_sign.h @@ -56,12 +56,6 @@ public: bool is_EDMM_supported(sgx_enclave_id_t enclave_id); bool is_driver_compatible(); int get_enclave_info(uint8_t *hash, int size, uint64_t *quota); - int emodpr(uint64_t addr, uint64_t size, uint64_t flag); - int mktcs(uint64_t tcs_addr); - int trim_range(uint64_t fromaddr, uint64_t toaddr); - int trim_accept(uint64_t addr); - int remove_range(uint64_t fromaddr, uint64_t numpages); - private: uint8_t m_enclave_hash[SGX_HASH_SIZE]; EVP_MD_CTX *m_ctx; diff --git a/sdk/sign_tool/SignTool/manage_metadata.cpp b/sdk/sign_tool/SignTool/manage_metadata.cpp index e75a18fe..5d2023a0 100644 --- a/sdk/sign_tool/SignTool/manage_metadata.cpp +++ b/sdk/sign_tool/SignTool/manage_metadata.cpp @@ -48,6 +48,8 @@ #include "crypto_wrapper.h" #include "global_data.h" #include "se_version.h" +#include "ema_imp.h" +#include "bit_array_imp.h" #include #include @@ -281,7 +283,7 @@ bool CMetadata::fill_enclave_css(const xml_parameter_t *para) m_metadata->enclave_css.body.misc_mask = (uint32_t)para[MISCMASK].value; //low 64 bit m_metadata->enclave_css.body.attributes.flags = 0; - m_metadata->enclave_css.body.attribute_mask.flags = ~SGX_FLAGS_DEBUG; + m_metadata->enclave_css.body.attribute_mask.flags = ~(SGX_FLAGS_DEBUG | SGX_FLAGS_NON_CHECK_BITS); if(para[DISABLEDEBUG].value == 1) { m_metadata->enclave_css.body.attributes.flags &= ~SGX_FLAGS_DEBUG; @@ -351,6 +353,25 @@ bool CMetadata::fill_enclave_css(const xml_parameter_t *para) m_metadata->enclave_css.body.attribute_mask.xfrm &= ~SGX_XFRM_PKRU; break; } + switch(para[AMX].value) + { + case FEATURE_MUST_BE_ENABLED: + // AMX must be enabled + m_metadata->enclave_css.body.attributes.xfrm |= SGX_XFRM_AMX; + m_metadata->enclave_css.body.attribute_mask.xfrm |= SGX_XFRM_AMX; + break; + case FEATURE_LOADER_SELECTS: + // Loader will enable this feature if it is avaiable on HW + m_metadata->enclave_css.body.attributes.xfrm &= ~SGX_XFRM_AMX; + m_metadata->enclave_css.body.attribute_mask.xfrm &= ~SGX_XFRM_AMX; + break; + case FEATURE_MUST_BE_DISABLED: + default: + // AMX must be disabled + m_metadata->enclave_css.body.attributes.xfrm &= ~SGX_XFRM_AMX; + m_metadata->enclave_css.body.attribute_mask.xfrm |= SGX_XFRM_AMX; + break; + } m_metadata->enclave_css.body.isv_prod_id = (uint16_t)para[PRODID].value; m_metadata->enclave_css.body.isv_svn = (uint16_t)para[ISVSVN].value; @@ -378,8 +399,7 @@ bool CMetadata::modify_metadata(const xml_parameter_t *parameter) m_metadata->size = offsetof(metadata_t, data); m_metadata->tcs_policy = (uint32_t)parameter[TCSPOLICY].value; - m_metadata->ssa_frame_size = SSA_FRAME_SIZE; - m_metadata->max_save_buffer_size = MAX_SAVE_BUF_SIZE; + m_metadata->magic_num = METADATA_MAGIC; m_metadata->desired_misc_select = 0; m_metadata->tcs_min_pool = (uint32_t)parameter[TCSMINPOOL].value; @@ -401,9 +421,18 @@ bool CMetadata::modify_metadata(const xml_parameter_t *parameter) //set bits that have been set '1' and need to be checked m_metadata->attributes.xfrm |= (m_metadata->enclave_css.body.attributes.xfrm & m_metadata->enclave_css.body.attribute_mask.xfrm); - return true; -} + // set m_create_param.xsave_size and ssa_fram_size + if(false == get_xsave_size(m_metadata->attributes.xfrm, &m_create_param.xsave_size)) + { + return false; + } + + m_metadata->ssa_frame_size = ROUND_TO_PAGE(m_create_param.xsave_size + (uint32_t)sizeof(ssa_gpr_t)) >> SE_PAGE_SHIFT; + m_metadata->max_save_buffer_size = m_create_param.xsave_size; + bool ret = check_config(); + return ret; +} bool CMetadata::check_xml_parameter(const xml_parameter_t *parameter) { @@ -489,6 +518,12 @@ bool CMetadata::check_xml_parameter(const xml_parameter_t *parameter) } } + if ((parameter[USERREGIONSIZE].value % ALIGN_SIZE)) + { + se_trace(SE_TRACE_ERROR, SET_USER_REGION_SIZE_ALIGN_ERROR); + return false; + } + // LE setting: HW != 0, Licensekey = 1 // Other enclave setting: HW = 0, Licensekey = 0 if((parameter[HW].value == 0 && parameter[LAUNCHKEY].value != 0) || @@ -547,6 +582,7 @@ bool CMetadata::check_xml_parameter(const xml_parameter_t *parameter) m_create_param.rsrv_min_size = parameter[RSRVMINSIZE].value; m_create_param.rsrv_max_size = parameter[RSRVMAXSIZE].value; m_create_param.rsrv_executable = parameter[RSRVEXECUTABLE].flag ? parameter[RSRVEXECUTABLE].value : 0; + m_create_param.user_region_size = parameter[USERREGIONSIZE].value; m_create_param.stack_max_size = parameter[STACKMAXSIZE].value; m_create_param.stack_min_size = parameter[STACKMINSIZE].value; m_create_param.tcs_num = (uint32_t)parameter[TCSNUM].value; @@ -558,10 +594,152 @@ bool CMetadata::check_xml_parameter(const xml_parameter_t *parameter) SE_TRACE_DEBUG("RSRV_MIN_SIZE = 0x%016llX\n", m_create_param.rsrv_min_size); SE_TRACE_DEBUG("RSRV_INIT_SIZE = 0x%016llX\n", m_create_param.rsrv_init_size); SE_TRACE_DEBUG("RSRV_MAX_SIZE = 0x%016llX\n", m_create_param.rsrv_max_size); + SE_TRACE_DEBUG("USER_REGION_SIZE = 0x%016llX\n", m_create_param.user_region_size); return true; } +uint64_t CMetadata::calculate_rts_bk_overhead() +{ + uint64_t ema_overhead = sizeof(struct ema_t_); + uint64_t bit_array_overhead = sizeof(struct bit_array_); + + // MIN heap + uint32_t page_count = (uint32_t)(m_create_param.heap_min_size >> SE_PAGE_SHIFT); + uint64_t heap_node_overhead = ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + + if(m_create_param.heap_init_size > m_create_param.heap_min_size) + { + // INIT heap + page_count = (uint32_t)((m_create_param.heap_init_size - m_create_param.heap_min_size) >> SE_PAGE_SHIFT); + heap_node_overhead += ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + } + + if(m_create_param.heap_max_size > m_create_param.heap_init_size) + { + page_count = (uint32_t)((m_create_param.heap_max_size - m_create_param.heap_init_size) >> SE_PAGE_SHIFT); + heap_node_overhead += ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + } + + page_count = (uint32_t)(m_create_param.rsrv_min_size >> SE_PAGE_SHIFT); + uint64_t rsrv_node_overhead = ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + + if(m_create_param.rsrv_init_size > m_create_param.rsrv_min_size) + { + // INIT RSRV + page_count = (uint32_t)((m_create_param.rsrv_init_size - m_create_param.rsrv_min_size) >> SE_PAGE_SHIFT); + rsrv_node_overhead += ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + } + + if(m_create_param.rsrv_max_size > m_create_param.rsrv_init_size) + { + page_count = (uint32_t)((m_create_param.rsrv_max_size - m_create_param.rsrv_init_size) >> SE_PAGE_SHIFT); + rsrv_node_overhead += ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + } + // guard page | stack | guard page | TCS | SSA | guard page | TLS + + // guard page + uint64_t non_removed_ctx_overhead = ema_overhead; + uint64_t removed_ctx_overhead = ema_overhead; + + // stack + page_count = (uint32_t)(m_create_param.stack_min_size >> SE_PAGE_SHIFT); + non_removed_ctx_overhead += ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + removed_ctx_overhead += ema_overhead; + + if(m_create_param.stack_max_size > m_create_param.stack_min_size) + { + page_count = (uint32_t)((m_create_param.stack_max_size - m_create_param.stack_min_size) >> SE_PAGE_SHIFT); + non_removed_ctx_overhead += ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + removed_ctx_overhead += ema_overhead; + } + + // guard page + non_removed_ctx_overhead += ema_overhead; + removed_ctx_overhead += ema_overhead; + + // tcs + page_count = TCS_SIZE >> SE_PAGE_SHIFT; + non_removed_ctx_overhead += ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + removed_ctx_overhead += ema_overhead; + + // ssa + page_count = m_metadata->ssa_frame_size * SSA_NUM; + non_removed_ctx_overhead += ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + removed_ctx_overhead += ema_overhead; + + // guard page + non_removed_ctx_overhead += ema_overhead; + removed_ctx_overhead += ema_overhead; + + // td + page_count = 1; + const Section *section = m_parser->get_tls_section(); + if(section) + { + page_count += (uint32_t)(ROUND_TO_PAGE(section->virtual_size()) >> SE_PAGE_SHIFT); + } + non_removed_ctx_overhead += ema_overhead + bit_array_overhead + (ROUND_TO(page_count, 8) >> 3); + removed_ctx_overhead += ema_overhead; + + uint32_t tcs_min_pool = 0; /* Number of static threads (EADD) */ + uint32_t tcs_eremove = 0; + if(m_create_param.tcs_min_pool > m_create_param.tcs_num - 1) + { + tcs_min_pool = m_create_param.tcs_num - 1; + tcs_eremove = 0; + } + else + { + tcs_min_pool = m_create_param.tcs_min_pool; + tcs_eremove = m_create_param.tcs_num -1 - m_create_param.tcs_min_pool; + } + + // static thread contexts + uint64_t total_non_removed_ctx_overhead = non_removed_ctx_overhead; + if (tcs_min_pool > 0) + { + total_non_removed_ctx_overhead += non_removed_ctx_overhead; + + if (tcs_min_pool > 1) + { + total_non_removed_ctx_overhead += non_removed_ctx_overhead * (tcs_min_pool - 1); + } + } + + // eremoved thread contexts + uint64_t total_removed_ctx_overhead = removed_ctx_overhead; + if (tcs_eremove > 0) + { + total_removed_ctx_overhead += removed_ctx_overhead; + + if (tcs_eremove > 1) + { + total_removed_ctx_overhead += removed_ctx_overhead * (tcs_eremove - 1); + } + } + + // dynamic thread contexts + if (m_create_param.tcs_max_num > tcs_min_pool + 1) + { + total_non_removed_ctx_overhead += non_removed_ctx_overhead * (m_create_param.tcs_max_num - tcs_min_pool); + } + + // PT_LOAD segments + uint64_t total_sections_overhead = 0; + std::vector sections = m_parser->get_sections(); + for (auto s : sections) { + uint32_t p_count = (uint32_t)(ROUND_TO_PAGE(s->virtual_size()) >> SE_PAGE_SHIFT); + total_sections_overhead += ema_overhead + bit_array_overhead + (ROUND_TO(p_count, 8) >> 3); + } + + return heap_node_overhead + + rsrv_node_overhead + + total_non_removed_ctx_overhead + + total_removed_ctx_overhead + + total_sections_overhead; +} + void *CMetadata::alloc_buffer_from_metadata(uint32_t size) { void *addr = GET_PTR(void, m_metadata, m_metadata->size); @@ -860,7 +1038,7 @@ bool CMetadata::build_layout_table() // ssa layout.entry.id = LAYOUT_ID_SSA; - layout.entry.page_count = SSA_FRAME_SIZE * SSA_NUM; + layout.entry.page_count = m_metadata->ssa_frame_size * SSA_NUM; layout.entry.attributes = PAGE_ATTR_EADD | PAGE_ATTR_EEXTEND; layout.entry.si_flags = SI_FLAGS_RW; thread_layouts.push_back(layout); @@ -998,6 +1176,33 @@ bool CMetadata::build_layout_table() } } + // USER_REGION + uint8_t meta_versions = get_meta_versions(); + // SGX2 metadata required + if ((meta_versions & 2u) == 2u) + { + // 0x20000 comes from initial emalloc reserve size (0x10000 bytes), + // plus two guard pages (0x8000 bytes each) + uint64_t rts_bk_overhead = calculate_rts_bk_overhead() + 0x20000; + uint64_t user_region_size = ROUND_TO_PAGE(rts_bk_overhead); + se_trace(SE_TRACE_ERROR, "RTS bookkeeping overhead: 0x%016llX\n", user_region_size); + + if (m_create_param.user_region_size > 0) + { + user_region_size += m_create_param.user_region_size; + + // one-byte ema bookkeeping struct can roughly cover 2^15 byte data + uint64_t extra_overhead = (m_create_param.user_region_size >> 15); + user_region_size += ROUND_TO_PAGE(extra_overhead); + } + memset(&layout, 0, sizeof(layout)); + layout.entry.id = LAYOUT_ID_USER_REGION; + layout.entry.page_count = (uint32_t)(user_region_size >> SE_PAGE_SHIFT); + layout.entry.attributes = PAGE_ATTR_POST_ADD; + layout.entry.si_flags = SI_FLAGS_RW; + m_layouts.push_back(layout); + } + // update layout entries if(false == update_layout_entries()) { @@ -1179,7 +1384,8 @@ bool CMetadata::get_xsave_size(uint64_t xfrm, uint32_t *xsave_size) {SGX_XFRM_MPX, 512 + 64 + 256 + 256}, // 256 for MPX {SGX_XFRM_AVX512, 512 + 64 + 256 + 256 + 1600}, // 1600 for k0 - k7, ZMM0_H - ZMM15_H, ZMM16 - ZMM31 // Ignore PT as PT is a supervisor state. - {SGX_XFRM_PKRU, 512 + 64 + 256 + 256 + 1600 + 64}, // 8 for PKRU, 56 for alignment + {SGX_XFRM_PKRU, 512 + 64 + 256 + 256 + 1600 + 64}, // 8 for PKRU, 56 for alignment + {SGX_XFRM_AMX, 512 + 64 + 256 + 256 + 1600 + 64 + 64 + 8192}, // 64 for XTILECFG, 8196 for XTILEDATA }; bool ret = true; *xsave_size = 0; @@ -1199,11 +1405,6 @@ bool CMetadata::get_xsave_size(uint64_t xfrm, uint32_t *xsave_size) bool CMetadata::build_gd_template(uint8_t *data, uint32_t *data_size) { - if(false == get_xsave_size(m_metadata->attributes.xfrm, &m_create_param.xsave_size)) - { - return false; - } - m_create_param.stack_base_addr = (size_t)(get_entry_by_id(LAYOUT_ID_STACK_MIN)->rva + m_create_param.stack_min_size - get_entry_by_id(LAYOUT_ID_TCS)->rva); m_create_param.stack_limit_addr = (size_t)(m_create_param.stack_base_addr - m_create_param.stack_max_size); m_create_param.ssa_base_addr = (size_t)(get_entry_by_id(LAYOUT_ID_SSA)->rva - get_entry_by_id(LAYOUT_ID_TCS)->rva); @@ -1219,6 +1420,16 @@ bool CMetadata::build_gd_template(uint8_t *data, uint32_t *data_size) m_create_param.rsrv_offset = (size_t)layout_rsrv->rva; } + layout_entry_t * layout_user = get_entry_by_id(LAYOUT_ID_USER_REGION, false); + if (NULL == layout_user) + { + m_create_param.user_region_offset = (size_t)0; + } + else + { + m_create_param.user_region_offset = (size_t)layout_user->rva; + } + size_t tmp_tls_addr = (size_t)(get_entry_by_id(LAYOUT_ID_TD)->rva - get_entry_by_id(LAYOUT_ID_TCS)->rva); m_create_param.td_addr = tmp_tls_addr + (size_t)((get_entry_by_id(LAYOUT_ID_TD)->page_count - 1) << SE_PAGE_SHIFT); @@ -1327,6 +1538,117 @@ uint64_t CMetadata::calculate_enclave_size(uint64_t size) return round_size; } +bool CMetadata::rts_dynamic() +{ + bool no_dynamic_heap = + ((m_create_param.heap_init_size == m_create_param.heap_min_size) && + (m_create_param.heap_init_size == m_create_param.heap_max_size)); + + bool no_dynamic_stack = + (m_create_param.stack_max_size == m_create_param.stack_min_size); + + bool no_dynamic_rsrv = + ((m_create_param.rsrv_init_size == m_create_param.rsrv_min_size) && + (m_create_param.rsrv_init_size == m_create_param.rsrv_max_size)); + + + uint32_t tcs_min_pool = 0; + if(m_create_param.tcs_min_pool > m_create_param.tcs_num - 1) + { + tcs_min_pool = m_create_param.tcs_num - 1; + } + else + { + tcs_min_pool = m_create_param.tcs_min_pool; + } + + bool no_dynamic_thread = (m_create_param.tcs_max_num == tcs_min_pool + 1); + + bool no_rts_dynamic = (no_dynamic_heap && no_dynamic_stack && + no_dynamic_rsrv && no_dynamic_thread); + + return !no_rts_dynamic; +} + +bool CMetadata::user_dynamic() +{ + return (m_create_param.user_region_size > 0); +} + +sgx_misc_select_t CMetadata::get_config_misc_select() +{ + return m_metadata->enclave_css.body.misc_select; +} + +sgx_misc_select_t CMetadata::get_config_misc_mask() +{ + return m_metadata->enclave_css.body.misc_mask; +} + +bool CMetadata::check_config() +{ + uint32_t misc_select_0 = (uint32_t)get_config_misc_select() & 1u; + uint32_t misc_mask_0 = (uint32_t)get_config_misc_mask() & 1u; + + bool has_rts_dynamic = rts_dynamic(); + bool has_user_dynamic = user_dynamic(); + + // user region configured, either mask or select, or both are zero + if (has_user_dynamic) + { + if ((misc_mask_0 && misc_select_0) == 0) + { + m_meta_verions = 0; + se_trace(SE_TRACE_ERROR, "\033[0;31mERROR: Enclave configuration 'UserRegionSize' requires MiscSelect[0] and MiscMask[0] set to 1.\n\033[0m"); + return false; + } + else + { + // SGX2 metadata only + m_meta_verions = 1u << 1; + se_trace(SE_TRACE_ERROR, "\033[0;32mINFO: Enclave configuration 'UserRegionSize' requires the enclave to be run on SGX2 platform.\n\033[0m"); + return true; + } + } + + if (has_rts_dynamic) + { + if (misc_select_0 == 0) + { + // SGX1 metadata only + m_meta_verions = 1u; + se_trace(SE_TRACE_ERROR, "\033[0;32mINFO: Enclave configuration 'MiscSelect' and 'MiscSelectMask' will prevent enclave from using dynamic features. To use the dynamic features on SGX2 platform, suggest to set MiscMask[0]=0 and MiscSelect[0]=1.\n\033[0m"); + return true; + } + + if (misc_mask_0 == 1) + { + // SGX2 metadata only + m_meta_verions = 1u << 1; + se_trace(SE_TRACE_ERROR, "\033[0;32mINFO: Enclave configuration 'MiscSelect' and 'MiscSelectMask' will prevent enclave from running on SGX1 platform. To make it run on SGX1 platform, suggest to set MiscMask[0]=0 and MiscSelect[0]=1.\n\033[0m"); + return true; + } + + // SGX1 and SGX2 metadata + m_meta_verions = (1u << 1) | 1u; + se_trace(SE_TRACE_ERROR, "\033[0;32mINFO: Enclave configuration 'MiscSelect' and 'MiscSelectMask' will work on SGX1 and SGX2 platforms with respective metadata.\n\033[0m"); + return true; + } + + // SGX1 metadata only + m_meta_verions = 1u; + if (misc_select_0 == 1) + { + se_trace(SE_TRACE_ERROR, "\033[0;32mINFO: Enclave configuration 'MiscSelect' and 'MiscSelectMask' will prevent enclave from running on SGX1 platform.\n\033[0m"); + return true; + } + else + { + se_trace(SE_TRACE_ERROR, "\033[0;32mINFO: SGX1 only enclave, which will run on all platforms.\n\033[0m"); + return true; + } +} + bool update_metadata(const char *path, const metadata_t *metadata, uint64_t meta_offset) { assert(path != NULL && metadata != NULL); diff --git a/sdk/sign_tool/SignTool/manage_metadata.h b/sdk/sign_tool/SignTool/manage_metadata.h index 856e6abc..337e1307 100644 --- a/sdk/sign_tool/SignTool/manage_metadata.h +++ b/sdk/sign_tool/SignTool/manage_metadata.h @@ -83,7 +83,9 @@ typedef enum _para_type_t ENCLAVEIMAGEADDRESS, ELRANGESTARTADDRESS, ELRANGESIZE, - PKRU + PKRU, + AMX, + USERREGIONSIZE } para_type_t; typedef struct _xml_parameter_t @@ -106,6 +108,11 @@ public: CMetadata(metadata_t *metadata, BinParser *parser); ~CMetadata(); bool build_metadata(const xml_parameter_t *parameter); + bool rts_dynamic(); + bool user_dynamic(); + sgx_misc_select_t get_config_misc_select(); + sgx_misc_select_t get_config_misc_mask(); + uint8_t get_meta_versions() { return m_meta_verions; } private: bool get_time(uint32_t *date); bool modify_metadata(const xml_parameter_t *parameter); @@ -128,6 +135,9 @@ private: void* get_rawdata_by_rva(uint64_t rva); bool vaildate_elrange_config(); bool build_elrange_config_entry(); + uint64_t calculate_rts_bk_overhead(); + bool check_config(); + uint8_t m_meta_verions; metadata_t *m_metadata; BinParser *m_parser; diff --git a/sdk/sign_tool/SignTool/sign_tool.cpp b/sdk/sign_tool/SignTool/sign_tool.cpp index ba5d896f..3fe8ef76 100644 --- a/sdk/sign_tool/SignTool/sign_tool.cpp +++ b/sdk/sign_tool/SignTool/sign_tool.cpp @@ -141,9 +141,9 @@ static bool get_enclave_info(BinParser *parser, bin_fmt_t *bf, uint64_t * meta_o // measure_enclave(): // 1. Get the enclave hash by loading enclave // 2. Get the enclave info - metadata offset and enclave file format -static bool measure_enclave(uint8_t *hash, const char *dllpath, const xml_parameter_t *parameter, uint32_t option_flag_bits, metadata_t *metadata, uint64_t *meta_offset) +static bool measure_enclave(uint8_t *hash, const char *dllpath, const xml_parameter_t *parameter, uint32_t option_flag_bits, metadata_t *metadata, uint64_t *meta_offset, uint8_t *meta_versions) { - assert(hash && dllpath && metadata && meta_offset); + assert(hash && dllpath && metadata && meta_offset && meta_versions); bool res = false; off_t file_size = 0; uint64_t quota = 0; @@ -189,6 +189,9 @@ static bool measure_enclave(uint8_t *hash, const char *dllpath, const xml_parame return false; } + // get the versions of metadata we need to output + *meta_versions = meta.get_meta_versions(); + // Collect enclave info if(get_enclave_info(parser.get(), &bin_fmt, meta_offset, false, ENABLE_RESIGN(option_flag_bits)) == false) { @@ -1066,28 +1069,50 @@ static bool append_compatible_metadata(metadata_t *compat_metadata, metadata_t * return true; } -static bool generate_compatible_metadata(metadata_t *metadata, const xml_parameter_t *parameter) +static bool handle_compatible_metadata(metadata_t *compat_metadata, metadata_t *metadata, bool append) { + if (append) { + se_trace(SE_TRACE_ERROR, "%s: Append metadata version 0x%lx\n", __FUNCTION__, compat_metadata->version); + return append_compatible_metadata(compat_metadata, metadata); + } else { + // overwrite + memset(metadata, 0, METADATA_SIZE); + if(memcpy_s(metadata, METADATA_SIZE, compat_metadata, compat_metadata->size)) + return false; + se_trace(SE_TRACE_ERROR, "%s: Overwrite with metadata version 0x%lx\n", __FUNCTION__, metadata->version); + return true; + } +} + +static bool generate_compatible_metadata(metadata_t *metadata, const xml_parameter_t *parameter, uint8_t meta_versions) +{ + if(meta_versions == 0) + { + se_trace(SE_TRACE_ERROR, "metadata version is invalid"); + return false; + } + + bool meta_sgx1_only = ((meta_versions & 3u) == 1u); + bool meta_sgx2_only = ((meta_versions & 3u) == 2u); + bool append = (meta_sgx1_only ? false : true); + + if (meta_sgx2_only) { + se_trace(SE_TRACE_ERROR, "%s: Only requires SGX2 metadata\n", __FUNCTION__); + return true; + } + metadata_t *metadata2 = (metadata_t *)malloc(metadata->size); if(!metadata2) { se_trace(SE_TRACE_ERROR, NO_MEMORY_ERROR); return false; } - SE_TRACE_DEBUG("\n"); - - // append 2_0 metadata - memcpy_s(metadata2, metadata->size, metadata, metadata->size); - //if elrange is set, we can remove this metadata - if(parameter[ELRANGESIZE].value == 0) - { - metadata2->version = META_DATA_MAKE_VERSION(SGX_2_0_MAJOR_VERSION,SGX_2_0_MINOR_VERSION); - if (!append_compatible_metadata(metadata2, metadata)) - { - free(metadata2); - return false; - } + + if (memcpy_s(metadata2, metadata->size, metadata, metadata->size)) { + se_trace(SE_TRACE_ERROR, "%s: Error memcpy_s failed\n", __FUNCTION__); + free(metadata2); + return false; } // append 1_9 metadata @@ -1157,7 +1182,7 @@ static bool generate_compatible_metadata(metadata_t *metadata, const xml_paramet { se_trace(SE_TRACE_DEBUG, "%s: Utility thread TD is the last layout\n", __FUNCTION__); metadata_cleanup(metadata2, 0); - ret = append_compatible_metadata(metadata2, metadata); + ret = handle_compatible_metadata(metadata2, metadata, append); free(metadata2); return ret; } @@ -1176,7 +1201,7 @@ static bool generate_compatible_metadata(metadata_t *metadata, const xml_paramet max_rsrv_entry->entry.si_flags = SI_FLAG_NONE; max_rsrv_entry->entry.attributes &= (uint16_t)(~PAGE_ATTR_POST_ADD); } - ret = append_compatible_metadata(metadata2, metadata); + ret = handle_compatible_metadata(metadata2, metadata, append); free(metadata2); return ret; } @@ -1204,7 +1229,7 @@ static bool generate_compatible_metadata(metadata_t *metadata, const xml_paramet if (false == ret) goto end; } - ret = append_compatible_metadata(metadata2, metadata); + ret = handle_compatible_metadata(metadata2, metadata, append); if (false == ret) goto end; ret = dump_metadata_layout(metadata); @@ -1306,7 +1331,9 @@ int main(int argc, char* argv[]) {"EnclaveImageAddress", 0xFFFFFFFFFFFFFFFF, 0x1000, 0, 0}, {"ELRangeStartAddress", 0xFFFFFFFFFFFFFFFF, 0, 0, 0}, {"ELRangeSize", 0xFFFFFFFFFFFFFFFF, 0x1000, 0, 0}, - {"PKRU", FEATURE_LOADER_SELECTS, FEATURE_MUST_BE_DISABLED, FEATURE_MUST_BE_DISABLED, 0}}; + {"PKRU", FEATURE_LOADER_SELECTS, FEATURE_MUST_BE_DISABLED, FEATURE_MUST_BE_DISABLED, 0}, + {"AMX", FEATURE_LOADER_SELECTS, FEATURE_MUST_BE_DISABLED, FEATURE_MUST_BE_DISABLED, 0}, + {"UserRegionSize", ENCLAVE_MAX_SIZE_64/2, 0, USER_REGION_SIZE, 0}}; const char *path[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; uint8_t enclave_hash[SGX_HASH_SIZE] = {0}; uint8_t metadata_raw[METADATA_SIZE]; @@ -1318,7 +1345,7 @@ int main(int argc, char* argv[]) uint32_t option_flag_bits = 0; RSA *rsa = NULL; memset(&metadata_raw, 0, sizeof(metadata_raw)); - + uint8_t meta_versions = 0; #if OPENSSL_VERSION_NUMBER < 0x10100000L OpenSSL_add_all_algorithms(); @@ -1369,7 +1396,7 @@ int main(int argc, char* argv[]) goto clear_return; } - if(measure_enclave(enclave_hash, path[OUTPUT], parameter, option_flag_bits, metadata, &meta_offset) == false) + if(measure_enclave(enclave_hash, path[OUTPUT], parameter, option_flag_bits, metadata, &meta_offset, &meta_versions) == false) { se_trace(SE_TRACE_ERROR, OVERALL_ERROR); goto clear_return; @@ -1388,7 +1415,7 @@ int main(int argc, char* argv[]) se_trace(SE_TRACE_ERROR, OVERALL_ERROR); goto clear_return; } - if(false == generate_compatible_metadata(metadata, parameter)) + if(false == generate_compatible_metadata(metadata, parameter, meta_versions)) { se_trace(SE_TRACE_ERROR, OVERALL_ERROR); goto clear_return; diff --git a/sdk/sign_tool/SignTool/util_st.h b/sdk/sign_tool/SignTool/util_st.h index 8dbe1db2..98b5c1f4 100644 --- a/sdk/sign_tool/SignTool/util_st.h +++ b/sdk/sign_tool/SignTool/util_st.h @@ -140,6 +140,7 @@ #define SET_RSRV_SIZE_INIT_MIN_ERROR "Reserved memory size setting is not correct: min value should not be larger than init value.\n" #define SET_RSRV_SIZE_MAX_MIN_ERROR "Reserved memory size setting is not correct: max value should not be smaller than min value.\n" #define SET_RSRV_EXECUTABLE_ERROR "Reserved memory executable setting is not correct: the executable value should be set to 1 or 0.\n" +#define SET_USER_REGION_SIZE_ALIGN_ERROR "User region size setting is not correct: size is not page aligned.\n" #define SET_HW_LE_ERROR "Conflicting setting between the 'HW' and 'LaunchKey'.\n" #define SET_TCS_MAX_NUM_ERROR "Maximum number of TCS is not correct.\n" #define SET_TCS_MIN_POOL_ERROR "Minimum number of TCS Pool is not correct.\n" diff --git a/sdk/simulation/trtssim/linux/Makefile b/sdk/simulation/trtssim/linux/Makefile index 7a0a9bf5..bcb68e5d 100644 --- a/sdk/simulation/trtssim/linux/Makefile +++ b/sdk/simulation/trtssim/linux/Makefile @@ -66,8 +66,9 @@ TRTS1_OBJS := init_enclave.o \ trts_veh.o \ trts_xsave.o \ init_optimized_lib.o \ - trts_emodpr.o \ - trts_add_trim.o + trts_add_trim.o \ + trts_emm_sim.o + TRTS2_OBJS := trts_nsp.o TRTS_OBJS := $(TRTS1_OBJS) $(TRTS2_OBJS) diff --git a/sdk/simulation/uinst/u_instructions.cpp b/sdk/simulation/uinst/u_instructions.cpp index 3532a5db..72e7add7 100644 --- a/sdk/simulation/uinst/u_instructions.cpp +++ b/sdk/simulation/uinst/u_instructions.cpp @@ -62,6 +62,7 @@ static uintptr_t _EREMOVE(const void* epc_lin_addr); extern "C" void* get_td_addr(void); extern "C" bool get_elrange_start_address(void* base_address, uint64_t &elrange_start_address); +static __thread uintptr_t _dtv_u = 0; //////////////////////////////////////////////////////////////////////// #define __GP__() exit(EXIT_FAILURE) @@ -127,7 +128,7 @@ void sig_handler_sim(int signum, siginfo_t *siginfo, void *priv) GP_ON(signum != SIGFPE && signum != SIGSEGV); thread_data_t *thread_data = (thread_data_t*)get_td_addr(); - if (thread_data != NULL && (uintptr_t)thread_data == (uintptr_t)thread_data->self_addr) + if (thread_data != NULL && _dtv_u != 0 && (uintptr_t)thread_data != _dtv_u && (uintptr_t)thread_data == (uintptr_t)thread_data->self_addr) { // first SSA can be used to get tcs, even cssa > 0. ssa_gpr_t *p_ssa_gpr = (ssa_gpr_t*)thread_data->first_ssa_gpr; @@ -453,6 +454,9 @@ void _SE3(uintptr_t xax, uintptr_t xbx, tcs_sim->tcs_offset_update_flag = true; } + // init _dtv_u + if(_dtv_u == 0) + _dtv_u = (uintptr_t)get_td_addr(); secs = ce->get_secs(); enclave_base_addr = secs->base; diff --git a/sdk/simulation/urtssim/enclave_creator_sim.cpp b/sdk/simulation/urtssim/enclave_creator_sim.cpp index 8bed968e..dfad04d0 100644 --- a/sdk/simulation/urtssim/enclave_creator_sim.cpp +++ b/sdk/simulation/urtssim/enclave_creator_sim.cpp @@ -46,7 +46,6 @@ #include #include "sgx_enclave_common.h" #include - #include #include #include @@ -308,44 +307,3 @@ bool EnclaveCreatorSim::get_plat_cap(sgx_misc_attribute_t *se_attr) return false; } -int EnclaveCreatorSim::emodpr(uint64_t addr, uint64_t size, uint64_t flag) -{ - UNUSED(addr); - UNUSED(size); - UNUSED(flag); - - return SGX_SUCCESS; -} - -int EnclaveCreatorSim::mktcs(uint64_t tcs_addr) -{ - UNUSED(tcs_addr); - - return SGX_SUCCESS; -} - -int EnclaveCreatorSim::trim_range(uint64_t fromaddr, uint64_t toaddr) -{ - UNUSED(fromaddr); - UNUSED(toaddr); - - return SGX_SUCCESS; - -} - -int EnclaveCreatorSim::trim_accept(uint64_t addr) -{ - UNUSED(addr); - - return SGX_SUCCESS; -} - -int EnclaveCreatorSim::remove_range(uint64_t fromaddr, uint64_t numpages) -{ - UNUSED(fromaddr); - UNUSED(numpages); - - return SGX_SUCCESS; -} - - diff --git a/sdk/simulation/urtssim/enclave_creator_sim.h b/sdk/simulation/urtssim/enclave_creator_sim.h index 8896d452..6dd9365f 100644 --- a/sdk/simulation/urtssim/enclave_creator_sim.h +++ b/sdk/simulation/urtssim/enclave_creator_sim.h @@ -51,11 +51,6 @@ public: bool use_se_hw() const; bool is_EDMM_supported(sgx_enclave_id_t enclave_id); bool is_driver_compatible(); - int emodpr(uint64_t addr, uint64_t size, uint64_t flag); - int mktcs(uint64_t tcs_addr); - int trim_range(uint64_t fromaddr, uint64_t toaddr); - int trim_accept(uint64_t addr); - int remove_range(uint64_t fromaddr, uint64_t numpages); private: bool m_sig_registered; }; diff --git a/sdk/simulation/urtssim/linux/Makefile b/sdk/simulation/urtssim/linux/Makefile index f2be8b34..d9a43450 100644 --- a/sdk/simulation/urtssim/linux/Makefile +++ b/sdk/simulation/urtssim/linux/Makefile @@ -31,6 +31,8 @@ include ../../../../buildenv.mk +URTS_VER:= $(shell awk '$$2 ~ /URTS_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) + SIM_DIR := $(LINUX_SDK_DIR)/simulation VTUNE_DIR = $(LINUX_EXTERNAL_DIR)/vtune/linux @@ -87,8 +89,7 @@ OBJ2 := urts.o \ sig_handler.o \ debugger_support.o \ get_thread_id.o \ - urts_trim.o \ - urts_emodpr.o + urts_emm.o OBJ3 := section.o \ elfparser.o @@ -181,7 +182,7 @@ ittnotify: CFLAGS= CXXFLAGS= $(MAKE) -C $(VTUNE_DIR)/sdk/src/ittnotify/ $(LIBURTS_DEPLOY):../urts_deploy.c - $(CC) -I$(COMMON_DIR)/inc $(CET_FLAGS) -shared -fPIC -Wl,-soname=libsgx_urts.so $< -o $@ + $(CC) -I$(COMMON_DIR)/inc $(CET_FLAGS) -shared -fPIC -Wl,-soname=libsgx_urts.so.$(call SPLIT_VERSION,$(URTS_VER),1) $< -o $@ .PHONY: clean clean:: diff --git a/sdk/switchless/inc/sl_bitops.h b/sdk/switchless/inc/sl_bitops.h index 587b1a4c..31652a29 100644 --- a/sdk/switchless/inc/sl_bitops.h +++ b/sdk/switchless/inc/sl_bitops.h @@ -53,12 +53,12 @@ static inline uint32_t count_leading_zeroes(uint64_t value) -static inline void set_bit(volatile uint64_t* l, uint32_t i) +static inline void set_bit(volatile uint64_t* l, uint64_t i) { lock_or64(l, 1ULL << i); } -static inline int32_t test_and_clear_bit(volatile uint64_t* l, uint32_t i) +static inline int32_t test_and_clear_bit(volatile uint64_t* l, uint64_t i) { uint64_t old_l, new_l; retry: diff --git a/sdk/switchless/inc/sl_fcall_mngr.h b/sdk/switchless/inc/sl_fcall_mngr.h index 5ce4751a..a47c228d 100644 --- a/sdk/switchless/inc/sl_fcall_mngr.h +++ b/sdk/switchless/inc/sl_fcall_mngr.h @@ -61,7 +61,7 @@ #include -typedef enum { +typedef enum : unsigned long long { SL_TYPE_OCALL, SL_TYPE_ECALL } sl_call_type_t; @@ -69,12 +69,12 @@ typedef enum { typedef sgx_status_t(*sl_call_func_t)(const void* /* ms */); typedef struct { - uint32_t size; + uint64_t size; sl_call_func_t funcs[]; } sl_call_table_t; /* compatible with sgx_ocall_table_t */ -typedef enum { +typedef enum : unsigned long long { SL_INIT, SL_SUBMITTED, SL_ACCEPTED, @@ -85,12 +85,12 @@ typedef enum { struct sl_call_task { volatile sl_call_status_t status; // status of the current task - uint32_t func_id; // function id to be called (index to the call table) + uint64_t func_id; // function id to be called (index to the call table) void* func_data; // data to be passed to the function - sgx_status_t ret_code; // return code of the function + alignas(8) sgx_status_t ret_code; // return code of the function }; -#define SL_INVALID_FUNC_ID ((uint32_t)-1) +#define SL_INVALID_FUNC_ID ((uint64_t)-1) struct sl_call_mngr { sl_call_type_t type; // type of the call manager (ECALL / OCALL) @@ -181,7 +181,7 @@ __BEGIN_DECLS uint32_t sl_call_mngr_init(struct sl_call_mngr* mngr, sl_call_type_t type, - uint32_t max_pending_ocalls); + uint64_t max_pending_ocalls); void sl_call_mngr_destroy(struct sl_call_mngr* mngr); diff --git a/sdk/switchless/inc/sl_fcall_mngr_common.h b/sdk/switchless/inc/sl_fcall_mngr_common.h index 06c3a664..04a46f99 100644 --- a/sdk/switchless/inc/sl_fcall_mngr_common.h +++ b/sdk/switchless/inc/sl_fcall_mngr_common.h @@ -84,7 +84,7 @@ static inline void sl_call_mngr_register_calls(struct sl_call_mngr* mngr, mngr->call_table = call_table; } -static inline uint32_t sl_call_mngr_process(struct sl_call_mngr* mngr) +static inline uint64_t sl_call_mngr_process(struct sl_call_mngr* mngr) { BUG_ON(!can_type_process(mngr->type)); return sl_siglines_process_signals(&mngr->siglns); @@ -104,7 +104,7 @@ static inline uint32_t sl_call_mngr_process(struct sl_call_mngr* mngr) } while(0) #endif -static inline void process_switchless_call(struct sl_siglines* siglns, uint32_t line) +static inline void process_switchless_call(struct sl_siglines* siglns, uint64_t line) { /* @@ -140,7 +140,7 @@ static inline void process_switchless_call(struct sl_siglines* siglns, uint32_t BUG_ON(call_task_u->status != SL_SUBMITTED); SET_VALUE_HARDEN_FOR_PROCESS_TASK(&call_task_u->status, SL_ACCEPTED, sl_call_status_t); - uint32_t func_id = call_task_u->func_id; + uint64_t func_id = call_task_u->func_id; /* Get the function pointer */ sl_call_func_t call_func_ptr = NULL; @@ -190,7 +190,7 @@ on_done: } while(0) #endif -static inline int sl_call_mngr_call(struct sl_call_mngr* mngr, struct sl_call_task* call_task, uint32_t max_tries) +static inline int sl_call_mngr_call(struct sl_call_mngr* mngr, struct sl_call_task* call_task, uint64_t max_tries) { /* Used to make actual switchless call by both enclave & untrusted code @@ -208,7 +208,7 @@ static inline int sl_call_mngr_call(struct sl_call_mngr* mngr, struct sl_call_ta /* Allocate a free signal line to send signal */ struct sl_siglines* siglns = &mngr->siglns; - uint32_t line = sl_siglines_alloc_line(siglns); + uint64_t line = sl_siglines_alloc_line(siglns); if (line == SL_INVALID_SIGLINE) return -EAGAIN; @@ -260,7 +260,7 @@ static inline int sl_call_mngr_call(struct sl_call_mngr* mngr, struct sl_call_ta call_task->ret_code = mngr->tasks[line].ret_code; on_exit: - SET_VALUE_HARDEN_FOR_SEND_TASK(&mngr->tasks[line].func_id, SL_INVALID_FUNC_ID, uint32_t); + SET_VALUE_HARDEN_FOR_SEND_TASK(&mngr->tasks[line].func_id, SL_INVALID_FUNC_ID, uint64_t); sl_siglines_free_line(siglns, line); return ret; } diff --git a/sdk/switchless/inc/sl_siglines.h b/sdk/switchless/inc/sl_siglines.h index 26e7c47a..8f403a42 100644 --- a/sdk/switchless/inc/sl_siglines.h +++ b/sdk/switchless/inc/sl_siglines.h @@ -74,33 +74,34 @@ #include #include #include +#include #pragma pack(push, 1) /* ID of a signal line */ typedef int_type sl_sigline_t; -#define NBITS_PER_LINE ((uint32_t)(sizeof(sl_sigline_t) * 8)) +#define NBITS_PER_LINE ((sizeof(sl_sigline_t) * 8)) /* ID of a signal line */ -#define SL_INVALID_SIGLINE (uint32_t)(-1) +#define SL_INVALID_SIGLINE (uint64_t)(-1) #define SL_FREE_LINE_INIT ((sl_sigline_t)(-1)) -typedef enum { +typedef enum : unsigned long long { SL_SIGLINES_DIR_T2U, SL_SIGLINES_DIR_U2T } sl_siglines_dir_t; struct sl_siglines; typedef void (*sl_sighandler_t)(struct sl_siglines* /*siglines*/, - uint32_t /*line*/); + uint64_t /*line*/); struct sl_siglines { sl_siglines_dir_t direction; - uint32_t num_lines; + uint64_t num_lines; sl_sigline_t* event_lines; /* bitmap: 1 - event, 0 - no event */ sl_sigline_t* free_lines; /* bitmap: 1 - free, 0 - occupied */ sl_sighandler_t handler; @@ -115,7 +116,7 @@ __BEGIN_DECLS uint32_t sl_siglines_init(struct sl_siglines* sglns, sl_siglines_dir_t direction, - uint32_t num_lines, + uint64_t num_lines, sl_sighandler_t handler); void sl_siglines_destroy(struct sl_siglines* sglns); @@ -129,7 +130,7 @@ uint32_t sl_siglines_clone(struct sl_siglines* sglns, #endif /* SL_INSIDE_ENCLAVE */ -static inline uint32_t sl_siglines_size(const struct sl_siglines* sglns) { +static inline uint64_t sl_siglines_size(const struct sl_siglines* sglns) { return sglns->num_lines; } @@ -156,26 +157,26 @@ static inline int is_direction_receiver(sl_siglines_dir_t direction) #endif } -static inline int is_line_valid(struct sl_siglines* sglns, uint32_t line) +static inline int is_line_valid(struct sl_siglines* sglns, uint64_t line) { return (line < sglns->num_lines); } -static inline uint32_t sl_siglines_alloc_line(struct sl_siglines* sglns) +static inline uint64_t sl_siglines_alloc_line(struct sl_siglines* sglns) { BUG_ON(!is_direction_sender(sglns->direction)); - uint32_t i, max_i = (sglns->num_lines / NBITS_PER_LINE); + uint64_t i, max_i = (sglns->num_lines / NBITS_PER_LINE); sl_sigline_t* bits_p; for (i = 0; i < max_i; i++) { bits_p = &sglns->free_lines[i]; - int32_t j = extract_one_bit(bits_p); + int64_t j = extract_one_bit(bits_p); if (j < 0) continue; - uint32_t free_line = NBITS_PER_LINE * i + (uint32_t)j; + uint64_t free_line = NBITS_PER_LINE * i + (uint64_t)j; return free_line; } @@ -183,36 +184,36 @@ static inline uint32_t sl_siglines_alloc_line(struct sl_siglines* sglns) return SL_INVALID_SIGLINE; } -static inline void sl_siglines_free_line(struct sl_siglines* sglns, uint32_t line) +static inline void sl_siglines_free_line(struct sl_siglines* sglns, uint64_t line) { BUG_ON(!is_direction_sender(sglns->direction)); BUG_ON(!is_line_valid(sglns, line)); - uint32_t i = line / NBITS_PER_LINE; - uint32_t j = line % NBITS_PER_LINE; + uint64_t i = line / NBITS_PER_LINE; + uint64_t j = line % NBITS_PER_LINE; set_bit(&sglns->free_lines[i], j); } -static inline int sl_siglines_trigger_signal(struct sl_siglines* sglns, uint32_t line) +static inline int sl_siglines_trigger_signal(struct sl_siglines* sglns, uint64_t line) { BUG_ON(!is_direction_sender(sglns->direction)); BUG_ON(!is_line_valid(sglns, line)); - uint32_t i = line / NBITS_PER_LINE; - uint32_t j = line % NBITS_PER_LINE; + uint64_t i = line / NBITS_PER_LINE; + uint64_t j = line % NBITS_PER_LINE; set_bit(&sglns->event_lines[i], j); return 0; } -static inline int sl_siglines_revoke_signal(struct sl_siglines* sglns, uint32_t line) +static inline int sl_siglines_revoke_signal(struct sl_siglines* sglns, uint64_t line) { BUG_ON(!is_direction_sender(sglns->direction)); BUG_ON(!is_line_valid(sglns, line)); - uint32_t i = line / NBITS_PER_LINE; - uint32_t j = line % NBITS_PER_LINE; + uint64_t i = line / NBITS_PER_LINE; + uint64_t j = line % NBITS_PER_LINE; return test_and_clear_bit(&sglns->event_lines[i], j) == 0; } -static inline uint32_t sl_siglines_process_signals(struct sl_siglines* sglns) +static inline uint64_t sl_siglines_process_signals(struct sl_siglines* sglns) { // function checks bits in array of bitmaps // if it detects a 1 bit (which indicates a pending task) and succeeded to change it atomically to 0, @@ -220,8 +221,8 @@ static inline uint32_t sl_siglines_process_signals(struct sl_siglines* sglns) BUG_ON(!is_direction_receiver(sglns->direction)); - uint32_t nprocessed = 0; - uint32_t i, bit_n, start_bit, end_bit, max_i = (sglns->num_lines / NBITS_PER_LINE); + uint64_t nprocessed = 0; + uint64_t i, bit_n, start_bit, end_bit, max_i = (sglns->num_lines / NBITS_PER_LINE); sl_sigline_t* bits_p; sl_sigline_t bits_value; @@ -241,7 +242,7 @@ static inline uint32_t sl_siglines_process_signals(struct sl_siglines* sglns) { if (unlikely(test_and_clear_bit(bits_p, bit_n) == 0)) continue; - uint32_t line = NBITS_PER_LINE * i + bit_n; + uint64_t line = NBITS_PER_LINE * i + bit_n; sglns->handler(sglns, line); nprocessed++; diff --git a/sdk/switchless/inc/sl_uswitchless.h b/sdk/switchless/inc/sl_uswitchless.h index 38fdc7f4..58aaf4af 100644 --- a/sdk/switchless/inc/sl_uswitchless.h +++ b/sdk/switchless/inc/sl_uswitchless.h @@ -61,7 +61,7 @@ typedef struct _ocall_table_t { - uint32_t count; + uint64_t count; void *ocall[]; } sgx_ocall_table_t; diff --git a/sdk/switchless/inc/sl_workers.h b/sdk/switchless/inc/sl_workers.h index 4ce5f957..4c7ece8a 100644 --- a/sdk/switchless/inc/sl_workers.h +++ b/sdk/switchless/inc/sl_workers.h @@ -37,6 +37,7 @@ #ifndef SL_INSIDE_ENCLAVE /* Untrusted */ #include #endif +#include /* * Abbreviations @@ -60,9 +61,9 @@ struct sl_uswitchless; struct sl_workers { struct sl_uswitchless* handle; - sl_worker_type_t type; + alignas(8) sl_worker_type_t type; sl_worker_stats_t stats; - volatile int32_t should_wake; + alignas(8) volatile int32_t should_wake; uint64_t num_all; uint64_t num_running; uint64_t num_sleeping; diff --git a/sdk/switchless/sgx_tswitchless/Makefile b/sdk/switchless/sgx_tswitchless/Makefile index 759e705b..34bc95a6 100644 --- a/sdk/switchless/sgx_tswitchless/Makefile +++ b/sdk/switchless/sgx_tswitchless/Makefile @@ -60,8 +60,19 @@ SL_CFLAGS += -I$(COMMON_DIR)/inc \ -I$(LINUX_SDK_DIR)/trts \ -I$(SL_DIR)/inc +SL_CXXFLAGS := $(CXXFLAGS) +SL_CXXFLAGS += -fPIC $(CET_FLAGS) +SL_CXXFLAGS += $(ENCLAVE_CXXFLAGS) +SL_CXXFLAGS += -DSL_INSIDE_ENCLAVE +SL_CXXFLAGS += -I$(COMMON_DIR)/inc \ + -I$(COMMON_DIR)/inc/internal \ + -I$(COMMON_DIR)/inc/tlibc \ + -I$(LINUX_SDK_DIR)/trts \ + -I$(SL_DIR)/inc + ifdef DEBUG SL_CFLAGS += -DSL_DEBUG + SL_CXXFLAGS += -DSL_DEBUG endif @@ -82,8 +93,8 @@ $(OUT_LIB): $(ALL_OBJS) @echo "$(GREEN)LINK => $@$(NC)" $(C_OBJS): %.o: %.c sgx_tswitchless_t.h - @$(CC) $(SL_CFLAGS) -c $< -o $@ - @echo "$(CC) <= $@" + @$(CXX) $(SL_CXXFLAGS) -c $< -o $@ + @echo "$(CXX) <= $@" sgx_tswitchless_t.h: $(EDGER8R) diff --git a/sdk/switchless/sgx_tswitchless/sl_init.c b/sdk/switchless/sgx_tswitchless/sl_init.c index 02c08587..d094dbbc 100644 --- a/sdk/switchless/sgx_tswitchless/sl_init.c +++ b/sdk/switchless/sgx_tswitchless/sl_init.c @@ -35,6 +35,7 @@ #include #include +#define CHECK_ALIGNMENT(x) if (((uint64_t)x) % 8 != 0) abort(); // holds the pointer to untrusted structure describing switchless configuration // pointer is assigned only after all necessary checks @@ -49,9 +50,18 @@ sgx_status_t sl_init_switchless(void* _handle_u) PANIC_ON(!sgx_is_outside_enclave(handle_u, sizeof(*handle_u))); sgx_lfence(); - if (lock_cmpxchg_ptr((void*)&g_uswitchless_handle, NULL, (void*)handle_u) != NULL) + if (lock_cmpxchg_ptr((void * volatile *)&g_uswitchless_handle, NULL, (void*)handle_u) != NULL) { return SGX_ERROR_UNEXPECTED; } + CHECK_ALIGNMENT(&g_uswitchless_handle->us_config); + CHECK_ALIGNMENT(&g_uswitchless_handle->us_has_new_ocall_fallback); + CHECK_ALIGNMENT(&g_uswitchless_handle->us_ocall_mngr); + CHECK_ALIGNMENT(&g_uswitchless_handle->us_ecall_mngr); + CHECK_ALIGNMENT(&g_uswitchless_handle->us_should_stop); + CHECK_ALIGNMENT(&g_uswitchless_handle->us_uworkers.num_running); + CHECK_ALIGNMENT(&g_uswitchless_handle->us_uworkers.num_sleeping); + CHECK_ALIGNMENT(&g_uswitchless_handle->us_uworkers.stats); + CHECK_ALIGNMENT(&g_uswitchless_handle->us_wake_workers); return SGX_SUCCESS; } diff --git a/sdk/switchless/sgx_tswitchless/sl_siglines.c b/sdk/switchless/sgx_tswitchless/sl_siglines.c index c0a0fa99..b6b7c594 100644 --- a/sdk/switchless/sgx_tswitchless/sl_siglines.c +++ b/sdk/switchless/sgx_tswitchless/sl_siglines.c @@ -59,12 +59,12 @@ uint32_t sl_siglines_clone(struct sl_siglines* sglns, BUG_ON(is_direction_sender(direction) && (handler != NULL)); - uint32_t num_lines = untrusted->num_lines; + uint64_t num_lines = untrusted->num_lines; if ((num_lines <= 0) || ((num_lines % NBITS_PER_LINE) != 0)) return EINVAL; sglns->num_lines = num_lines; - uint32_t nlong = num_lines / NBITS_PER_LINE; + uint64_t nlong = num_lines / NBITS_PER_LINE; sl_sigline_t* event_lines_u = untrusted->event_lines; if (event_lines_u == NULL) diff --git a/sdk/switchless/sgx_tswitchless/sl_workers.c b/sdk/switchless/sgx_tswitchless/sl_workers.c index e2f8e1a9..1ea9df89 100644 --- a/sdk/switchless/sgx_tswitchless/sl_workers.c +++ b/sdk/switchless/sgx_tswitchless/sl_workers.c @@ -62,7 +62,7 @@ static sl_call_table_t* __attribute__((optimize("O0"))) new_ecall_table(void) + sizeof(sl_call_func_t) * num_ecalls; // fcall_table never gets freed. no global termination hooks defined - sl_call_table_t* fcall_table = malloc(table_size); + sl_call_table_t* fcall_table = (sl_call_table_t*)malloc(table_size); if (fcall_table == NULL) return NULL; @@ -127,8 +127,8 @@ sgx_status_t sl_run_switchless_tworker() return SGX_ERROR_UNEXPECTED; // g_uswitchels_handle pointer is checked in sl_init_switchless() function - uint32_t max_retries = g_uswitchless_handle->us_config.retries_before_sleep; - uint32_t retries = 0; + uint64_t max_retries = g_uswitchless_handle->us_config.retries_before_sleep; + uint64_t retries = 0; while (retries < max_retries) { diff --git a/sdk/switchless/sgx_uswitchless/Makefile b/sdk/switchless/sgx_uswitchless/Makefile index 7ba633d4..b4122a86 100644 --- a/sdk/switchless/sgx_uswitchless/Makefile +++ b/sdk/switchless/sgx_uswitchless/Makefile @@ -87,12 +87,12 @@ $(OUT_LIB): $(ALL_OBJS) @echo "$(GREEN)LINK => $@$(NC)" $(C_OBJS): %.o: %.c sgx_tswitchless_u.h - @$(CC) $(SL_CFLAGS) -c $< -o $@ - @echo "$(CC) <= $@" + @$(CXX) $(SL_CXXFLAGS) -c $< -o $@ + @echo "$(CXX) <= $@" $(CPP_OBJS): %.o: %.cpp @$(CXX) $(SL_CXXFLAGS) -c $< -o $@ - @echo "$(CXX) <= $@" + @echo "$(CXX) <= $@" sgx_tswitchless_u.h: $(EDGER8R) diff --git a/sdk/switchless/sgx_uswitchless/sl_fcall_mngr_untrusted.c b/sdk/switchless/sgx_uswitchless/sl_fcall_mngr_untrusted.c index 7f7b4e94..0f509ad4 100644 --- a/sdk/switchless/sgx_uswitchless/sl_fcall_mngr_untrusted.c +++ b/sdk/switchless/sgx_uswitchless/sl_fcall_mngr_untrusted.c @@ -33,9 +33,9 @@ uint32_t sl_call_mngr_init(struct sl_call_mngr* mngr, sl_call_type_t type, - uint32_t max_pending_calls) + uint64_t max_pending_calls) { - uint32_t i; + uint64_t i; mngr->type = type; struct sl_call_task* tasks = (struct sl_call_task*)calloc(max_pending_calls, sizeof(tasks[0])); diff --git a/sdk/switchless/sgx_uswitchless/sl_siglines_untrusted.c b/sdk/switchless/sgx_uswitchless/sl_siglines_untrusted.c index bc05c421..2676351b 100644 --- a/sdk/switchless/sgx_uswitchless/sl_siglines_untrusted.c +++ b/sdk/switchless/sgx_uswitchless/sl_siglines_untrusted.c @@ -41,18 +41,18 @@ uint32_t sl_siglines_init(struct sl_siglines* sglns, sl_siglines_dir_t direction, - uint32_t num_lines, + uint64_t num_lines, sl_sighandler_t handler) { BUG_ON(is_direction_sender(direction) && (handler != NULL)); if (num_lines <= 0) return EINVAL; num_lines = ALIGN_UP(num_lines, NBITS_PER_LINE); - uint32_t nlong = num_lines / NBITS_PER_LINE; + uint64_t nlong = num_lines / NBITS_PER_LINE; sl_sigline_t *event_lines = NULL, *free_lines = NULL; - uint32_t i = 0; + uint64_t i = 0; event_lines = (sl_sigline_t*)calloc(nlong, sizeof(sl_sigline_t)); diff --git a/sdk/switchless/sgx_uswitchless/sl_uswitchless_untrusted.c b/sdk/switchless/sgx_uswitchless/sl_uswitchless_untrusted.c index e9460acf..5c9fd8e0 100644 --- a/sdk/switchless/sgx_uswitchless/sl_uswitchless_untrusted.c +++ b/sdk/switchless/sgx_uswitchless/sl_uswitchless_untrusted.c @@ -81,10 +81,10 @@ sgx_status_t sl_uswitchless_new(const sgx_uswitchless_config_t* config, handle->us_config.retries_before_fallback = (handle->us_config.retries_before_fallback == 0) ? SL_DEFAULT_FALLBACK_RETRIES : handle->us_config.retries_before_fallback; - handle->us_config.retries_before_sleep = (handle->us_config.retries_before_sleep == 0) ? + handle->us_config.retries_before_sleep = (handle->us_config.retries_before_sleep == 0) ? SL_DEFAULT_SLEEP_RETRIES : handle->us_config.retries_before_sleep; - uint32_t max_tasks = handle->us_config.switchless_calls_pool_size_qwords == 0 ? + uint64_t max_tasks = handle->us_config.switchless_calls_pool_size_qwords == 0 ? SL_DEFUALT_MAX_TASKS_QWORDS : handle->us_config.switchless_calls_pool_size_qwords; max_tasks *= BITS_IN_QWORD; @@ -191,7 +191,7 @@ uint32_t sl_uswitchless_start_workers(struct sl_uswitchless* handle, BUG_ON(ocall_table == NULL); /* Silently ignore harmless duplication of staring workers */ - if (lock_cmpxchg_ptr((void*)&handle->us_ocall_table, NULL, (void*)ocall_table) != NULL) + if (lock_cmpxchg_ptr((void* volatile*)&handle->us_ocall_table, NULL, (void*)ocall_table) != NULL) return 0; /* switchless ocall_table to the sl_fcall_mngr for switchless Calls */ diff --git a/sdk/switchless/sgx_uswitchless/sl_workers_untrusted.c b/sdk/switchless/sgx_uswitchless/sl_workers_untrusted.c index 9c837375..fe20870c 100644 --- a/sdk/switchless/sgx_uswitchless/sl_workers_untrusted.c +++ b/sdk/switchless/sgx_uswitchless/sl_workers_untrusted.c @@ -56,7 +56,7 @@ uint32_t sl_workers_init(struct sl_workers* workers, workers->handle = handle; workers->type = type; - uint32_t num_workers = type == SL_WORKER_TYPE_UNTRUSTED ? + uint64_t num_workers = type == SL_WORKER_TYPE_UNTRUSTED ? handle->us_config.num_uworkers : handle->us_config.num_tworkers ; workers->num_all = num_workers; @@ -282,8 +282,8 @@ static uint32_t uworker_process_calls(struct sl_workers* workers) struct sl_uswitchless* handle = workers->handle; struct sl_call_mngr* ocall_mngr = &handle->us_ocall_mngr; - uint32_t max_retries = handle->us_config.retries_before_sleep; - uint32_t retries = 0; + uint64_t max_retries = handle->us_config.retries_before_sleep; + uint64_t retries = 0; while (retries < max_retries) { diff --git a/sdk/tlibc/gen/sbrk.c b/sdk/tlibc/gen/sbrk.c index e05a93fe..9dff9a63 100644 --- a/sdk/tlibc/gen/sbrk.c +++ b/sdk/tlibc/gen/sbrk.c @@ -78,7 +78,8 @@ void* sbrk(intptr_t n) size_t prev_heap_used = heap_used; void * start_addr; size_t size = 0; - + assert((heap_used & (SE_PAGE_SIZE - 1)) == 0); + if (!heap_base) return (void *)(~(size_t)0); @@ -113,7 +114,8 @@ void* sbrk(intptr_t n) start_addr = (void *)((size_t)(heap_base) + heap_min_size); size = prev_heap_used - heap_min_size; } - int ret = trim_EPC_pages(start_addr, size >> SE_PAGE_SHIFT); + assert((size & (SE_PAGE_SIZE - 1)) == 0); + int ret = mm_uncommit(start_addr, size); if (ret != 0) { heap_used = prev_heap_used; @@ -131,6 +133,8 @@ void* sbrk(intptr_t n) there's no integer overflow here. */ heap_ptr = (void *)((size_t)heap_base + (size_t)heap_used); + if(n==0) return heap_ptr; + heap_used += n; /* update g_peak_heap_used */ @@ -154,7 +158,8 @@ void* sbrk(intptr_t n) start_addr = (void *)((size_t)(heap_base) + heap_min_size); size = heap_used - heap_min_size; } - int ret = apply_EPC_pages(start_addr, size >> SE_PAGE_SHIFT); + assert((size & (SE_PAGE_SIZE - 1)) == 0); + int ret = mm_commit(start_addr, size); if (ret != 0) { heap_used = prev_heap_used; diff --git a/sdk/tlibc/stdlib/aligned_alloc.c b/sdk/tlibc/stdlib/aligned_alloc.c new file mode 100644 index 00000000..c3abd94c --- /dev/null +++ b/sdk/tlibc/stdlib/aligned_alloc.c @@ -0,0 +1,6 @@ +#include + +void *aligned_alloc(size_t align, size_t len) +{ + return memalign(align, len); +} diff --git a/sdk/tlibc/stdlib/malloc.c b/sdk/tlibc/stdlib/malloc.c index 1b1b398b..efed7be5 100755 --- a/sdk/tlibc/stdlib/malloc.c +++ b/sdk/tlibc/stdlib/malloc.c @@ -846,8 +846,8 @@ extern "C" { void* __attribute__((weak)) memalign(size_t align, size_t s) ALIAS(dlmemalign); int __attribute__((weak)) posix_memalign(void**pptr, size_t align, size_t size) ALIAS(dlposix_memalign); struct mallinfo __attribute__((weak)) mallinfo(void) ALIAS(dlmallinfo); + int __attribute__((weak)) posix_memalign(void** pp, size_t alignment, size_t n) ALIAS(dlposix_memalign); #ifdef USE_MALLOC_DEPRECATED -#define dlposix_memalign posix_memalign #define dlrealloc_in_place realloc_in_place #define dlvalloc valloc #define dlpvalloc pvalloc diff --git a/sdk/tlibc/string/memcpy.c b/sdk/tlibc/string/memcpy.c index 4c4cbc1c..c3d2d8a5 100644 --- a/sdk/tlibc/string/memcpy.c +++ b/sdk/tlibc/string/memcpy.c @@ -117,12 +117,13 @@ void* memcpy_verw(void *dst0, const void *src0, size_t len) } while (len >= 8) { - if((unsigned long long)dst%8 == 0) { + if(((unsigned long long)dst%8 == 0) && ((unsigned long long)src%8 == 0)) { // 8-byte-aligned - don't need bracketing - __memcpy_8a(dst, src); - src += 8; - dst += 8; - len -= 8; + size_t len0 = len - len%8; + memcpy_nochecks(dst, src, len0); + src += len0; + dst += len0; + len -= len0; } else{ // not 8-byte-aligned - need bracketing @@ -134,9 +135,9 @@ void* memcpy_verw(void *dst0, const void *src0, size_t len) } // less than 8 bytes left - need bracketing for (unsigned i = 0; i < len; i++) { - __memcpy_verw(dst, src); - src++; - dst++; + __memcpy_verw(dst, src); + src++; + dst++; } return dst0; } @@ -156,27 +157,35 @@ memcpy_nochecks(void *dst0, const void *src0, size_t length) static void copy_external_memory(void* dst, const void* src, size_t count, bool is_dst_external) { - unsigned char tmp_buf[16]={0}; + char tmp_buf[16]={0}; unsigned int off_src = (unsigned long long)src%8; + char* src_buf = NULL; if(count == 0) { return; } - - //if src is 8-byte-aligned, copy 8 bytes from outside the enclave to the buffer - //if src is not 8-byte-aligned and off_src + count > 8, copy 16 bytes from outside the enclave to the buffer - __memcpy_8a(tmp_buf, src - off_src); - if(off_src != 0 && off_src + count > 8) + //if external src is not 8-byte-aligned or count != 8 + if(off_src != 0 || count != 8) { - __memcpy_8a(tmp_buf + 8, src - off_src + 8); - } - if(is_dst_external) - { - memcpy_verw(dst, tmp_buf + off_src, count); + //if external src is not 8-byte-aligned, need to copy from src-off_src to a tmp_buf inside the enclave + __memcpy_8a(tmp_buf, src - off_src); + if(off_src != 0 && off_src + count > 8) + { + __memcpy_8a(tmp_buf + 8, src - off_src + 8); + } + src_buf = tmp_buf + off_src; } else { - memcpy_nochecks(dst, tmp_buf + off_src, count); + src_buf = (char*)src; + } + if(is_dst_external) + { + memcpy_verw(dst, src_buf, count); + } + else + { + memcpy_nochecks(dst, src_buf, count); } return; } @@ -206,16 +215,28 @@ memcpy(void *dst0, const void *src0, size_t length) } //src is outside the enclave - unsigned int len = 0; + size_t len = 0; char* dst = dst0; const char *src = (const char *)src0; while(length >= 8) { - len = 8 - (unsigned long long)dst%8; - copy_external_memory(dst, src, len, is_dst_external); - src += len; - dst += len; - length -= len; + //if dst and src are both 8-byte-aligned, direct call memcpy_nochecks + if(((unsigned long long)dst%8 == 0) && ((unsigned long long)src%8 == 0)) + { + len = length - length%8; + memcpy_nochecks(dst, src, len); + src += len; + dst += len; + length -= len; + } + else + { + len = 8 - (unsigned long long)dst%8; + copy_external_memory(dst, src, len, is_dst_external); + src += len; + dst += len; + length -= len; + } } //less than 8 bytes left copy_external_memory(dst, src, length, is_dst_external); diff --git a/sdk/tlibcxx/LICENSE.TXT b/sdk/tlibcxx/LICENSE.TXT index 339e232c..e159d283 100644 --- a/sdk/tlibcxx/LICENSE.TXT +++ b/sdk/tlibcxx/LICENSE.TXT @@ -1,5 +1,240 @@ ============================================================================== -libc++ License +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): ============================================================================== The libc++ library is dual licensed under both the University of Illinois @@ -14,7 +249,7 @@ Full text of the relevant licenses is included below. University of Illinois/NCSA Open Source License -Copyright (c) 2009-2016 by the contributors listed in CREDITS.TXT +Copyright (c) 2009-2019 by the contributors listed in CREDITS.TXT All rights reserved. diff --git a/sdk/tlibcxx/include/CMakeLists.txt b/sdk/tlibcxx/include/CMakeLists.txt index 219d1b73..29a317b8 100644 --- a/sdk/tlibcxx/include/CMakeLists.txt +++ b/sdk/tlibcxx/include/CMakeLists.txt @@ -1,63 +1,277 @@ -if (NOT LIBCXX_INSTALL_SUPPORT_HEADERS) - set(LIBCXX_SUPPORT_HEADER_PATTERN PATTERN "support" EXCLUDE) +set(files + __availability + __bit_reference + __bits + __bsd_locale_defaults.h + __bsd_locale_fallbacks.h + __debug + __errc + __functional_03 + __functional_base + __functional_base_03 + __hash_table + __libcpp_version + __locale + __memory/allocator_traits.h + __memory/base.h + __memory/pointer_traits.h + __memory/utilities.h + __mutex_base + __node_handle + __nullptr + __split_buffer + __sso_allocator + __std_stream + __string + __threading_support + __tree + __tuple + __undef_macros + algorithm + any + array + atomic + barrier + bit + bitset + cassert + ccomplex + cctype + cerrno + cfenv + cfloat + charconv + chrono + cinttypes + ciso646 + climits + clocale + cmath + codecvt + compare + complex + complex.h + concepts + condition_variable + csetjmp + csignal + cstdarg + cstdbool + cstddef + cstdint + cstdio + cstdlib + cstring + ctgmath + ctime + ctype.h + cwchar + cwctype + deque + errno.h + exception + execution + experimental/__config + experimental/__memory + experimental/algorithm + experimental/coroutine + experimental/deque + experimental/filesystem + experimental/forward_list + experimental/functional + experimental/iterator + experimental/list + experimental/map + experimental/memory_resource + experimental/propagate_const + experimental/regex + experimental/set + experimental/simd + experimental/string + experimental/type_traits + experimental/unordered_map + experimental/unordered_set + experimental/utility + experimental/vector + ext/__hash + ext/hash_map + ext/hash_set + fenv.h + filesystem + float.h + forward_list + fstream + functional + future + initializer_list + inttypes.h + iomanip + ios + iosfwd + iostream + istream + iterator + latch + limits + limits.h + list + locale + locale.h + map + math.h + memory + module.modulemap + mutex + new + numbers + numeric + optional + ostream + queue + random + ratio + regex + scoped_allocator + semaphore + set + setjmp.h + shared_mutex + span + sstream + stack + stdbool.h + stddef.h + stdexcept + stdint.h + stdio.h + stdlib.h + streambuf + string + string.h + string_view + strstream + __support/android/locale_bionic.h + __support/fuchsia/xlocale.h + __support/ibm/limits.h + __support/ibm/locale_mgmt_aix.h + __support/ibm/nanosleep.h + __support/ibm/support.h + __support/ibm/xlocale.h + __support/musl/xlocale.h + __support/newlib/xlocale.h + __support/nuttx/xlocale.h + __support/openbsd/xlocale.h + __support/solaris/floatingpoint.h + __support/solaris/wchar.h + __support/solaris/xlocale.h + __support/win32/limits_msvc_win32.h + __support/win32/locale_win32.h + __support/xlocale/__nop_locale_mgmt.h + __support/xlocale/__posix_l_fallback.h + __support/xlocale/__strtonum_fallback.h + system_error + tgmath.h + thread + tuple + type_traits + typeindex + typeinfo + unordered_map + unordered_set + utility + valarray + variant + vector + version + wchar.h + wctype.h + ) + +configure_file("__config_site.in" + "${LIBCXX_BINARY_DIR}/__config_site" + @ONLY) + +# Generate a custom __config header. The new header is created +# by prepending __config_site to the current __config header. +add_custom_command(OUTPUT ${LIBCXX_BINARY_DIR}/__generated_config + COMMAND ${Python3_EXECUTABLE} ${LIBCXX_SOURCE_DIR}/utils/cat_files.py + ${LIBCXX_BINARY_DIR}/__config_site + ${LIBCXX_SOURCE_DIR}/include/__config + -o ${LIBCXX_BINARY_DIR}/__generated_config + DEPENDS ${LIBCXX_SOURCE_DIR}/include/__config + ${LIBCXX_BINARY_DIR}/__config_site +) +# Add a target that executes the generation commands. +add_custom_target(cxx-generated-config ALL + DEPENDS ${LIBCXX_BINARY_DIR}/__generated_config) + +if(LIBCXX_HEADER_DIR) + set(output_dir ${LIBCXX_HEADER_DIR}/include/c++/v1) + + set(out_files) + foreach(f ${files}) + set(src ${CMAKE_CURRENT_SOURCE_DIR}/${f}) + set(dst ${output_dir}/${f}) + add_custom_command(OUTPUT ${dst} + DEPENDS ${src} + COMMAND ${CMAKE_COMMAND} -E copy_if_different ${src} ${dst} + COMMENT "Copying CXX header ${f}") + list(APPEND out_files ${dst}) + endforeach() + + # Copy the generated header as __config into build directory. + set(src ${LIBCXX_BINARY_DIR}/__generated_config) + set(dst ${output_dir}/__config) + add_custom_command(OUTPUT ${dst} + DEPENDS ${src} cxx-generated-config + COMMAND ${CMAKE_COMMAND} -E copy_if_different ${src} ${dst} + COMMENT "Copying CXX __config") + list(APPEND out_files ${dst}) + add_custom_target(generate-cxx-headers ALL DEPENDS ${out_files}) + + add_library(cxx-headers INTERFACE) + add_dependencies(cxx-headers generate-cxx-headers ${LIBCXX_CXX_ABI_HEADER_TARGET}) + # TODO: Use target_include_directories once we figure out why that breaks the runtimes build + if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC" OR "${CMAKE_CXX_SIMULATE_ID}" STREQUAL "MSVC") + target_compile_options(cxx-headers INTERFACE /I "${output_dir}") + else() + target_compile_options(cxx-headers INTERFACE -I "${output_dir}") + endif() + + # Make sure the generated __config_site header is included when we build the library. + if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC" OR "${CMAKE_CXX_SIMULATE_ID}" STREQUAL "MSVC") + target_compile_options(cxx-headers INTERFACE /FI "${LIBCXX_BINARY_DIR}/__config_site") + else() + target_compile_options(cxx-headers INTERFACE -include "${LIBCXX_BINARY_DIR}/__config_site") + endif() +else() + add_library(cxx-headers INTERFACE) endif() -set(LIBCXX_HEADER_PATTERN - PATTERN "*" - PATTERN "CMakeLists.txt" EXCLUDE - PATTERN ".svn" EXCLUDE - PATTERN "__config_site.in" EXCLUDE - ${LIBCXX_SUPPORT_HEADER_PATTERN} - ) - -file(COPY . - DESTINATION "${CMAKE_BINARY_DIR}/include/c++/v1" - FILES_MATCHING - ${LIBCXX_HEADER_PATTERN} - ) - if (LIBCXX_INSTALL_HEADERS) - install(DIRECTORY . - DESTINATION include/c++/v1 - COMPONENT libcxx-headers - FILES_MATCHING - ${LIBCXX_HEADER_PATTERN} - PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ - ) - - if (LIBCXX_NEEDS_SITE_CONFIG) - set(UNIX_CAT cat) - if (WIN32) - set(UNIX_CAT type) - endif() - # Generate and install a custom __config header. The new header is created - # by prepending __config_site to the current __config header. - add_custom_command(OUTPUT ${LIBCXX_BINARY_DIR}/__generated_config - COMMAND ${CMAKE_COMMAND} -E copy ${LIBCXX_BINARY_DIR}/__config_site ${LIBCXX_BINARY_DIR}/__generated_config - COMMAND ${UNIX_CAT} ${LIBCXX_SOURCE_DIR}/include/__config >> ${LIBCXX_BINARY_DIR}/__generated_config - DEPENDS ${LIBCXX_SOURCE_DIR}/include/__config - ${LIBCXX_BINARY_DIR}/__config_site - ) - # Add a target that executes the generation commands. - add_custom_target(generate_config_header ALL - DEPENDS ${LIBCXX_BINARY_DIR}/__generated_config) - set(generated_config_deps generate_config_header) - # Install the generated header as __config. - install(FILES ${LIBCXX_BINARY_DIR}/__generated_config - DESTINATION include/c++/v1 + foreach(file ${files}) + get_filename_component(dir ${file} DIRECTORY) + install(FILES ${file} + DESTINATION ${LIBCXX_INSTALL_HEADER_PREFIX}include/c++/v1/${dir} + COMPONENT cxx-headers PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ - RENAME __config - COMPONENT libcxx-headers) - endif() + ) + endforeach() + + # Install the generated header as __config. + install(FILES ${LIBCXX_BINARY_DIR}/__generated_config + DESTINATION ${LIBCXX_INSTALL_HEADER_PREFIX}include/c++/v1 + PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ + RENAME __config + COMPONENT cxx-headers) if (NOT CMAKE_CONFIGURATION_TYPES) - # this target is just needed as a placeholder for the distribution target - add_custom_target(libcxx-headers) - add_custom_target(install-libcxx-headers - DEPENDS libcxx-headers ${generated_config_deps} + add_custom_target(install-cxx-headers + DEPENDS cxx-headers cxx-generated-config COMMAND "${CMAKE_COMMAND}" - -DCMAKE_INSTALL_COMPONENT=libcxx-headers + -DCMAKE_INSTALL_COMPONENT=cxx-headers -P "${CMAKE_BINARY_DIR}/cmake_install.cmake") + # Stripping is a no-op for headers + add_custom_target(install-cxx-headers-stripped DEPENDS install-cxx-headers) endif() - endif() diff --git a/sdk/tlibcxx/include/__availability b/sdk/tlibcxx/include/__availability new file mode 100644 index 00000000..cc3b6fab --- /dev/null +++ b/sdk/tlibcxx/include/__availability @@ -0,0 +1,249 @@ +// -*- C++ -*- +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___AVAILABILITY +#define _LIBCPP___AVAILABILITY + +#include <__config> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +// Libc++ is shipped by various vendors. In particular, it is used as a system +// library on macOS, iOS and other Apple platforms. In order for users to be +// able to compile a binary that is intended to be deployed to an older version +// of a platform, Clang provides availability attributes [1]. These attributes +// can be placed on declarations and are used to describe the life cycle of a +// symbol in the library. +// +// The main goal is to ensure a compile-time error if a symbol that hasn't been +// introduced in a previously released library is used in a program that targets +// that previously released library. Normally, this would be a load-time error +// when one tries to launch the program against the older library. +// +// For example, the filesystem library was introduced in the dylib in macOS 10.15. +// If a user compiles on a macOS 10.15 host but targets macOS 10.13 with their +// program, the compiler would normally not complain (because the required +// declarations are in the headers), but the dynamic loader would fail to find +// the symbols when actually trying to launch the program on macOS 10.13. To +// turn this into a compile-time issue instead, declarations are annotated with +// when they were introduced, and the compiler can produce a diagnostic if the +// program references something that isn't available on the deployment target. +// +// This mechanism is general in nature, and any vendor can add their markup to +// the library (see below). Whenever a new feature is added that requires support +// in the shared library, a macro should be added below to mark this feature +// as unavailable. When vendors decide to ship the feature as part of their +// shared library, they can update the markup appropriately. +// +// Furthermore, many features in the standard library have corresponding +// feature-test macros. When a feature is made unavailable on some deployment +// target, a macro should be defined to signal that it is unavailable. That +// macro can then be picked up when feature-test macros are generated (see +// generate_feature_test_macro_components.py) to make sure that feature-test +// macros don't announce a feature as being implemented if it has been marked +// as unavailable. +// +// Note that this mechanism is disabled by default in the "upstream" libc++. +// Availability annotations are only meaningful when shipping libc++ inside +// a platform (i.e. as a system library), and so vendors that want them should +// turn those annotations on at CMake configuration time. +// +// [1]: https://clang.llvm.org/docs/AttributeReference.html#availability + + +// For backwards compatibility, allow users to define _LIBCPP_DISABLE_AVAILABILITY +// for a while. +#if defined(_LIBCPP_DISABLE_AVAILABILITY) +# if !defined(_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS) +# define _LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS +# endif +#endif + +// Availability markup is disabled when building the library, or when the compiler +// doesn't support the proper attributes. +#if defined(_LIBCPP_BUILDING_LIBRARY) || \ + defined(_LIBCXXABI_BUILDING_LIBRARY) || \ + !__has_feature(attribute_availability_with_strict) || \ + !__has_feature(attribute_availability_in_templates) || \ + !__has_extension(pragma_clang_attribute_external_declaration) +# if !defined(_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS) +# define _LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS +# endif +#endif + +#if defined(_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS) + + // This controls the availability of std::shared_mutex and std::shared_timed_mutex, + // which were added to the dylib later. +# define _LIBCPP_AVAILABILITY_SHARED_MUTEX +// # define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex +// # define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex + + // These macros control the availability of std::bad_optional_access and + // other exception types. These were put in the shared library to prevent + // code bloat from every user program defining the vtable for these exception + // types. +# define _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS +# define _LIBCPP_AVAILABILITY_BAD_VARIANT_ACCESS +# define _LIBCPP_AVAILABILITY_BAD_ANY_CAST + + // This controls the availability of std::uncaught_exceptions(). +# define _LIBCPP_AVAILABILITY_UNCAUGHT_EXCEPTIONS + + // This controls the availability of the sized version of ::operator delete, + // which was added to the dylib later. +# define _LIBCPP_AVAILABILITY_SIZED_NEW_DELETE + + // This controls the availability of the std::future_error exception. +# define _LIBCPP_AVAILABILITY_FUTURE_ERROR + + // This controls the availability of std::type_info's vtable. + // I can't imagine how using std::type_info can work at all if + // this isn't supported. +# define _LIBCPP_AVAILABILITY_TYPEINFO_VTABLE + + // This controls the availability of std::locale::category members + // (e.g. std::locale::collate), which are defined in the dylib. +# define _LIBCPP_AVAILABILITY_LOCALE_CATEGORY + + // This controls the availability of atomic operations on std::shared_ptr + // (e.g. `std::atomic_store(std::shared_ptr)`), which require a shared + // lock table located in the dylib. +# define _LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR + + // These macros control the availability of all parts of that + // depend on something in the dylib. +# define _LIBCPP_AVAILABILITY_FILESYSTEM +# define _LIBCPP_AVAILABILITY_FILESYSTEM_PUSH +# define _LIBCPP_AVAILABILITY_FILESYSTEM_POP +// # define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_filesystem + + // This controls the availability of std::to_chars. +# define _LIBCPP_AVAILABILITY_TO_CHARS + + // This controls the availability of the C++20 synchronization library, + // which requires shared library support for various operations + // (see libcxx/src/atomic.cpp). +# define _LIBCPP_AVAILABILITY_SYNC +// # define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_atomic_wait +// # define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_barrier +// # define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch +// # define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore + +#elif defined(__APPLE__) + +# define _LIBCPP_AVAILABILITY_SHARED_MUTEX \ + __attribute__((availability(macosx,strict,introduced=10.12))) \ + __attribute__((availability(ios,strict,introduced=10.0))) \ + __attribute__((availability(tvos,strict,introduced=10.0))) \ + __attribute__((availability(watchos,strict,introduced=3.0))) +# if (defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101200) || \ + (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 100000) || \ + (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 100000) || \ + (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 30000) +# define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex +# define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex +# endif + +# define _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS \ + __attribute__((availability(macosx,strict,introduced=10.13))) \ + __attribute__((availability(ios,strict,introduced=11.0))) \ + __attribute__((availability(tvos,strict,introduced=11.0))) \ + __attribute__((availability(watchos,strict,introduced=4.0))) +# define _LIBCPP_AVAILABILITY_BAD_VARIANT_ACCESS \ + _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS +# define _LIBCPP_AVAILABILITY_BAD_ANY_CAST \ + _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS + +# define _LIBCPP_AVAILABILITY_UNCAUGHT_EXCEPTIONS \ + __attribute__((availability(macosx,strict,introduced=10.12))) \ + __attribute__((availability(ios,strict,introduced=10.0))) \ + __attribute__((availability(tvos,strict,introduced=10.0))) \ + __attribute__((availability(watchos,strict,introduced=3.0))) + +# define _LIBCPP_AVAILABILITY_SIZED_NEW_DELETE \ + __attribute__((availability(macosx,strict,introduced=10.12))) \ + __attribute__((availability(ios,strict,introduced=10.0))) \ + __attribute__((availability(tvos,strict,introduced=10.0))) \ + __attribute__((availability(watchos,strict,introduced=3.0))) + +# define _LIBCPP_AVAILABILITY_FUTURE_ERROR \ + __attribute__((availability(ios,strict,introduced=6.0))) + +# define _LIBCPP_AVAILABILITY_TYPEINFO_VTABLE \ + __attribute__((availability(macosx,strict,introduced=10.9))) \ + __attribute__((availability(ios,strict,introduced=7.0))) + +# define _LIBCPP_AVAILABILITY_LOCALE_CATEGORY \ + __attribute__((availability(macosx,strict,introduced=10.9))) \ + __attribute__((availability(ios,strict,introduced=7.0))) + +# define _LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR \ + __attribute__((availability(macosx,strict,introduced=10.9))) \ + __attribute__((availability(ios,strict,introduced=7.0))) + +# define _LIBCPP_AVAILABILITY_FILESYSTEM \ + __attribute__((availability(macosx,strict,introduced=10.15))) \ + __attribute__((availability(ios,strict,introduced=13.0))) \ + __attribute__((availability(tvos,strict,introduced=13.0))) \ + __attribute__((availability(watchos,strict,introduced=6.0))) +# define _LIBCPP_AVAILABILITY_FILESYSTEM_PUSH \ + _Pragma("clang attribute push(__attribute__((availability(macosx,strict,introduced=10.15))), apply_to=any(function,record))") \ + _Pragma("clang attribute push(__attribute__((availability(ios,strict,introduced=13.0))), apply_to=any(function,record))") \ + _Pragma("clang attribute push(__attribute__((availability(tvos,strict,introduced=13.0))), apply_to=any(function,record))") \ + _Pragma("clang attribute push(__attribute__((availability(watchos,strict,introduced=6.0))), apply_to=any(function,record))") +# define _LIBCPP_AVAILABILITY_FILESYSTEM_POP \ + _Pragma("clang attribute pop") \ + _Pragma("clang attribute pop") \ + _Pragma("clang attribute pop") \ + _Pragma("clang attribute pop") +# if (defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101500) || \ + (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 130000) || \ + (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 130000) || \ + (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 60000) +# define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_filesystem +# endif + +# define _LIBCPP_AVAILABILITY_TO_CHARS \ + _LIBCPP_AVAILABILITY_FILESYSTEM + + // Note: Those are not ABI-stable yet, so we can't ship them. +# define _LIBCPP_AVAILABILITY_SYNC \ + __attribute__((unavailable)) +# define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_atomic_wait +# define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_barrier +# define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch +# define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore + +#else + +// ...New vendors can add availability markup here... + +# error "It looks like you're trying to enable vendor availability markup, but you haven't defined the corresponding macros yet!" + +#endif + +// Define availability attributes that depend on _LIBCPP_NO_EXCEPTIONS. +// Those are defined in terms of the availability attributes above, and +// should not be vendor-specific. +#if defined(_LIBCPP_NO_EXCEPTIONS) +# define _LIBCPP_AVAILABILITY_FUTURE +# define _LIBCPP_AVAILABILITY_THROW_BAD_ANY_CAST +# define _LIBCPP_AVAILABILITY_THROW_BAD_OPTIONAL_ACCESS +# define _LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS +#else +# define _LIBCPP_AVAILABILITY_FUTURE _LIBCPP_AVAILABILITY_FUTURE_ERROR +# define _LIBCPP_AVAILABILITY_THROW_BAD_ANY_CAST _LIBCPP_AVAILABILITY_BAD_ANY_CAST +# define _LIBCPP_AVAILABILITY_THROW_BAD_OPTIONAL_ACCESS _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS +# define _LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS _LIBCPP_AVAILABILITY_BAD_VARIANT_ACCESS +#endif + +#endif // _LIBCPP___AVAILABILITY diff --git a/sdk/tlibcxx/include/__bit_reference b/sdk/tlibcxx/include/__bit_reference index 5659ed06..d44ad03d 100644 --- a/sdk/tlibcxx/include/__bit_reference +++ b/sdk/tlibcxx/include/__bit_reference @@ -1,10 +1,9 @@ // -*- C++ -*- //===----------------------------------------------------------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// @@ -12,14 +11,17 @@ #define _LIBCPP___BIT_REFERENCE #include <__config> +#include <__bits> #include -#include <__undef_min_max> - #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif +_LIBCPP_PUSH_MACROS +#include <__undef_macros> + + _LIBCPP_BEGIN_NAMESPACE_STD template class __bit_iterator; @@ -40,14 +42,14 @@ class __bit_reference __storage_pointer __seg_; __storage_type __mask_; -#if defined(__clang__) || defined(__IBMCPP__) || defined(_LIBCPP_MSVC) friend typename _Cp::__self; -#else - friend class _Cp::__self; -#endif + friend class __bit_const_reference<_Cp>; friend class __bit_iterator<_Cp, false>; public: + _LIBCPP_INLINE_VISIBILITY + __bit_reference(const __bit_reference&) = default; + _LIBCPP_INLINE_VISIBILITY operator bool() const _NOEXCEPT {return static_cast(*__seg_ & __mask_);} _LIBCPP_INLINE_VISIBILITY bool operator ~() const _NOEXCEPT @@ -69,7 +71,7 @@ public: _LIBCPP_INLINE_VISIBILITY void flip() _NOEXCEPT {*__seg_ ^= __mask_;} _LIBCPP_INLINE_VISIBILITY __bit_iterator<_Cp, false> operator&() const _NOEXCEPT - {return __bit_iterator<_Cp, false>(__seg_, static_cast(__ctz(__mask_)));} + {return __bit_iterator<_Cp, false>(__seg_, static_cast(__libcpp_ctz(__mask_)));} private: _LIBCPP_INLINE_VISIBILITY __bit_reference(__storage_pointer __s, __storage_type __m) _NOEXCEPT @@ -130,13 +132,12 @@ class __bit_const_reference __storage_pointer __seg_; __storage_type __mask_; -#if defined(__clang__) || defined(__IBMCPP__) || defined(_LIBCPP_MSVC) friend typename _Cp::__self; -#else - friend class _Cp::__self; -#endif friend class __bit_iterator<_Cp, true>; public: + _LIBCPP_INLINE_VISIBILITY + __bit_const_reference(const __bit_const_reference&) = default; + _LIBCPP_INLINE_VISIBILITY __bit_const_reference(const __bit_reference<_Cp>& __x) _NOEXCEPT : __seg_(__x.__seg_), __mask_(__x.__mask_) {} @@ -145,14 +146,14 @@ public: {return static_cast(*__seg_ & __mask_);} _LIBCPP_INLINE_VISIBILITY __bit_iterator<_Cp, true> operator&() const _NOEXCEPT - {return __bit_iterator<_Cp, true>(__seg_, static_cast(__ctz(__mask_)));} + {return __bit_iterator<_Cp, true>(__seg_, static_cast(__libcpp_ctz(__mask_)));} private: _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR __bit_const_reference(__storage_pointer __s, __storage_type __m) _NOEXCEPT : __seg_(__s), __mask_(__m) {} - __bit_const_reference& operator=(const __bit_const_reference& __x); + __bit_const_reference& operator=(const __bit_const_reference&) = delete; }; // find @@ -163,7 +164,7 @@ __find_bool_true(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_type { typedef __bit_iterator<_Cp, _IsConst> _It; typedef typename _It::__storage_type __storage_type; - static const unsigned __bits_per_word = _It::__bits_per_word; + static const int __bits_per_word = _It::__bits_per_word; // do first partial word if (__first.__ctz_ != 0) { @@ -172,7 +173,7 @@ __find_bool_true(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_type __storage_type __m = (~__storage_type(0) << __first.__ctz_) & (~__storage_type(0) >> (__clz_f - __dn)); __storage_type __b = *__first.__seg_ & __m; if (__b) - return _It(__first.__seg_, static_cast(_VSTD::__ctz(__b))); + return _It(__first.__seg_, static_cast(_VSTD::__libcpp_ctz(__b))); if (__n == __dn) return __first + __n; __n -= __dn; @@ -181,14 +182,14 @@ __find_bool_true(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_type // do middle whole words for (; __n >= __bits_per_word; ++__first.__seg_, __n -= __bits_per_word) if (*__first.__seg_) - return _It(__first.__seg_, static_cast(_VSTD::__ctz(*__first.__seg_))); + return _It(__first.__seg_, static_cast(_VSTD::__libcpp_ctz(*__first.__seg_))); // do last partial word if (__n > 0) { __storage_type __m = ~__storage_type(0) >> (__bits_per_word - __n); __storage_type __b = *__first.__seg_ & __m; if (__b) - return _It(__first.__seg_, static_cast(_VSTD::__ctz(__b))); + return _It(__first.__seg_, static_cast(_VSTD::__libcpp_ctz(__b))); } return _It(__first.__seg_, static_cast(__n)); } @@ -199,7 +200,7 @@ __find_bool_false(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_type { typedef __bit_iterator<_Cp, _IsConst> _It; typedef typename _It::__storage_type __storage_type; - static const unsigned __bits_per_word = _It::__bits_per_word; + const int __bits_per_word = _It::__bits_per_word; // do first partial word if (__first.__ctz_ != 0) { @@ -208,7 +209,7 @@ __find_bool_false(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_type __storage_type __m = (~__storage_type(0) << __first.__ctz_) & (~__storage_type(0) >> (__clz_f - __dn)); __storage_type __b = ~*__first.__seg_ & __m; if (__b) - return _It(__first.__seg_, static_cast(_VSTD::__ctz(__b))); + return _It(__first.__seg_, static_cast(_VSTD::__libcpp_ctz(__b))); if (__n == __dn) return __first + __n; __n -= __dn; @@ -219,7 +220,7 @@ __find_bool_false(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_type { __storage_type __b = ~*__first.__seg_; if (__b) - return _It(__first.__seg_, static_cast(_VSTD::__ctz(__b))); + return _It(__first.__seg_, static_cast(_VSTD::__libcpp_ctz(__b))); } // do last partial word if (__n > 0) @@ -227,7 +228,7 @@ __find_bool_false(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_type __storage_type __m = ~__storage_type(0) >> (__bits_per_word - __n); __storage_type __b = ~*__first.__seg_ & __m; if (__b) - return _It(__first.__seg_, static_cast(_VSTD::__ctz(__b))); + return _It(__first.__seg_, static_cast(_VSTD::__libcpp_ctz(__b))); } return _It(__first.__seg_, static_cast(__n)); } @@ -238,8 +239,8 @@ __bit_iterator<_Cp, _IsConst> find(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsConst> __last, const _Tp& __value_) { if (static_cast(__value_)) - return __find_bool_true(__first, static_cast(__last - __first)); - return __find_bool_false(__first, static_cast(__last - __first)); + return _VSTD::__find_bool_true(__first, static_cast(__last - __first)); + return _VSTD::__find_bool_false(__first, static_cast(__last - __first)); } // count @@ -251,7 +252,7 @@ __count_bool_true(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_type typedef __bit_iterator<_Cp, _IsConst> _It; typedef typename _It::__storage_type __storage_type; typedef typename _It::difference_type difference_type; - static const unsigned __bits_per_word = _It::__bits_per_word; + const int __bits_per_word = _It::__bits_per_word; difference_type __r = 0; // do first partial word if (__first.__ctz_ != 0) @@ -259,18 +260,18 @@ __count_bool_true(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_type __storage_type __clz_f = static_cast<__storage_type>(__bits_per_word - __first.__ctz_); __storage_type __dn = _VSTD::min(__clz_f, __n); __storage_type __m = (~__storage_type(0) << __first.__ctz_) & (~__storage_type(0) >> (__clz_f - __dn)); - __r = _VSTD::__pop_count(*__first.__seg_ & __m); + __r = _VSTD::__libcpp_popcount(*__first.__seg_ & __m); __n -= __dn; ++__first.__seg_; } // do middle whole words for (; __n >= __bits_per_word; ++__first.__seg_, __n -= __bits_per_word) - __r += _VSTD::__pop_count(*__first.__seg_); + __r += _VSTD::__libcpp_popcount(*__first.__seg_); // do last partial word if (__n > 0) { __storage_type __m = ~__storage_type(0) >> (__bits_per_word - __n); - __r += _VSTD::__pop_count(*__first.__seg_ & __m); + __r += _VSTD::__libcpp_popcount(*__first.__seg_ & __m); } return __r; } @@ -282,7 +283,7 @@ __count_bool_false(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_typ typedef __bit_iterator<_Cp, _IsConst> _It; typedef typename _It::__storage_type __storage_type; typedef typename _It::difference_type difference_type; - static const unsigned __bits_per_word = _It::__bits_per_word; + const int __bits_per_word = _It::__bits_per_word; difference_type __r = 0; // do first partial word if (__first.__ctz_ != 0) @@ -290,18 +291,18 @@ __count_bool_false(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_typ __storage_type __clz_f = static_cast<__storage_type>(__bits_per_word - __first.__ctz_); __storage_type __dn = _VSTD::min(__clz_f, __n); __storage_type __m = (~__storage_type(0) << __first.__ctz_) & (~__storage_type(0) >> (__clz_f - __dn)); - __r = _VSTD::__pop_count(~*__first.__seg_ & __m); + __r = _VSTD::__libcpp_popcount(~*__first.__seg_ & __m); __n -= __dn; ++__first.__seg_; } // do middle whole words for (; __n >= __bits_per_word; ++__first.__seg_, __n -= __bits_per_word) - __r += _VSTD::__pop_count(~*__first.__seg_); + __r += _VSTD::__libcpp_popcount(~*__first.__seg_); // do last partial word if (__n > 0) { __storage_type __m = ~__storage_type(0) >> (__bits_per_word - __n); - __r += _VSTD::__pop_count(~*__first.__seg_ & __m); + __r += _VSTD::__libcpp_popcount(~*__first.__seg_ & __m); } return __r; } @@ -312,8 +313,8 @@ typename __bit_iterator<_Cp, _IsConst>::difference_type count(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsConst> __last, const _Tp& __value_) { if (static_cast(__value_)) - return __count_bool_true(__first, static_cast(__last - __first)); - return __count_bool_false(__first, static_cast(__last - __first)); + return _VSTD::__count_bool_true(__first, static_cast(__last - __first)); + return _VSTD::__count_bool_false(__first, static_cast(__last - __first)); } // fill_n @@ -324,7 +325,7 @@ __fill_n_false(__bit_iterator<_Cp, false> __first, typename _Cp::size_type __n) { typedef __bit_iterator<_Cp, false> _It; typedef typename _It::__storage_type __storage_type; - static const unsigned __bits_per_word = _It::__bits_per_word; + const int __bits_per_word = _It::__bits_per_word; // do first partial word if (__first.__ctz_ != 0) { @@ -337,7 +338,7 @@ __fill_n_false(__bit_iterator<_Cp, false> __first, typename _Cp::size_type __n) } // do middle whole words __storage_type __nw = __n / __bits_per_word; - _VSTD::memset(_VSTD::__to_raw_pointer(__first.__seg_), 0, __nw * sizeof(__storage_type)); + _VSTD::memset(_VSTD::__to_address(__first.__seg_), 0, __nw * sizeof(__storage_type)); __n -= __nw * __bits_per_word; // do last partial word if (__n > 0) @@ -354,7 +355,7 @@ __fill_n_true(__bit_iterator<_Cp, false> __first, typename _Cp::size_type __n) { typedef __bit_iterator<_Cp, false> _It; typedef typename _It::__storage_type __storage_type; - static const unsigned __bits_per_word = _It::__bits_per_word; + const int __bits_per_word = _It::__bits_per_word; // do first partial word if (__first.__ctz_ != 0) { @@ -367,7 +368,7 @@ __fill_n_true(__bit_iterator<_Cp, false> __first, typename _Cp::size_type __n) } // do middle whole words __storage_type __nw = __n / __bits_per_word; - _VSTD::memset(_VSTD::__to_raw_pointer(__first.__seg_), -1, __nw * sizeof(__storage_type)); + _VSTD::memset(_VSTD::__to_address(__first.__seg_), -1, __nw * sizeof(__storage_type)); __n -= __nw * __bits_per_word; // do last partial word if (__n > 0) @@ -386,9 +387,9 @@ fill_n(__bit_iterator<_Cp, false> __first, typename _Cp::size_type __n, bool __v if (__n > 0) { if (__value_) - __fill_n_true(__first, __n); + _VSTD::__fill_n_true(__first, __n); else - __fill_n_false(__first, __n); + _VSTD::__fill_n_false(__first, __n); } } @@ -412,7 +413,7 @@ __copy_aligned(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsCon typedef __bit_iterator<_Cp, _IsConst> _In; typedef typename _In::difference_type difference_type; typedef typename _In::__storage_type __storage_type; - static const unsigned __bits_per_word = _In::__bits_per_word; + const int __bits_per_word = _In::__bits_per_word; difference_type __n = __last - __first; if (__n > 0) { @@ -434,8 +435,8 @@ __copy_aligned(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsCon // __first.__ctz_ == 0; // do middle words __storage_type __nw = __n / __bits_per_word; - _VSTD::memmove(_VSTD::__to_raw_pointer(__result.__seg_), - _VSTD::__to_raw_pointer(__first.__seg_), + _VSTD::memmove(_VSTD::__to_address(__result.__seg_), + _VSTD::__to_address(__first.__seg_), __nw * sizeof(__storage_type)); __n -= __nw * __bits_per_word; __result.__seg_ += __nw; @@ -461,7 +462,7 @@ __copy_unaligned(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsC typedef __bit_iterator<_Cp, _IsConst> _In; typedef typename _In::difference_type difference_type; typedef typename _In::__storage_type __storage_type; - static const unsigned __bits_per_word = _In::__bits_per_word; + static const int __bits_per_word = _In::__bits_per_word; difference_type __n = __last - __first; if (__n > 0) { @@ -537,8 +538,8 @@ __bit_iterator<_Cp, false> copy(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsConst> __last, __bit_iterator<_Cp, false> __result) { if (__first.__ctz_ == __result.__ctz_) - return __copy_aligned(__first, __last, __result); - return __copy_unaligned(__first, __last, __result); + return _VSTD::__copy_aligned(__first, __last, __result); + return _VSTD::__copy_unaligned(__first, __last, __result); } // copy_backward @@ -551,7 +552,7 @@ __copy_backward_aligned(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_C typedef __bit_iterator<_Cp, _IsConst> _In; typedef typename _In::difference_type difference_type; typedef typename _In::__storage_type __storage_type; - static const unsigned __bits_per_word = _In::__bits_per_word; + const int __bits_per_word = _In::__bits_per_word; difference_type __n = __last - __first; if (__n > 0) { @@ -575,8 +576,8 @@ __copy_backward_aligned(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_C __storage_type __nw = __n / __bits_per_word; __result.__seg_ -= __nw; __last.__seg_ -= __nw; - _VSTD::memmove(_VSTD::__to_raw_pointer(__result.__seg_), - _VSTD::__to_raw_pointer(__last.__seg_), + _VSTD::memmove(_VSTD::__to_address(__result.__seg_), + _VSTD::__to_address(__last.__seg_), __nw * sizeof(__storage_type)); __n -= __nw * __bits_per_word; // do last word @@ -600,7 +601,7 @@ __copy_backward_unaligned(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator< typedef __bit_iterator<_Cp, _IsConst> _In; typedef typename _In::difference_type difference_type; typedef typename _In::__storage_type __storage_type; - static const unsigned __bits_per_word = _In::__bits_per_word; + const int __bits_per_word = _In::__bits_per_word; difference_type __n = __last - __first; if (__n > 0) { @@ -684,8 +685,8 @@ __bit_iterator<_Cp, false> copy_backward(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsConst> __last, __bit_iterator<_Cp, false> __result) { if (__last.__ctz_ == __result.__ctz_) - return __copy_backward_aligned(__first, __last, __result); - return __copy_backward_unaligned(__first, __last, __result); + return _VSTD::__copy_backward_aligned(__first, __last, __result); + return _VSTD::__copy_backward_unaligned(__first, __last, __result); } // move @@ -718,7 +719,7 @@ __swap_ranges_aligned(__bit_iterator<__C1, false> __first, __bit_iterator<__C1, typedef __bit_iterator<__C1, false> _I1; typedef typename _I1::difference_type difference_type; typedef typename _I1::__storage_type __storage_type; - static const unsigned __bits_per_word = _I1::__bits_per_word; + const int __bits_per_word = _I1::__bits_per_word; difference_type __n = __last - __first; if (__n > 0) { @@ -768,7 +769,7 @@ __swap_ranges_unaligned(__bit_iterator<__C1, false> __first, __bit_iterator<__C1 typedef __bit_iterator<__C1, false> _I1; typedef typename _I1::difference_type difference_type; typedef typename _I1::__storage_type __storage_type; - static const unsigned __bits_per_word = _I1::__bits_per_word; + const int __bits_per_word = _I1::__bits_per_word; difference_type __n = __last - __first; if (__n > 0) { @@ -867,8 +868,8 @@ swap_ranges(__bit_iterator<__C1, false> __first1, __bit_iterator<__C1, false> __ __bit_iterator<__C2, false> __first2) { if (__first1.__ctz_ == __first2.__ctz_) - return __swap_ranges_aligned(__first1, __last1, __first2); - return __swap_ranges_unaligned(__first1, __last1, __first2); + return _VSTD::__swap_ranges_aligned(__first1, __last1, __first2); + return _VSTD::__swap_ranges_unaligned(__first1, __last1, __first2); } // rotate @@ -959,7 +960,7 @@ __equal_unaligned(__bit_iterator<_Cp, _IC1> __first1, __bit_iterator<_Cp, _IC1> typedef __bit_iterator<_Cp, _IC1> _It; typedef typename _It::difference_type difference_type; typedef typename _It::__storage_type __storage_type; - static const unsigned __bits_per_word = _It::__bits_per_word; + static const int __bits_per_word = _It::__bits_per_word; difference_type __n = __last1 - __first1; if (__n > 0) { @@ -1041,7 +1042,7 @@ __equal_aligned(__bit_iterator<_Cp, _IC1> __first1, __bit_iterator<_Cp, _IC1> __ typedef __bit_iterator<_Cp, _IC1> _It; typedef typename _It::difference_type difference_type; typedef typename _It::__storage_type __storage_type; - static const unsigned __bits_per_word = _It::__bits_per_word; + static const int __bits_per_word = _It::__bits_per_word; difference_type __n = __last1 - __first1; if (__n > 0) { @@ -1082,8 +1083,8 @@ bool equal(__bit_iterator<_Cp, _IC1> __first1, __bit_iterator<_Cp, _IC1> __last1, __bit_iterator<_Cp, _IC2> __first2) { if (__first1.__ctz_ == __first2.__ctz_) - return __equal_aligned(__first1, __last1, __first2); - return __equal_unaligned(__first1, __last1, __first2); + return _VSTD::__equal_aligned(__first1, __last1, __first2); + return _VSTD::__equal_unaligned(__first1, __last1, __first2); } template & __it) _NOEXCEPT : __seg_(__it.__seg_), __ctz_(__it.__ctz_) {} + // When _IsConst=false, we have a user-provided copy constructor, + // so we must also provide a copy assignment operator because + // the implicit generation of a defaulted one is deprecated. + // When _IsConst=true, the assignment operators are + // implicitly generated and trivial. + _LIBCPP_INLINE_VISIBILITY + __bit_iterator& operator=(const _If<_IsConst, struct __private_nat, __bit_iterator>& __it) { + __seg_ = __it.__seg_; + __ctz_ = __it.__ctz_; + return *this; + } + _LIBCPP_INLINE_VISIBILITY reference operator*() const _NOEXCEPT {return reference(__seg_, __storage_type(1) << __ctz_);} @@ -1221,11 +1239,8 @@ private: __bit_iterator(__storage_pointer __s, unsigned __ctz) _NOEXCEPT : __seg_(__s), __ctz_(__ctz) {} -#if defined(__clang__) || defined(__IBMCPP__) || defined(_LIBCPP_MSVC) friend typename _Cp::__self; -#else - friend class _Cp::__self; -#endif + friend class __bit_reference<_Cp>; friend class __bit_const_reference<_Cp>; friend class __bit_iterator<_Cp, true>; @@ -1283,4 +1298,6 @@ private: _LIBCPP_END_NAMESPACE_STD +_LIBCPP_POP_MACROS + #endif // _LIBCPP___BIT_REFERENCE diff --git a/sdk/tlibcxx/include/__bits b/sdk/tlibcxx/include/__bits new file mode 100644 index 00000000..0d321da9 --- /dev/null +++ b/sdk/tlibcxx/include/__bits @@ -0,0 +1,146 @@ +// -*- C++ -*- +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___BITS +#define _LIBCPP___BITS + +#include <__config> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +#pragma GCC system_header +#endif + +_LIBCPP_PUSH_MACROS +#include <__undef_macros> + + +_LIBCPP_BEGIN_NAMESPACE_STD + +#ifndef _LIBCPP_COMPILER_MSVC + +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR +int __libcpp_ctz(unsigned __x) _NOEXCEPT { return __builtin_ctz(__x); } + +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR +int __libcpp_ctz(unsigned long __x) _NOEXCEPT { return __builtin_ctzl(__x); } + +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR +int __libcpp_ctz(unsigned long long __x) _NOEXCEPT { return __builtin_ctzll(__x); } + + +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR +int __libcpp_clz(unsigned __x) _NOEXCEPT { return __builtin_clz(__x); } + +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR +int __libcpp_clz(unsigned long __x) _NOEXCEPT { return __builtin_clzl(__x); } + +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR +int __libcpp_clz(unsigned long long __x) _NOEXCEPT { return __builtin_clzll(__x); } + + +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR +int __libcpp_popcount(unsigned __x) _NOEXCEPT { return __builtin_popcount(__x); } + +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR +int __libcpp_popcount(unsigned long __x) _NOEXCEPT { return __builtin_popcountl(__x); } + +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR +int __libcpp_popcount(unsigned long long __x) _NOEXCEPT { return __builtin_popcountll(__x); } + +#else // _LIBCPP_COMPILER_MSVC + +// Precondition: __x != 0 +inline _LIBCPP_INLINE_VISIBILITY +int __libcpp_ctz(unsigned __x) { + static_assert(sizeof(unsigned) == sizeof(unsigned long), ""); + static_assert(sizeof(unsigned long) == 4, ""); + unsigned long __where; + if (_BitScanForward(&__where, __x)) + return static_cast(__where); + return 32; +} + +inline _LIBCPP_INLINE_VISIBILITY +int __libcpp_ctz(unsigned long __x) { + static_assert(sizeof(unsigned long) == sizeof(unsigned), ""); + return __ctz(static_cast(__x)); +} + +inline _LIBCPP_INLINE_VISIBILITY +int __libcpp_ctz(unsigned long long __x) { + unsigned long __where; +#if defined(_LIBCPP_HAS_BITSCAN64) + (defined(_M_AMD64) || defined(__x86_64__)) + if (_BitScanForward64(&__where, __x)) + return static_cast(__where); +#else + // Win32 doesn't have _BitScanForward64 so emulate it with two 32 bit calls. + if (_BitScanForward(&__where, static_cast(__x))) + return static_cast(__where); + if (_BitScanForward(&__where, static_cast(__x >> 32))) + return static_cast(__where + 32); +#endif + return 64; +} + +// Precondition: __x != 0 +inline _LIBCPP_INLINE_VISIBILITY +int __libcpp_clz(unsigned __x) { + static_assert(sizeof(unsigned) == sizeof(unsigned long), ""); + static_assert(sizeof(unsigned long) == 4, ""); + unsigned long __where; + if (_BitScanReverse(&__where, __x)) + return static_cast(31 - __where); + return 32; // Undefined Behavior. +} + +inline _LIBCPP_INLINE_VISIBILITY +int __libcpp_clz(unsigned long __x) { + static_assert(sizeof(unsigned) == sizeof(unsigned long), ""); + return __libcpp_clz(static_cast(__x)); +} + +inline _LIBCPP_INLINE_VISIBILITY +int __libcpp_clz(unsigned long long __x) { + unsigned long __where; +#if defined(_LIBCPP_HAS_BITSCAN64) + if (_BitScanReverse64(&__where, __x)) + return static_cast(63 - __where); +#else + // Win32 doesn't have _BitScanReverse64 so emulate it with two 32 bit calls. + if (_BitScanReverse(&__where, static_cast(__x >> 32))) + return static_cast(63 - (__where + 32)); + if (_BitScanReverse(&__where, static_cast(__x))) + return static_cast(63 - __where); +#endif + return 64; // Undefined Behavior. +} + +inline _LIBCPP_INLINE_VISIBILITY int __libcpp_popcount(unsigned __x) { + static_assert(sizeof(unsigned) == 4, ""); + return __popcnt(__x); +} + +inline _LIBCPP_INLINE_VISIBILITY int __libcpp_popcount(unsigned long __x) { + static_assert(sizeof(unsigned long) == 4, ""); + return __popcnt(__x); +} + +inline _LIBCPP_INLINE_VISIBILITY int __libcpp_popcount(unsigned long long __x) { + static_assert(sizeof(unsigned long long) == 8, ""); + return __popcnt64(__x); +} + +#endif // _LIBCPP_COMPILER_MSVC + +_LIBCPP_END_NAMESPACE_STD + +_LIBCPP_POP_MACROS + +#endif // _LIBCPP__BITS diff --git a/sdk/tlibcxx/include/__bsd_locale_defaults.h b/sdk/tlibcxx/include/__bsd_locale_defaults.h index f315ca29..2ace2a21 100644 --- a/sdk/tlibcxx/include/__bsd_locale_defaults.h +++ b/sdk/tlibcxx/include/__bsd_locale_defaults.h @@ -1,10 +1,9 @@ // -*- C++ -*- //===---------------------- __bsd_locale_defaults.h -----------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // The BSDs have lots of *_l functions. We don't want to define those symbols @@ -15,6 +14,10 @@ #ifndef _LIBCPP_BSD_LOCALE_DEFAULTS_H #define _LIBCPP_BSD_LOCALE_DEFAULTS_H +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +#pragma GCC system_header +#endif + #define __libcpp_mb_cur_max_l(loc) MB_CUR_MAX_L(loc) #define __libcpp_btowc_l(ch, loc) btowc_l(ch, loc) #define __libcpp_wctob_l(wch, loc) wctob_l(wch, loc) diff --git a/sdk/tlibcxx/include/__bsd_locale_fallbacks.h b/sdk/tlibcxx/include/__bsd_locale_fallbacks.h index 1cbd0f28..c9a4ee4f 100644 --- a/sdk/tlibcxx/include/__bsd_locale_fallbacks.h +++ b/sdk/tlibcxx/include/__bsd_locale_fallbacks.h @@ -1,10 +1,9 @@ // -*- C++ -*- //===---------------------- __bsd_locale_fallbacks.h ----------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // The BSDs have lots of *_l functions. This file provides reimplementations @@ -15,92 +14,94 @@ #define _LIBCPP_BSD_LOCALE_FALLBACKS_DEFAULTS_H #include +#include #include +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +#pragma GCC system_header +#endif + _LIBCPP_BEGIN_NAMESPACE_STD -typedef _VSTD::remove_pointer::type __use_locale_struct; -typedef _VSTD::unique_ptr<__use_locale_struct, decltype(&uselocale)> __locale_raii; - -inline _LIBCPP_ALWAYS_INLINE -wint_t __libcpp_btowc_l(int __c, locale_t __l) -{ - __locale_raii __current( uselocale(__l), uselocale ); - return btowc(__c); -} - -inline _LIBCPP_ALWAYS_INLINE -int __libcpp_wctob_l(wint_t __c, locale_t __l) -{ - __locale_raii __current( uselocale(__l), uselocale ); - return wctob(__c); -} - -inline _LIBCPP_ALWAYS_INLINE +inline _LIBCPP_INLINE_VISIBILITY decltype(MB_CUR_MAX) __libcpp_mb_cur_max_l(locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return MB_CUR_MAX; } -inline _LIBCPP_ALWAYS_INLINE +inline _LIBCPP_INLINE_VISIBILITY +wint_t __libcpp_btowc_l(int __c, locale_t __l) +{ + __libcpp_locale_guard __current(__l); + return btowc(__c); +} + +inline _LIBCPP_INLINE_VISIBILITY +int __libcpp_wctob_l(wint_t __c, locale_t __l) +{ + __libcpp_locale_guard __current(__l); + return wctob(__c); +} + +inline _LIBCPP_INLINE_VISIBILITY size_t __libcpp_wcsnrtombs_l(char *__dest, const wchar_t **__src, size_t __nwc, size_t __len, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return wcsnrtombs(__dest, __src, __nwc, __len, __ps); } -inline _LIBCPP_ALWAYS_INLINE +inline _LIBCPP_INLINE_VISIBILITY size_t __libcpp_wcrtomb_l(char *__s, wchar_t __wc, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return wcrtomb(__s, __wc, __ps); } -inline _LIBCPP_ALWAYS_INLINE +inline _LIBCPP_INLINE_VISIBILITY size_t __libcpp_mbsnrtowcs_l(wchar_t * __dest, const char **__src, size_t __nms, size_t __len, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return mbsnrtowcs(__dest, __src, __nms, __len, __ps); } -inline _LIBCPP_ALWAYS_INLINE +inline _LIBCPP_INLINE_VISIBILITY size_t __libcpp_mbrtowc_l(wchar_t *__pwc, const char *__s, size_t __n, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return mbrtowc(__pwc, __s, __n, __ps); } -inline _LIBCPP_ALWAYS_INLINE +inline _LIBCPP_INLINE_VISIBILITY int __libcpp_mbtowc_l(wchar_t *__pwc, const char *__pmb, size_t __max, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return mbtowc(__pwc, __pmb, __max); } -inline _LIBCPP_ALWAYS_INLINE +inline _LIBCPP_INLINE_VISIBILITY size_t __libcpp_mbrlen_l(const char *__s, size_t __n, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return mbrlen(__s, __n, __ps); } -inline _LIBCPP_ALWAYS_INLINE +inline _LIBCPP_INLINE_VISIBILITY size_t __libcpp_mbsrtowcs_l(wchar_t *__dest, const char **__src, size_t __len, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return mbsrtowcs(__dest, __src, __len, __ps); } #if !defined(_LIBCPP_SGX_CONFIG) -inline _LIBCPP_ALWAYS_INLINE +inline _LIBCPP_INLINE_VISIBILITY lconv *__libcpp_localeconv_l(locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return localeconv(); } @@ -108,7 +109,7 @@ inline int __libcpp_snprintf_l(char *__s, size_t __n, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); int __res = vsnprintf(__s, __n, __format, __va); va_end(__va); return __res; @@ -118,7 +119,7 @@ inline int __libcpp_asprintf_l(char **__s, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); int __res = vasprintf(__s, __format, __va); va_end(__va); return __res; @@ -128,7 +129,7 @@ inline int __libcpp_sscanf_l(const char *__s, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); int __res = vsscanf(__s, __format, __va); va_end(__va); return __res; diff --git a/sdk/tlibcxx/include/__config b/sdk/tlibcxx/include/__config index e5d7a2de..7835a963 100644 --- a/sdk/tlibcxx/include/__config +++ b/sdk/tlibcxx/include/__config @@ -1,10 +1,9 @@ // -*- C++ -*- //===--------------------------- __config ---------------------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// @@ -12,7 +11,9 @@ #define _LIBCPP_CONFIG #if defined(_MSC_VER) && !defined(__clang__) -#define _LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER +# if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# define _LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER +# endif #endif #ifndef _LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER @@ -22,371 +23,435 @@ #ifdef __cplusplus #ifdef __GNUC__ -#define _GNUC_VER (__GNUC__ * 100 + __GNUC_MINOR__) +# define _GNUC_VER (__GNUC__ * 100 + __GNUC_MINOR__) +// The _GNUC_VER_NEW macro better represents the new GCC versioning scheme +// introduced in GCC 5.0. +# define _GNUC_VER_NEW (_GNUC_VER * 10 + __GNUC_PATCHLEVEL__) #else -#define _GNUC_VER 0 +# define _GNUC_VER 0 +# define _GNUC_VER_NEW 0 #endif -#define _LIBCPP_VERSION 3900 +#define _LIBCPP_VERSION 12000 #ifndef _LIBCPP_ABI_VERSION -#define _LIBCPP_ABI_VERSION 1 +# define _LIBCPP_ABI_VERSION 1 +#endif + +#if __STDC_HOSTED__ == 0 +# define _LIBCPP_FREESTANDING +#endif + +#ifndef _LIBCPP_STD_VER +# if __cplusplus <= 201103L +# define _LIBCPP_STD_VER 11 +# elif __cplusplus <= 201402L +# define _LIBCPP_STD_VER 14 +# elif __cplusplus <= 201703L +# define _LIBCPP_STD_VER 17 +# elif __cplusplus <= 202002L +# define _LIBCPP_STD_VER 20 +# else +# define _LIBCPP_STD_VER 21 // current year, or date of c++2b ratification +# endif +#endif // _LIBCPP_STD_VER + +#if defined(__ELF__) +# define _LIBCPP_OBJECT_FORMAT_ELF 1 +#elif defined(__MACH__) +# define _LIBCPP_OBJECT_FORMAT_MACHO 1 +#elif defined(_WIN32) +# define _LIBCPP_OBJECT_FORMAT_COFF 1 +#elif defined(__wasm__) +# define _LIBCPP_OBJECT_FORMAT_WASM 1 +#else + // ... add new file formats here ... #endif #if defined(_LIBCPP_ABI_UNSTABLE) || _LIBCPP_ABI_VERSION >= 2 -// Change short string represention so that string data starts at offset 0, +// Change short string representation so that string data starts at offset 0, // improving its alignment in some cases. -#define _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT +# define _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT // Fix deque iterator type in order to support incomplete types. -#define _LIBCPP_ABI_INCOMPLETE_TYPES_IN_DEQUE -// Fix undefined behavior in how std::list stores it's linked nodes. -#define _LIBCPP_ABI_LIST_REMOVE_NODE_POINTER_UB +# define _LIBCPP_ABI_INCOMPLETE_TYPES_IN_DEQUE +// Fix undefined behavior in how std::list stores its linked nodes. +# define _LIBCPP_ABI_LIST_REMOVE_NODE_POINTER_UB // Fix undefined behavior in how __tree stores its end and parent nodes. -#define _LIBCPP_ABI_TREE_REMOVE_NODE_POINTER_UB -#define _LIBCPP_ABI_FORWARD_LIST_REMOVE_NODE_POINTER_UB -#define _LIBCPP_ABI_FIX_UNORDERED_CONTAINER_SIZE_TYPE -#define _LIBCPP_ABI_VARIADIC_LOCK_GUARD +# define _LIBCPP_ABI_TREE_REMOVE_NODE_POINTER_UB +// Fix undefined behavior in how __hash_table stores its pointer types. +# define _LIBCPP_ABI_FIX_UNORDERED_NODE_POINTER_UB +# define _LIBCPP_ABI_FORWARD_LIST_REMOVE_NODE_POINTER_UB +# define _LIBCPP_ABI_FIX_UNORDERED_CONTAINER_SIZE_TYPE +// Don't use a nullptr_t simulation type in C++03 instead using C++11 nullptr +// provided under the alternate keyword __nullptr, which changes the mangling +// of nullptr_t. This option is ABI incompatible with GCC in C++03 mode. +# define _LIBCPP_ABI_ALWAYS_USE_CXX11_NULLPTR +// Define the `pointer_safety` enum as a C++11 strongly typed enumeration +// instead of as a class simulating an enum. If this option is enabled +// `pointer_safety` and `get_pointer_safety()` will no longer be available +// in C++03. +# define _LIBCPP_ABI_POINTER_SAFETY_ENUM_TYPE +// Define a key function for `bad_function_call` in the library, to centralize +// its vtable and typeinfo to libc++ rather than having all other libraries +// using that class define their own copies. +# define _LIBCPP_ABI_BAD_FUNCTION_CALL_KEY_FUNCTION +// Enable optimized version of __do_get_(un)signed which avoids redundant copies. +# define _LIBCPP_ABI_OPTIMIZED_LOCALE_NUM_GET +// Use the smallest possible integer type to represent the index of the variant. +// Previously libc++ used "unsigned int" exclusively. +# define _LIBCPP_ABI_VARIANT_INDEX_TYPE_OPTIMIZATION +// Unstable attempt to provide a more optimized std::function +# define _LIBCPP_ABI_OPTIMIZED_FUNCTION +// All the regex constants must be distinct and nonzero. +# define _LIBCPP_ABI_REGEX_CONSTANTS_NONZERO +// Re-worked external template instantiations for std::string with a focus on +// performance and fast-path inlining. +# define _LIBCPP_ABI_STRING_OPTIMIZED_EXTERNAL_INSTANTIATION +// Enable clang::trivial_abi on std::unique_ptr. +# define _LIBCPP_ABI_ENABLE_UNIQUE_PTR_TRIVIAL_ABI +// Enable clang::trivial_abi on std::shared_ptr and std::weak_ptr +# define _LIBCPP_ABI_ENABLE_SHARED_PTR_TRIVIAL_ABI #elif _LIBCPP_ABI_VERSION == 1 +# if !defined(_LIBCPP_OBJECT_FORMAT_COFF) +// Enable compiling copies of now inline methods into the dylib to support +// applications compiled against older libraries. This is unnecessary with +// COFF dllexport semantics, since dllexport forces a non-inline definition +// of inline functions to be emitted anyway. Our own non-inline copy would +// conflict with the dllexport-emitted copy, so we disable it. +# define _LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS +# endif // Feature macros for disabling pre ABI v1 features. All of these options // are deprecated. -#if defined(__FreeBSD__) -#define _LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR -#endif +# if defined(__FreeBSD__) +# define _LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR +# endif #endif -#ifdef _LIBCPP_TRIVIAL_PAIR_COPY_CTOR -#error "_LIBCPP_TRIVIAL_PAIR_COPY_CTOR" is no longer supported. \ - use _LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR instead +#if defined(_LIBCPP_BUILDING_LIBRARY) || defined(_LIBCPP_ABI_UNSTABLE) || _LIBCPP_ABI_VERSION >= 2 +// Enable additional explicit instantiations of iostreams components. This +// reduces the number of weak definitions generated in programs that use +// iostreams by providing a single strong definition in the shared library. +# define _LIBCPP_ABI_ENABLE_ADDITIONAL_IOSTREAM_EXPLICIT_INSTANTIATIONS_1 #endif #define _LIBCPP_CONCAT1(_LIBCPP_X,_LIBCPP_Y) _LIBCPP_X##_LIBCPP_Y #define _LIBCPP_CONCAT(_LIBCPP_X,_LIBCPP_Y) _LIBCPP_CONCAT1(_LIBCPP_X,_LIBCPP_Y) -#define _LIBCPP_NAMESPACE _LIBCPP_CONCAT(__,_LIBCPP_ABI_VERSION) +#ifndef _LIBCPP_ABI_NAMESPACE +# define _LIBCPP_ABI_NAMESPACE _LIBCPP_CONCAT(__,_LIBCPP_ABI_VERSION) +#endif +#if __cplusplus < 201103L +#define _LIBCPP_CXX03_LANG +#endif #ifndef __has_attribute #define __has_attribute(__x) 0 #endif + #ifndef __has_builtin #define __has_builtin(__x) 0 #endif + #ifndef __has_extension #define __has_extension(__x) 0 #endif + #ifndef __has_feature #define __has_feature(__x) 0 #endif + +#ifndef __has_cpp_attribute +#define __has_cpp_attribute(__x) 0 +#endif + // '__is_identifier' returns '0' if '__x' is a reserved identifier provided by // the compiler and '1' otherwise. #ifndef __is_identifier #define __is_identifier(__x) 1 #endif - -#ifdef __LITTLE_ENDIAN__ -#if __LITTLE_ENDIAN__ -#define _LIBCPP_LITTLE_ENDIAN 1 -#define _LIBCPP_BIG_ENDIAN 0 -#endif // __LITTLE_ENDIAN__ -#endif // __LITTLE_ENDIAN__ - -#ifdef __BIG_ENDIAN__ -#if __BIG_ENDIAN__ -#define _LIBCPP_LITTLE_ENDIAN 0 -#define _LIBCPP_BIG_ENDIAN 1 -#endif // __BIG_ENDIAN__ -#endif // __BIG_ENDIAN__ - -#ifdef __BYTE_ORDER__ -#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -#define _LIBCPP_LITTLE_ENDIAN 1 -#define _LIBCPP_BIG_ENDIAN 0 -#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -#define _LIBCPP_LITTLE_ENDIAN 0 -#define _LIBCPP_BIG_ENDIAN 1 -#endif // __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -#endif // __BYTE_ORDER__ - -#ifdef __FreeBSD__ -# include -# if _BYTE_ORDER == _LITTLE_ENDIAN -# define _LIBCPP_LITTLE_ENDIAN 1 -# define _LIBCPP_BIG_ENDIAN 0 -# else // _BYTE_ORDER == _LITTLE_ENDIAN -# define _LIBCPP_LITTLE_ENDIAN 0 -# define _LIBCPP_BIG_ENDIAN 1 -# endif // _BYTE_ORDER == _LITTLE_ENDIAN -# ifndef __LONG_LONG_SUPPORTED -# define _LIBCPP_HAS_NO_LONG_LONG -# endif // __LONG_LONG_SUPPORTED -#endif // __FreeBSD__ - -#ifdef __NetBSD__ -# include -# if _BYTE_ORDER == _LITTLE_ENDIAN -# define _LIBCPP_LITTLE_ENDIAN 1 -# define _LIBCPP_BIG_ENDIAN 0 -# else // _BYTE_ORDER == _LITTLE_ENDIAN -# define _LIBCPP_LITTLE_ENDIAN 0 -# define _LIBCPP_BIG_ENDIAN 1 -# endif // _BYTE_ORDER == _LITTLE_ENDIAN -# define _LIBCPP_HAS_QUICK_EXIT -#endif // __NetBSD__ - -#ifdef _WIN32 -# define _LIBCPP_LITTLE_ENDIAN 1 -# define _LIBCPP_BIG_ENDIAN 0 -// Compiler intrinsics (MSVC) -#if defined(_MSC_VER) && _MSC_VER >= 1400 -# define _LIBCPP_HAS_IS_BASE_OF -# endif -# if defined(_MSC_VER) && !defined(__clang__) -# define _LIBCPP_MSVC // Using Microsoft Visual C++ compiler -# define _LIBCPP_TOSTRING2(x) #x -# define _LIBCPP_TOSTRING(x) _LIBCPP_TOSTRING2(x) -# define _LIBCPP_WARNING(x) __pragma(message(__FILE__ "(" _LIBCPP_TOSTRING(__LINE__) ") : warning note: " x)) -# endif -# // If mingw not explicitly detected, assume using MS C runtime only. -# ifndef __MINGW32__ -# define _LIBCPP_MSVCRT // Using Microsoft's C Runtime library -# endif -#endif // _WIN32 - -#ifdef __sun__ -# include -# ifdef _LITTLE_ENDIAN -# define _LIBCPP_LITTLE_ENDIAN 1 -# define _LIBCPP_BIG_ENDIAN 0 -# else -# define _LIBCPP_LITTLE_ENDIAN 0 -# define _LIBCPP_BIG_ENDIAN 1 -# endif -#endif // __sun__ - -#if defined(__CloudABI__) - // Certain architectures provide arc4random(). Prefer using - // arc4random() over /dev/{u,}random to make it possible to obtain - // random data even when using sandboxing mechanisms such as chroots, - // Capsicum, etc. -# define _LIBCPP_USING_ARC4_RANDOM -#elif defined(__native_client__) - // NaCl's sandbox (which PNaCl also runs in) doesn't allow filesystem access, - // including accesses to the special files under /dev. C++11's - // std::random_device is instead exposed through a NaCl syscall. -# define _LIBCPP_USING_NACL_RANDOM -#elif defined(_WIN32) -# define _LIBCPP_USING_WIN32_RANDOM -#else -# define _LIBCPP_USING_DEV_RANDOM +#ifndef __has_declspec_attribute +#define __has_declspec_attribute(__x) 0 #endif -#if !defined(_LIBCPP_LITTLE_ENDIAN) || !defined(_LIBCPP_BIG_ENDIAN) -# include -# if __BYTE_ORDER == __LITTLE_ENDIAN -# define _LIBCPP_LITTLE_ENDIAN 1 -# define _LIBCPP_BIG_ENDIAN 0 -# elif __BYTE_ORDER == __BIG_ENDIAN -# define _LIBCPP_LITTLE_ENDIAN 0 -# define _LIBCPP_BIG_ENDIAN 1 -# else // __BYTE_ORDER == __BIG_ENDIAN -# error unable to determine endian -# endif -#endif // !defined(_LIBCPP_LITTLE_ENDIAN) || !defined(_LIBCPP_BIG_ENDIAN) +#define __has_keyword(__x) !(__is_identifier(__x)) -#if __has_attribute(__no_sanitize__) -#define _LIBCPP_NO_CFI __attribute__((__no_sanitize__("cfi"))) -#else -#define _LIBCPP_NO_CFI -#endif - -#ifdef _WIN32 - -// only really useful for a DLL -#ifdef _LIBCPP_DLL // this should be a compiler builtin define ideally... -# ifdef cxx_EXPORTS -# define _LIBCPP_HIDDEN -# define _LIBCPP_FUNC_VIS __declspec(dllexport) -# define _LIBCPP_TYPE_VIS __declspec(dllexport) -# else -# define _LIBCPP_HIDDEN -# define _LIBCPP_FUNC_VIS __declspec(dllimport) -# define _LIBCPP_TYPE_VIS __declspec(dllimport) -# endif -#else -# define _LIBCPP_HIDDEN -# define _LIBCPP_FUNC_VIS -# define _LIBCPP_TYPE_VIS -#endif - -#define _LIBCPP_TYPE_VIS_ONLY -#define _LIBCPP_FUNC_VIS_ONLY - -#ifndef _LIBCPP_INLINE_VISIBILITY -# ifdef _LIBCPP_MSVC -# define _LIBCPP_INLINE_VISIBILITY __forceinline -# else // MinGW GCC and Clang -# define _LIBCPP_INLINE_VISIBILITY __attribute__ ((__always_inline__)) -# endif -#endif - -#ifndef _LIBCPP_EXCEPTION_ABI -#define _LIBCPP_EXCEPTION_ABI _LIBCPP_TYPE_VIS -#endif - -#ifndef _LIBCPP_ALWAYS_INLINE -# ifdef _LIBCPP_MSVC -# define _LIBCPP_ALWAYS_INLINE __forceinline -# endif -#endif - -#endif // _WIN32 - -#ifndef _LIBCPP_HIDDEN -#define _LIBCPP_HIDDEN __attribute__ ((__visibility__("hidden"))) -#endif - -#ifndef _LIBCPP_FUNC_VIS -#define _LIBCPP_FUNC_VIS __attribute__ ((__visibility__("default"))) -#endif - -#ifndef _LIBCPP_TYPE_VIS -# if __has_attribute(__type_visibility__) -# define _LIBCPP_TYPE_VIS __attribute__ ((__type_visibility__("default"))) -# else -# define _LIBCPP_TYPE_VIS __attribute__ ((__visibility__("default"))) -# endif -#endif - -#ifndef _LIBCPP_PREFERRED_OVERLOAD -# if __has_attribute(__enable_if__) -# define _LIBCPP_PREFERRED_OVERLOAD __attribute__ ((__enable_if__(true, ""))) -# endif -#endif - -#ifndef _LIBCPP_TYPE_VIS_ONLY -# define _LIBCPP_TYPE_VIS_ONLY _LIBCPP_TYPE_VIS -#endif - -#ifndef _LIBCPP_FUNC_VIS_ONLY -# define _LIBCPP_FUNC_VIS_ONLY _LIBCPP_FUNC_VIS -#endif - -#ifndef _LIBCPP_INLINE_VISIBILITY -#define _LIBCPP_INLINE_VISIBILITY __attribute__ ((__visibility__("hidden"), __always_inline__)) -#endif - -#ifndef _LIBCPP_EXCEPTION_ABI -#define _LIBCPP_EXCEPTION_ABI __attribute__ ((__visibility__("default"))) -#endif - -#ifndef _LIBCPP_ALWAYS_INLINE -#define _LIBCPP_ALWAYS_INLINE __attribute__ ((__visibility__("hidden"), __always_inline__)) +#ifndef __has_include +#define __has_include(...) 0 #endif #if defined(__clang__) +# define _LIBCPP_COMPILER_CLANG +# ifndef __apple_build_version__ +# define _LIBCPP_CLANG_VER (__clang_major__ * 100 + __clang_minor__) +# endif +#elif defined(__GNUC__) +# define _LIBCPP_COMPILER_GCC +#elif defined(_MSC_VER) +# define _LIBCPP_COMPILER_MSVC +#elif defined(__IBMCPP__) +# define _LIBCPP_COMPILER_IBM +#endif -// _LIBCPP_ALTERNATE_STRING_LAYOUT is an old name for -// _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT left here for backward compatibility. -#if (defined(__APPLE__) && !defined(__i386__) && !defined(__x86_64__) && \ - !defined(__arm__)) || \ - defined(_LIBCPP_ALTERNATE_STRING_LAYOUT) -#define _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT +#if defined(_LIBCPP_COMPILER_GCC) && __cplusplus < 201103L +#error "libc++ does not support using GCC with C++03. Please enable C++11" +#endif + +// FIXME: ABI detection should be done via compiler builtin macros. This +// is just a placeholder until Clang implements such macros. For now assume +// that Windows compilers pretending to be MSVC++ target the Microsoft ABI, +// and allow the user to explicitly specify the ABI to handle cases where this +// heuristic falls short. +#if defined(_LIBCPP_ABI_FORCE_ITANIUM) && defined(_LIBCPP_ABI_FORCE_MICROSOFT) +# error "Only one of _LIBCPP_ABI_FORCE_ITANIUM and _LIBCPP_ABI_FORCE_MICROSOFT can be defined" +#elif defined(_LIBCPP_ABI_FORCE_ITANIUM) +# define _LIBCPP_ABI_ITANIUM +#elif defined(_LIBCPP_ABI_FORCE_MICROSOFT) +# define _LIBCPP_ABI_MICROSOFT +#else +# if defined(_WIN32) && defined(_MSC_VER) +# define _LIBCPP_ABI_MICROSOFT +# else +# define _LIBCPP_ABI_ITANIUM +# endif +#endif + +#if defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_NO_VCRUNTIME) +# define _LIBCPP_ABI_VCRUNTIME +#endif + +// Need to detect which libc we're using if we're on Linux. +#if defined(__linux__) +# if defined(__GLIBC_PREREQ) +# define _LIBCPP_GLIBC_PREREQ(a, b) __GLIBC_PREREQ(a, b) +# else +# define _LIBCPP_GLIBC_PREREQ(a, b) 0 +# endif // defined(__GLIBC_PREREQ) +#endif // defined(__linux__) + +#ifdef __LITTLE_ENDIAN__ +# if __LITTLE_ENDIAN__ +# define _LIBCPP_LITTLE_ENDIAN +# endif // __LITTLE_ENDIAN__ +#endif // __LITTLE_ENDIAN__ + +#ifdef __BIG_ENDIAN__ +# if __BIG_ENDIAN__ +# define _LIBCPP_BIG_ENDIAN +# endif // __BIG_ENDIAN__ +#endif // __BIG_ENDIAN__ + +#ifdef __BYTE_ORDER__ +# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +# define _LIBCPP_LITTLE_ENDIAN +# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +# define _LIBCPP_BIG_ENDIAN +# endif // __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#endif // __BYTE_ORDER__ + +#ifdef __FreeBSD__ +# include +# include +# if _BYTE_ORDER == _LITTLE_ENDIAN +# define _LIBCPP_LITTLE_ENDIAN +# else // _BYTE_ORDER == _LITTLE_ENDIAN +# define _LIBCPP_BIG_ENDIAN +# endif // _BYTE_ORDER == _LITTLE_ENDIAN +# ifndef __LONG_LONG_SUPPORTED +# define _LIBCPP_HAS_NO_LONG_LONG +# endif // __LONG_LONG_SUPPORTED +#endif // __FreeBSD__ + +#if defined(__NetBSD__) || defined(__OpenBSD__) +# include +# if _BYTE_ORDER == _LITTLE_ENDIAN +# define _LIBCPP_LITTLE_ENDIAN +# else // _BYTE_ORDER == _LITTLE_ENDIAN +# define _LIBCPP_BIG_ENDIAN +# endif // _BYTE_ORDER == _LITTLE_ENDIAN +#endif // defined(__NetBSD__) || defined(__OpenBSD__) + +#if defined(_WIN32) +# define _LIBCPP_WIN32API +# define _LIBCPP_LITTLE_ENDIAN +# define _LIBCPP_SHORT_WCHAR 1 +// Both MinGW and native MSVC provide a "MSVC"-like environment +# define _LIBCPP_MSVCRT_LIKE +// If mingw not explicitly detected, assume using MS C runtime only if +// a MS compatibility version is specified. +# if defined(_MSC_VER) && !defined(__MINGW32__) +# define _LIBCPP_MSVCRT // Using Microsoft's C Runtime library +# endif +# if (defined(_M_AMD64) || defined(__x86_64__)) || (defined(_M_ARM) || defined(__arm__)) +# define _LIBCPP_HAS_BITSCAN64 +# endif +# define _LIBCPP_HAS_OPEN_WITH_WCHAR +# if defined(_LIBCPP_MSVCRT) +# define _LIBCPP_HAS_QUICK_EXIT +# endif + +// Some CRT APIs are unavailable to store apps +# if defined(WINAPI_FAMILY) +# include +# if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && \ + (!defined(WINAPI_PARTITION_SYSTEM) || \ + !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_SYSTEM)) +# define _LIBCPP_WINDOWS_STORE_APP +# endif +# endif +#endif // defined(_WIN32) + +#ifdef __sun__ +# include +# ifdef _LITTLE_ENDIAN +# define _LIBCPP_LITTLE_ENDIAN +# else +# define _LIBCPP_BIG_ENDIAN +# endif +#endif // __sun__ + +#if defined(__OpenBSD__) || defined(__CloudABI__) + // Certain architectures provide arc4random(). Prefer using + // arc4random() over /dev/{u,}random to make it possible to obtain + // random data even when using sandboxing mechanisms such as chroots, + // Capsicum, etc. +# define _LIBCPP_USING_ARC4_RANDOM +#elif defined(__Fuchsia__) || defined(__wasi__) +# define _LIBCPP_USING_GETENTROPY +#elif defined(__native_client__) + // NaCl's sandbox (which PNaCl also runs in) doesn't allow filesystem access, + // including accesses to the special files under /dev. C++11's + // std::random_device is instead exposed through a NaCl syscall. +# define _LIBCPP_USING_NACL_RANDOM +#elif defined(_LIBCPP_WIN32API) +# define _LIBCPP_USING_WIN32_RANDOM +#else +# define _LIBCPP_USING_DEV_RANDOM +#endif + +#if !defined(_LIBCPP_LITTLE_ENDIAN) && !defined(_LIBCPP_BIG_ENDIAN) +# include +# if __BYTE_ORDER == __LITTLE_ENDIAN +# define _LIBCPP_LITTLE_ENDIAN +# elif __BYTE_ORDER == __BIG_ENDIAN +# define _LIBCPP_BIG_ENDIAN +# else // __BYTE_ORDER == __BIG_ENDIAN +# error unable to determine endian +# endif +#endif // !defined(_LIBCPP_LITTLE_ENDIAN) && !defined(_LIBCPP_BIG_ENDIAN) + +#if __has_attribute(__no_sanitize__) && !defined(_LIBCPP_COMPILER_GCC) +# define _LIBCPP_NO_CFI __attribute__((__no_sanitize__("cfi"))) +#else +# define _LIBCPP_NO_CFI +#endif + +#if __ISO_C_VISIBLE >= 2011 || __cplusplus >= 201103L +# if defined(__FreeBSD__) +# define _LIBCPP_HAS_ALIGNED_ALLOC +# define _LIBCPP_HAS_QUICK_EXIT +# if __FreeBSD_version >= 1300064 || \ + (__FreeBSD_version >= 1201504 && __FreeBSD_version < 1300000) +# define _LIBCPP_HAS_TIMESPEC_GET +# endif +# elif defined(__BIONIC__) +# if __ANDROID_API__ >= 21 +# define _LIBCPP_HAS_QUICK_EXIT +# endif +# if __ANDROID_API__ >= 28 +# define _LIBCPP_HAS_ALIGNED_ALLOC +# endif +# if __ANDROID_API__ >= 29 +# define _LIBCPP_HAS_TIMESPEC_GET +# endif +# elif defined(__Fuchsia__) || defined(__wasi__) || defined(__NetBSD__) +# define _LIBCPP_HAS_ALIGNED_ALLOC +# define _LIBCPP_HAS_QUICK_EXIT +# define _LIBCPP_HAS_TIMESPEC_GET +# elif defined(__OpenBSD__) +# define _LIBCPP_HAS_ALIGNED_ALLOC +# define _LIBCPP_HAS_TIMESPEC_GET +# elif defined(__linux__) +# if !defined(_LIBCPP_HAS_MUSL_LIBC) +# if _LIBCPP_GLIBC_PREREQ(2, 15) || defined(__BIONIC__) +# define _LIBCPP_HAS_QUICK_EXIT +# endif +# if _LIBCPP_GLIBC_PREREQ(2, 17) +# define _LIBCPP_HAS_ALIGNED_ALLOC +# define _LIBCPP_HAS_TIMESPEC_GET +# endif +# else // defined(_LIBCPP_HAS_MUSL_LIBC) +# define _LIBCPP_HAS_ALIGNED_ALLOC +# define _LIBCPP_HAS_QUICK_EXIT +# define _LIBCPP_HAS_TIMESPEC_GET +# endif +# elif defined(__APPLE__) + // timespec_get and aligned_alloc were introduced in macOS 10.15 and + // aligned releases +# if (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101500 || \ + __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 130000 || \ + __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ >= 130000 || \ + __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ >= 60000) +# define _LIBCPP_HAS_ALIGNED_ALLOC +# define _LIBCPP_HAS_TIMESPEC_GET +# endif +# endif // __APPLE__ +#endif + +#ifndef _LIBCPP_CXX03_LANG +# define _LIBCPP_ALIGNOF(_Tp) alignof(_Tp) +#elif defined(_LIBCPP_COMPILER_CLANG) +# define _LIBCPP_ALIGNOF(_Tp) _Alignof(_Tp) +#else +# error "We don't know a correct way to implement alignof(T) in C++03 outside of Clang" +#endif + +#define _LIBCPP_PREFERRED_ALIGNOF(_Tp) __alignof(_Tp) + +#if defined(_LIBCPP_COMPILER_CLANG) + +#if defined(_LIBCPP_ALTERNATE_STRING_LAYOUT) +# error _LIBCPP_ALTERNATE_STRING_LAYOUT is deprecated, please use _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT instead +#endif +#if defined(__APPLE__) && !defined(__i386__) && !defined(__x86_64__) && \ + (!defined(__arm__) || __ARM_ARCH_7K__ >= 2) +# define _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT #endif #if __has_feature(cxx_alignas) # define _ALIGNAS_TYPE(x) alignas(x) # define _ALIGNAS(x) alignas(x) #else -# define _ALIGNAS_TYPE(x) __attribute__((__aligned__(__alignof(x)))) +# define _ALIGNAS_TYPE(x) __attribute__((__aligned__(_LIBCPP_ALIGNOF(x)))) # define _ALIGNAS(x) __attribute__((__aligned__(x))) #endif -#if !__has_feature(cxx_alias_templates) -#define _LIBCPP_HAS_NO_TEMPLATE_ALIASES -#endif - #if __cplusplus < 201103L typedef __char16_t char16_t; typedef __char32_t char32_t; #endif -#if !(__has_feature(cxx_exceptions)) && !defined(_LIBCPP_NO_EXCEPTIONS) -#define _LIBCPP_NO_EXCEPTIONS -#endif - -#if !(__has_feature(cxx_rtti)) -#define _LIBCPP_NO_RTTI +#if !__has_feature(cxx_exceptions) +# define _LIBCPP_NO_EXCEPTIONS #endif #if !(__has_feature(cxx_strong_enums)) #define _LIBCPP_HAS_NO_STRONG_ENUMS #endif -#if !(__has_feature(cxx_decltype)) -#define _LIBCPP_HAS_NO_DECLTYPE -#endif - #if __has_feature(cxx_attributes) # define _LIBCPP_NORETURN [[noreturn]] #else # define _LIBCPP_NORETURN __attribute__ ((noreturn)) #endif -#if !(__has_feature(cxx_default_function_template_args)) -#define _LIBCPP_HAS_NO_DEFAULT_FUNCTION_TEMPLATE_ARGS -#endif - -#if !(__has_feature(cxx_defaulted_functions)) -#define _LIBCPP_HAS_NO_DEFAULTED_FUNCTIONS -#endif // !(__has_feature(cxx_defaulted_functions)) - -#if !(__has_feature(cxx_deleted_functions)) -#define _LIBCPP_HAS_NO_DELETED_FUNCTIONS -#endif // !(__has_feature(cxx_deleted_functions)) - -#if !(__has_feature(cxx_lambdas)) -#define _LIBCPP_HAS_NO_LAMBDAS -#endif - #if !(__has_feature(cxx_nullptr)) -#define _LIBCPP_HAS_NO_NULLPTR -#endif - -#if !(__has_feature(cxx_rvalue_references)) -#define _LIBCPP_HAS_NO_RVALUE_REFERENCES -#endif - -#if !(__has_feature(cxx_static_assert)) -#define _LIBCPP_HAS_NO_STATIC_ASSERT -#endif - -#if !(__has_feature(cxx_auto_type)) -#define _LIBCPP_HAS_NO_AUTO_TYPE -#endif - -#if !(__has_feature(cxx_access_control_sfinae)) || !__has_feature(cxx_trailing_return) -#define _LIBCPP_HAS_NO_ADVANCED_SFINAE -#endif - -#if !(__has_feature(cxx_variadic_templates)) -#define _LIBCPP_HAS_NO_VARIADICS -#endif - -#if !(__has_feature(cxx_trailing_return)) -#define _LIBCPP_HAS_NO_TRAILING_RETURN -#endif - -#if !(__has_feature(cxx_generalized_initializers)) -#define _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS -#endif - -#if __has_feature(is_base_of) -# define _LIBCPP_HAS_IS_BASE_OF -#endif - -#if __has_feature(is_final) -# define _LIBCPP_HAS_IS_FINAL +# if (__has_extension(cxx_nullptr) || __has_keyword(__nullptr)) && defined(_LIBCPP_ABI_ALWAYS_USE_CXX11_NULLPTR) +# define nullptr __nullptr +# else +# define _LIBCPP_HAS_NO_NULLPTR +# endif #endif // Objective-C++ features (opt-in) @@ -396,11 +461,14 @@ typedef __char32_t char32_t; #if __has_feature(objc_arc_weak) #define _LIBCPP_HAS_OBJC_ARC_WEAK -#define _LIBCPP_HAS_NO_STRONG_ENUMS #endif -#if !(__has_feature(cxx_constexpr)) -#define _LIBCPP_HAS_NO_CONSTEXPR +#if __has_extension(blocks) +# define _LIBCPP_HAS_EXTENSION_BLOCKS +#endif + +#if defined(_LIBCPP_HAS_EXTENSION_BLOCKS) && defined(__APPLE__) +# define _LIBCPP_HAS_BLOCKS_RUNTIME #endif #if !(__has_feature(cxx_relaxed_constexpr)) @@ -411,42 +479,10 @@ typedef __char32_t char32_t; #define _LIBCPP_HAS_NO_VARIABLE_TEMPLATES #endif -#if __ISO_C_VISIBLE >= 2011 || __cplusplus >= 201103L -#if defined(__FreeBSD__) -#define _LIBCPP_HAS_QUICK_EXIT -#define _LIBCPP_HAS_C11_FEATURES -#elif defined(__ANDROID__) -#define _LIBCPP_HAS_QUICK_EXIT -#elif defined(__linux__) -#if defined(_LIBCPP_HAS_MUSL_LIBC) -#define _LIBCPP_HAS_QUICK_EXIT -#define _LIBCPP_HAS_C11_FEATURES -#endif -#endif // __linux__ -#endif - #if !(__has_feature(cxx_noexcept)) #define _LIBCPP_HAS_NO_NOEXCEPT #endif -#if __has_feature(underlying_type) -# define _LIBCPP_UNDERLYING_TYPE(T) __underlying_type(T) -#endif - -#if __has_feature(is_literal) -# define _LIBCPP_IS_LITERAL(T) __is_literal(T) -#endif - -// Inline namespaces are available in Clang regardless of C++ dialect. -#define _LIBCPP_BEGIN_NAMESPACE_STD namespace std {inline namespace _LIBCPP_NAMESPACE { -#define _LIBCPP_END_NAMESPACE_STD } } -#define _VSTD std::_LIBCPP_NAMESPACE - -namespace std { - inline namespace _LIBCPP_NAMESPACE { - } -} - #if !defined(_LIBCPP_HAS_NO_ASAN) && !__has_feature(address_sanitizer) #define _LIBCPP_HAS_NO_ASAN #endif @@ -454,39 +490,41 @@ namespace std { // Allow for build-time disabling of unsigned integer sanitization #if !defined(_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK) && __has_attribute(no_sanitize) #define _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK __attribute__((__no_sanitize__("unsigned-integer-overflow"))) -#endif +#endif -#include <__sgx> +#if __has_builtin(__builtin_launder) +#define _LIBCPP_COMPILER_HAS_BUILTIN_LAUNDER +#endif -#elif defined(__GNUC__) +#if __has_builtin(__builtin_constant_p) +#define _LIBCPP_COMPILER_HAS_BUILTIN_CONSTANT_P +#endif + +#if !__is_identifier(__has_unique_object_representations) +#define _LIBCPP_HAS_UNIQUE_OBJECT_REPRESENTATIONS +#endif + +#define _LIBCPP_ALWAYS_INLINE __attribute__ ((__always_inline__)) + +// Literal operators ""d and ""y are supported starting with LLVM Clang 8 and AppleClang 10.0.1 +#if (defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER < 800) || \ + (defined(__apple_build_version__) && __apple_build_version__ < 10010000) +#define _LIBCPP_HAS_NO_CXX20_CHRONO_LITERALS +#endif + +#define _LIBCPP_DISABLE_EXTENSION_WARNING __extension__ + +#elif defined(_LIBCPP_COMPILER_GCC) #include <__sgx> #define _ALIGNAS(x) __attribute__((__aligned__(x))) -#define _ALIGNAS_TYPE(x) __attribute__((__aligned__(__alignof(x)))) +#define _ALIGNAS_TYPE(x) __attribute__((__aligned__(_LIBCPP_ALIGNOF(x)))) #define _LIBCPP_NORETURN __attribute__((noreturn)) -#if _GNUC_VER >= 407 -#define _LIBCPP_UNDERLYING_TYPE(T) __underlying_type(T) -#define _LIBCPP_IS_LITERAL(T) __is_literal_type(T) -#define _LIBCPP_HAS_IS_FINAL -#endif - -#if defined(__GNUC__) && _GNUC_VER >= 403 -# define _LIBCPP_HAS_IS_BASE_OF -#endif - #if !__EXCEPTIONS -#define _LIBCPP_NO_EXCEPTIONS -#endif - -// constexpr was added to GCC in 4.6. -#if _GNUC_VER < 406 -#define _LIBCPP_HAS_NO_CONSTEXPR -// Can only use constexpr in c++11 mode. -#elif !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L -#define _LIBCPP_HAS_NO_CONSTEXPR +# define _LIBCPP_NO_EXCEPTIONS #endif // Determine if GCC supports relaxed constexpr @@ -494,132 +532,272 @@ namespace std { #define _LIBCPP_HAS_NO_CXX14_CONSTEXPR #endif -// GCC 5 will support variable templates +// GCC 5 supports variable templates #if !defined(__cpp_variable_templates) || __cpp_variable_templates < 201304L #define _LIBCPP_HAS_NO_VARIABLE_TEMPLATES #endif -#ifndef __GXX_EXPERIMENTAL_CXX0X__ - -#define _LIBCPP_HAS_NO_ADVANCED_SFINAE -#define _LIBCPP_HAS_NO_DECLTYPE -#define _LIBCPP_HAS_NO_DEFAULT_FUNCTION_TEMPLATE_ARGS -#define _LIBCPP_HAS_NO_DEFAULTED_FUNCTIONS -#define _LIBCPP_HAS_NO_DELETED_FUNCTIONS -#define _LIBCPP_HAS_NO_NULLPTR -#define _LIBCPP_HAS_NO_STATIC_ASSERT -#define _LIBCPP_HAS_NO_UNICODE_CHARS -#define _LIBCPP_HAS_NO_VARIADICS -#define _LIBCPP_HAS_NO_RVALUE_REFERENCES -#define _LIBCPP_HAS_NO_STRONG_ENUMS -#define _LIBCPP_HAS_NO_TEMPLATE_ALIASES -#define _LIBCPP_HAS_NO_NOEXCEPT - -#else // __GXX_EXPERIMENTAL_CXX0X__ - -#if _GNUC_VER < 403 -#define _LIBCPP_HAS_NO_DEFAULT_FUNCTION_TEMPLATE_ARGS -#define _LIBCPP_HAS_NO_RVALUE_REFERENCES -#define _LIBCPP_HAS_NO_STATIC_ASSERT -#endif - - -#if _GNUC_VER < 404 -#define _LIBCPP_HAS_NO_DECLTYPE -#define _LIBCPP_HAS_NO_DELETED_FUNCTIONS -#define _LIBCPP_HAS_NO_TRAILING_RETURN -#define _LIBCPP_HAS_NO_UNICODE_CHARS -#define _LIBCPP_HAS_NO_VARIADICS -#define _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS -#endif // _GNUC_VER < 404 - -#if _GNUC_VER < 406 -#define _LIBCPP_HAS_NO_NOEXCEPT -#define _LIBCPP_HAS_NO_NULLPTR -#define _LIBCPP_HAS_NO_TEMPLATE_ALIASES -#endif - -#if _GNUC_VER < 407 -#define _LIBCPP_HAS_NO_ADVANCED_SFINAE -#define _LIBCPP_HAS_NO_DEFAULTED_FUNCTIONS -#endif - -#endif // __GXX_EXPERIMENTAL_CXX0X__ - -#define _LIBCPP_BEGIN_NAMESPACE_STD namespace std { inline namespace _LIBCPP_NAMESPACE { -#define _LIBCPP_END_NAMESPACE_STD } } -#define _VSTD std::_LIBCPP_NAMESPACE - -namespace std { - inline namespace _LIBCPP_NAMESPACE { - } -} - #if !defined(_LIBCPP_HAS_NO_ASAN) && !defined(__SANITIZE_ADDRESS__) #define _LIBCPP_HAS_NO_ASAN #endif -#elif defined(_LIBCPP_MSVC) +#if _GNUC_VER >= 700 +#define _LIBCPP_COMPILER_HAS_BUILTIN_LAUNDER +#define _LIBCPP_COMPILER_HAS_BUILTIN_CONSTANT_P +#define _LIBCPP_HAS_UNIQUE_OBJECT_REPRESENTATIONS +#endif + +#define _LIBCPP_ALWAYS_INLINE __attribute__ ((__always_inline__)) + +#define _LIBCPP_DISABLE_EXTENSION_WARNING __extension__ + +#elif defined(_LIBCPP_COMPILER_MSVC) + +#define _LIBCPP_TOSTRING2(x) #x +#define _LIBCPP_TOSTRING(x) _LIBCPP_TOSTRING2(x) +#define _LIBCPP_WARNING(x) __pragma(message(__FILE__ "(" _LIBCPP_TOSTRING(__LINE__) ") : warning note: " x)) + +#if _MSC_VER < 1900 +#error "MSVC versions prior to Visual Studio 2015 are not supported" +#endif -#define _LIBCPP_HAS_NO_TEMPLATE_ALIASES -#define _LIBCPP_HAS_NO_CONSTEXPR #define _LIBCPP_HAS_NO_CXX14_CONSTEXPR #define _LIBCPP_HAS_NO_VARIABLE_TEMPLATES -#define _LIBCPP_HAS_NO_UNICODE_CHARS -#define _LIBCPP_HAS_NO_DELETED_FUNCTIONS -#define _LIBCPP_HAS_NO_DEFAULTED_FUNCTIONS -#define _LIBCPP_HAS_NO_NOEXCEPT #define __alignof__ __alignof #define _LIBCPP_NORETURN __declspec(noreturn) #define _ALIGNAS(x) __declspec(align(x)) -#define _LIBCPP_HAS_NO_VARIADICS +#define _ALIGNAS_TYPE(x) alignas(x) - - -#define _LIBCPP_BEGIN_NAMESPACE_STD namespace std { -#define _LIBCPP_END_NAMESPACE_STD } -#define _VSTD std - -# define _LIBCPP_WEAK -namespace std { -} +#define _LIBCPP_WEAK #define _LIBCPP_HAS_NO_ASAN -#elif defined(__IBMCPP__) +#define _LIBCPP_ALWAYS_INLINE __forceinline + +#define _LIBCPP_HAS_NO_VECTOR_EXTENSION + +#define _LIBCPP_DISABLE_EXTENSION_WARNING + +#elif defined(_LIBCPP_COMPILER_IBM) #define _ALIGNAS(x) __attribute__((__aligned__(x))) -#define _ALIGNAS_TYPE(x) __attribute__((__aligned__(__alignof(x)))) +#define _ALIGNAS_TYPE(x) __attribute__((__aligned__(_LIBCPP_ALIGNOF(x)))) #define _ATTRIBUTE(x) __attribute__((x)) #define _LIBCPP_NORETURN __attribute__((noreturn)) -#define _LIBCPP_HAS_NO_DEFAULT_FUNCTION_TEMPLATE_ARGS -#define _LIBCPP_HAS_NO_TEMPLATE_ALIASES -#define _LIBCPP_HAS_NO_ADVANCED_SFINAE -#define _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS -#define _LIBCPP_HAS_NO_NOEXCEPT -#define _LIBCPP_HAS_NO_NULLPTR #define _LIBCPP_HAS_NO_UNICODE_CHARS -#define _LIBCPP_HAS_IS_BASE_OF -#define _LIBCPP_HAS_IS_FINAL #define _LIBCPP_HAS_NO_VARIABLE_TEMPLATES #if defined(_AIX) #define __MULTILOCALE_API #endif -#define _LIBCPP_BEGIN_NAMESPACE_STD namespace std {inline namespace _LIBCPP_NAMESPACE { -#define _LIBCPP_END_NAMESPACE_STD } } -#define _VSTD std::_LIBCPP_NAMESPACE - -namespace std { - inline namespace _LIBCPP_NAMESPACE { - } -} - #define _LIBCPP_HAS_NO_ASAN -#endif // __clang__ || __GNUC__ || _MSC_VER || __IBMCPP__ +#define _LIBCPP_ALWAYS_INLINE __attribute__ ((__always_inline__)) + +#define _LIBCPP_HAS_NO_VECTOR_EXTENSION + +#define _LIBCPP_DISABLE_EXTENSION_WARNING + +#endif // _LIBCPP_COMPILER_[CLANG|GCC|MSVC|IBM] + +#if defined(_LIBCPP_OBJECT_FORMAT_COFF) + +#ifdef _DLL +# define _LIBCPP_CRT_FUNC __declspec(dllimport) +#else +# define _LIBCPP_CRT_FUNC +#endif + +#if defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) +# define _LIBCPP_DLL_VIS +# define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS +# define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS +# define _LIBCPP_OVERRIDABLE_FUNC_VIS +# define _LIBCPP_EXPORTED_FROM_ABI +#elif defined(_LIBCPP_BUILDING_LIBRARY) +# define _LIBCPP_DLL_VIS __declspec(dllexport) +# if defined(__MINGW32__) +# define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS _LIBCPP_DLL_VIS +# define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS +# else +# define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS +# define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS _LIBCPP_DLL_VIS +# endif +# define _LIBCPP_OVERRIDABLE_FUNC_VIS _LIBCPP_DLL_VIS +# define _LIBCPP_EXPORTED_FROM_ABI __declspec(dllexport) +#else +# define _LIBCPP_DLL_VIS __declspec(dllimport) +# define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS _LIBCPP_DLL_VIS +# define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS +# define _LIBCPP_OVERRIDABLE_FUNC_VIS +# define _LIBCPP_EXPORTED_FROM_ABI __declspec(dllimport) +#endif + +#define _LIBCPP_TYPE_VIS _LIBCPP_DLL_VIS +#define _LIBCPP_FUNC_VIS _LIBCPP_DLL_VIS +#define _LIBCPP_EXCEPTION_ABI _LIBCPP_DLL_VIS +#define _LIBCPP_HIDDEN +#define _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS +#define _LIBCPP_TEMPLATE_VIS +#define _LIBCPP_ENUM_VIS + +#endif // defined(_LIBCPP_OBJECT_FORMAT_COFF) + +#ifndef _LIBCPP_HIDDEN +# if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) +# define _LIBCPP_HIDDEN __attribute__ ((__visibility__("hidden"))) +# else +# define _LIBCPP_HIDDEN +# endif +#endif + +#ifndef _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS +# if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) +// The inline should be removed once PR32114 is resolved +# define _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS inline _LIBCPP_HIDDEN +# else +# define _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS +# endif +#endif + +#ifndef _LIBCPP_FUNC_VIS +# if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) +# define _LIBCPP_FUNC_VIS __attribute__ ((__visibility__("default"))) +# else +# define _LIBCPP_FUNC_VIS +# endif +#endif + +#ifndef _LIBCPP_TYPE_VIS +# if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) +# define _LIBCPP_TYPE_VIS __attribute__ ((__visibility__("default"))) +# else +# define _LIBCPP_TYPE_VIS +# endif +#endif + +#ifndef _LIBCPP_TEMPLATE_VIS +# if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) +# if __has_attribute(__type_visibility__) +# define _LIBCPP_TEMPLATE_VIS __attribute__ ((__type_visibility__("default"))) +# else +# define _LIBCPP_TEMPLATE_VIS __attribute__ ((__visibility__("default"))) +# endif +# else +# define _LIBCPP_TEMPLATE_VIS +# endif +#endif + +#ifndef _LIBCPP_EXPORTED_FROM_ABI +# if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) +# define _LIBCPP_EXPORTED_FROM_ABI __attribute__((__visibility__("default"))) +# else +# define _LIBCPP_EXPORTED_FROM_ABI +# endif +#endif + +#ifndef _LIBCPP_OVERRIDABLE_FUNC_VIS +#define _LIBCPP_OVERRIDABLE_FUNC_VIS _LIBCPP_FUNC_VIS +#endif + +#ifndef _LIBCPP_EXCEPTION_ABI +# if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) +# define _LIBCPP_EXCEPTION_ABI __attribute__ ((__visibility__("default"))) +# else +# define _LIBCPP_EXCEPTION_ABI +# endif +#endif + +#ifndef _LIBCPP_ENUM_VIS +# if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) && __has_attribute(__type_visibility__) +# define _LIBCPP_ENUM_VIS __attribute__ ((__type_visibility__("default"))) +# else +# define _LIBCPP_ENUM_VIS +# endif +#endif + +#ifndef _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS +# if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) +# define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS __attribute__ ((__visibility__("default"))) +# else +# define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS +# endif +#endif + +#ifndef _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS +#define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS +#endif + +#if __has_attribute(internal_linkage) +# define _LIBCPP_INTERNAL_LINKAGE __attribute__ ((internal_linkage)) +#else +# define _LIBCPP_INTERNAL_LINKAGE _LIBCPP_ALWAYS_INLINE +#endif + +#if __has_attribute(exclude_from_explicit_instantiation) +# define _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION __attribute__ ((__exclude_from_explicit_instantiation__)) +#else + // Try to approximate the effect of exclude_from_explicit_instantiation + // (which is that entities are not assumed to be provided by explicit + // template instantiations in the dylib) by always inlining those entities. +# define _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION _LIBCPP_ALWAYS_INLINE +#endif + +#ifndef _LIBCPP_HIDE_FROM_ABI_PER_TU +# ifndef _LIBCPP_HIDE_FROM_ABI_PER_TU_BY_DEFAULT +# define _LIBCPP_HIDE_FROM_ABI_PER_TU 0 +# else +# define _LIBCPP_HIDE_FROM_ABI_PER_TU 1 +# endif +#endif + +#ifndef _LIBCPP_HIDE_FROM_ABI +# if _LIBCPP_HIDE_FROM_ABI_PER_TU +# define _LIBCPP_HIDE_FROM_ABI _LIBCPP_HIDDEN _LIBCPP_INTERNAL_LINKAGE +# else +# define _LIBCPP_HIDE_FROM_ABI _LIBCPP_HIDDEN _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION +# endif +#endif + +#ifdef _LIBCPP_BUILDING_LIBRARY +# if _LIBCPP_ABI_VERSION > 1 +# define _LIBCPP_HIDE_FROM_ABI_AFTER_V1 _LIBCPP_HIDE_FROM_ABI +# else +# define _LIBCPP_HIDE_FROM_ABI_AFTER_V1 +# endif +#else +# define _LIBCPP_HIDE_FROM_ABI_AFTER_V1 _LIBCPP_HIDE_FROM_ABI +#endif + +// Just so we can migrate to the new macros gradually. +#define _LIBCPP_INLINE_VISIBILITY _LIBCPP_HIDE_FROM_ABI + +// Inline namespaces are available in Clang/GCC/MSVC regardless of C++ dialect. +#define _LIBCPP_BEGIN_NAMESPACE_STD namespace std { inline namespace _LIBCPP_ABI_NAMESPACE { +#define _LIBCPP_END_NAMESPACE_STD } } +#define _VSTD std::_LIBCPP_ABI_NAMESPACE +_LIBCPP_BEGIN_NAMESPACE_STD _LIBCPP_END_NAMESPACE_STD + +#if _LIBCPP_STD_VER >= 17 +#define _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM \ + _LIBCPP_BEGIN_NAMESPACE_STD inline namespace __fs { namespace filesystem { +#else +#define _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM \ + _LIBCPP_BEGIN_NAMESPACE_STD namespace __fs { namespace filesystem { +#endif + +#define _LIBCPP_END_NAMESPACE_FILESYSTEM \ + _LIBCPP_END_NAMESPACE_STD } } + +#define _VSTD_FS _VSTD::__fs::filesystem + +#ifndef _LIBCPP_PREFERRED_OVERLOAD +# if __has_attribute(__enable_if__) +# define _LIBCPP_PREFERRED_OVERLOAD __attribute__ ((__enable_if__(true, ""))) +# endif +#endif #ifndef _LIBCPP_HAS_NO_NOEXCEPT # define _NOEXCEPT noexcept @@ -638,114 +816,145 @@ typedef unsigned int char32_t; #define _LIBCPP_HAS_NO_INT128 #endif -#ifdef _LIBCPP_HAS_NO_STATIC_ASSERT +#ifdef _LIBCPP_CXX03_LANG +# define static_assert(...) _Static_assert(__VA_ARGS__) +# define decltype(...) __decltype(__VA_ARGS__) +#endif // _LIBCPP_CXX03_LANG -extern "C++" { -template struct __static_assert_test; -template <> struct __static_assert_test {}; -template struct __static_assert_check {}; -} -#define static_assert(__b, __m) \ - typedef __static_assert_check)> \ - _LIBCPP_CONCAT(__t, __LINE__) - -#endif // _LIBCPP_HAS_NO_STATIC_ASSERT - -#ifdef _LIBCPP_HAS_NO_DECLTYPE -// GCC 4.6 provides __decltype in all standard modes. -#if !__is_identifier(__decltype) || _GNUC_VER >= 406 -# define decltype(__x) __decltype(__x) +#ifdef _LIBCPP_CXX03_LANG +# define _LIBCPP_CONSTEXPR #else -# define decltype(__x) __typeof__(__x) -#endif +# define _LIBCPP_CONSTEXPR constexpr #endif -#ifdef _LIBCPP_HAS_NO_CONSTEXPR -#define _LIBCPP_CONSTEXPR +#ifndef __cpp_consteval +# define _LIBCPP_CONSTEVAL _LIBCPP_CONSTEXPR #else -#define _LIBCPP_CONSTEXPR constexpr +# define _LIBCPP_CONSTEVAL consteval #endif -#ifdef _LIBCPP_HAS_NO_DEFAULTED_FUNCTIONS -#define _LIBCPP_DEFAULT {} +#ifdef _LIBCPP_CXX03_LANG +# define _LIBCPP_DEFAULT {} #else -#define _LIBCPP_DEFAULT = default; +# define _LIBCPP_DEFAULT = default; #endif -#ifdef _LIBCPP_HAS_NO_DELETED_FUNCTIONS -#define _LIBCPP_EQUAL_DELETE +#ifdef _LIBCPP_CXX03_LANG +# define _LIBCPP_EQUAL_DELETE #else -#define _LIBCPP_EQUAL_DELETE = delete +# define _LIBCPP_EQUAL_DELETE = delete #endif #ifdef __GNUC__ -#define _NOALIAS __attribute__((__malloc__)) +# define _LIBCPP_NOALIAS __attribute__((__malloc__)) #else -#define _NOALIAS +# define _LIBCPP_NOALIAS #endif -#if __has_feature(cxx_explicit_conversions) || defined(__IBMCPP__) -# define _LIBCPP_EXPLICIT explicit +#if __has_feature(cxx_explicit_conversions) || defined(__IBMCPP__) || \ + (!defined(_LIBCPP_CXX03_LANG) && defined(__GNUC__)) // All supported GCC versions +# define _LIBCPP_EXPLICIT explicit #else -# define _LIBCPP_EXPLICIT -#endif - -#if !__has_builtin(__builtin_operator_new) || !__has_builtin(__builtin_operator_delete) -# define _LIBCPP_HAS_NO_BUILTIN_OPERATOR_NEW_DELETE +# define _LIBCPP_EXPLICIT #endif #ifdef _LIBCPP_HAS_NO_STRONG_ENUMS -#define _LIBCPP_DECLARE_STRONG_ENUM(x) struct _LIBCPP_TYPE_VIS x { enum __lx -#define _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(x) \ - __lx __v_; \ - _LIBCPP_ALWAYS_INLINE x(__lx __v) : __v_(__v) {} \ - _LIBCPP_ALWAYS_INLINE explicit x(int __v) : __v_(static_cast<__lx>(__v)) {} \ - _LIBCPP_ALWAYS_INLINE operator int() const {return __v_;} \ - }; +# define _LIBCPP_DECLARE_STRONG_ENUM(x) struct _LIBCPP_TYPE_VIS x { enum __lx +# define _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(x) \ + __lx __v_; \ + _LIBCPP_INLINE_VISIBILITY x(__lx __v) : __v_(__v) {} \ + _LIBCPP_INLINE_VISIBILITY explicit x(int __v) : __v_(static_cast<__lx>(__v)) {} \ + _LIBCPP_INLINE_VISIBILITY operator int() const {return __v_;} \ + }; #else // _LIBCPP_HAS_NO_STRONG_ENUMS -#define _LIBCPP_DECLARE_STRONG_ENUM(x) enum class _LIBCPP_TYPE_VIS x -#define _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(x) +# define _LIBCPP_DECLARE_STRONG_ENUM(x) enum class _LIBCPP_ENUM_VIS x +# define _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(x) #endif // _LIBCPP_HAS_NO_STRONG_ENUMS -#ifdef _LIBCPP_DEBUG -# if _LIBCPP_DEBUG == 0 -# define _LIBCPP_DEBUG_LEVEL 1 -# elif _LIBCPP_DEBUG == 1 -# define _LIBCPP_DEBUG_LEVEL 2 -# else -# error Supported values for _LIBCPP_DEBUG are 0 and 1 -# endif -# define _LIBCPP_EXTERN_TEMPLATE(...) +// _LIBCPP_DEBUG potential values: +// - undefined: No assertions. This is the default. +// - 0: Basic assertions +// - 1: Basic assertions + iterator validity checks. +#if !defined(_LIBCPP_DEBUG) +# define _LIBCPP_DEBUG_LEVEL 0 +#elif _LIBCPP_DEBUG == 0 +# define _LIBCPP_DEBUG_LEVEL 1 +#elif _LIBCPP_DEBUG == 1 +# define _LIBCPP_DEBUG_LEVEL 2 +#else +# error Supported values for _LIBCPP_DEBUG are 0 and 1 +#endif + +// _LIBCPP_DEBUG_LEVEL is always defined to one of [0, 1, 2] at this point +#if _LIBCPP_DEBUG_LEVEL >= 1 && !defined(_LIBCPP_DISABLE_EXTERN_TEMPLATE) +# define _LIBCPP_EXTERN_TEMPLATE(...) +#endif + +#ifdef _LIBCPP_DISABLE_EXTERN_TEMPLATE +# define _LIBCPP_EXTERN_TEMPLATE(...) +# define _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(...) #endif #ifndef _LIBCPP_EXTERN_TEMPLATE #define _LIBCPP_EXTERN_TEMPLATE(...) extern template __VA_ARGS__; #endif -#ifndef _LIBCPP_EXTERN_TEMPLATE2 -#define _LIBCPP_EXTERN_TEMPLATE2(...) extern template __VA_ARGS__; +// When the Debug mode is enabled, we disable extern declarations because we +// don't want to use the functions compiled in the library, which might not +// have had the debug mode enabled when built. However, some extern declarations +// need to be used, because code correctness depends on it (several instances +// in the ). Those special declarations are declared with +// _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE, which is enabled even +// when the debug mode is enabled. +#ifndef _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE +# define _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(...) extern template __VA_ARGS__; #endif -#if defined(__APPLE__) && defined(__LP64__) && !defined(__x86_64__) -#define _LIBCPP_NONUNIQUE_RTTI_BIT (1ULL << 63) +#ifndef _LIBCPP_EXTERN_TEMPLATE_DEFINE +#define _LIBCPP_EXTERN_TEMPLATE_DEFINE(...) template __VA_ARGS__; #endif -#if defined(__APPLE__) || defined(__FreeBSD__) || defined(_WIN32) || \ +#if defined(__APPLE__) || defined(__FreeBSD__) || defined(_LIBCPP_MSVCRT_LIKE) || \ defined(__sun__) || defined(__NetBSD__) || defined(__CloudABI__) #define _LIBCPP_LOCALE__L_EXTENSIONS 1 #endif #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) // Most unix variants have catopen. These are the specific ones that don't. -#if !defined(_WIN32) && !defined(__ANDROID__) && !defined(_NEWLIB_VERSION) && !defined(__LIBCPP_SGX) -#define _LIBCPP_HAS_CATOPEN 1 -#endif +# if !defined(__BIONIC__) && !defined(_NEWLIB_VERSION) && !defined(__LIBCPP_SGX) +# define _LIBCPP_HAS_CATOPEN 1 +# endif #endif #ifdef __FreeBSD__ #define _DECLARE_C99_LDBL_MATH 1 #endif +// If we are getting operator new from the MSVC CRT, then allocation overloads +// for align_val_t were added in 19.12, aka VS 2017 version 15.3. +#if defined(_LIBCPP_MSVCRT) && defined(_MSC_VER) && _MSC_VER < 1912 +# define _LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION +#elif defined(_LIBCPP_ABI_VCRUNTIME) && !defined(__cpp_aligned_new) + // We're deferring to Microsoft's STL to provide aligned new et al. We don't + // have it unless the language feature test macro is defined. +# define _LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION +#elif defined(__MVS__) +# define _LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION +#endif + +#if defined(__APPLE__) +# if !defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \ + defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) +# define __MAC_OS_X_VERSION_MIN_REQUIRED __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ +# endif +#endif // defined(__APPLE__) + +#if !defined(_LIBCPP_HAS_NO_ALIGNED_ALLOCATION) && \ + (defined(_LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION) || \ + (!defined(__cpp_aligned_new) || __cpp_aligned_new < 201606)) +# define _LIBCPP_HAS_NO_ALIGNED_ALLOCATION +#endif + #if defined(__APPLE__) || defined(__FreeBSD__) #define _LIBCPP_HAS_DEFAULTRUNELOCALE #endif @@ -754,91 +963,244 @@ template struct __static_assert_check {}; #define _LIBCPP_WCTYPE_IS_MASK #endif -#ifndef _LIBCPP_STD_VER -# if __cplusplus <= 201103L -# define _LIBCPP_STD_VER 11 -# elif __cplusplus <= 201402L -# define _LIBCPP_STD_VER 14 -# else -# define _LIBCPP_STD_VER 16 // current year, or date of c++17 ratification -# endif -#endif // _LIBCPP_STD_VER +#if _LIBCPP_STD_VER <= 17 || !defined(__cpp_char8_t) +#define _LIBCPP_NO_HAS_CHAR8_T +#endif -#if _LIBCPP_STD_VER > 11 -#define _LIBCPP_DEPRECATED [[deprecated]] +// Deprecation macros. +// +// Deprecations warnings are always enabled, except when users explicitly opt-out +// by defining _LIBCPP_DISABLE_DEPRECATION_WARNINGS. +#if !defined(_LIBCPP_DISABLE_DEPRECATION_WARNINGS) +# if __has_attribute(deprecated) +# define _LIBCPP_DEPRECATED __attribute__ ((deprecated)) +# elif _LIBCPP_STD_VER > 11 +# define _LIBCPP_DEPRECATED [[deprecated]] +# else +# define _LIBCPP_DEPRECATED +# endif #else -#define _LIBCPP_DEPRECATED +# define _LIBCPP_DEPRECATED +#endif + +#if !defined(_LIBCPP_CXX03_LANG) +# define _LIBCPP_DEPRECATED_IN_CXX11 _LIBCPP_DEPRECATED +#else +# define _LIBCPP_DEPRECATED_IN_CXX11 +#endif + +#if _LIBCPP_STD_VER >= 14 +# define _LIBCPP_DEPRECATED_IN_CXX14 _LIBCPP_DEPRECATED +#else +# define _LIBCPP_DEPRECATED_IN_CXX14 +#endif + +#if _LIBCPP_STD_VER >= 17 +# define _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_DEPRECATED +#else +# define _LIBCPP_DEPRECATED_IN_CXX17 +#endif + +#if _LIBCPP_STD_VER > 17 +# define _LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_DEPRECATED +#else +# define _LIBCPP_DEPRECATED_IN_CXX20 +#endif + +#if !defined(_LIBCPP_NO_HAS_CHAR8_T) +# define _LIBCPP_DEPRECATED_WITH_CHAR8_T _LIBCPP_DEPRECATED +#else +# define _LIBCPP_DEPRECATED_WITH_CHAR8_T +#endif + +// Macros to enter and leave a state where deprecation warnings are suppressed. +#if !defined(_LIBCPP_SUPPRESS_DEPRECATED_PUSH) && \ + (defined(_LIBCPP_COMPILER_CLANG) || defined(_LIBCPP_COMPILER_GCC)) +# define _LIBCPP_SUPPRESS_DEPRECATED_PUSH \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wdeprecated\"") +# define _LIBCPP_SUPPRESS_DEPRECATED_POP \ + _Pragma("GCC diagnostic pop") +#endif +#if !defined(_LIBCPP_SUPPRESS_DEPRECATED_PUSH) +# define _LIBCPP_SUPPRESS_DEPRECATED_PUSH +# define _LIBCPP_SUPPRESS_DEPRECATED_POP #endif #if _LIBCPP_STD_VER <= 11 -#define _LIBCPP_EXPLICIT_AFTER_CXX11 -#define _LIBCPP_DEPRECATED_AFTER_CXX11 +# define _LIBCPP_EXPLICIT_AFTER_CXX11 #else -#define _LIBCPP_EXPLICIT_AFTER_CXX11 explicit -#define _LIBCPP_DEPRECATED_AFTER_CXX11 [[deprecated]] +# define _LIBCPP_EXPLICIT_AFTER_CXX11 explicit #endif #if _LIBCPP_STD_VER > 11 && !defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR) -#define _LIBCPP_CONSTEXPR_AFTER_CXX11 constexpr +# define _LIBCPP_CONSTEXPR_AFTER_CXX11 constexpr #else -#define _LIBCPP_CONSTEXPR_AFTER_CXX11 +# define _LIBCPP_CONSTEXPR_AFTER_CXX11 #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR) -#define _LIBCPP_CONSTEXPR_AFTER_CXX14 constexpr +# define _LIBCPP_CONSTEXPR_AFTER_CXX14 constexpr #else -#define _LIBCPP_CONSTEXPR_AFTER_CXX14 +# define _LIBCPP_CONSTEXPR_AFTER_CXX14 #endif -#ifdef _LIBCPP_HAS_NO_RVALUE_REFERENCES -# define _LIBCPP_EXPLICIT_MOVE(x) _VSTD::move(x) +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR) +# define _LIBCPP_CONSTEXPR_AFTER_CXX17 constexpr #else -# define _LIBCPP_EXPLICIT_MOVE(x) (x) +# define _LIBCPP_CONSTEXPR_AFTER_CXX17 +#endif + +// The _LIBCPP_NODISCARD_ATTRIBUTE should only be used to define other +// NODISCARD macros to the correct attribute. +#if __has_cpp_attribute(nodiscard) || defined(_LIBCPP_COMPILER_MSVC) +# define _LIBCPP_NODISCARD_ATTRIBUTE [[nodiscard]] +#elif defined(_LIBCPP_COMPILER_CLANG) && !defined(_LIBCPP_CXX03_LANG) +# define _LIBCPP_NODISCARD_ATTRIBUTE [[clang::warn_unused_result]] +#else +// We can't use GCC's [[gnu::warn_unused_result]] and +// __attribute__((warn_unused_result)), because GCC does not silence them via +// (void) cast. +# define _LIBCPP_NODISCARD_ATTRIBUTE +#endif + +// _LIBCPP_NODISCARD_EXT may be used to apply [[nodiscard]] to entities not +// specified as such as an extension. +#if defined(_LIBCPP_ENABLE_NODISCARD) && !defined(_LIBCPP_DISABLE_NODISCARD_EXT) +# define _LIBCPP_NODISCARD_EXT _LIBCPP_NODISCARD_ATTRIBUTE +#else +# define _LIBCPP_NODISCARD_EXT +#endif + +#if !defined(_LIBCPP_DISABLE_NODISCARD_AFTER_CXX17) && \ + (_LIBCPP_STD_VER > 17 || defined(_LIBCPP_ENABLE_NODISCARD)) +# define _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_NODISCARD_ATTRIBUTE +#else +# define _LIBCPP_NODISCARD_AFTER_CXX17 +#endif + +#if _LIBCPP_STD_VER > 14 && defined(__cpp_inline_variables) && (__cpp_inline_variables >= 201606L) +# define _LIBCPP_INLINE_VAR inline +#else +# define _LIBCPP_INLINE_VAR +#endif + +#ifndef _LIBCPP_CONSTEXPR_IF_NODEBUG +#if defined(_LIBCPP_DEBUG) || defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR) +#define _LIBCPP_CONSTEXPR_IF_NODEBUG +#else +#define _LIBCPP_CONSTEXPR_IF_NODEBUG constexpr +#endif +#endif + +#if __has_attribute(no_destroy) +# define _LIBCPP_NO_DESTROY __attribute__((__no_destroy__)) +#else +# define _LIBCPP_NO_DESTROY #endif #ifndef _LIBCPP_HAS_NO_ASAN -extern "C" void __sanitizer_annotate_contiguous_container( +extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container( const void *, const void *, const void *, const void *); #endif // Try to find out if RTTI is disabled. -// g++ and cl.exe have RTTI on by default and define a macro when it is. -// g++ only defines the macro in 4.3.2 and onwards. -#if !defined(_LIBCPP_NO_RTTI) -# if defined(__GNUC__) && ((__GNUC__ >= 5) || (__GNUC__ == 4 && \ - (__GNUC_MINOR__ >= 3 || __GNUC_PATCHLEVEL__ >= 2))) && !defined(__GXX_RTTI) -# define _LIBCPP_NO_RTTI -# elif (defined(_MSC_VER) && !defined(__clang__)) && !defined(_CPPRTTI) -# define _LIBCPP_NO_RTTI -# endif +#if defined(_LIBCPP_COMPILER_CLANG) && !__has_feature(cxx_rtti) +# define _LIBCPP_NO_RTTI +#elif defined(__GNUC__) && !defined(__GXX_RTTI) +# define _LIBCPP_NO_RTTI +#elif defined(_LIBCPP_COMPILER_MSVC) && !defined(_CPPRTTI) +# define _LIBCPP_NO_RTTI #endif #ifndef _LIBCPP_WEAK -# define _LIBCPP_WEAK __attribute__((__weak__)) +#define _LIBCPP_WEAK __attribute__((__weak__)) #endif // Thread API -#if !defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_HAS_THREAD_API_PTHREAD) -# if defined(__FreeBSD__) || \ - defined(__NetBSD__) || \ - defined(__linux__) || \ - defined(__APPLE__) || \ - defined(__CloudABI__) || \ - defined(__sun__) -# define _LIBCPP_HAS_THREAD_API_PTHREAD -# else -# error "No thread API" -# endif // _LIBCPP_HAS_THREAD_API +#if !defined(_LIBCPP_HAS_NO_THREADS) && \ + !defined(_LIBCPP_HAS_THREAD_API_PTHREAD) && \ + !defined(_LIBCPP_HAS_THREAD_API_WIN32) && \ + !defined(_LIBCPP_HAS_THREAD_API_EXTERNAL) +# if defined(__FreeBSD__) || \ + defined(__wasi__) || \ + defined(__NetBSD__) || \ + defined(__OpenBSD__) || \ + defined(__NuttX__) || \ + defined(__linux__) || \ + defined(__GNU__) || \ + defined(__APPLE__) || \ + defined(__CloudABI__) || \ + defined(__sun__) || \ + defined(__MVS__) || \ + (defined(__MINGW32__) && __has_include()) +# define _LIBCPP_HAS_THREAD_API_PTHREAD +# elif defined(__Fuchsia__) + // TODO(44575): Switch to C11 thread API when possible. +# define _LIBCPP_HAS_THREAD_API_PTHREAD +# elif defined(_LIBCPP_WIN32API) +# define _LIBCPP_HAS_THREAD_API_WIN32 +# else +# error "No thread API" +# endif // _LIBCPP_HAS_THREAD_API #endif // _LIBCPP_HAS_NO_THREADS +#if defined(_LIBCPP_HAS_THREAD_API_PTHREAD) +#if defined(__ANDROID__) && __ANDROID_API__ >= 30 +#define _LIBCPP_HAS_COND_CLOCKWAIT +#elif defined(_LIBCPP_GLIBC_PREREQ) +#if _LIBCPP_GLIBC_PREREQ(2, 30) +#define _LIBCPP_HAS_COND_CLOCKWAIT +#endif +#endif +#endif + #if defined(_LIBCPP_HAS_NO_THREADS) && defined(_LIBCPP_HAS_THREAD_API_PTHREAD) -# error _LIBCPP_HAS_THREAD_API_PTHREAD may only be defined when \ - _LIBCPP_HAS_NO_THREADS is not defined. +#error _LIBCPP_HAS_THREAD_API_PTHREAD may only be defined when \ + _LIBCPP_HAS_NO_THREADS is not defined. +#endif + +#if defined(_LIBCPP_HAS_NO_THREADS) && defined(_LIBCPP_HAS_THREAD_API_EXTERNAL) +#error _LIBCPP_HAS_THREAD_API_EXTERNAL may not be defined when \ + _LIBCPP_HAS_NO_THREADS is defined. #endif #if defined(_LIBCPP_HAS_NO_MONOTONIC_CLOCK) && !defined(_LIBCPP_HAS_NO_THREADS) -# error _LIBCPP_HAS_NO_MONOTONIC_CLOCK may only be defined when \ - _LIBCPP_HAS_NO_THREADS is defined. +#error _LIBCPP_HAS_NO_MONOTONIC_CLOCK may only be defined when \ + _LIBCPP_HAS_NO_THREADS is defined. +#endif + +#if !defined(_LIBCPP_HAS_NO_THREADS) && !defined(__STDCPP_THREADS__) +#define __STDCPP_THREADS__ 1 +#endif + +// The glibc and Bionic implementation of pthreads implements +// pthread_mutex_destroy as nop for regular mutexes. Additionally, Win32 +// mutexes have no destroy mechanism. +// +// This optimization can't be performed on Apple platforms, where +// pthread_mutex_destroy can allow the kernel to release resources. +// See https://llvm.org/D64298 for details. +// +// TODO(EricWF): Enable this optimization on Bionic after speaking to their +// respective stakeholders. +#if (defined(_LIBCPP_HAS_THREAD_API_PTHREAD) && defined(__GLIBC__)) \ + || (defined(_LIBCPP_HAS_THREAD_API_C11) && defined(__Fuchsia__)) \ + || defined(_LIBCPP_HAS_THREAD_API_WIN32) +# define _LIBCPP_HAS_TRIVIAL_MUTEX_DESTRUCTION +#endif + +// Destroying a condvar is a nop on Windows. +// +// This optimization can't be performed on Apple platforms, where +// pthread_cond_destroy can allow the kernel to release resources. +// See https://llvm.org/D64298 for details. +// +// TODO(EricWF): This is potentially true for some pthread implementations +// as well. +#if (defined(_LIBCPP_HAS_THREAD_API_C11) && defined(__Fuchsia__)) || \ + defined(_LIBCPP_HAS_THREAD_API_WIN32) +# define _LIBCPP_HAS_TRIVIAL_CONDVAR_DESTRUCTION #endif // Systems that use capability-based security (FreeBSD with Capsicum, @@ -856,42 +1218,232 @@ extern "C" void __sanitizer_annotate_contiguous_container( #define _LIBCPP_HAS_NO_STDOUT #endif -#if defined(__ANDROID__) || defined(__CloudABI__) || defined(_LIBCPP_HAS_MUSL_LIBC) || defined(_LIBCPP_SGX_CONFIG) +// Some systems do not provide gets() in their C library, for security reasons. +#ifndef _LIBCPP_C_HAS_NO_GETS +# if defined(_LIBCPP_MSVCRT) || \ + (defined(__FreeBSD_version) && __FreeBSD_version >= 1300043) || \ + defined(__OpenBSD__) +# define _LIBCPP_C_HAS_NO_GETS +# endif +#endif + +#if defined(__BIONIC__) || defined(__CloudABI__) || defined(__NuttX__) || \ + defined(__Fuchsia__) || defined(__wasi__) || defined(_LIBCPP_HAS_MUSL_LIBC) || \ + defined(__MVS__) || defined(__OpenBSD__) || defined(_LIBCPP_SGX_CONFIG) #define _LIBCPP_PROVIDES_DEFAULT_RUNE_TABLE #endif -// Thread-unsafe functions such as strtok(), mbtowc() and localtime() +// Thread-unsafe functions such as strtok() and localtime() // are not available. #ifdef __CloudABI__ #define _LIBCPP_HAS_NO_THREAD_UNSAFE_C_FUNCTIONS #endif -#if __has_feature(cxx_atomic) || __has_extension(c_atomic) -#define _LIBCPP_HAS_C_ATOMIC_IMP -#elif _GNUC_VER > 407 -#define _LIBCPP_HAS_GCC_ATOMIC_IMP +#if __has_feature(cxx_atomic) || __has_extension(c_atomic) || __has_keyword(_Atomic) +# define _LIBCPP_HAS_C_ATOMIC_IMP +#elif defined(_LIBCPP_COMPILER_GCC) +# define _LIBCPP_HAS_GCC_ATOMIC_IMP #endif -#if (!defined(_LIBCPP_HAS_C_ATOMIC_IMP) && !defined(_LIBCPP_HAS_GCC_ATOMIC_IMP)) \ +#if (!defined(_LIBCPP_HAS_C_ATOMIC_IMP) && \ + !defined(_LIBCPP_HAS_GCC_ATOMIC_IMP) && \ + !defined(_LIBCPP_HAS_EXTERNAL_ATOMIC_IMP)) \ || defined(_LIBCPP_HAS_NO_THREADS) -#define _LIBCPP_HAS_NO_ATOMIC_HEADER +# define _LIBCPP_HAS_NO_ATOMIC_HEADER +#else +# ifndef _LIBCPP_ATOMIC_FLAG_TYPE +# define _LIBCPP_ATOMIC_FLAG_TYPE bool +# endif +# ifdef _LIBCPP_FREESTANDING +# define _LIBCPP_ATOMIC_ONLY_USE_BUILTINS +# endif #endif #ifndef _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK #define _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK #endif -#if __cplusplus < 201103L -#define _LIBCPP_CXX03_LANG -#else -#if defined(_LIBCPP_HAS_NO_VARIADIC_TEMPLATES) || defined(_LIBCPP_HAS_NO_RVALUE_REFERENCES) -#error Libc++ requires a feature complete C++11 compiler in C++11 or greater. -#endif +#if defined(_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS) +# if defined(__clang__) && __has_attribute(acquire_capability) +// Work around the attribute handling in clang. When both __declspec and +// __attribute__ are present, the processing goes awry preventing the definition +// of the types. +# if !defined(_LIBCPP_OBJECT_FORMAT_COFF) +# define _LIBCPP_HAS_THREAD_SAFETY_ANNOTATIONS +# endif +# endif #endif -#if (defined(_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS) && defined(__clang__) \ - && __has_attribute(acquire_capability)) -#define _LIBCPP_HAS_THREAD_SAFETY_ANNOTATIONS +#ifndef _LIBCPP_THREAD_SAFETY_ANNOTATION +# ifdef _LIBCPP_HAS_THREAD_SAFETY_ANNOTATIONS +# define _LIBCPP_THREAD_SAFETY_ANNOTATION(x) __attribute__((x)) +# else +# define _LIBCPP_THREAD_SAFETY_ANNOTATION(x) +# endif +#endif // _LIBCPP_THREAD_SAFETY_ANNOTATION + +#if __has_attribute(require_constant_initialization) +# define _LIBCPP_SAFE_STATIC __attribute__((__require_constant_initialization__)) +#else +# define _LIBCPP_SAFE_STATIC +#endif + +#if !__has_builtin(__builtin_addressof) && _GNUC_VER < 700 +#define _LIBCPP_HAS_NO_BUILTIN_ADDRESSOF +#endif + +#if !__has_builtin(__builtin_is_constant_evaluated) && _GNUC_VER < 900 +#define _LIBCPP_HAS_NO_BUILTIN_IS_CONSTANT_EVALUATED +#endif + +#if !defined(_LIBCPP_HAS_NO_OFF_T_FUNCTIONS) +# if defined(_LIBCPP_MSVCRT) || defined(_NEWLIB_VERSION) +# define _LIBCPP_HAS_NO_OFF_T_FUNCTIONS +# endif +#endif + +#if __has_attribute(diagnose_if) && !defined(_LIBCPP_DISABLE_ADDITIONAL_DIAGNOSTICS) +# define _LIBCPP_DIAGNOSE_WARNING(...) \ + __attribute__((diagnose_if(__VA_ARGS__, "warning"))) +# define _LIBCPP_DIAGNOSE_ERROR(...) \ + __attribute__((diagnose_if(__VA_ARGS__, "error"))) +#else +# define _LIBCPP_DIAGNOSE_WARNING(...) +# define _LIBCPP_DIAGNOSE_ERROR(...) +#endif + +// Use a function like macro to imply that it must be followed by a semicolon +#if __cplusplus > 201402L && __has_cpp_attribute(fallthrough) +# define _LIBCPP_FALLTHROUGH() [[fallthrough]] +#elif __has_cpp_attribute(clang::fallthrough) +# define _LIBCPP_FALLTHROUGH() [[clang::fallthrough]] +#elif __has_attribute(fallthrough) || _GNUC_VER >= 700 +# define _LIBCPP_FALLTHROUGH() __attribute__((__fallthrough__)) +#else +# define _LIBCPP_FALLTHROUGH() ((void)0) +#endif + +#if __has_attribute(__nodebug__) +#define _LIBCPP_NODEBUG __attribute__((__nodebug__)) +#else +#define _LIBCPP_NODEBUG +#endif + +#ifndef _LIBCPP_NODEBUG_TYPE +#if __has_attribute(__nodebug__) && \ + (defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER >= 900) +#define _LIBCPP_NODEBUG_TYPE __attribute__((nodebug)) +#else +#define _LIBCPP_NODEBUG_TYPE +#endif +#endif // !defined(_LIBCPP_NODEBUG_TYPE) + +#if __has_attribute(__preferred_name__) +#define _LIBCPP_PREFERRED_NAME(x) __attribute__((__preferred_name__(x))) +#else +#define _LIBCPP_PREFERRED_NAME(x) +#endif + +#if defined(_LIBCPP_ABI_MICROSOFT) && \ + (defined(_LIBCPP_COMPILER_MSVC) || __has_declspec_attribute(empty_bases)) +# define _LIBCPP_DECLSPEC_EMPTY_BASES __declspec(empty_bases) +#else +# define _LIBCPP_DECLSPEC_EMPTY_BASES +#endif + +#if defined(_LIBCPP_ENABLE_CXX17_REMOVED_FEATURES) +#define _LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR +#define _LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS +#define _LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE +#define _LIBCPP_ENABLE_CXX17_REMOVED_BINDERS +#endif // _LIBCPP_ENABLE_CXX17_REMOVED_FEATURES + +#if !defined(__cpp_deduction_guides) || __cpp_deduction_guides < 201611 +#define _LIBCPP_HAS_NO_DEDUCTION_GUIDES +#endif + +#if !__has_keyword(__is_aggregate) && (_GNUC_VER_NEW < 7001) +#define _LIBCPP_HAS_NO_IS_AGGREGATE +#endif + +#if !defined(__cpp_coroutines) || __cpp_coroutines < 201703L +#define _LIBCPP_HAS_NO_COROUTINES +#endif + +#if !defined(__cpp_impl_three_way_comparison) || __cpp_impl_three_way_comparison < 201907L +#define _LIBCPP_HAS_NO_SPACESHIP_OPERATOR +#endif + +#if defined(_LIBCPP_COMPILER_IBM) +#define _LIBCPP_HAS_NO_PRAGMA_PUSH_POP_MACRO +#endif + +#if defined(_LIBCPP_HAS_NO_PRAGMA_PUSH_POP_MACRO) +# define _LIBCPP_PUSH_MACROS +# define _LIBCPP_POP_MACROS +#else + // Don't warn about macro conflicts when we can restore them at the + // end of the header. +# ifndef _LIBCPP_DISABLE_MACRO_CONFLICT_WARNINGS +# define _LIBCPP_DISABLE_MACRO_CONFLICT_WARNINGS +# endif +# if defined(_LIBCPP_COMPILER_MSVC) +# define _LIBCPP_PUSH_MACROS \ + __pragma(push_macro("min")) \ + __pragma(push_macro("max")) +# define _LIBCPP_POP_MACROS \ + __pragma(pop_macro("min")) \ + __pragma(pop_macro("max")) +# else +# define _LIBCPP_PUSH_MACROS \ + _Pragma("push_macro(\"min\")") \ + _Pragma("push_macro(\"max\")") +# define _LIBCPP_POP_MACROS \ + _Pragma("pop_macro(\"min\")") \ + _Pragma("pop_macro(\"max\")") +# endif +#endif // defined(_LIBCPP_HAS_NO_PRAGMA_PUSH_POP_MACRO) + +#ifndef _LIBCPP_NO_AUTO_LINK +# if defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_BUILDING_LIBRARY) +# if defined(_DLL) +# pragma comment(lib, "c++.lib") +# else +# pragma comment(lib, "libc++.lib") +# endif +# endif // defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_BUILDING_LIBRARY) +#endif // _LIBCPP_NO_AUTO_LINK + +#define _LIBCPP_UNUSED_VAR(x) ((void)(x)) + +// Configures the fopen close-on-exec mode character, if any. This string will +// be appended to any mode string used by fstream for fopen/fdopen. +// +// Not all platforms support this, but it helps avoid fd-leaks on platforms that +// do. +#if defined(__BIONIC__) +# define _LIBCPP_FOPEN_CLOEXEC_MODE "e" +#else +# define _LIBCPP_FOPEN_CLOEXEC_MODE +#endif + +#ifdef _LIBCPP_COMPILER_HAS_BUILTIN_CONSTANT_P +#define _LIBCPP_BUILTIN_CONSTANT_P(x) __builtin_constant_p(x) +#else +#define _LIBCPP_BUILTIN_CONSTANT_P(x) false +#endif + +// Support for _FILE_OFFSET_BITS=64 landed gradually in Android, so the full set +// of functions used in cstdio may not be available for low API levels when +// using 64-bit file offsets on LP32. +#if defined(__BIONIC__) && defined(__USE_FILE_OFFSET64) && __ANDROID_API__ < 24 +#define _LIBCPP_HAS_NO_FGETPOS_FSETPOS +#endif + +#if __has_attribute(init_priority) +# define _LIBCPP_INIT_PRIORITY_MAX __attribute__((init_priority(101))) +#else +# define _LIBCPP_INIT_PRIORITY_MAX #endif #endif // __cplusplus diff --git a/sdk/tlibcxx/include/__config_site.in b/sdk/tlibcxx/include/__config_site.in index 6c2b7bb4..ec4d410b 100644 --- a/sdk/tlibcxx/include/__config_site.in +++ b/sdk/tlibcxx/include/__config_site.in @@ -1,9 +1,8 @@ //===----------------------------------------------------------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// @@ -12,6 +11,9 @@ #cmakedefine _LIBCPP_ABI_VERSION @_LIBCPP_ABI_VERSION@ #cmakedefine _LIBCPP_ABI_UNSTABLE +#cmakedefine _LIBCPP_ABI_FORCE_ITANIUM +#cmakedefine _LIBCPP_ABI_FORCE_MICROSOFT +#cmakedefine _LIBCPP_HIDE_FROM_ABI_PER_TU_BY_DEFAULT #cmakedefine _LIBCPP_HAS_NO_GLOBAL_FILESYSTEM_NAMESPACE #cmakedefine _LIBCPP_HAS_NO_STDIN #cmakedefine _LIBCPP_HAS_NO_STDOUT @@ -20,5 +22,19 @@ #cmakedefine _LIBCPP_HAS_NO_THREAD_UNSAFE_C_FUNCTIONS #cmakedefine _LIBCPP_HAS_MUSL_LIBC #cmakedefine _LIBCPP_HAS_THREAD_API_PTHREAD +#cmakedefine _LIBCPP_HAS_THREAD_API_EXTERNAL +#cmakedefine _LIBCPP_HAS_THREAD_API_WIN32 +#cmakedefine _LIBCPP_HAS_THREAD_LIBRARY_EXTERNAL +#cmakedefine _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS +#cmakedefine _LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS +#cmakedefine _LIBCPP_NO_VCRUNTIME +#cmakedefine _LIBCPP_TYPEINFO_COMPARISON_IMPLEMENTATION @_LIBCPP_TYPEINFO_COMPARISON_IMPLEMENTATION@ +#cmakedefine _LIBCPP_ABI_NAMESPACE @_LIBCPP_ABI_NAMESPACE@ +#cmakedefine _LIBCPP_HAS_NO_FILESYSTEM_LIBRARY +#cmakedefine _LIBCPP_HAS_PARALLEL_ALGORITHMS +#cmakedefine _LIBCPP_HAS_NO_RANDOM_DEVICE +#cmakedefine _LIBCPP_HAS_NO_LOCALIZATION + +@_LIBCPP_ABI_DEFINES@ #endif // _LIBCPP_CONFIG_SITE diff --git a/sdk/tlibcxx/include/__debug b/sdk/tlibcxx/include/__debug index 80395974..8f55e08a 100644 --- a/sdk/tlibcxx/include/__debug +++ b/sdk/tlibcxx/include/__debug @@ -1,10 +1,9 @@ // -*- C++ -*- //===--------------------------- __debug ----------------------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// @@ -13,29 +12,77 @@ // Not supported. #include <__config> -#if !defined(_LIBCPP_SGX_CONFIG) +//#if !defined(_LIBCPP_SGX_CONFIG) + +#include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif -#if _LIBCPP_DEBUG_LEVEL >= 1 +#if defined(_LIBCPP_HAS_NO_NULLPTR) +# include +#endif + +#if _LIBCPP_DEBUG_LEVEL >= 1 || defined(_LIBCPP_BUILDING_LIBRARY) # include # include # include -# ifndef _LIBCPP_ASSERT -# define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : (_VSTD::fprintf(stderr, "%s\n", m), _VSTD::abort())) -# endif #endif -#ifndef _LIBCPP_ASSERT -# define _LIBCPP_ASSERT(x, m) ((void)0) +#if _LIBCPP_DEBUG_LEVEL == 0 +# define _LIBCPP_DEBUG_ASSERT(x, m) ((void)0) +# define _LIBCPP_ASSERT_IMPL(x, m) ((void)0) +#elif _LIBCPP_DEBUG_LEVEL == 1 +# define _LIBCPP_DEBUG_ASSERT(x, m) ((void)0) +# define _LIBCPP_ASSERT_IMPL(x, m) ((x) ? (void)0 : _VSTD::__libcpp_debug_function(_VSTD::__libcpp_debug_info(__FILE__, __LINE__, #x, m))) +#elif _LIBCPP_DEBUG_LEVEL == 2 +# define _LIBCPP_DEBUG_ASSERT(x, m) _LIBCPP_ASSERT(x, m) +# define _LIBCPP_ASSERT_IMPL(x, m) ((x) ? (void)0 : _VSTD::__libcpp_debug_function(_VSTD::__libcpp_debug_info(__FILE__, __LINE__, #x, m))) +#else +# error _LIBCPP_DEBUG_LEVEL must be one of 0, 1, 2 #endif -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if !defined(_LIBCPP_ASSERT) +# define _LIBCPP_ASSERT(x, m) _LIBCPP_ASSERT_IMPL(x, m) +#endif _LIBCPP_BEGIN_NAMESPACE_STD +struct _LIBCPP_TEMPLATE_VIS __libcpp_debug_info { + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR + __libcpp_debug_info() + : __file_(nullptr), __line_(-1), __pred_(nullptr), __msg_(nullptr) {} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR + __libcpp_debug_info(const char* __f, int __l, const char* __p, const char* __m) + : __file_(__f), __line_(__l), __pred_(__p), __msg_(__m) {} + + _LIBCPP_FUNC_VIS string what() const; + + const char* __file_; + int __line_; + const char* __pred_; + const char* __msg_; +}; + +/// __libcpp_debug_function_type - The type of the assertion failure handler. +typedef void(*__libcpp_debug_function_type)(__libcpp_debug_info const&); + +/// __libcpp_debug_function - The handler function called when a _LIBCPP_ASSERT +/// fails. +extern _LIBCPP_EXPORTED_FROM_ABI __libcpp_debug_function_type __libcpp_debug_function; + +/// __libcpp_abort_debug_function - A debug handler that aborts when called. +_LIBCPP_NORETURN _LIBCPP_FUNC_VIS +void __libcpp_abort_debug_function(__libcpp_debug_info const&); + +/// __libcpp_set_debug_function - Set the debug handler to the specified +/// function. +_LIBCPP_FUNC_VIS +bool __libcpp_set_debug_function(__libcpp_debug_function_type __func); + +#if _LIBCPP_DEBUG_LEVEL == 2 || defined(_LIBCPP_BUILDING_LIBRARY) + struct _LIBCPP_TYPE_VIS __c_node; struct _LIBCPP_TYPE_VIS __i_node @@ -44,7 +91,7 @@ struct _LIBCPP_TYPE_VIS __i_node __i_node* __next_; __c_node* __c_; -#ifndef _LIBCPP_HAS_NO_DELETED_FUNCTIONS +#ifndef _LIBCPP_CXX03_LANG __i_node(const __i_node&) = delete; __i_node& operator=(const __i_node&) = delete; #else @@ -67,7 +114,7 @@ struct _LIBCPP_TYPE_VIS __c_node __i_node** end_; __i_node** cap_; -#ifndef _LIBCPP_HAS_NO_DELETED_FUNCTIONS +#ifndef _LIBCPP_CXX03_LANG __c_node(const __c_node&) = delete; __c_node& operator=(const __c_node&) = delete; #else @@ -104,7 +151,7 @@ struct _C_node }; template -bool +inline bool _C_node<_Cont>::__dereferenceable(const void* __i) const { typedef typename _Cont::const_iterator iterator; @@ -114,7 +161,7 @@ _C_node<_Cont>::__dereferenceable(const void* __i) const } template -bool +inline bool _C_node<_Cont>::__decrementable(const void* __i) const { typedef typename _Cont::const_iterator iterator; @@ -124,7 +171,7 @@ _C_node<_Cont>::__decrementable(const void* __i) const } template -bool +inline bool _C_node<_Cont>::__addable(const void* __i, ptrdiff_t __n) const { typedef typename _Cont::const_iterator iterator; @@ -134,7 +181,7 @@ _C_node<_Cont>::__addable(const void* __i, ptrdiff_t __n) const } template -bool +inline bool _C_node<_Cont>::__subscriptable(const void* __i, ptrdiff_t __n) const { typedef typename _Cont::const_iterator iterator; @@ -154,7 +201,7 @@ class _LIBCPP_TYPE_VIS __libcpp_db __libcpp_db(); public: -#ifndef _LIBCPP_HAS_NO_DELETED_FUNCTIONS +#ifndef _LIBCPP_CXX03_LANG __libcpp_db(const __libcpp_db&) = delete; __libcpp_db& operator=(const __libcpp_db&) = delete; #else @@ -173,16 +220,22 @@ public: __db_c_const_iterator __c_end() const; __db_i_const_iterator __i_end() const; + typedef __c_node*(_InsertConstruct)(void*, void*, __c_node*); + + template + _LIBCPP_INLINE_VISIBILITY static __c_node* __create_C_node(void *__mem, void *__c, __c_node *__next) { + return ::new (__mem) _C_node<_Cont>(__c, __next); + } + template _LIBCPP_INLINE_VISIBILITY void __insert_c(_Cont* __c) { - __c_node* __n = __insert_c(static_cast(__c)); - ::new(__n) _C_node<_Cont>(__n->__c_, __n->__next_); + __insert_c(static_cast(__c), &__create_C_node<_Cont>); } void __insert_i(void* __i); - __c_node* __insert_c(void* __c); + void __insert_c(void* __c, _InsertConstruct* __fn); void __erase_c(void* __c); void __insert_ic(void* __i, const void* __c); @@ -216,11 +269,10 @@ _LIBCPP_FUNC_VIS __libcpp_db* __get_db(); _LIBCPP_FUNC_VIS const __libcpp_db* __get_const_db(); +#endif // _LIBCPP_DEBUG_LEVEL == 2 || defined(_LIBCPP_BUILDING_LIBRARY) + _LIBCPP_END_NAMESPACE_STD -#endif - -#endif // !defined(_LIBCPP_SGX_CONFIG) +//#endif // !defined(_LIBCPP_SGX_CONFIG) #endif // _LIBCPP_DEBUG_H - diff --git a/sdk/tlibcxx/include/__errc b/sdk/tlibcxx/include/__errc new file mode 100644 index 00000000..a8ad29f3 --- /dev/null +++ b/sdk/tlibcxx/include/__errc @@ -0,0 +1,217 @@ +// -*- C++ -*- +//===---------------------------- __errc ----------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ERRC +#define _LIBCPP___ERRC + +/* + system_error synopsis + +namespace std +{ + +enum class errc +{ + address_family_not_supported, // EAFNOSUPPORT + address_in_use, // EADDRINUSE + address_not_available, // EADDRNOTAVAIL + already_connected, // EISCONN + argument_list_too_long, // E2BIG + argument_out_of_domain, // EDOM + bad_address, // EFAULT + bad_file_descriptor, // EBADF + bad_message, // EBADMSG + broken_pipe, // EPIPE + connection_aborted, // ECONNABORTED + connection_already_in_progress, // EALREADY + connection_refused, // ECONNREFUSED + connection_reset, // ECONNRESET + cross_device_link, // EXDEV + destination_address_required, // EDESTADDRREQ + device_or_resource_busy, // EBUSY + directory_not_empty, // ENOTEMPTY + executable_format_error, // ENOEXEC + file_exists, // EEXIST + file_too_large, // EFBIG + filename_too_long, // ENAMETOOLONG + function_not_supported, // ENOSYS + host_unreachable, // EHOSTUNREACH + identifier_removed, // EIDRM + illegal_byte_sequence, // EILSEQ + inappropriate_io_control_operation, // ENOTTY + interrupted, // EINTR + invalid_argument, // EINVAL + invalid_seek, // ESPIPE + io_error, // EIO + is_a_directory, // EISDIR + message_size, // EMSGSIZE + network_down, // ENETDOWN + network_reset, // ENETRESET + network_unreachable, // ENETUNREACH + no_buffer_space, // ENOBUFS + no_child_process, // ECHILD + no_link, // ENOLINK + no_lock_available, // ENOLCK + no_message_available, // ENODATA + no_message, // ENOMSG + no_protocol_option, // ENOPROTOOPT + no_space_on_device, // ENOSPC + no_stream_resources, // ENOSR + no_such_device_or_address, // ENXIO + no_such_device, // ENODEV + no_such_file_or_directory, // ENOENT + no_such_process, // ESRCH + not_a_directory, // ENOTDIR + not_a_socket, // ENOTSOCK + not_a_stream, // ENOSTR + not_connected, // ENOTCONN + not_enough_memory, // ENOMEM + not_supported, // ENOTSUP + operation_canceled, // ECANCELED + operation_in_progress, // EINPROGRESS + operation_not_permitted, // EPERM + operation_not_supported, // EOPNOTSUPP + operation_would_block, // EWOULDBLOCK + owner_dead, // EOWNERDEAD + permission_denied, // EACCES + protocol_error, // EPROTO + protocol_not_supported, // EPROTONOSUPPORT + read_only_file_system, // EROFS + resource_deadlock_would_occur, // EDEADLK + resource_unavailable_try_again, // EAGAIN + result_out_of_range, // ERANGE + state_not_recoverable, // ENOTRECOVERABLE + stream_timeout, // ETIME + text_file_busy, // ETXTBSY + timed_out, // ETIMEDOUT + too_many_files_open_in_system, // ENFILE + too_many_files_open, // EMFILE + too_many_links, // EMLINK + too_many_symbolic_link_levels, // ELOOP + value_too_large, // EOVERFLOW + wrong_protocol_type // EPROTOTYPE +}; + +*/ + +#include <__config> +#include + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +#pragma GCC system_header +#endif + +_LIBCPP_BEGIN_NAMESPACE_STD + +// Some error codes are not present on all platforms, so we provide equivalents +// for them: + +//enum class errc +_LIBCPP_DECLARE_STRONG_ENUM(errc) +{ + address_family_not_supported = EAFNOSUPPORT, + address_in_use = EADDRINUSE, + address_not_available = EADDRNOTAVAIL, + already_connected = EISCONN, + argument_list_too_long = E2BIG, + argument_out_of_domain = EDOM, + bad_address = EFAULT, + bad_file_descriptor = EBADF, + bad_message = EBADMSG, + broken_pipe = EPIPE, + connection_aborted = ECONNABORTED, + connection_already_in_progress = EALREADY, + connection_refused = ECONNREFUSED, + connection_reset = ECONNRESET, + cross_device_link = EXDEV, + destination_address_required = EDESTADDRREQ, + device_or_resource_busy = EBUSY, + directory_not_empty = ENOTEMPTY, + executable_format_error = ENOEXEC, + file_exists = EEXIST, + file_too_large = EFBIG, + filename_too_long = ENAMETOOLONG, + function_not_supported = ENOSYS, + host_unreachable = EHOSTUNREACH, + identifier_removed = EIDRM, + illegal_byte_sequence = EILSEQ, + inappropriate_io_control_operation = ENOTTY, + interrupted = EINTR, + invalid_argument = EINVAL, + invalid_seek = ESPIPE, + io_error = EIO, + is_a_directory = EISDIR, + message_size = EMSGSIZE, + network_down = ENETDOWN, + network_reset = ENETRESET, + network_unreachable = ENETUNREACH, + no_buffer_space = ENOBUFS, + no_child_process = ECHILD, + no_link = ENOLINK, + no_lock_available = ENOLCK, +#ifdef ENODATA + no_message_available = ENODATA, +#else + no_message_available = ENOMSG, +#endif + no_message = ENOMSG, + no_protocol_option = ENOPROTOOPT, + no_space_on_device = ENOSPC, +#ifdef ENOSR + no_stream_resources = ENOSR, +#else + no_stream_resources = ENOMEM, +#endif + no_such_device_or_address = ENXIO, + no_such_device = ENODEV, + no_such_file_or_directory = ENOENT, + no_such_process = ESRCH, + not_a_directory = ENOTDIR, + not_a_socket = ENOTSOCK, +#ifdef ENOSTR + not_a_stream = ENOSTR, +#else + not_a_stream = EINVAL, +#endif + not_connected = ENOTCONN, + not_enough_memory = ENOMEM, + not_supported = ENOTSUP, + operation_canceled = ECANCELED, + operation_in_progress = EINPROGRESS, + operation_not_permitted = EPERM, + operation_not_supported = EOPNOTSUPP, + operation_would_block = EWOULDBLOCK, + owner_dead = EOWNERDEAD, + permission_denied = EACCES, + protocol_error = EPROTO, + protocol_not_supported = EPROTONOSUPPORT, + read_only_file_system = EROFS, + resource_deadlock_would_occur = EDEADLK, + resource_unavailable_try_again = EAGAIN, + result_out_of_range = ERANGE, + state_not_recoverable = ENOTRECOVERABLE, +#ifdef ETIME + stream_timeout = ETIME, +#else + stream_timeout = ETIMEDOUT, +#endif + text_file_busy = ETXTBSY, + timed_out = ETIMEDOUT, + too_many_files_open_in_system = ENFILE, + too_many_files_open = EMFILE, + too_many_links = EMLINK, + too_many_symbolic_link_levels = ELOOP, + value_too_large = EOVERFLOW, + wrong_protocol_type = EPROTOTYPE +}; +_LIBCPP_DECLARE_STRONG_ENUM_EPILOG(errc) + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP___ERRC diff --git a/sdk/tlibcxx/include/__functional_03 b/sdk/tlibcxx/include/__functional_03 index 4edbb099..96164806 100644 --- a/sdk/tlibcxx/include/__functional_03 +++ b/sdk/tlibcxx/include/__functional_03 @@ -1,10 +1,9 @@ // -*- C++ -*- //===----------------------------------------------------------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// @@ -105,7 +104,7 @@ class __func<_Fp, _Alloc, _Rp()> { __compressed_pair<_Fp, _Alloc> __f_; public: - explicit __func(_Fp __f) : __f_(_VSTD::move(__f)) {} + explicit __func(_Fp __f) : __f_(_VSTD::move(__f), __default_init_tag()) {} explicit __func(_Fp __f, _Alloc __a) : __f_(_VSTD::move(__f), _VSTD::move(__a)) {} virtual __base<_Rp()>* __clone() const; virtual void __clone(__base<_Rp()>*) const; @@ -127,7 +126,7 @@ __func<_Fp, _Alloc, _Rp()>::__clone() const _Ap __a(__f_.second()); typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__func, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) __func(__f_.first(), _Alloc(__a)); + ::new ((void*)__hold.get()) __func(__f_.first(), _Alloc(__a)); return __hold.release(); } @@ -135,7 +134,7 @@ template void __func<_Fp, _Alloc, _Rp()>::__clone(__base<_Rp()>* __p) const { - ::new (__p) __func(__f_.first(), __f_.second()); + ::new ((void*)__p) __func(__f_.first(), __f_.second()); } template @@ -190,7 +189,7 @@ class __func<_Fp, _Alloc, _Rp(_A0)> { __compressed_pair<_Fp, _Alloc> __f_; public: - _LIBCPP_INLINE_VISIBILITY explicit __func(_Fp __f) : __f_(_VSTD::move(__f)) {} + _LIBCPP_INLINE_VISIBILITY explicit __func(_Fp __f) : __f_(_VSTD::move(__f), __default_init_tag()) {} _LIBCPP_INLINE_VISIBILITY explicit __func(_Fp __f, _Alloc __a) : __f_(_VSTD::move(__f), _VSTD::move(__a)) {} virtual __base<_Rp(_A0)>* __clone() const; @@ -213,7 +212,7 @@ __func<_Fp, _Alloc, _Rp(_A0)>::__clone() const _Ap __a(__f_.second()); typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__func, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) __func(__f_.first(), _Alloc(__a)); + ::new ((void*)__hold.get()) __func(__f_.first(), _Alloc(__a)); return __hold.release(); } @@ -221,7 +220,7 @@ template void __func<_Fp, _Alloc, _Rp(_A0)>::__clone(__base<_Rp(_A0)>* __p) const { - ::new (__p) __func(__f_.first(), __f_.second()); + ::new ((void*)__p) __func(__f_.first(), __f_.second()); } template @@ -276,7 +275,7 @@ class __func<_Fp, _Alloc, _Rp(_A0, _A1)> { __compressed_pair<_Fp, _Alloc> __f_; public: - _LIBCPP_INLINE_VISIBILITY explicit __func(_Fp __f) : __f_(_VSTD::move(__f)) {} + _LIBCPP_INLINE_VISIBILITY explicit __func(_Fp __f) : __f_(_VSTD::move(__f), __default_init_tag()) {} _LIBCPP_INLINE_VISIBILITY explicit __func(_Fp __f, _Alloc __a) : __f_(_VSTD::move(__f), _VSTD::move(__a)) {} virtual __base<_Rp(_A0, _A1)>* __clone() const; @@ -299,7 +298,7 @@ __func<_Fp, _Alloc, _Rp(_A0, _A1)>::__clone() const _Ap __a(__f_.second()); typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__func, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) __func(__f_.first(), _Alloc(__a)); + ::new ((void*)__hold.get()) __func(__f_.first(), _Alloc(__a)); return __hold.release(); } @@ -307,7 +306,7 @@ template void __func<_Fp, _Alloc, _Rp(_A0, _A1)>::__clone(__base<_Rp(_A0, _A1)>* __p) const { - ::new (__p) __func(__f_.first(), __f_.second()); + ::new ((void*)__p) __func(__f_.first(), __f_.second()); } template @@ -362,7 +361,7 @@ class __func<_Fp, _Alloc, _Rp(_A0, _A1, _A2)> { __compressed_pair<_Fp, _Alloc> __f_; public: - _LIBCPP_INLINE_VISIBILITY explicit __func(_Fp __f) : __f_(_VSTD::move(__f)) {} + _LIBCPP_INLINE_VISIBILITY explicit __func(_Fp __f) : __f_(_VSTD::move(__f), __default_init_tag()) {} _LIBCPP_INLINE_VISIBILITY explicit __func(_Fp __f, _Alloc __a) : __f_(_VSTD::move(__f), _VSTD::move(__a)) {} virtual __base<_Rp(_A0, _A1, _A2)>* __clone() const; @@ -385,7 +384,7 @@ __func<_Fp, _Alloc, _Rp(_A0, _A1, _A2)>::__clone() const _Ap __a(__f_.second()); typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__func, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) __func(__f_.first(), _Alloc(__a)); + ::new ((void*)__hold.get()) __func(__f_.first(), _Alloc(__a)); return __hold.release(); } @@ -393,7 +392,7 @@ template void __func<_Fp, _Alloc, _Rp(_A0, _A1, _A2)>::__clone(__base<_Rp(_A0, _A1, _A2)>* __p) const { - ::new (__p) __func(__f_.first(), __f_.second()); + ::new ((void*)__p) __func(__f_.first(), __f_.second()); } template @@ -445,7 +444,7 @@ __func<_Fp, _Alloc, _Rp(_A0, _A1, _A2)>::target_type() const } // __function template -class _LIBCPP_TYPE_VIS_ONLY function<_Rp()> +class _LIBCPP_TEMPLATE_VIS function<_Rp()> { typedef __function::__base<_Rp()> __base; aligned_storage<3*sizeof(void*)>::type __buf_; @@ -555,7 +554,7 @@ function<_Rp()>::function(_Fp __f, if (sizeof(_FF) <= sizeof(__buf_)) { __f_ = (__base*)&__buf_; - ::new (__f_) _FF(__f); + ::new ((void*)__f_) _FF(__f); } else { @@ -563,7 +562,7 @@ function<_Rp()>::function(_Fp __f, _Ap __a; typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) _FF(__f, allocator<_Fp>(__a)); + ::new ((void*)__hold.get()) _FF(__f, allocator<_Fp>(__a)); __f_ = __hold.release(); } } @@ -582,7 +581,7 @@ function<_Rp()>::function(allocator_arg_t, const _Alloc& __a0, _Fp __f, if (sizeof(_FF) <= sizeof(__buf_)) { __f_ = (__base*)&__buf_; - ::new (__f_) _FF(__f, __a0); + ::new ((void*)__f_) _FF(__f, __a0); } else { @@ -590,7 +589,7 @@ function<_Rp()>::function(allocator_arg_t, const _Alloc& __a0, _Fp __f, _Ap __a(__a0); typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) _FF(__f, _Alloc(__a)); + ::new ((void*)__hold.get()) _FF(__f, _Alloc(__a)); __f_ = __hold.release(); } } @@ -600,7 +599,10 @@ template function<_Rp()>& function<_Rp()>::operator=(const function& __f) { - function(__f).swap(*this); + if (__f) + function(__f).swap(*this); + else + *this = nullptr; return *this; } @@ -608,11 +610,12 @@ template function<_Rp()>& function<_Rp()>::operator=(nullptr_t) { - if (__f_ == (__base*)&__buf_) - __f_->destroy(); - else if (__f_) - __f_->destroy_deallocate(); + __base* __t = __f_; __f_ = 0; + if (__t == (__base*)&__buf_) + __t->destroy(); + else if (__t) + __t->destroy_deallocate(); return *this; } @@ -642,6 +645,8 @@ template void function<_Rp()>::swap(function& __f) { + if (_VSTD::addressof(__f) == this) + return; if (__f_ == (__base*)&__buf_ && __f.__f_ == (__base*)&__f.__buf_) { typename aligned_storage::type __tempbuf; @@ -679,10 +684,8 @@ template _Rp function<_Rp()>::operator()() const { -#ifndef _LIBCPP_NO_EXCEPTIONS if (__f_ == 0) - throw bad_function_call(); -#endif // _LIBCPP_NO_EXCEPTIONS + __throw_bad_function_call(); return (*__f_)(); } @@ -704,7 +707,7 @@ function<_Rp()>::target() { if (__f_ == 0) return (_Tp*)0; - return (_Tp*)__f_->target(typeid(_Tp)); + return (_Tp*) const_cast(__f_->target(typeid(_Tp))); } template @@ -720,7 +723,7 @@ function<_Rp()>::target() const #endif // _LIBCPP_NO_RTTI template -class _LIBCPP_TYPE_VIS_ONLY function<_Rp(_A0)> +class _LIBCPP_TEMPLATE_VIS function<_Rp(_A0)> : public unary_function<_A0, _Rp> { typedef __function::__base<_Rp(_A0)> __base; @@ -831,7 +834,7 @@ function<_Rp(_A0)>::function(_Fp __f, if (sizeof(_FF) <= sizeof(__buf_)) { __f_ = (__base*)&__buf_; - ::new (__f_) _FF(__f); + ::new ((void*)__f_) _FF(__f); } else { @@ -839,7 +842,7 @@ function<_Rp(_A0)>::function(_Fp __f, _Ap __a; typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) _FF(__f, allocator<_Fp>(__a)); + ::new ((void*)__hold.get()) _FF(__f, allocator<_Fp>(__a)); __f_ = __hold.release(); } } @@ -858,7 +861,7 @@ function<_Rp(_A0)>::function(allocator_arg_t, const _Alloc& __a0, _Fp __f, if (sizeof(_FF) <= sizeof(__buf_)) { __f_ = (__base*)&__buf_; - ::new (__f_) _FF(__f, __a0); + ::new ((void*)__f_) _FF(__f, __a0); } else { @@ -866,7 +869,7 @@ function<_Rp(_A0)>::function(allocator_arg_t, const _Alloc& __a0, _Fp __f, _Ap __a(__a0); typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) _FF(__f, _Alloc(__a)); + ::new ((void*)__hold.get()) _FF(__f, _Alloc(__a)); __f_ = __hold.release(); } } @@ -876,7 +879,10 @@ template function<_Rp(_A0)>& function<_Rp(_A0)>::operator=(const function& __f) { - function(__f).swap(*this); + if (__f) + function(__f).swap(*this); + else + *this = nullptr; return *this; } @@ -884,11 +890,12 @@ template function<_Rp(_A0)>& function<_Rp(_A0)>::operator=(nullptr_t) { - if (__f_ == (__base*)&__buf_) - __f_->destroy(); - else if (__f_) - __f_->destroy_deallocate(); + __base* __t = __f_; __f_ = 0; + if (__t == (__base*)&__buf_) + __t->destroy(); + else if (__t) + __t->destroy_deallocate(); return *this; } @@ -918,6 +925,8 @@ template void function<_Rp(_A0)>::swap(function& __f) { + if (_VSTD::addressof(__f) == this) + return; if (__f_ == (__base*)&__buf_ && __f.__f_ == (__base*)&__f.__buf_) { typename aligned_storage::type __tempbuf; @@ -955,10 +964,8 @@ template _Rp function<_Rp(_A0)>::operator()(_A0 __a0) const { -#ifndef _LIBCPP_NO_EXCEPTIONS if (__f_ == 0) - throw bad_function_call(); -#endif // _LIBCPP_NO_EXCEPTIONS + __throw_bad_function_call(); return (*__f_)(__a0); } @@ -980,7 +987,7 @@ function<_Rp(_A0)>::target() { if (__f_ == 0) return (_Tp*)0; - return (_Tp*)__f_->target(typeid(_Tp)); + return (_Tp*) const_cast(__f_->target(typeid(_Tp))); } template @@ -996,7 +1003,7 @@ function<_Rp(_A0)>::target() const #endif // _LIBCPP_NO_RTTI template -class _LIBCPP_TYPE_VIS_ONLY function<_Rp(_A0, _A1)> +class _LIBCPP_TEMPLATE_VIS function<_Rp(_A0, _A1)> : public binary_function<_A0, _A1, _Rp> { typedef __function::__base<_Rp(_A0, _A1)> __base; @@ -1107,7 +1114,7 @@ function<_Rp(_A0, _A1)>::function(_Fp __f, if (sizeof(_FF) <= sizeof(__buf_)) { __f_ = (__base*)&__buf_; - ::new (__f_) _FF(__f); + ::new ((void*)__f_) _FF(__f); } else { @@ -1115,7 +1122,7 @@ function<_Rp(_A0, _A1)>::function(_Fp __f, _Ap __a; typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) _FF(__f, allocator<_Fp>(__a)); + ::new ((void*)__hold.get()) _FF(__f, allocator<_Fp>(__a)); __f_ = __hold.release(); } } @@ -1134,7 +1141,7 @@ function<_Rp(_A0, _A1)>::function(allocator_arg_t, const _Alloc& __a0, _Fp __f, if (sizeof(_FF) <= sizeof(__buf_)) { __f_ = (__base*)&__buf_; - ::new (__f_) _FF(__f, __a0); + ::new ((void*)__f_) _FF(__f, __a0); } else { @@ -1142,7 +1149,7 @@ function<_Rp(_A0, _A1)>::function(allocator_arg_t, const _Alloc& __a0, _Fp __f, _Ap __a(__a0); typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) _FF(__f, _Alloc(__a)); + ::new ((void*)__hold.get()) _FF(__f, _Alloc(__a)); __f_ = __hold.release(); } } @@ -1152,7 +1159,10 @@ template function<_Rp(_A0, _A1)>& function<_Rp(_A0, _A1)>::operator=(const function& __f) { - function(__f).swap(*this); + if (__f) + function(__f).swap(*this); + else + *this = nullptr; return *this; } @@ -1160,11 +1170,12 @@ template function<_Rp(_A0, _A1)>& function<_Rp(_A0, _A1)>::operator=(nullptr_t) { - if (__f_ == (__base*)&__buf_) - __f_->destroy(); - else if (__f_) - __f_->destroy_deallocate(); + __base* __t = __f_; __f_ = 0; + if (__t == (__base*)&__buf_) + __t->destroy(); + else if (__t) + __t->destroy_deallocate(); return *this; } @@ -1194,6 +1205,8 @@ template void function<_Rp(_A0, _A1)>::swap(function& __f) { + if (_VSTD::addressof(__f) == this) + return; if (__f_ == (__base*)&__buf_ && __f.__f_ == (__base*)&__f.__buf_) { typename aligned_storage::type __tempbuf; @@ -1231,10 +1244,8 @@ template _Rp function<_Rp(_A0, _A1)>::operator()(_A0 __a0, _A1 __a1) const { -#ifndef _LIBCPP_NO_EXCEPTIONS if (__f_ == 0) - throw bad_function_call(); -#endif // _LIBCPP_NO_EXCEPTIONS + __throw_bad_function_call(); return (*__f_)(__a0, __a1); } @@ -1256,7 +1267,7 @@ function<_Rp(_A0, _A1)>::target() { if (__f_ == 0) return (_Tp*)0; - return (_Tp*)__f_->target(typeid(_Tp)); + return (_Tp*) const_cast(__f_->target(typeid(_Tp))); } template @@ -1272,7 +1283,7 @@ function<_Rp(_A0, _A1)>::target() const #endif // _LIBCPP_NO_RTTI template -class _LIBCPP_TYPE_VIS_ONLY function<_Rp(_A0, _A1, _A2)> +class _LIBCPP_TEMPLATE_VIS function<_Rp(_A0, _A1, _A2)> { typedef __function::__base<_Rp(_A0, _A1, _A2)> __base; aligned_storage<3*sizeof(void*)>::type __buf_; @@ -1383,7 +1394,7 @@ function<_Rp(_A0, _A1, _A2)>::function(_Fp __f, if (sizeof(_FF) <= sizeof(__buf_)) { __f_ = (__base*)&__buf_; - ::new (__f_) _FF(__f); + ::new ((void*)__f_) _FF(__f); } else { @@ -1391,7 +1402,7 @@ function<_Rp(_A0, _A1, _A2)>::function(_Fp __f, _Ap __a; typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) _FF(__f, allocator<_Fp>(__a)); + ::new ((void*)__hold.get()) _FF(__f, allocator<_Fp>(__a)); __f_ = __hold.release(); } } @@ -1410,7 +1421,7 @@ function<_Rp(_A0, _A1, _A2)>::function(allocator_arg_t, const _Alloc& __a0, _Fp if (sizeof(_FF) <= sizeof(__buf_)) { __f_ = (__base*)&__buf_; - ::new (__f_) _FF(__f, __a0); + ::new ((void*)__f_) _FF(__f, __a0); } else { @@ -1418,7 +1429,7 @@ function<_Rp(_A0, _A1, _A2)>::function(allocator_arg_t, const _Alloc& __a0, _Fp _Ap __a(__a0); typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); - ::new (__hold.get()) _FF(__f, _Alloc(__a)); + ::new ((void*)__hold.get()) _FF(__f, _Alloc(__a)); __f_ = __hold.release(); } } @@ -1428,7 +1439,10 @@ template function<_Rp(_A0, _A1, _A2)>& function<_Rp(_A0, _A1, _A2)>::operator=(const function& __f) { - function(__f).swap(*this); + if (__f) + function(__f).swap(*this); + else + *this = nullptr; return *this; } @@ -1436,11 +1450,12 @@ template function<_Rp(_A0, _A1, _A2)>& function<_Rp(_A0, _A1, _A2)>::operator=(nullptr_t) { - if (__f_ == (__base*)&__buf_) - __f_->destroy(); - else if (__f_) - __f_->destroy_deallocate(); + __base* __t = __f_; __f_ = 0; + if (__t == (__base*)&__buf_) + __t->destroy(); + else if (__t) + __t->destroy_deallocate(); return *this; } @@ -1470,6 +1485,8 @@ template void function<_Rp(_A0, _A1, _A2)>::swap(function& __f) { + if (_VSTD::addressof(__f) == this) + return; if (__f_ == (__base*)&__buf_ && __f.__f_ == (__base*)&__f.__buf_) { typename aligned_storage::type __tempbuf; @@ -1507,10 +1524,8 @@ template _Rp function<_Rp(_A0, _A1, _A2)>::operator()(_A0 __a0, _A1 __a1, _A2 __a2) const { -#ifndef _LIBCPP_NO_EXCEPTIONS if (__f_ == 0) - throw bad_function_call(); -#endif // _LIBCPP_NO_EXCEPTIONS + __throw_bad_function_call(); return (*__f_)(__a0, __a1, __a2); } @@ -1532,7 +1547,7 @@ function<_Rp(_A0, _A1, _A2)>::target() { if (__f_ == 0) return (_Tp*)0; - return (_Tp*)__f_->target(typeid(_Tp)); + return (_Tp*) const_cast(__f_->target(typeid(_Tp))); } template diff --git a/sdk/tlibcxx/include/__functional_base b/sdk/tlibcxx/include/__functional_base index 1a08ea29..9d93ddae 100644 --- a/sdk/tlibcxx/include/__functional_base +++ b/sdk/tlibcxx/include/__functional_base @@ -1,10 +1,9 @@ // -*- C++ -*- //===----------------------------------------------------------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// @@ -16,6 +15,8 @@ #include #include #include +#include +#include <__memory/base.h> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header @@ -23,15 +24,8 @@ _LIBCPP_BEGIN_NAMESPACE_STD -template -struct _LIBCPP_TYPE_VIS_ONLY unary_function -{ - typedef _Arg argument_type; - typedef _Result result_type; -}; - template -struct _LIBCPP_TYPE_VIS_ONLY binary_function +struct _LIBCPP_TEMPLATE_VIS binary_function { typedef _Arg1 first_argument_type; typedef _Arg2 second_argument_type; @@ -54,18 +48,18 @@ template #else template #endif -struct _LIBCPP_TYPE_VIS_ONLY less : binary_function<_Tp, _Tp, bool> +struct _LIBCPP_TEMPLATE_VIS less : binary_function<_Tp, _Tp, bool> { - _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY + _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY bool operator()(const _Tp& __x, const _Tp& __y) const {return __x < __y;} }; #if _LIBCPP_STD_VER > 11 template <> -struct _LIBCPP_TYPE_VIS_ONLY less +struct _LIBCPP_TEMPLATE_VIS less { - template + template _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) < _VSTD::forward<_T2>(__u))) @@ -132,7 +126,7 @@ struct __weak_result_type_imp // bool is true : public __maybe_derive_from_unary_function<_Tp>, public __maybe_derive_from_binary_function<_Tp> { - typedef typename _Tp::result_type result_type; + typedef _LIBCPP_NODEBUG_TYPE typename _Tp::result_type result_type; }; template @@ -153,19 +147,19 @@ struct __weak_result_type template struct __weak_result_type<_Rp ()> { - typedef _Rp result_type; + typedef _LIBCPP_NODEBUG_TYPE _Rp result_type; }; template struct __weak_result_type<_Rp (&)()> { - typedef _Rp result_type; + typedef _LIBCPP_NODEBUG_TYPE _Rp result_type; }; template struct __weak_result_type<_Rp (*)()> { - typedef _Rp result_type; + typedef _LIBCPP_NODEBUG_TYPE _Rp result_type; }; // 1 argument case @@ -257,7 +251,7 @@ struct __weak_result_type<_Rp (_Cp::*)(_A1) const volatile> }; -#ifndef _LIBCPP_HAS_NO_VARIADICS +#ifndef _LIBCPP_CXX03_LANG // 3 or more arguments template @@ -302,14 +296,10 @@ struct __weak_result_type<_Rp (_Cp::*)(_A1, _A2, _A3...) const volatile> typedef _Rp result_type; }; -#endif // _LIBCPP_HAS_NO_VARIADICS - -#ifndef _LIBCPP_CXX03_LANG - template struct __invoke_return { - typedef decltype(__invoke(_VSTD::declval<_Tp>(), _VSTD::declval<_Args>()...)) type; + typedef decltype(_VSTD::__invoke(declval<_Tp>(), declval<_Args>()...)) type; }; #else // defined(_LIBCPP_CXX03_LANG) @@ -319,70 +309,70 @@ struct __invoke_return #endif // !defined(_LIBCPP_CXX03_LANG) -template +template ::value> struct __invoke_void_return_wrapper { -#ifndef _LIBCPP_HAS_NO_VARIADICS +#ifndef _LIBCPP_CXX03_LANG template static _Ret __call(_Args&&... __args) { - return __invoke(_VSTD::forward<_Args>(__args)...); + return _VSTD::__invoke(_VSTD::forward<_Args>(__args)...); } #else template static _Ret __call(_Fn __f) { - return __invoke(__f); + return _VSTD::__invoke(__f); } template static _Ret __call(_Fn __f, _A0& __a0) { - return __invoke(__f, __a0); + return _VSTD::__invoke(__f, __a0); } template static _Ret __call(_Fn __f, _A0& __a0, _A1& __a1) { - return __invoke(__f, __a0, __a1); + return _VSTD::__invoke(__f, __a0, __a1); } template static _Ret __call(_Fn __f, _A0& __a0, _A1& __a1, _A2& __a2){ - return __invoke(__f, __a0, __a1, __a2); + return _VSTD::__invoke(__f, __a0, __a1, __a2); } #endif }; -template <> -struct __invoke_void_return_wrapper +template +struct __invoke_void_return_wrapper<_Ret, true> { -#ifndef _LIBCPP_HAS_NO_VARIADICS +#ifndef _LIBCPP_CXX03_LANG template static void __call(_Args&&... __args) { - __invoke(_VSTD::forward<_Args>(__args)...); + _VSTD::__invoke(_VSTD::forward<_Args>(__args)...); } #else template static void __call(_Fn __f) { - __invoke(__f); + _VSTD::__invoke(__f); } template static void __call(_Fn __f, _A0& __a0) { - __invoke(__f, __a0); + _VSTD::__invoke(__f, __a0); } template static void __call(_Fn __f, _A0& __a0, _A1& __a1) { - __invoke(__f, __a0, __a1); + _VSTD::__invoke(__f, __a0, __a1); } template static void __call(_Fn __f, _A0& __a0, _A1& __a1, _A2& __a2) { - __invoke(__f, __a0, __a1, __a2); + _VSTD::__invoke(__f, __a0, __a1, __a2); } #endif }; template -class _LIBCPP_TYPE_VIS_ONLY reference_wrapper +class _LIBCPP_TEMPLATE_VIS reference_wrapper : public __weak_result_type<_Tp> { public: @@ -393,135 +383,138 @@ private: public: // construct/copy/destroy - _LIBCPP_INLINE_VISIBILITY reference_wrapper(type& __f) _NOEXCEPT + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 + reference_wrapper(type& __f) _NOEXCEPT : __f_(_VSTD::addressof(__f)) {} -#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES +#ifndef _LIBCPP_CXX03_LANG private: reference_wrapper(type&&); public: // = delete; // do not bind to temps #endif // access - _LIBCPP_INLINE_VISIBILITY operator type& () const _NOEXCEPT {return *__f_;} - _LIBCPP_INLINE_VISIBILITY type& get() const _NOEXCEPT {return *__f_;} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 + operator type&() const _NOEXCEPT {return *__f_;} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 + type& get() const _NOEXCEPT {return *__f_;} -#ifndef _LIBCPP_HAS_NO_VARIADICS +#ifndef _LIBCPP_CXX03_LANG // invoke template - _LIBCPP_INLINE_VISIBILITY + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 typename __invoke_of::type operator() (_ArgTypes&&... __args) const { - return __invoke(get(), _VSTD::forward<_ArgTypes>(__args)...); + return _VSTD::__invoke(get(), _VSTD::forward<_ArgTypes>(__args)...); } #else _LIBCPP_INLINE_VISIBILITY typename __invoke_return::type operator() () const { - return __invoke(get()); + return _VSTD::__invoke(get()); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return0::type operator() (_A0& __a0) const { - return __invoke(get(), __a0); + return _VSTD::__invoke(get(), __a0); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return0::type operator() (_A0 const& __a0) const { - return __invoke(get(), __a0); + return _VSTD::__invoke(get(), __a0); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return1::type operator() (_A0& __a0, _A1& __a1) const { - return __invoke(get(), __a0, __a1); + return _VSTD::__invoke(get(), __a0, __a1); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return1::type operator() (_A0 const& __a0, _A1& __a1) const { - return __invoke(get(), __a0, __a1); + return _VSTD::__invoke(get(), __a0, __a1); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return1::type operator() (_A0& __a0, _A1 const& __a1) const { - return __invoke(get(), __a0, __a1); + return _VSTD::__invoke(get(), __a0, __a1); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return1::type operator() (_A0 const& __a0, _A1 const& __a1) const { - return __invoke(get(), __a0, __a1); + return _VSTD::__invoke(get(), __a0, __a1); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return2::type operator() (_A0& __a0, _A1& __a1, _A2& __a2) const { - return __invoke(get(), __a0, __a1, __a2); + return _VSTD::__invoke(get(), __a0, __a1, __a2); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return2::type operator() (_A0 const& __a0, _A1& __a1, _A2& __a2) const { - return __invoke(get(), __a0, __a1, __a2); + return _VSTD::__invoke(get(), __a0, __a1, __a2); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return2::type operator() (_A0& __a0, _A1 const& __a1, _A2& __a2) const { - return __invoke(get(), __a0, __a1, __a2); + return _VSTD::__invoke(get(), __a0, __a1, __a2); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return2::type operator() (_A0& __a0, _A1& __a1, _A2 const& __a2) const { - return __invoke(get(), __a0, __a1, __a2); + return _VSTD::__invoke(get(), __a0, __a1, __a2); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return2::type operator() (_A0 const& __a0, _A1 const& __a1, _A2& __a2) const { - return __invoke(get(), __a0, __a1, __a2); + return _VSTD::__invoke(get(), __a0, __a1, __a2); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return2::type operator() (_A0 const& __a0, _A1& __a1, _A2 const& __a2) const { - return __invoke(get(), __a0, __a1, __a2); + return _VSTD::__invoke(get(), __a0, __a1, __a2); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return2::type operator() (_A0& __a0, _A1 const& __a1, _A2 const& __a2) const { - return __invoke(get(), __a0, __a1, __a2); + return _VSTD::__invoke(get(), __a0, __a1, __a2); } template _LIBCPP_INLINE_VISIBILITY typename __invoke_return2::type operator() (_A0 const& __a0, _A1 const& __a1, _A2 const& __a2) const { - return __invoke(get(), __a0, __a1, __a2); + return _VSTD::__invoke(get(), __a0, __a1, __a2); } -#endif // _LIBCPP_HAS_NO_VARIADICS +#endif // _LIBCPP_CXX03_LANG }; template -inline _LIBCPP_INLINE_VISIBILITY +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 reference_wrapper<_Tp> ref(_Tp& __t) _NOEXCEPT { @@ -529,15 +522,15 @@ ref(_Tp& __t) _NOEXCEPT } template -inline _LIBCPP_INLINE_VISIBILITY +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 reference_wrapper<_Tp> ref(reference_wrapper<_Tp> __t) _NOEXCEPT { - return ref(__t.get()); + return _VSTD::ref(__t.get()); } template -inline _LIBCPP_INLINE_VISIBILITY +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 reference_wrapper cref(const _Tp& __t) _NOEXCEPT { @@ -545,52 +538,36 @@ cref(const _Tp& __t) _NOEXCEPT } template -inline _LIBCPP_INLINE_VISIBILITY +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 reference_wrapper cref(reference_wrapper<_Tp> __t) _NOEXCEPT { - return cref(__t.get()); + return _VSTD::cref(__t.get()); } -#ifndef _LIBCPP_HAS_NO_VARIADICS -#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES -#ifndef _LIBCPP_HAS_NO_DELETED_FUNCTIONS - +#ifndef _LIBCPP_CXX03_LANG template void ref(const _Tp&&) = delete; template void cref(const _Tp&&) = delete; - -#else // _LIBCPP_HAS_NO_DELETED_FUNCTIONS - -template void ref(const _Tp&&);// = delete; -template void cref(const _Tp&&);// = delete; - -#endif // _LIBCPP_HAS_NO_DELETED_FUNCTIONS - -#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES - -#endif // _LIBCPP_HAS_NO_VARIADICS +#endif #if _LIBCPP_STD_VER > 11 -template -struct __is_transparent -{ -private: - struct __two {char __lx; char __lxx;}; - template static __two __test(...); - template static char __test(typename _Up::is_transparent* = 0); -public: - static const bool value = sizeof(__test<_Tp1>(0)) == 1; -}; +template +struct __is_transparent : false_type {}; + +template +struct __is_transparent<_Tp, _Up, + typename __void_t::type> + : true_type {}; #endif // allocator_arg_t -struct _LIBCPP_TYPE_VIS_ONLY allocator_arg_t { }; +struct _LIBCPP_TEMPLATE_VIS allocator_arg_t { explicit allocator_arg_t() = default; }; -#if defined(_LIBCPP_HAS_NO_CONSTEXPR) || defined(_LIBCPP_BUILDING_MEMORY) -extern const allocator_arg_t allocator_arg; +#if defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY) +extern _LIBCPP_EXPORTED_FROM_ABI const allocator_arg_t allocator_arg; #else -constexpr allocator_arg_t allocator_arg = allocator_arg_t(); +/* _LIBCPP_INLINE_VAR */ constexpr allocator_arg_t allocator_arg = allocator_arg_t(); #endif // uses_allocator @@ -620,19 +597,25 @@ struct __uses_allocator<_Tp, _Alloc, false> }; template -struct _LIBCPP_TYPE_VIS_ONLY uses_allocator +struct _LIBCPP_TEMPLATE_VIS uses_allocator : public __uses_allocator<_Tp, _Alloc> { }; -#ifndef _LIBCPP_HAS_NO_VARIADICS +#if _LIBCPP_STD_VER > 14 +template +_LIBCPP_INLINE_VAR constexpr size_t uses_allocator_v = uses_allocator<_Tp, _Alloc>::value; +#endif + +#ifndef _LIBCPP_CXX03_LANG // allocator construction template struct __uses_alloc_ctor_imp { - static const bool __ua = uses_allocator<_Tp, _Alloc>::value; + typedef _LIBCPP_NODEBUG_TYPE typename __uncvref<_Alloc>::type _RawAlloc; + static const bool __ua = uses_allocator<_Tp, _RawAlloc>::value; static const bool __ic = is_constructible<_Tp, allocator_arg_t, _Alloc, _Args...>::value; static const int value = __ua ? 2 - __ic : 0; @@ -650,6 +633,7 @@ void __user_alloc_construct_impl (integral_constant, _Tp *__storage, con new (__storage) _Tp (_VSTD::forward<_Args>(__args)...); } +// FIXME: This should have a version which takes a non-const alloc. template inline _LIBCPP_INLINE_VISIBILITY void __user_alloc_construct_impl (integral_constant, _Tp *__storage, const _Allocator &__a, _Args &&... __args ) @@ -657,6 +641,7 @@ void __user_alloc_construct_impl (integral_constant, _Tp *__storage, con new (__storage) _Tp (allocator_arg, __a, _VSTD::forward<_Args>(__args)...); } +// FIXME: This should have a version which takes a non-const alloc. template inline _LIBCPP_INLINE_VISIBILITY void __user_alloc_construct_impl (integral_constant, _Tp *__storage, const _Allocator &__a, _Args &&... __args ) @@ -664,16 +649,7 @@ void __user_alloc_construct_impl (integral_constant, _Tp *__storage, con new (__storage) _Tp (_VSTD::forward<_Args>(__args)..., __a); } -template -inline _LIBCPP_INLINE_VISIBILITY -void __user_alloc_construct (_Tp *__storage, const _Allocator &__a, _Args &&... __args) -{ - __user_alloc_construct_impl( - __uses_alloc_ctor<_Tp, _Allocator>(), - __storage, __a, _VSTD::forward<_Args>(__args)... - ); -} -#endif // _LIBCPP_HAS_NO_VARIADICS +#endif // _LIBCPP_CXX03_LANG _LIBCPP_END_NAMESPACE_STD diff --git a/sdk/tlibcxx/include/__functional_base_03 b/sdk/tlibcxx/include/__functional_base_03 index 8407dcfa..9b08bd26 100644 --- a/sdk/tlibcxx/include/__functional_base_03 +++ b/sdk/tlibcxx/include/__functional_base_03 @@ -1,10 +1,9 @@ // -*- C++ -*- //===----------------------------------------------------------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// @@ -41,7 +40,7 @@ struct __enable_invoke_imp<_Ret, _T1, false, true> { template struct __enable_invoke_imp<_Ret, _T1, false, false> { typedef typename add_lvalue_reference< - typename __apply_cv()), _Ret>::type + typename __apply_cv()), _Ret>::type >::type _Bullet4; typedef _Bullet4 type; }; @@ -143,7 +142,7 @@ __invoke(_Fn __f, _T1& __t1) { template inline _LIBCPP_INLINE_VISIBILITY -decltype(_VSTD::declval<_Fp&>()()) +decltype(declval<_Fp&>()()) __invoke(_Fp& __f) { return __f(); @@ -151,7 +150,7 @@ __invoke(_Fp& __f) template inline _LIBCPP_INLINE_VISIBILITY -decltype(_VSTD::declval<_Fp&>()(_VSTD::declval<_A0&>())) +decltype(declval<_Fp&>()(declval<_A0&>())) __invoke(_Fp& __f, _A0& __a0) { return __f(__a0); @@ -159,7 +158,7 @@ __invoke(_Fp& __f, _A0& __a0) template inline _LIBCPP_INLINE_VISIBILITY -decltype(_VSTD::declval<_Fp&>()(_VSTD::declval<_A0&>(), _VSTD::declval<_A1&>())) +decltype(declval<_Fp&>()(declval<_A0&>(), declval<_A1&>())) __invoke(_Fp& __f, _A0& __a0, _A1& __a1) { return __f(__a0, __a1); @@ -167,7 +166,7 @@ __invoke(_Fp& __f, _A0& __a0, _A1& __a1) template inline _LIBCPP_INLINE_VISIBILITY -decltype(_VSTD::declval<_Fp&>()(_VSTD::declval<_A0&>(), _VSTD::declval<_A1&>(), _VSTD::declval<_A2&>())) +decltype(declval<_Fp&>()(declval<_A0&>(), declval<_A1&>(), declval<_A2&>())) __invoke(_Fp& __f, _A0& __a0, _A1& __a1, _A2& __a2) { return __f(__a0, __a1, __a2); @@ -182,13 +181,13 @@ struct __invoke_return template struct __invoke_return<_Fp, false> { - typedef decltype(__invoke(_VSTD::declval<_Fp&>())) type; + typedef decltype(_VSTD::__invoke(declval<_Fp&>())) type; }; template struct __invoke_return0 { - typedef decltype(__invoke(_VSTD::declval<_Tp&>(), _VSTD::declval<_A0&>())) type; + typedef decltype(_VSTD::__invoke(declval<_Tp&>(), declval<_A0&>())) type; }; template @@ -200,8 +199,8 @@ struct __invoke_return0<_Rp _Tp::*, _A0> template struct __invoke_return1 { - typedef decltype(__invoke(_VSTD::declval<_Tp&>(), _VSTD::declval<_A0&>(), - _VSTD::declval<_A1&>())) type; + typedef decltype(_VSTD::__invoke(declval<_Tp&>(), declval<_A0&>(), + declval<_A1&>())) type; }; template @@ -212,9 +211,9 @@ struct __invoke_return1<_Rp _Class::*, _A0, _A1> { template struct __invoke_return2 { - typedef decltype(__invoke(_VSTD::declval<_Tp&>(), _VSTD::declval<_A0&>(), - _VSTD::declval<_A1&>(), - _VSTD::declval<_A2&>())) type; + typedef decltype(_VSTD::__invoke(declval<_Tp&>(), declval<_A0&>(), + declval<_A1&>(), + declval<_A2&>())) type; }; template diff --git a/sdk/tlibcxx/include/__hash_table b/sdk/tlibcxx/include/__hash_table index 08bc519a..521ebbf2 100644 --- a/sdk/tlibcxx/include/__hash_table +++ b/sdk/tlibcxx/include/__hash_table @@ -1,10 +1,9 @@ // -*- C++ -*- //===----------------------------------------------------------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// @@ -18,9 +17,7 @@ #include #include #include - -#include <__undef_min_max> -#include <__undef___deallocate> +#include #include <__debug> @@ -28,30 +25,26 @@ #pragma GCC system_header #endif +_LIBCPP_PUSH_MACROS +#include <__undef_macros> + + _LIBCPP_BEGIN_NAMESPACE_STD - -#ifndef _LIBCPP_CXX03_LANG -template -union __hash_value_type; -#else template struct __hash_value_type; -#endif -#ifndef _LIBCPP_CXX03_LANG template struct __is_hash_value_type_imp : false_type {}; template -struct __is_hash_value_type_imp<__hash_value_type<_Key, _Value>> : true_type {}; +struct __is_hash_value_type_imp<__hash_value_type<_Key, _Value> > : true_type {}; template struct __is_hash_value_type : false_type {}; template struct __is_hash_value_type<_One> : __is_hash_value_type_imp::type> {}; -#endif _LIBCPP_FUNC_VIS size_t __next_prime(size_t __n); @@ -59,9 +52,38 @@ size_t __next_prime(size_t __n); template struct __hash_node_base { + typedef typename pointer_traits<_NodePtr>::element_type __node_type; typedef __hash_node_base __first_node; + typedef typename __rebind_pointer<_NodePtr, __first_node>::type __node_base_pointer; + typedef _NodePtr __node_pointer; - _NodePtr __next_; +#if defined(_LIBCPP_ABI_FIX_UNORDERED_NODE_POINTER_UB) + typedef __node_base_pointer __next_pointer; +#else + typedef typename conditional< + is_pointer<__node_pointer>::value, + __node_base_pointer, + __node_pointer>::type __next_pointer; +#endif + + __next_pointer __next_; + + _LIBCPP_INLINE_VISIBILITY + __next_pointer __ptr() _NOEXCEPT { + return static_cast<__next_pointer>( + pointer_traits<__node_base_pointer>::pointer_to(*this)); + } + + _LIBCPP_INLINE_VISIBILITY + __node_pointer __upcast() _NOEXCEPT { + return static_cast<__node_pointer>( + pointer_traits<__node_base_pointer>::pointer_to(*this)); + } + + _LIBCPP_INLINE_VISIBILITY + size_t __hash() const _NOEXCEPT { + return static_cast<__node_type const&>(*this).__hash_; + } _LIBCPP_INLINE_VISIBILITY __hash_node_base() _NOEXCEPT : __next_(nullptr) {} }; @@ -75,7 +97,7 @@ struct __hash_node { typedef _Tp __node_value_type; - size_t __hash_; + size_t __hash_; __node_value_type __value_; }; @@ -98,18 +120,18 @@ inline _LIBCPP_INLINE_VISIBILITY size_t __next_hash_pow2(size_t __n) { - return size_t(1) << (std::numeric_limits::digits - __clz(__n-1)); + return __n < 2 ? __n : (size_t(1) << (numeric_limits::digits - __libcpp_clz(__n-1))); } template class __hash_table; -template class _LIBCPP_TYPE_VIS_ONLY __hash_iterator; -template class _LIBCPP_TYPE_VIS_ONLY __hash_const_iterator; -template class _LIBCPP_TYPE_VIS_ONLY __hash_local_iterator; -template class _LIBCPP_TYPE_VIS_ONLY __hash_const_local_iterator; -template class _LIBCPP_TYPE_VIS_ONLY __hash_map_iterator; -template class _LIBCPP_TYPE_VIS_ONLY __hash_map_const_iterator; +template class _LIBCPP_TEMPLATE_VIS __hash_iterator; +template class _LIBCPP_TEMPLATE_VIS __hash_const_iterator; +template class _LIBCPP_TEMPLATE_VIS __hash_local_iterator; +template class _LIBCPP_TEMPLATE_VIS __hash_const_local_iterator; +template class _LIBCPP_TEMPLATE_VIS __hash_map_iterator; +template class _LIBCPP_TEMPLATE_VIS __hash_map_const_iterator; template struct __hash_key_value_types { @@ -131,12 +153,10 @@ struct __hash_key_value_types { static __container_value_type* __get_ptr(__node_value_type& __n) { return _VSTD::addressof(__n); } -#ifndef _LIBCPP_CXX03_LANG _LIBCPP_INLINE_VISIBILITY - static __container_value_type&& __move(__node_value_type& __v) { + static __container_value_type&& __move(__node_value_type& __v) { return _VSTD::move(__v); } -#endif }; template @@ -145,7 +165,6 @@ struct __hash_key_value_types<__hash_value_type<_Key, _Tp> > { typedef _Tp mapped_type; typedef __hash_value_type<_Key, _Tp> __node_value_type; typedef pair __container_value_type; - typedef pair<_Key, _Tp> __nc_value_type; typedef __container_value_type __map_value_type; static const bool __is_map = true; @@ -159,7 +178,7 @@ struct __hash_key_value_types<__hash_value_type<_Key, _Tp> > { static typename enable_if<__is_same_uncvref<_Up, __node_value_type>::value, __container_value_type const&>::type __get_value(_Up& __t) { - return __t.__cc; + return __t.__get_value(); } template @@ -172,15 +191,12 @@ struct __hash_key_value_types<__hash_value_type<_Key, _Tp> > { _LIBCPP_INLINE_VISIBILITY static __container_value_type* __get_ptr(__node_value_type& __n) { - return _VSTD::addressof(__n.__cc); + return _VSTD::addressof(__n.__get_value()); } -#ifndef _LIBCPP_CXX03_LANG _LIBCPP_INLINE_VISIBILITY - static __nc_value_type&& __move(__node_value_type& __v) { - return _VSTD::move(__v.__nc); + static pair __move(__node_value_type& __v) { + return __v.__move(); } -#endif - }; template , @@ -219,11 +235,14 @@ public: typedef typename __rebind_pointer<_NodePtr, __node_base_type>::type __node_base_pointer; + typedef typename __node_base_type::__next_pointer __next_pointer; + typedef _Tp __node_value_type; typedef typename __rebind_pointer<_VoidPtr, __node_value_type>::type __node_value_type_pointer; typedef typename __rebind_pointer<_VoidPtr, const __node_value_type>::type __const_node_value_type_pointer; + private: static_assert(!is_const<__node_type>::value, "_NodePtr should never be a pointer to const"); @@ -233,8 +252,6 @@ private: _NodePtr>::value), "_VoidPtr does not rebind to _NodePtr."); }; - - template struct __hash_node_types_from_iterator; template @@ -255,12 +272,13 @@ struct __make_hash_node_types { }; template -class _LIBCPP_TYPE_VIS_ONLY __hash_iterator +class _LIBCPP_TEMPLATE_VIS __hash_iterator { typedef __hash_node_types<_NodePtr> _NodeTypes; - typedef _NodePtr __node_pointer; + typedef _NodePtr __node_pointer; + typedef typename _NodeTypes::__next_pointer __next_pointer; - __node_pointer __node_; + __next_pointer __node_; public: typedef forward_iterator_tag iterator_category; @@ -269,18 +287,13 @@ public: typedef value_type& reference; typedef typename _NodeTypes::__node_value_type_pointer pointer; - _LIBCPP_INLINE_VISIBILITY __hash_iterator() _NOEXCEPT -#if _LIBCPP_STD_VER > 11 - : __node_(nullptr) -#endif - { -#if _LIBCPP_DEBUG_LEVEL >= 2 + _LIBCPP_INLINE_VISIBILITY __hash_iterator() _NOEXCEPT : __node_(nullptr) { +#if _LIBCPP_DEBUG_LEVEL == 2 __get_db()->__insert_i(this); #endif } -#if _LIBCPP_DEBUG_LEVEL >= 2 - +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY __hash_iterator(const __hash_iterator& __i) : __node_(__i.__node_) @@ -304,35 +317,26 @@ public: } return *this; } - -#endif // _LIBCPP_DEBUG_LEVEL >= 2 +#endif // _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY - reference operator*() const - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), + reference operator*() const { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), + "Attempted to dereference a non-dereferenceable unordered container iterator"); + return __node_->__upcast()->__value_; + } + + _LIBCPP_INLINE_VISIBILITY + pointer operator->() const { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), "Attempted to dereference a non-dereferenceable unordered container iterator"); -#endif - return __node_->__value_; - } - _LIBCPP_INLINE_VISIBILITY - pointer operator->() const - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), - "Attempted to dereference a non-dereferenceable unordered container iterator"); -#endif - return pointer_traits::pointer_to(__node_->__value_); - } + return pointer_traits::pointer_to(__node_->__upcast()->__value_); + } _LIBCPP_INLINE_VISIBILITY - __hash_iterator& operator++() - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), + __hash_iterator& operator++() { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), "Attempted to increment non-incrementable unordered container iterator"); -#endif __node_ = __node_->__next_; return *this; } @@ -355,35 +359,35 @@ public: {return !(__x == __y);} private: -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY - __hash_iterator(__node_pointer __node, const void* __c) _NOEXCEPT + __hash_iterator(__next_pointer __node, const void* __c) _NOEXCEPT : __node_(__node) { __get_db()->__insert_ic(this, __c); } #else _LIBCPP_INLINE_VISIBILITY - __hash_iterator(__node_pointer __node) _NOEXCEPT + __hash_iterator(__next_pointer __node) _NOEXCEPT : __node_(__node) {} #endif - template friend class __hash_table; - template friend class _LIBCPP_TYPE_VIS_ONLY __hash_const_iterator; - template friend class _LIBCPP_TYPE_VIS_ONLY __hash_map_iterator; - template friend class _LIBCPP_TYPE_VIS_ONLY unordered_map; - template friend class _LIBCPP_TYPE_VIS_ONLY unordered_multimap; + template friend class _LIBCPP_TEMPLATE_VIS __hash_const_iterator; + template friend class _LIBCPP_TEMPLATE_VIS __hash_map_iterator; + template friend class _LIBCPP_TEMPLATE_VIS unordered_map; + template friend class _LIBCPP_TEMPLATE_VIS unordered_multimap; }; template -class _LIBCPP_TYPE_VIS_ONLY __hash_const_iterator +class _LIBCPP_TEMPLATE_VIS __hash_const_iterator { static_assert(!is_const::element_type>::value, ""); typedef __hash_node_types<_NodePtr> _NodeTypes; - typedef _NodePtr __node_pointer; + typedef _NodePtr __node_pointer; + typedef typename _NodeTypes::__next_pointer __next_pointer; - __node_pointer __node_; + __next_pointer __node_; public: typedef __hash_iterator<_NodePtr> __non_const_iterator; @@ -395,26 +399,22 @@ public: typedef typename _NodeTypes::__const_node_value_type_pointer pointer; - _LIBCPP_INLINE_VISIBILITY __hash_const_iterator() _NOEXCEPT -#if _LIBCPP_STD_VER > 11 - : __node_(nullptr) -#endif - { -#if _LIBCPP_DEBUG_LEVEL >= 2 + _LIBCPP_INLINE_VISIBILITY __hash_const_iterator() _NOEXCEPT : __node_(nullptr) { +#if _LIBCPP_DEBUG_LEVEL == 2 __get_db()->__insert_i(this); #endif } - _LIBCPP_INLINE_VISIBILITY + + _LIBCPP_INLINE_VISIBILITY __hash_const_iterator(const __non_const_iterator& __x) _NOEXCEPT : __node_(__x.__node_) { -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 __get_db()->__iterator_copy(this, &__x); #endif } -#if _LIBCPP_DEBUG_LEVEL >= 2 - +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY __hash_const_iterator(const __hash_const_iterator& __i) : __node_(__i.__node_) @@ -438,35 +438,25 @@ public: } return *this; } - -#endif // _LIBCPP_DEBUG_LEVEL >= 2 +#endif // _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY - reference operator*() const - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), + reference operator*() const { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), "Attempted to dereference a non-dereferenceable unordered container const_iterator"); -#endif - return __node_->__value_; - } + return __node_->__upcast()->__value_; + } _LIBCPP_INLINE_VISIBILITY - pointer operator->() const - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), + pointer operator->() const { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), "Attempted to dereference a non-dereferenceable unordered container const_iterator"); -#endif - return pointer_traits::pointer_to(__node_->__value_); - } + return pointer_traits::pointer_to(__node_->__upcast()->__value_); + } _LIBCPP_INLINE_VISIBILITY - __hash_const_iterator& operator++() - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), - "Attempted to increment non-incrementable unordered container const_iterator"); -#endif + __hash_const_iterator& operator++() { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), + "Attempted to increment non-incrementable unordered container const_iterator"); __node_ = __node_->__next_; return *this; } @@ -489,33 +479,33 @@ public: {return !(__x == __y);} private: -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY - __hash_const_iterator(__node_pointer __node, const void* __c) _NOEXCEPT + __hash_const_iterator(__next_pointer __node, const void* __c) _NOEXCEPT : __node_(__node) { __get_db()->__insert_ic(this, __c); } #else _LIBCPP_INLINE_VISIBILITY - __hash_const_iterator(__node_pointer __node) _NOEXCEPT + __hash_const_iterator(__next_pointer __node) _NOEXCEPT : __node_(__node) {} #endif - template friend class __hash_table; - template friend class _LIBCPP_TYPE_VIS_ONLY __hash_map_const_iterator; - template friend class _LIBCPP_TYPE_VIS_ONLY unordered_map; - template friend class _LIBCPP_TYPE_VIS_ONLY unordered_multimap; + template friend class _LIBCPP_TEMPLATE_VIS __hash_map_const_iterator; + template friend class _LIBCPP_TEMPLATE_VIS unordered_map; + template friend class _LIBCPP_TEMPLATE_VIS unordered_multimap; }; template -class _LIBCPP_TYPE_VIS_ONLY __hash_local_iterator +class _LIBCPP_TEMPLATE_VIS __hash_local_iterator { typedef __hash_node_types<_NodePtr> _NodeTypes; - typedef _NodePtr __node_pointer; + typedef _NodePtr __node_pointer; + typedef typename _NodeTypes::__next_pointer __next_pointer; - __node_pointer __node_; + __next_pointer __node_; size_t __bucket_; size_t __bucket_count_; @@ -526,15 +516,13 @@ public: typedef value_type& reference; typedef typename _NodeTypes::__node_value_type_pointer pointer; - _LIBCPP_INLINE_VISIBILITY __hash_local_iterator() _NOEXCEPT - { -#if _LIBCPP_DEBUG_LEVEL >= 2 + _LIBCPP_INLINE_VISIBILITY __hash_local_iterator() _NOEXCEPT : __node_(nullptr) { +#if _LIBCPP_DEBUG_LEVEL == 2 __get_db()->__insert_i(this); #endif } -#if _LIBCPP_DEBUG_LEVEL >= 2 - +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY __hash_local_iterator(const __hash_local_iterator& __i) : __node_(__i.__node_), @@ -562,37 +550,28 @@ public: } return *this; } - -#endif // _LIBCPP_DEBUG_LEVEL >= 2 +#endif // _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY - reference operator*() const - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), + reference operator*() const { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), "Attempted to dereference a non-dereferenceable unordered container local_iterator"); -#endif - return __node_->__value_; - } - _LIBCPP_INLINE_VISIBILITY - pointer operator->() const - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), - "Attempted to dereference a non-dereferenceable unordered container local_iterator"); -#endif - return pointer_traits::pointer_to(__node_->__value_); - } + return __node_->__upcast()->__value_; + } _LIBCPP_INLINE_VISIBILITY - __hash_local_iterator& operator++() - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), + pointer operator->() const { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), + "Attempted to dereference a non-dereferenceable unordered container local_iterator"); + return pointer_traits::pointer_to(__node_->__upcast()->__value_); + } + + _LIBCPP_INLINE_VISIBILITY + __hash_local_iterator& operator++() { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), "Attempted to increment non-incrementable unordered container local_iterator"); -#endif __node_ = __node_->__next_; - if (__node_ != nullptr && __constrain_hash(__node_->__hash_, __bucket_count_) != __bucket_) + if (__node_ != nullptr && __constrain_hash(__node_->__hash(), __bucket_count_) != __bucket_) __node_ = nullptr; return *this; } @@ -615,9 +594,9 @@ public: {return !(__x == __y);} private: -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY - __hash_local_iterator(__node_pointer __node, size_t __bucket, + __hash_local_iterator(__next_pointer __node, size_t __bucket, size_t __bucket_count, const void* __c) _NOEXCEPT : __node_(__node), __bucket_(__bucket), @@ -629,7 +608,7 @@ private: } #else _LIBCPP_INLINE_VISIBILITY - __hash_local_iterator(__node_pointer __node, size_t __bucket, + __hash_local_iterator(__next_pointer __node, size_t __bucket, size_t __bucket_count) _NOEXCEPT : __node_(__node), __bucket_(__bucket), @@ -640,17 +619,18 @@ private: } #endif template friend class __hash_table; - template friend class _LIBCPP_TYPE_VIS_ONLY __hash_const_local_iterator; - template friend class _LIBCPP_TYPE_VIS_ONLY __hash_map_iterator; + template friend class _LIBCPP_TEMPLATE_VIS __hash_const_local_iterator; + template friend class _LIBCPP_TEMPLATE_VIS __hash_map_iterator; }; template -class _LIBCPP_TYPE_VIS_ONLY __hash_const_local_iterator +class _LIBCPP_TEMPLATE_VIS __hash_const_local_iterator { typedef __hash_node_types<_ConstNodePtr> _NodeTypes; - typedef _ConstNodePtr __node_pointer; + typedef _ConstNodePtr __node_pointer; + typedef typename _NodeTypes::__next_pointer __next_pointer; - __node_pointer __node_; + __next_pointer __node_; size_t __bucket_; size_t __bucket_count_; @@ -670,9 +650,8 @@ public: typedef typename _NodeTypes::__const_node_value_type_pointer pointer; - _LIBCPP_INLINE_VISIBILITY __hash_const_local_iterator() _NOEXCEPT - { -#if _LIBCPP_DEBUG_LEVEL >= 2 + _LIBCPP_INLINE_VISIBILITY __hash_const_local_iterator() _NOEXCEPT : __node_(nullptr) { +#if _LIBCPP_DEBUG_LEVEL == 2 __get_db()->__insert_i(this); #endif } @@ -683,13 +662,12 @@ public: __bucket_(__x.__bucket_), __bucket_count_(__x.__bucket_count_) { -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 __get_db()->__iterator_copy(this, &__x); #endif } -#if _LIBCPP_DEBUG_LEVEL >= 2 - +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY __hash_const_local_iterator(const __hash_const_local_iterator& __i) : __node_(__i.__node_), @@ -717,37 +695,28 @@ public: } return *this; } - -#endif // _LIBCPP_DEBUG_LEVEL >= 2 +#endif // _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY - reference operator*() const - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), + reference operator*() const { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), "Attempted to dereference a non-dereferenceable unordered container const_local_iterator"); -#endif - return __node_->__value_; - } - _LIBCPP_INLINE_VISIBILITY - pointer operator->() const - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), - "Attempted to dereference a non-dereferenceable unordered container const_local_iterator"); -#endif - return pointer_traits::pointer_to(__node_->__value_); - } + return __node_->__upcast()->__value_; + } _LIBCPP_INLINE_VISIBILITY - __hash_const_local_iterator& operator++() - { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this), + pointer operator->() const { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), + "Attempted to dereference a non-dereferenceable unordered container const_local_iterator"); + return pointer_traits::pointer_to(__node_->__upcast()->__value_); + } + + _LIBCPP_INLINE_VISIBILITY + __hash_const_local_iterator& operator++() { + _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this), "Attempted to increment non-incrementable unordered container const_local_iterator"); -#endif __node_ = __node_->__next_; - if (__node_ != nullptr && __constrain_hash(__node_->__hash_, __bucket_count_) != __bucket_) + if (__node_ != nullptr && __constrain_hash(__node_->__hash(), __bucket_count_) != __bucket_) __node_ = nullptr; return *this; } @@ -770,9 +739,9 @@ public: {return !(__x == __y);} private: -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_INLINE_VISIBILITY - __hash_const_local_iterator(__node_pointer __node, size_t __bucket, + __hash_const_local_iterator(__next_pointer __node, size_t __bucket, size_t __bucket_count, const void* __c) _NOEXCEPT : __node_(__node), __bucket_(__bucket), @@ -784,7 +753,7 @@ private: } #else _LIBCPP_INLINE_VISIBILITY - __hash_const_local_iterator(__node_pointer __node, size_t __bucket, + __hash_const_local_iterator(__next_pointer __node, size_t __bucket, size_t __bucket_count) _NOEXCEPT : __node_(__node), __bucket_(__bucket), @@ -795,7 +764,7 @@ private: } #endif template friend class __hash_table; - template friend class _LIBCPP_TYPE_VIS_ONLY __hash_map_const_iterator; + template friend class _LIBCPP_TEMPLATE_VIS __hash_map_const_iterator; }; template @@ -812,15 +781,13 @@ public: _LIBCPP_INLINE_VISIBILITY __bucket_list_deallocator() _NOEXCEPT_(is_nothrow_default_constructible::value) - : __data_(0) {} + : __data_(0, __default_init_tag()) {} _LIBCPP_INLINE_VISIBILITY __bucket_list_deallocator(const allocator_type& __a, size_type __size) _NOEXCEPT_(is_nothrow_copy_constructible::value) : __data_(__size, __a) {} -#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES - _LIBCPP_INLINE_VISIBILITY __bucket_list_deallocator(__bucket_list_deallocator&& __x) _NOEXCEPT_(is_nothrow_move_constructible::value) @@ -829,8 +796,6 @@ public: __x.size() = 0; } -#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES - _LIBCPP_INLINE_VISIBILITY size_type& size() _NOEXCEPT {return __data_.first();} _LIBCPP_INLINE_VISIBILITY @@ -863,11 +828,13 @@ private: allocator_type& __na_; - __hash_node_destructor& operator=(const __hash_node_destructor&); - public: bool __value_constructed; + __hash_node_destructor(__hash_node_destructor const&) = default; + __hash_node_destructor& operator=(const __hash_node_destructor&) = delete; + + _LIBCPP_INLINE_VISIBILITY explicit __hash_node_destructor(allocator_type& __na, bool __constructed = false) _NOEXCEPT @@ -887,6 +854,45 @@ public: template friend class __hash_map_node_destructor; }; +#if _LIBCPP_STD_VER > 14 +template +struct __generic_container_node_destructor; + +template +struct __generic_container_node_destructor<__hash_node<_Tp, _VoidPtr>, _Alloc> + : __hash_node_destructor<_Alloc> +{ + using __hash_node_destructor<_Alloc>::__hash_node_destructor; +}; +#endif + +template +struct __enforce_unordered_container_requirements { +#ifndef _LIBCPP_CXX03_LANG + static_assert(__check_hash_requirements<_Key, _Hash>::value, + "the specified hash does not meet the Hash requirements"); + static_assert(is_copy_constructible<_Equal>::value, + "the specified comparator is required to be copy constructible"); +#endif + typedef int type; +}; + +template +#ifndef _LIBCPP_CXX03_LANG + _LIBCPP_DIAGNOSE_WARNING(!__invokable<_Equal const&, _Key const&, _Key const&>::value, + "the specified comparator type does not provide a viable const call operator") + _LIBCPP_DIAGNOSE_WARNING(!__invokable<_Hash const&, _Key const&>::value, + "the specified hash functor does not provide a viable const call operator") +#endif +typename __enforce_unordered_container_requirements<_Key, _Hash, _Equal>::type +__diagnose_unordered_container_requirements(int); + +// This dummy overload is used so that the compiler won't emit a spurious +// "no matching function for call to __diagnose_unordered_xxx" diagnostic +// when the overload above causes a hard error. +template +int __diagnose_unordered_container_requirements(void*); + template class __hash_table { @@ -927,6 +933,7 @@ public: typedef typename _NodeTypes::__node_pointer __node_const_pointer; typedef typename _NodeTypes::__node_base_type __first_node; typedef typename _NodeTypes::__node_base_pointer __node_base_pointer; + typedef typename _NodeTypes::__next_pointer __next_pointer; private: // check for sane allocator pointer rebinding semantics. Rebinding the @@ -942,11 +949,11 @@ private: private: - typedef typename __rebind_alloc_helper<__node_traits, __node_pointer>::type __pointer_allocator; + typedef typename __rebind_alloc_helper<__node_traits, __next_pointer>::type __pointer_allocator; typedef __bucket_list_deallocator<__pointer_allocator> __bucket_list_deleter; - typedef unique_ptr<__node_pointer[], __bucket_list_deleter> __bucket_list; + typedef unique_ptr<__next_pointer[], __bucket_list_deleter> __bucket_list; typedef allocator_traits<__pointer_allocator> __pointer_alloc_traits; - typedef typename __bucket_list_deleter::pointer __node_pointer_pointer; + typedef typename __bucket_list_deleter::pointer __node_pointer_pointer; // --- Member data begin --- __bucket_list __bucket_list_; @@ -1003,7 +1010,6 @@ public: explicit __hash_table(const allocator_type& __a); __hash_table(const __hash_table& __u); __hash_table(const __hash_table& __u, const allocator_type& __a); -#ifndef _LIBCPP_CXX03_LANG __hash_table(__hash_table&& __u) _NOEXCEPT_( is_nothrow_move_constructible<__bucket_list>::value && @@ -1012,11 +1018,9 @@ public: is_nothrow_move_constructible::value && is_nothrow_move_constructible::value); __hash_table(__hash_table&& __u, const allocator_type& __a); -#endif // _LIBCPP_CXX03_LANG ~__hash_table(); __hash_table& operator=(const __hash_table& __u); -#ifndef _LIBCPP_CXX03_LANG _LIBCPP_INLINE_VISIBILITY __hash_table& operator=(__hash_table&& __u) _NOEXCEPT_( @@ -1024,7 +1028,6 @@ public: is_nothrow_move_assignable<__node_allocator>::value && is_nothrow_move_assignable::value && is_nothrow_move_assignable::value); -#endif template void __assign_unique(_InputIterator __first, _InputIterator __last); template @@ -1033,16 +1036,35 @@ public: _LIBCPP_INLINE_VISIBILITY size_type max_size() const _NOEXCEPT { - return allocator_traits<__pointer_allocator>::max_size( - __bucket_list_.get_deleter().__alloc()); + return _VSTD::min( + __node_traits::max_size(__node_alloc()), + numeric_limits::max() + ); } +private: + _LIBCPP_INLINE_VISIBILITY + __next_pointer __node_insert_multi_prepare(size_t __cp_hash, + value_type& __cp_val); + _LIBCPP_INLINE_VISIBILITY + void __node_insert_multi_perform(__node_pointer __cp, + __next_pointer __pn) _NOEXCEPT; + + _LIBCPP_INLINE_VISIBILITY + __next_pointer __node_insert_unique_prepare(size_t __nd_hash, + value_type& __nd_val); + _LIBCPP_INLINE_VISIBILITY + void __node_insert_unique_perform(__node_pointer __ptr) _NOEXCEPT; + +public: + _LIBCPP_INLINE_VISIBILITY pair __node_insert_unique(__node_pointer __nd); + _LIBCPP_INLINE_VISIBILITY iterator __node_insert_multi(__node_pointer __nd); + _LIBCPP_INLINE_VISIBILITY iterator __node_insert_multi(const_iterator __p, __node_pointer __nd); -#ifndef _LIBCPP_CXX03_LANG template _LIBCPP_INLINE_VISIBILITY pair __emplace_unique_key_args(_Key const& __k, _Args&&... __args); @@ -1127,19 +1149,41 @@ public: return __emplace_hint_multi(__p, _VSTD::forward<_Pp>(__x)); } -#else // !defined(_LIBCPP_CXX03_LANG) - template - pair __emplace_unique_key_args(_Key const&, _Args& __args); - - iterator __insert_multi(const __container_value_type& __x); - iterator __insert_multi(const_iterator __p, const __container_value_type& __x); -#endif - _LIBCPP_INLINE_VISIBILITY pair __insert_unique(const __container_value_type& __x) { return __emplace_unique_key_args(_NodeTypes::__get_key(__x), __x); } +#if _LIBCPP_STD_VER > 14 + template + _LIBCPP_INLINE_VISIBILITY + _InsertReturnType __node_handle_insert_unique(_NodeHandle&& __nh); + template + _LIBCPP_INLINE_VISIBILITY + iterator __node_handle_insert_unique(const_iterator __hint, + _NodeHandle&& __nh); + template + _LIBCPP_INLINE_VISIBILITY + void __node_handle_merge_unique(_Table& __source); + + template + _LIBCPP_INLINE_VISIBILITY + iterator __node_handle_insert_multi(_NodeHandle&& __nh); + template + _LIBCPP_INLINE_VISIBILITY + iterator __node_handle_insert_multi(const_iterator __hint, _NodeHandle&& __nh); + template + _LIBCPP_INLINE_VISIBILITY + void __node_handle_merge_multi(_Table& __source); + + template + _LIBCPP_INLINE_VISIBILITY + _NodeHandle __node_handle_extract(key_type const& __key); + template + _LIBCPP_INLINE_VISIBILITY + _NodeHandle __node_handle_extract(const_iterator __it); +#endif + void clear() _NOEXCEPT; void rehash(size_type __n); _LIBCPP_INLINE_VISIBILITY void reserve(size_type __n) @@ -1220,7 +1264,7 @@ public: _LIBCPP_INLINE_VISIBILITY size_type max_bucket_count() const _NOEXCEPT - {return __pointer_alloc_traits::max_size(__bucket_list_.get_deleter().__alloc());} + {return max_size(); } size_type bucket_size(size_type __n) const; _LIBCPP_INLINE_VISIBILITY float load_factor() const _NOEXCEPT { @@ -1240,7 +1284,7 @@ public: { _LIBCPP_ASSERT(__n < bucket_count(), "unordered container::begin(n) called with n >= bucket_count()"); -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 return local_iterator(__bucket_list_[__n], __n, bucket_count(), this); #else return local_iterator(__bucket_list_[__n], __n, bucket_count()); @@ -1253,7 +1297,7 @@ public: { _LIBCPP_ASSERT(__n < bucket_count(), "unordered container::end(n) called with n >= bucket_count()"); -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 return local_iterator(nullptr, __n, bucket_count(), this); #else return local_iterator(nullptr, __n, bucket_count()); @@ -1266,7 +1310,7 @@ public: { _LIBCPP_ASSERT(__n < bucket_count(), "unordered container::cbegin(n) called with n >= bucket_count()"); -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 return const_local_iterator(__bucket_list_[__n], __n, bucket_count(), this); #else return const_local_iterator(__bucket_list_[__n], __n, bucket_count()); @@ -1279,35 +1323,30 @@ public: { _LIBCPP_ASSERT(__n < bucket_count(), "unordered container::cend(n) called with n >= bucket_count()"); -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 return const_local_iterator(nullptr, __n, bucket_count(), this); #else return const_local_iterator(nullptr, __n, bucket_count()); #endif } -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 bool __dereferenceable(const const_iterator* __i) const; bool __decrementable(const const_iterator* __i) const; bool __addable(const const_iterator* __i, ptrdiff_t __n) const; bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const; -#endif // _LIBCPP_DEBUG_LEVEL >= 2 +#endif // _LIBCPP_DEBUG_LEVEL == 2 private: void __rehash(size_type __n); -#ifndef _LIBCPP_CXX03_LANG template __node_holder __construct_node(_Args&& ...__args); template __node_holder __construct_node_hash(size_t __hash, _First&& __f, _Rest&&... __rest); -#else // _LIBCPP_CXX03_LANG - __node_holder __construct_node(const __container_value_type& __v); - __node_holder __construct_node_hash(size_t __hash, const __container_value_type& __v); -#endif _LIBCPP_INLINE_VISIBILITY @@ -1318,7 +1357,6 @@ private: _LIBCPP_INLINE_VISIBILITY void __copy_assign_alloc(const __hash_table&, false_type) {} -#ifndef _LIBCPP_CXX03_LANG void __move_assign(__hash_table& __u, false_type); void __move_assign(__hash_table& __u, true_type) _NOEXCEPT_( @@ -1345,13 +1383,12 @@ private: } _LIBCPP_INLINE_VISIBILITY void __move_assign_alloc(__hash_table&, false_type) _NOEXCEPT {} -#endif // _LIBCPP_CXX03_LANG - void __deallocate(__node_pointer __np) _NOEXCEPT; - __node_pointer __detach() _NOEXCEPT; + void __deallocate_node(__next_pointer __np) _NOEXCEPT; + __next_pointer __detach() _NOEXCEPT; - template friend class _LIBCPP_TYPE_VIS_ONLY unordered_map; - template friend class _LIBCPP_TYPE_VIS_ONLY unordered_multimap; + template friend class _LIBCPP_TEMPLATE_VIS unordered_map; + template friend class _LIBCPP_TEMPLATE_VIS unordered_multimap; }; template @@ -1363,8 +1400,8 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__hash_table() is_nothrow_default_constructible<__node_allocator>::value && is_nothrow_default_constructible::value && is_nothrow_default_constructible::value) - : __p2_(0), - __p3_(1.0f) + : __p2_(0, __default_init_tag()), + __p3_(1.0f, __default_init_tag()) { } @@ -1384,7 +1421,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__hash_table(const hasher& __hf, const key_equal& __eql, const allocator_type& __a) : __bucket_list_(nullptr, __bucket_list_deleter(__pointer_allocator(__a), 0)), - __p1_(__node_allocator(__a)), + __p1_(__default_init_tag(), __node_allocator(__a)), __p2_(0, __hf), __p3_(1.0f, __eql) { @@ -1393,9 +1430,9 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__hash_table(const hasher& __hf, template __hash_table<_Tp, _Hash, _Equal, _Alloc>::__hash_table(const allocator_type& __a) : __bucket_list_(nullptr, __bucket_list_deleter(__pointer_allocator(__a), 0)), - __p1_(__node_allocator(__a)), - __p2_(0), - __p3_(1.0f) + __p1_(__default_init_tag(), __node_allocator(__a)), + __p2_(0, __default_init_tag()), + __p3_(1.0f, __default_init_tag()) { } @@ -1405,7 +1442,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__hash_table(const __hash_table& __u) __bucket_list_deleter(allocator_traits<__pointer_allocator>:: select_on_container_copy_construction( __u.__bucket_list_.get_deleter().__alloc()), 0)), - __p1_(allocator_traits<__node_allocator>:: + __p1_(__default_init_tag(), allocator_traits<__node_allocator>:: select_on_container_copy_construction(__u.__node_alloc())), __p2_(0, __u.hash_function()), __p3_(__u.__p3_) @@ -1416,14 +1453,12 @@ template __hash_table<_Tp, _Hash, _Equal, _Alloc>::__hash_table(const __hash_table& __u, const allocator_type& __a) : __bucket_list_(nullptr, __bucket_list_deleter(__pointer_allocator(__a), 0)), - __p1_(__node_allocator(__a)), + __p1_(__default_init_tag(), __node_allocator(__a)), __p2_(0, __u.hash_function()), __p3_(__u.__p3_) { } -#ifndef _LIBCPP_CXX03_LANG - template __hash_table<_Tp, _Hash, _Equal, _Alloc>::__hash_table(__hash_table&& __u) _NOEXCEPT_( @@ -1439,8 +1474,8 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__hash_table(__hash_table&& __u) { if (size() > 0) { - __bucket_list_[__constrain_hash(__p1_.first().__next_->__hash_, bucket_count())] = - static_cast<__node_pointer>(pointer_traits<__node_base_pointer>::pointer_to(__p1_.first())); + __bucket_list_[__constrain_hash(__p1_.first().__next_->__hash(), bucket_count())] = + __p1_.first().__ptr(); __u.__p1_.first().__next_ = nullptr; __u.size() = 0; } @@ -1450,7 +1485,7 @@ template __hash_table<_Tp, _Hash, _Equal, _Alloc>::__hash_table(__hash_table&& __u, const allocator_type& __a) : __bucket_list_(nullptr, __bucket_list_deleter(__pointer_allocator(__a), 0)), - __p1_(__node_allocator(__a)), + __p1_(__default_init_tag(), __node_allocator(__a)), __p2_(0, _VSTD::move(__u.hash_function())), __p3_(_VSTD::move(__u.__p3_)) { @@ -1463,25 +1498,26 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__hash_table(__hash_table&& __u, { __p1_.first().__next_ = __u.__p1_.first().__next_; __u.__p1_.first().__next_ = nullptr; - __bucket_list_[__constrain_hash(__p1_.first().__next_->__hash_, bucket_count())] = - static_cast<__node_pointer>(pointer_traits<__node_base_pointer>::pointer_to(__p1_.first())); + __bucket_list_[__constrain_hash(__p1_.first().__next_->__hash(), bucket_count())] = + __p1_.first().__ptr(); size() = __u.size(); __u.size() = 0; } } } -#endif // _LIBCPP_CXX03_LANG - template __hash_table<_Tp, _Hash, _Equal, _Alloc>::~__hash_table() { +#if defined(_LIBCPP_CXX03_LANG) static_assert((is_copy_constructible::value), "Predicate must be copy-constructible."); static_assert((is_copy_constructible::value), "Hasher must be copy-constructible."); - __deallocate(__p1_.first().__next_); -#if _LIBCPP_DEBUG_LEVEL >= 2 +#endif + + __deallocate_node(__p1_.first().__next_); +#if _LIBCPP_DEBUG_LEVEL == 2 __get_db()->__erase_c(this); #endif } @@ -1518,14 +1554,14 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::operator=(const __hash_table& __u) template void -__hash_table<_Tp, _Hash, _Equal, _Alloc>::__deallocate(__node_pointer __np) +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__deallocate_node(__next_pointer __np) _NOEXCEPT { __node_allocator& __na = __node_alloc(); while (__np != nullptr) { - __node_pointer __next = __np->__next_; -#if _LIBCPP_DEBUG_LEVEL >= 2 + __next_pointer __next = __np->__next_; +#if _LIBCPP_DEBUG_LEVEL == 2 __c_node* __c = __get_db()->__find_c_and_lock(this); for (__i_node** __p = __c->end_; __p != __c->beg_; ) { @@ -1535,32 +1571,31 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__deallocate(__node_pointer __np) { (*__p)->__c_ = nullptr; if (--__c->end_ != __p) - memmove(__p, __p+1, (__c->end_ - __p)*sizeof(__i_node*)); + _VSTD::memmove(__p, __p+1, (__c->end_ - __p)*sizeof(__i_node*)); } } __get_db()->unlock(); #endif - __node_traits::destroy(__na, _NodeTypes::__get_ptr(__np->__value_)); - __node_traits::deallocate(__na, __np, 1); + __node_pointer __real_np = __np->__upcast(); + __node_traits::destroy(__na, _NodeTypes::__get_ptr(__real_np->__value_)); + __node_traits::deallocate(__na, __real_np, 1); __np = __next; } } template -typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_pointer +typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::__next_pointer __hash_table<_Tp, _Hash, _Equal, _Alloc>::__detach() _NOEXCEPT { size_type __bc = bucket_count(); for (size_type __i = 0; __i < __bc; ++__i) __bucket_list_[__i] = nullptr; size() = 0; - __node_pointer __cache = __p1_.first().__next_; + __next_pointer __cache = __p1_.first().__next_; __p1_.first().__next_ = nullptr; return __cache; } -#ifndef _LIBCPP_CXX03_LANG - template void __hash_table<_Tp, _Hash, _Equal, _Alloc>::__move_assign( @@ -1582,12 +1617,12 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__move_assign( __p1_.first().__next_ = __u.__p1_.first().__next_; if (size() > 0) { - __bucket_list_[__constrain_hash(__p1_.first().__next_->__hash_, bucket_count())] = - static_cast<__node_pointer>(pointer_traits<__node_base_pointer>::pointer_to(__p1_.first())); + __bucket_list_[__constrain_hash(__p1_.first().__next_->__hash(), bucket_count())] = + __p1_.first().__ptr(); __u.__p1_.first().__next_ = nullptr; __u.size() = 0; } -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 __get_db()->swap(this, &__u); #endif } @@ -1606,7 +1641,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__move_assign( max_load_factor() = __u.max_load_factor(); if (bucket_count() != 0) { - __node_pointer __cache = __detach(); + __next_pointer __cache = __detach(); #ifndef _LIBCPP_NO_EXCEPTIONS try { @@ -1614,20 +1649,21 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__move_assign( const_iterator __i = __u.begin(); while (__cache != nullptr && __u.size() != 0) { - __cache->__value_ = _VSTD::move(__u.remove(__i++)->__value_); - __node_pointer __next = __cache->__next_; - __node_insert_multi(__cache); + __cache->__upcast()->__value_ = + _VSTD::move(__u.remove(__i++)->__value_); + __next_pointer __next = __cache->__next_; + __node_insert_multi(__cache->__upcast()); __cache = __next; } #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { - __deallocate(__cache); + __deallocate_node(__cache); throw; } #endif // _LIBCPP_NO_EXCEPTIONS - __deallocate(__cache); + __deallocate_node(__cache); } const_iterator __i = __u.begin(); while (__u.size() != 0) @@ -1654,8 +1690,6 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::operator=(__hash_table&& __u) return *this; } -#endif // _LIBCPP_CXX03_LANG - template template void @@ -1669,27 +1703,27 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__assign_unique(_InputIterator __first if (bucket_count() != 0) { - __node_pointer __cache = __detach(); + __next_pointer __cache = __detach(); #ifndef _LIBCPP_NO_EXCEPTIONS try { #endif // _LIBCPP_NO_EXCEPTIONS for (; __cache != nullptr && __first != __last; ++__first) { - __cache->__value_ = *__first; - __node_pointer __next = __cache->__next_; - __node_insert_unique(__cache); + __cache->__upcast()->__value_ = *__first; + __next_pointer __next = __cache->__next_; + __node_insert_unique(__cache->__upcast()); __cache = __next; } #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { - __deallocate(__cache); + __deallocate_node(__cache); throw; } #endif // _LIBCPP_NO_EXCEPTIONS - __deallocate(__cache); + __deallocate_node(__cache); } for (; __first != __last; ++__first) __insert_unique(*__first); @@ -1709,27 +1743,27 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__assign_multi(_InputIterator __first, " or the nodes value type"); if (bucket_count() != 0) { - __node_pointer __cache = __detach(); + __next_pointer __cache = __detach(); #ifndef _LIBCPP_NO_EXCEPTIONS try { #endif // _LIBCPP_NO_EXCEPTIONS for (; __cache != nullptr && __first != __last; ++__first) { - __cache->__value_ = *__first; - __node_pointer __next = __cache->__next_; - __node_insert_multi(__cache); + __cache->__upcast()->__value_ = *__first; + __next_pointer __next = __cache->__next_; + __node_insert_multi(__cache->__upcast()); __cache = __next; } #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { - __deallocate(__cache); + __deallocate_node(__cache); throw; } #endif // _LIBCPP_NO_EXCEPTIONS - __deallocate(__cache); + __deallocate_node(__cache); } for (; __first != __last; ++__first) __insert_multi(_NodeTypes::__get_value(*__first)); @@ -1740,7 +1774,7 @@ inline typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator __hash_table<_Tp, _Hash, _Equal, _Alloc>::begin() _NOEXCEPT { -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 return iterator(__p1_.first().__next_, this); #else return iterator(__p1_.first().__next_); @@ -1752,7 +1786,7 @@ inline typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator __hash_table<_Tp, _Hash, _Equal, _Alloc>::end() _NOEXCEPT { -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 return iterator(nullptr, this); #else return iterator(nullptr); @@ -1764,7 +1798,7 @@ inline typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::const_iterator __hash_table<_Tp, _Hash, _Equal, _Alloc>::begin() const _NOEXCEPT { -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 return const_iterator(__p1_.first().__next_, this); #else return const_iterator(__p1_.first().__next_); @@ -1776,7 +1810,7 @@ inline typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::const_iterator __hash_table<_Tp, _Hash, _Equal, _Alloc>::end() const _NOEXCEPT { -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 return const_iterator(nullptr, this); #else return const_iterator(nullptr); @@ -1789,7 +1823,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::clear() _NOEXCEPT { if (size() > 0) { - __deallocate(__p1_.first().__next_); + __deallocate_node(__p1_.first().__next_); __p1_.first().__next_ = nullptr; size_type __bc = bucket_count(); for (size_type __i = 0; __i < __bc; ++__i) @@ -1798,73 +1832,112 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::clear() _NOEXCEPT } } + +// Prepare the container for an insertion of the value __value with the hash +// __hash. This does a lookup into the container to see if __value is already +// present, and performs a rehash if necessary. Returns a pointer to the +// existing element if it exists, otherwise nullptr. +// +// Note that this function does forward exceptions if key_eq() throws, and never +// mutates __value or actually inserts into the map. +template +_LIBCPP_INLINE_VISIBILITY +typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::__next_pointer +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_unique_prepare( + size_t __hash, value_type& __value) +{ + size_type __bc = bucket_count(); + + if (__bc != 0) + { + size_t __chash = __constrain_hash(__hash, __bc); + __next_pointer __ndptr = __bucket_list_[__chash]; + if (__ndptr != nullptr) + { + for (__ndptr = __ndptr->__next_; __ndptr != nullptr && + __constrain_hash(__ndptr->__hash(), __bc) == __chash; + __ndptr = __ndptr->__next_) + { + if (key_eq()(__ndptr->__upcast()->__value_, __value)) + return __ndptr; + } + } + } + if (size()+1 > __bc * max_load_factor() || __bc == 0) + { + rehash(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), + size_type(ceil(float(size() + 1) / max_load_factor())))); + } + return nullptr; +} + +// Insert the node __nd into the container by pushing it into the right bucket, +// and updating size(). Assumes that __nd->__hash is up-to-date, and that +// rehashing has already occurred and that no element with the same key exists +// in the map. +template +_LIBCPP_INLINE_VISIBILITY +void +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_unique_perform( + __node_pointer __nd) _NOEXCEPT +{ + size_type __bc = bucket_count(); + size_t __chash = __constrain_hash(__nd->__hash(), __bc); + // insert_after __bucket_list_[__chash], or __first_node if bucket is null + __next_pointer __pn = __bucket_list_[__chash]; + if (__pn == nullptr) + { + __pn =__p1_.first().__ptr(); + __nd->__next_ = __pn->__next_; + __pn->__next_ = __nd->__ptr(); + // fix up __bucket_list_ + __bucket_list_[__chash] = __pn; + if (__nd->__next_ != nullptr) + __bucket_list_[__constrain_hash(__nd->__next_->__hash(), __bc)] = __nd->__ptr(); + } + else + { + __nd->__next_ = __pn->__next_; + __pn->__next_ = __nd->__ptr(); + } + ++size(); +} + template pair::iterator, bool> __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_unique(__node_pointer __nd) { __nd->__hash_ = hash_function()(__nd->__value_); - size_type __bc = bucket_count(); + __next_pointer __existing_node = + __node_insert_unique_prepare(__nd->__hash(), __nd->__value_); + + // Insert the node, unless it already exists in the container. bool __inserted = false; - __node_pointer __ndptr; - size_t __chash; - if (__bc != 0) + if (__existing_node == nullptr) { - __chash = __constrain_hash(__nd->__hash_, __bc); - __ndptr = __bucket_list_[__chash]; - if (__ndptr != nullptr) - { - for (__ndptr = __ndptr->__next_; __ndptr != nullptr && - __constrain_hash(__ndptr->__hash_, __bc) == __chash; - __ndptr = __ndptr->__next_) - { - if (key_eq()(__ndptr->__value_, __nd->__value_)) - goto __done; - } - } - } - { - if (size()+1 > __bc * max_load_factor() || __bc == 0) - { - rehash(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), - size_type(ceil(float(size() + 1) / max_load_factor())))); - __bc = bucket_count(); - __chash = __constrain_hash(__nd->__hash_, __bc); - } - // insert_after __bucket_list_[__chash], or __first_node if bucket is null - __node_pointer __pn = __bucket_list_[__chash]; - if (__pn == nullptr) - { - __pn = static_cast<__node_pointer>(pointer_traits<__node_base_pointer>::pointer_to(__p1_.first())); - __nd->__next_ = __pn->__next_; - __pn->__next_ = __nd; - // fix up __bucket_list_ - __bucket_list_[__chash] = __pn; - if (__nd->__next_ != nullptr) - __bucket_list_[__constrain_hash(__nd->__next_->__hash_, __bc)] = __nd; - } - else - { - __nd->__next_ = __pn->__next_; - __pn->__next_ = __nd; - } - __ndptr = __nd; - // increment size - ++size(); + __node_insert_unique_perform(__nd); + __existing_node = __nd->__ptr(); __inserted = true; } -__done: -#if _LIBCPP_DEBUG_LEVEL >= 2 - return pair(iterator(__ndptr, this), __inserted); +#if _LIBCPP_DEBUG_LEVEL == 2 + return pair(iterator(__existing_node, this), __inserted); #else - return pair(iterator(__ndptr), __inserted); + return pair(iterator(__existing_node), __inserted); #endif } +// Prepare the container for an insertion of the value __cp_val with the hash +// __cp_hash. This does a lookup into the container to see if __cp_value is +// already present, and performs a rehash if necessary. Returns a pointer to the +// last occurrence of __cp_val in the map. +// +// Note that this function does forward exceptions if key_eq() throws, and never +// mutates __value or actually inserts into the map. template -typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator -__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi(__node_pointer __cp) +typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::__next_pointer +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi_prepare( + size_t __cp_hash, value_type& __cp_val) { - __cp->__hash_ = hash_function()(__cp->__value_); size_type __bc = bucket_count(); if (size()+1 > __bc * max_load_factor() || __bc == 0) { @@ -1872,22 +1945,12 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi(__node_pointer __c size_type(ceil(float(size() + 1) / max_load_factor())))); __bc = bucket_count(); } - size_t __chash = __constrain_hash(__cp->__hash_, __bc); - __node_pointer __pn = __bucket_list_[__chash]; - if (__pn == nullptr) - { - __pn = static_cast<__node_pointer>(pointer_traits<__node_base_pointer>::pointer_to(__p1_.first())); - __cp->__next_ = __pn->__next_; - __pn->__next_ = __cp; - // fix up __bucket_list_ - __bucket_list_[__chash] = __pn; - if (__cp->__next_ != nullptr) - __bucket_list_[__constrain_hash(__cp->__next_->__hash_, __bc)] = __cp; - } - else + size_t __chash = __constrain_hash(__cp_hash, __bc); + __next_pointer __pn = __bucket_list_[__chash]; + if (__pn != nullptr) { for (bool __found = false; __pn->__next_ != nullptr && - __constrain_hash(__pn->__next_->__hash_, __bc) == __chash; + __constrain_hash(__pn->__next_->__hash(), __bc) == __chash; __pn = __pn->__next_) { // __found key_eq() action @@ -1895,8 +1958,8 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi(__node_pointer __c // true true loop // false true set __found to true // true false break - if (__found != (__pn->__next_->__hash_ == __cp->__hash_ && - key_eq()(__pn->__next_->__value_, __cp->__value_))) + if (__found != (__pn->__next_->__hash() == __cp_hash && + key_eq()(__pn->__next_->__upcast()->__value_, __cp_val))) { if (!__found) __found = true; @@ -1904,20 +1967,60 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi(__node_pointer __c break; } } + } + return __pn; +} + +// Insert the node __cp into the container after __pn (which is the last node in +// the bucket that compares equal to __cp). Rehashing, and checking for +// uniqueness has already been performed (in __node_insert_multi_prepare), so +// all we need to do is update the bucket and size(). Assumes that __cp->__hash +// is up-to-date. +template +void +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi_perform( + __node_pointer __cp, __next_pointer __pn) _NOEXCEPT +{ + size_type __bc = bucket_count(); + size_t __chash = __constrain_hash(__cp->__hash_, __bc); + if (__pn == nullptr) + { + __pn =__p1_.first().__ptr(); __cp->__next_ = __pn->__next_; - __pn->__next_ = __cp; + __pn->__next_ = __cp->__ptr(); + // fix up __bucket_list_ + __bucket_list_[__chash] = __pn; + if (__cp->__next_ != nullptr) + __bucket_list_[__constrain_hash(__cp->__next_->__hash(), __bc)] + = __cp->__ptr(); + } + else + { + __cp->__next_ = __pn->__next_; + __pn->__next_ = __cp->__ptr(); if (__cp->__next_ != nullptr) { - size_t __nhash = __constrain_hash(__cp->__next_->__hash_, __bc); + size_t __nhash = __constrain_hash(__cp->__next_->__hash(), __bc); if (__nhash != __chash) - __bucket_list_[__nhash] = __cp; + __bucket_list_[__nhash] = __cp->__ptr(); } } ++size(); -#if _LIBCPP_DEBUG_LEVEL >= 2 - return iterator(__cp, this); +} + + +template +typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi(__node_pointer __cp) +{ + __cp->__hash_ = hash_function()(__cp->__value_); + __next_pointer __pn = __node_insert_multi_prepare(__cp->__hash(), __cp->__value_); + __node_insert_multi_perform(__cp, __pn); + +#if _LIBCPP_DEBUG_LEVEL == 2 + return iterator(__cp->__ptr(), this); #else - return iterator(__cp); + return iterator(__cp->__ptr()); #endif } @@ -1926,15 +2029,15 @@ typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi( const_iterator __p, __node_pointer __cp) { -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__p) == this, "unordered container::emplace_hint(const_iterator, args...) called with an iterator not" " referring to this unordered container"); #endif if (__p != end() && key_eq()(*__p, __cp->__value_)) { - __node_pointer __np = __p.__node_; - __cp->__hash_ = __np->__hash_; + __next_pointer __np = __p.__node_; + __cp->__hash_ = __np->__hash(); size_type __bc = bucket_count(); if (size()+1 > __bc * max_load_factor() || __bc == 0) { @@ -1943,16 +2046,16 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi( __bc = bucket_count(); } size_t __chash = __constrain_hash(__cp->__hash_, __bc); - __node_pointer __pp = __bucket_list_[__chash]; + __next_pointer __pp = __bucket_list_[__chash]; while (__pp->__next_ != __np) __pp = __pp->__next_; __cp->__next_ = __np; - __pp->__next_ = __cp; + __pp->__next_ = static_cast<__next_pointer>(__cp); ++size(); -#if _LIBCPP_DEBUG_LEVEL >= 2 - return iterator(__cp, this); +#if _LIBCPP_DEBUG_LEVEL == 2 + return iterator(static_cast<__next_pointer>(__cp), this); #else - return iterator(__cp); + return iterator(static_cast<__next_pointer>(__cp)); #endif } return __node_insert_multi(__cp); @@ -1960,25 +2063,16 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi( -#ifndef _LIBCPP_CXX03_LANG template template -_LIBCPP_INLINE_VISIBILITY pair::iterator, bool> __hash_table<_Tp, _Hash, _Equal, _Alloc>::__emplace_unique_key_args(_Key const& __k, _Args&&... __args) -#else -template -template -_LIBCPP_INLINE_VISIBILITY -pair::iterator, bool> -__hash_table<_Tp, _Hash, _Equal, _Alloc>::__emplace_unique_key_args(_Key const& __k, _Args& __args) -#endif { size_t __hash = hash_function()(__k); size_type __bc = bucket_count(); bool __inserted = false; - __node_pointer __nd; + __next_pointer __nd; size_t __chash; if (__bc != 0) { @@ -1987,20 +2081,16 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__emplace_unique_key_args(_Key const& if (__nd != nullptr) { for (__nd = __nd->__next_; __nd != nullptr && - __constrain_hash(__nd->__hash_, __bc) == __chash; + (__nd->__hash() == __hash || __constrain_hash(__nd->__hash(), __bc) == __chash); __nd = __nd->__next_) { - if (key_eq()(__nd->__value_, __k)) + if (key_eq()(__nd->__upcast()->__value_, __k)) goto __done; } } } { -#ifndef _LIBCPP_CXX03_LANG __node_holder __h = __construct_node_hash(__hash, _VSTD::forward<_Args>(__args)...); -#else - __node_holder __h = __construct_node_hash(__hash, __args); -#endif if (size()+1 > __bc * max_load_factor() || __bc == 0) { rehash(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), @@ -2009,37 +2099,36 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__emplace_unique_key_args(_Key const& __chash = __constrain_hash(__hash, __bc); } // insert_after __bucket_list_[__chash], or __first_node if bucket is null - __node_pointer __pn = __bucket_list_[__chash]; + __next_pointer __pn = __bucket_list_[__chash]; if (__pn == nullptr) { - __pn = static_cast<__node_pointer>(static_cast<__void_pointer>(pointer_traits<__node_base_pointer>::pointer_to(__p1_.first()))); + __pn = __p1_.first().__ptr(); __h->__next_ = __pn->__next_; - __pn->__next_ = __h.get(); + __pn->__next_ = __h.get()->__ptr(); // fix up __bucket_list_ __bucket_list_[__chash] = __pn; if (__h->__next_ != nullptr) - __bucket_list_[__constrain_hash(__h->__next_->__hash_, __bc)] = __h.get(); + __bucket_list_[__constrain_hash(__h->__next_->__hash(), __bc)] + = __h.get()->__ptr(); } else { __h->__next_ = __pn->__next_; - __pn->__next_ = __h.get(); + __pn->__next_ = static_cast<__next_pointer>(__h.get()); } - __nd = __h.release(); + __nd = static_cast<__next_pointer>(__h.release()); // increment size ++size(); __inserted = true; } __done: -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 return pair(iterator(__nd, this), __inserted); #else return pair(iterator(__nd), __inserted); #endif } -#ifndef _LIBCPP_CXX03_LANG - template template pair::iterator, bool> @@ -2069,7 +2158,7 @@ typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator __hash_table<_Tp, _Hash, _Equal, _Alloc>::__emplace_hint_multi( const_iterator __p, _Args&&... __args) { -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__p) == this, "unordered container::emplace_hint(const_iterator, args...) called with an iterator not" " referring to this unordered container"); @@ -2080,39 +2169,142 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__emplace_hint_multi( return __r; } -#else // _LIBCPP_CXX03_LANG - +#if _LIBCPP_STD_VER > 14 template -typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator -__hash_table<_Tp, _Hash, _Equal, _Alloc>::__insert_multi(const __container_value_type& __x) +template +_LIBCPP_INLINE_VISIBILITY +_InsertReturnType +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_handle_insert_unique( + _NodeHandle&& __nh) { - __node_holder __h = __construct_node(__x); - iterator __r = __node_insert_multi(__h.get()); - __h.release(); - return __r; + if (__nh.empty()) + return _InsertReturnType{end(), false, _NodeHandle()}; + pair __result = __node_insert_unique(__nh.__ptr_); + if (__result.second) + __nh.__release_ptr(); + return _InsertReturnType{__result.first, __result.second, _VSTD::move(__nh)}; } template +template +_LIBCPP_INLINE_VISIBILITY typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator -__hash_table<_Tp, _Hash, _Equal, _Alloc>::__insert_multi(const_iterator __p, - const __container_value_type& __x) +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_handle_insert_unique( + const_iterator, _NodeHandle&& __nh) { -#if _LIBCPP_DEBUG_LEVEL >= 2 - _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__p) == this, - "unordered container::insert(const_iterator, lvalue) called with an iterator not" - " referring to this unordered container"); -#endif - __node_holder __h = __construct_node(__x); - iterator __r = __node_insert_multi(__p, __h.get()); - __h.release(); - return __r; + if (__nh.empty()) + return end(); + pair __result = __node_insert_unique(__nh.__ptr_); + if (__result.second) + __nh.__release_ptr(); + return __result.first; } -#endif // _LIBCPP_CXX03_LANG +template +template +_LIBCPP_INLINE_VISIBILITY +_NodeHandle +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_handle_extract( + key_type const& __key) +{ + iterator __i = find(__key); + if (__i == end()) + return _NodeHandle(); + return __node_handle_extract<_NodeHandle>(__i); +} + +template +template +_LIBCPP_INLINE_VISIBILITY +_NodeHandle +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_handle_extract( + const_iterator __p) +{ + allocator_type __alloc(__node_alloc()); + return _NodeHandle(remove(__p).release(), __alloc); +} + +template +template +_LIBCPP_INLINE_VISIBILITY +void +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_handle_merge_unique( + _Table& __source) +{ + static_assert(is_same<__node, typename _Table::__node>::value, ""); + + for (typename _Table::iterator __it = __source.begin(); + __it != __source.end();) + { + __node_pointer __src_ptr = __it.__node_->__upcast(); + size_t __hash = hash_function()(__src_ptr->__value_); + __next_pointer __existing_node = + __node_insert_unique_prepare(__hash, __src_ptr->__value_); + auto __prev_iter = __it++; + if (__existing_node == nullptr) + { + (void)__source.remove(__prev_iter).release(); + __src_ptr->__hash_ = __hash; + __node_insert_unique_perform(__src_ptr); + } + } +} + +template +template +_LIBCPP_INLINE_VISIBILITY +typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_handle_insert_multi( + _NodeHandle&& __nh) +{ + if (__nh.empty()) + return end(); + iterator __result = __node_insert_multi(__nh.__ptr_); + __nh.__release_ptr(); + return __result; +} + +template +template +_LIBCPP_INLINE_VISIBILITY +typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_handle_insert_multi( + const_iterator __hint, _NodeHandle&& __nh) +{ + if (__nh.empty()) + return end(); + iterator __result = __node_insert_multi(__hint, __nh.__ptr_); + __nh.__release_ptr(); + return __result; +} + +template +template +_LIBCPP_INLINE_VISIBILITY +void +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_handle_merge_multi( + _Table& __source) +{ + static_assert(is_same::value, ""); + + for (typename _Table::iterator __it = __source.begin(); + __it != __source.end();) + { + __node_pointer __src_ptr = __it.__node_->__upcast(); + size_t __src_hash = hash_function()(__src_ptr->__value_); + __next_pointer __pn = + __node_insert_multi_prepare(__src_hash, __src_ptr->__value_); + (void)__source.remove(__it++).release(); + __src_ptr->__hash_ = __src_hash; + __node_insert_multi_perform(__src_ptr, __pn); + } +} +#endif // _LIBCPP_STD_VER > 14 template void __hash_table<_Tp, _Hash, _Equal, _Alloc>::rehash(size_type __n) +_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK { if (__n == 1) __n = 2; @@ -2138,9 +2330,9 @@ template void __hash_table<_Tp, _Hash, _Equal, _Alloc>::__rehash(size_type __nbc) { -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 __get_db()->__invalidate_all(this); -#endif // _LIBCPP_DEBUG_LEVEL >= 2 +#endif __pointer_allocator& __npa = __bucket_list_.get_deleter().__alloc(); __bucket_list_.reset(__nbc > 0 ? __pointer_alloc_traits::allocate(__npa, __nbc) : nullptr); @@ -2149,17 +2341,17 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__rehash(size_type __nbc) { for (size_type __i = 0; __i < __nbc; ++__i) __bucket_list_[__i] = nullptr; - __node_pointer __pp(static_cast<__node_pointer>(pointer_traits<__node_base_pointer>::pointer_to(__p1_.first()))); - __node_pointer __cp = __pp->__next_; + __next_pointer __pp = __p1_.first().__ptr(); + __next_pointer __cp = __pp->__next_; if (__cp != nullptr) { - size_type __chash = __constrain_hash(__cp->__hash_, __nbc); + size_type __chash = __constrain_hash(__cp->__hash(), __nbc); __bucket_list_[__chash] = __pp; size_type __phash = __chash; for (__pp = __cp, __cp = __cp->__next_; __cp != nullptr; __cp = __pp->__next_) { - __chash = __constrain_hash(__cp->__hash_, __nbc); + __chash = __constrain_hash(__cp->__hash(), __nbc); if (__chash == __phash) __pp = __cp; else @@ -2172,9 +2364,10 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__rehash(size_type __nbc) } else { - __node_pointer __np = __cp; + __next_pointer __np = __cp; for (; __np->__next_ != nullptr && - key_eq()(__cp->__value_, __np->__next_->__value_); + key_eq()(__cp->__upcast()->__value_, + __np->__next_->__upcast()->__value_); __np = __np->__next_) ; __pp->__next_ = __np->__next_; @@ -2198,16 +2391,17 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::find(const _Key& __k) if (__bc != 0) { size_t __chash = __constrain_hash(__hash, __bc); - __node_pointer __nd = __bucket_list_[__chash]; + __next_pointer __nd = __bucket_list_[__chash]; if (__nd != nullptr) { for (__nd = __nd->__next_; __nd != nullptr && - (__nd->__hash_ == __hash - || __constrain_hash(__nd->__hash_, __bc) == __chash); + (__nd->__hash() == __hash + || __constrain_hash(__nd->__hash(), __bc) == __chash); __nd = __nd->__next_) { - if ((__nd->__hash_ == __hash) && key_eq()(__nd->__value_, __k)) -#if _LIBCPP_DEBUG_LEVEL >= 2 + if ((__nd->__hash() == __hash) + && key_eq()(__nd->__upcast()->__value_, __k)) +#if _LIBCPP_DEBUG_LEVEL == 2 return iterator(__nd, this); #else return iterator(__nd); @@ -2228,15 +2422,17 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::find(const _Key& __k) const if (__bc != 0) { size_t __chash = __constrain_hash(__hash, __bc); - __node_const_pointer __nd = __bucket_list_[__chash]; + __next_pointer __nd = __bucket_list_[__chash]; if (__nd != nullptr) { for (__nd = __nd->__next_; __nd != nullptr && - (__hash == __nd->__hash_ || __constrain_hash(__nd->__hash_, __bc) == __chash); + (__hash == __nd->__hash() + || __constrain_hash(__nd->__hash(), __bc) == __chash); __nd = __nd->__next_) { - if ((__nd->__hash_ == __hash) && key_eq()(__nd->__value_, __k)) -#if _LIBCPP_DEBUG_LEVEL >= 2 + if ((__nd->__hash() == __hash) + && key_eq()(__nd->__upcast()->__value_, __k)) +#if _LIBCPP_DEBUG_LEVEL == 2 return const_iterator(__nd, this); #else return const_iterator(__nd); @@ -2248,8 +2444,6 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::find(const _Key& __k) const return end(); } -#ifndef _LIBCPP_CXX03_LANG - template template typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_holder @@ -2285,43 +2479,12 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__construct_node_hash( return __h; } -#else // _LIBCPP_CXX03_LANG - -template -typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_holder -__hash_table<_Tp, _Hash, _Equal, _Alloc>::__construct_node(const __container_value_type& __v) -{ - __node_allocator& __na = __node_alloc(); - __node_holder __h(__node_traits::allocate(__na, 1), _Dp(__na)); - __node_traits::construct(__na, _NodeTypes::__get_ptr(__h->__value_), __v); - __h.get_deleter().__value_constructed = true; - __h->__hash_ = hash_function()(__h->__value_); - __h->__next_ = nullptr; - return _LIBCPP_EXPLICIT_MOVE(__h); // explicitly moved for C++03 -} - -template -typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_holder -__hash_table<_Tp, _Hash, _Equal, _Alloc>::__construct_node_hash(size_t __hash, - const __container_value_type& __v) -{ - __node_allocator& __na = __node_alloc(); - __node_holder __h(__node_traits::allocate(__na, 1), _Dp(__na)); - __node_traits::construct(__na, _NodeTypes::__get_ptr(__h->__value_), __v); - __h.get_deleter().__value_constructed = true; - __h->__hash_ = __hash; - __h->__next_ = nullptr; - return _LIBCPP_EXPLICIT_MOVE(__h); // explicitly moved for C++03 -} - -#endif // _LIBCPP_CXX03_LANG - template typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator __hash_table<_Tp, _Hash, _Equal, _Alloc>::erase(const_iterator __p) { - __node_pointer __np = __p.__node_; -#if _LIBCPP_DEBUG_LEVEL >= 2 + __next_pointer __np = __p.__node_; +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__p) == this, "unordered container erase(iterator) called with an iterator not" " referring to this container"); @@ -2341,7 +2504,7 @@ typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator __hash_table<_Tp, _Hash, _Equal, _Alloc>::erase(const_iterator __first, const_iterator __last) { -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__first) == this, "unodered container::erase(iterator, iterator) called with an iterator not" " referring to this unodered container"); @@ -2354,8 +2517,8 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::erase(const_iterator __first, ++__first; erase(__p); } - __node_pointer __np = __last.__node_; -#if _LIBCPP_DEBUG_LEVEL >= 2 + __next_pointer __np = __last.__node_; +#if _LIBCPP_DEBUG_LEVEL == 2 return iterator (__np, this); #else return iterator (__np); @@ -2398,26 +2561,27 @@ typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_holder __hash_table<_Tp, _Hash, _Equal, _Alloc>::remove(const_iterator __p) _NOEXCEPT { // current node - __node_pointer __cn = __p.__node_; + __next_pointer __cn = __p.__node_; size_type __bc = bucket_count(); - size_t __chash = __constrain_hash(__cn->__hash_, __bc); + size_t __chash = __constrain_hash(__cn->__hash(), __bc); // find previous node - __node_pointer __pn = __bucket_list_[__chash]; + __next_pointer __pn = __bucket_list_[__chash]; for (; __pn->__next_ != __cn; __pn = __pn->__next_) ; // Fix up __bucket_list_ // if __pn is not in same bucket (before begin is not in same bucket) && // if __cn->__next_ is not in same bucket (nullptr is not in same bucket) - if (__pn == static_cast<__node_pointer>(pointer_traits<__node_base_pointer>::pointer_to(__p1_.first())) - || __constrain_hash(__pn->__hash_, __bc) != __chash) + if (__pn == __p1_.first().__ptr() + || __constrain_hash(__pn->__hash(), __bc) != __chash) { - if (__cn->__next_ == nullptr || __constrain_hash(__cn->__next_->__hash_, __bc) != __chash) + if (__cn->__next_ == nullptr + || __constrain_hash(__cn->__next_->__hash(), __bc) != __chash) __bucket_list_[__chash] = nullptr; } // if __cn->__next_ is not in same bucket (nullptr is in same bucket) if (__cn->__next_ != nullptr) { - size_t __nhash = __constrain_hash(__cn->__next_->__hash_, __bc); + size_t __nhash = __constrain_hash(__cn->__next_->__hash(), __bc); if (__nhash != __chash) __bucket_list_[__nhash] = __pn; } @@ -2425,22 +2589,22 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::remove(const_iterator __p) _NOEXCEPT __pn->__next_ = __cn->__next_; __cn->__next_ = nullptr; --size(); -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 __c_node* __c = __get_db()->__find_c_and_lock(this); - for (__i_node** __p = __c->end_; __p != __c->beg_; ) + for (__i_node** __dp = __c->end_; __dp != __c->beg_; ) { - --__p; - iterator* __i = static_cast((*__p)->__i_); + --__dp; + iterator* __i = static_cast((*__dp)->__i_); if (__i->__node_ == __cn) { - (*__p)->__c_ = nullptr; - if (--__c->end_ != __p) - memmove(__p, __p+1, (__c->end_ - __p)*sizeof(__i_node*)); + (*__dp)->__c_ = nullptr; + if (--__c->end_ != __dp) + _VSTD::memmove(__dp, __dp+1, (__c->end_ - __dp)*sizeof(__i_node*)); } } __get_db()->unlock(); #endif - return __node_holder(__cn, _Dp(__node_alloc(), true)); + return __node_holder(__cn->__upcast(), _Dp(__node_alloc(), true)); } template @@ -2554,25 +2718,29 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::swap(__hash_table& __u) _NOEXCEPT_(__is_nothrow_swappable::value && __is_nothrow_swappable::value) #endif { + _LIBCPP_ASSERT(__node_traits::propagate_on_container_swap::value || + this->__node_alloc() == __u.__node_alloc(), + "list::swap: Either propagate_on_container_swap must be true" + " or the allocators must compare equal"); { __node_pointer_pointer __npp = __bucket_list_.release(); __bucket_list_.reset(__u.__bucket_list_.release()); __u.__bucket_list_.reset(__npp); } _VSTD::swap(__bucket_list_.get_deleter().size(), __u.__bucket_list_.get_deleter().size()); - __swap_allocator(__bucket_list_.get_deleter().__alloc(), + _VSTD::__swap_allocator(__bucket_list_.get_deleter().__alloc(), __u.__bucket_list_.get_deleter().__alloc()); - __swap_allocator(__node_alloc(), __u.__node_alloc()); + _VSTD::__swap_allocator(__node_alloc(), __u.__node_alloc()); _VSTD::swap(__p1_.first().__next_, __u.__p1_.first().__next_); __p2_.swap(__u.__p2_); __p3_.swap(__u.__p3_); if (size() > 0) - __bucket_list_[__constrain_hash(__p1_.first().__next_->__hash_, bucket_count())] = - static_cast<__node_pointer>(pointer_traits<__node_base_pointer>::pointer_to(__p1_.first())); + __bucket_list_[__constrain_hash(__p1_.first().__next_->__hash(), bucket_count())] = + __p1_.first().__ptr(); if (__u.size() > 0) - __u.__bucket_list_[__constrain_hash(__u.__p1_.first().__next_->__hash_, __u.bucket_count())] = - static_cast<__node_pointer>(pointer_traits<__node_base_pointer>::pointer_to(__u.__p1_.first())); -#if _LIBCPP_DEBUG_LEVEL >= 2 + __u.__bucket_list_[__constrain_hash(__u.__p1_.first().__next_->__hash(), __u.bucket_count())] = + __u.__p1_.first().__ptr(); +#if _LIBCPP_DEBUG_LEVEL == 2 __get_db()->swap(this, &__u); #endif } @@ -2583,13 +2751,13 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::bucket_size(size_type __n) const { _LIBCPP_ASSERT(__n < bucket_count(), "unordered container::bucket_size(n) called with n >= bucket_count()"); - __node_const_pointer __np = __bucket_list_[__n]; + __next_pointer __np = __bucket_list_[__n]; size_type __bc = bucket_count(); size_type __r = 0; if (__np != nullptr) { for (__np = __np->__next_; __np != nullptr && - __constrain_hash(__np->__hash_, __bc) == __n; + __constrain_hash(__np->__hash(), __bc) == __n; __np = __np->__next_, ++__r) ; } @@ -2606,7 +2774,7 @@ swap(__hash_table<_Tp, _Hash, _Equal, _Alloc>& __x, __x.swap(__y); } -#if _LIBCPP_DEBUG_LEVEL >= 2 +#if _LIBCPP_DEBUG_LEVEL == 2 template bool @@ -2636,7 +2804,10 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__subscriptable(const const_iterator*, return false; } -#endif // _LIBCPP_DEBUG_LEVEL >= 2 +#endif // _LIBCPP_DEBUG_LEVEL == 2 + _LIBCPP_END_NAMESPACE_STD +_LIBCPP_POP_MACROS + #endif // _LIBCPP__HASH_TABLE diff --git a/sdk/tlibcxx/include/__libcpp_version b/sdk/tlibcxx/include/__libcpp_version new file mode 100644 index 00000000..e334181b --- /dev/null +++ b/sdk/tlibcxx/include/__libcpp_version @@ -0,0 +1 @@ +12000 diff --git a/sdk/tlibcxx/include/__locale b/sdk/tlibcxx/include/__locale index 71fee667..077a7801 100644 --- a/sdk/tlibcxx/include/__locale +++ b/sdk/tlibcxx/include/__locale @@ -1,18 +1,19 @@ // -*- C++ -*- //===----------------------------------------------------------------------===// // -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef _LIBCPP___LOCALE #define _LIBCPP___LOCALE -// Not supported in SGX. +// partially supported in SGX + #include <__config> +#include <__availability> #include #include #include @@ -22,29 +23,35 @@ #if !defined(_LIBCPP_SGX_CONFIG) #include #endif -#if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) -# include -#elif defined(_AIX) -# include +#if defined(_LIBCPP_MSVCRT_LIKE) +# include +# include <__support/win32/locale_win32.h> +#elif defined(__NuttX__) +# include <__support/nuttx/xlocale.h> +#elif defined(_AIX) || defined(__MVS__) +# include <__support/ibm/xlocale.h> #elif defined(__ANDROID__) -// Android gained the locale aware functions in L (API level 21) -# include -# if __ANDROID_API__ <= 20 -# include -# endif +# include <__support/android/locale_bionic.h> #elif defined(__sun__) # include -# include +# include <__support/solaris/xlocale.h> #elif defined(_NEWLIB_VERSION) -# include -#elif (defined(__GLIBC__) || defined(__APPLE__) || defined(__FreeBSD__) \ +# include <__support/newlib/xlocale.h> +#elif defined(__OpenBSD__) +# include <__support/openbsd/xlocale.h> +#elif (defined(__APPLE__) || defined(__FreeBSD__) \ || defined(__EMSCRIPTEN__) || defined(__IBMCPP__)) # include +#elif defined(__Fuchsia__) +# include <__support/fuchsia/xlocale.h> +#elif defined(__wasi__) +// WASI libc uses musl's locales support. +# include <__support/musl/xlocale.h> #elif defined(_LIBCPP_HAS_MUSL_LIBC) -# include +# include <__support/musl/xlocale.h> #elif defined(_LIBCPP_SGX_CONFIG) -# include -#endif // __GLIBC__ || __APPLE__ || __FreeBSD__ || __sun__ || __EMSCRIPTEN__ || __IBMCPP__ +# include <__support/sgx/xlocale.h> +#endif #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header @@ -52,6 +59,63 @@ _LIBCPP_BEGIN_NAMESPACE_STD +#if !defined(_LIBCPP_LOCALE__L_EXTENSIONS) +struct __libcpp_locale_guard { + _LIBCPP_INLINE_VISIBILITY + __libcpp_locale_guard(locale_t& __loc) : __old_loc_(uselocale(__loc)) {} + + _LIBCPP_INLINE_VISIBILITY + ~__libcpp_locale_guard() { + if (__old_loc_) + uselocale(__old_loc_); + } + + locale_t __old_loc_; +private: + __libcpp_locale_guard(__libcpp_locale_guard const&); + __libcpp_locale_guard& operator=(__libcpp_locale_guard const&); +}; +#elif defined(_LIBCPP_MSVCRT_LIKE) +struct __libcpp_locale_guard { + __libcpp_locale_guard(locale_t __l) : + __status(_configthreadlocale(_ENABLE_PER_THREAD_LOCALE)) { + // Setting the locale can be expensive even when the locale given is + // already the current locale, so do an explicit check to see if the + // current locale is already the one we want. + const char* __lc = __setlocale(nullptr); + // If every category is the same, the locale string will simply be the + // locale name, otherwise it will be a semicolon-separated string listing + // each category. In the second case, we know at least one category won't + // be what we want, so we only have to check the first case. + if (_VSTD::strcmp(__l.__get_locale(), __lc) != 0) { + __locale_all = _strdup(__lc); + if (__locale_all == nullptr) + __throw_bad_alloc(); + __setlocale(__l.__get_locale()); + } + } + ~__libcpp_locale_guard() { + // The CRT documentation doesn't explicitly say, but setlocale() does the + // right thing when given a semicolon-separated list of locale settings + // for the different categories in the same format as returned by + // setlocale(LC_ALL, nullptr). + if (__locale_all != nullptr) { + __setlocale(__locale_all); + free(__locale_all); + } + _configthreadlocale(__status); + } + static const char* __setlocale(const char* __locale) { + const char* __new_locale = setlocale(LC_ALL, __locale); + if (__new_locale == nullptr) + __throw_bad_alloc(); + return __new_locale; + } + int __status; + char* __locale_all = nullptr; +}; +#endif + class _LIBCPP_TYPE_VIS locale; template @@ -72,6 +136,7 @@ public: class _LIBCPP_TYPE_VIS id; typedef int category; + _LIBCPP_AVAILABILITY_LOCALE_CATEGORY static const category // values assigned here are for exposition only none = 0, #if !defined(_LIBCPP_SGX_CONFIG) @@ -105,13 +170,16 @@ public: const locale& operator=(const locale&) _NOEXCEPT; - template locale combine(const locale&) const; + template + _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS + locale combine(const locale&) const; // locale operations: string name() const; bool operator==(const locale&) const; bool operator!=(const locale& __y) const {return !(*this == __y);} template + _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS bool operator()(const basic_string<_CharT, _Traits, _Allocator>&, const basic_string<_CharT, _Traits, _Allocator>&) const; @@ -178,10 +246,9 @@ template locale locale::combine(const locale& __other) const { -#ifndef _LIBCPP_NO_EXCEPTIONS if (!_VSTD::has_facet<_Facet>(__other)) - throw runtime_error("locale::combine: locale missing facet"); -#endif // _LIBCPP_NO_EXCEPTIONS + __throw_runtime_error("locale::combine: locale missing facet"); + return locale(*this, &const_cast<_Facet&>(_VSTD::use_facet<_Facet>(__other))); } @@ -205,7 +272,7 @@ use_facet(const locale& __l) // template class collate; template -class _LIBCPP_TYPE_VIS_ONLY collate +class _LIBCPP_TEMPLATE_VIS collate : public locale::facet { public: @@ -223,7 +290,10 @@ public: return do_compare(__lo1, __hi1, __lo2, __hi2); } + // FIXME(EricWF): The _LIBCPP_ALWAYS_INLINE is needed on Windows to work + // around a dllimport bug that expects an external instantiation. _LIBCPP_INLINE_VISIBILITY + _LIBCPP_ALWAYS_INLINE string_type transform(const char_type* __lo, const char_type* __hi) const { return do_transform(__lo, __hi); @@ -284,12 +354,12 @@ collate<_CharT>::do_hash(const char_type* __lo, const char_type* __hi) const return static_cast(__h); } -_LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS collate) -_LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS collate) +_LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS collate) +_LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS collate) // template class collate_byname; -template class _LIBCPP_TYPE_VIS_ONLY collate_byname; +template class _LIBCPP_TEMPLATE_VIS collate_byname; template <> class _LIBCPP_TYPE_VIS collate_byname @@ -346,7 +416,26 @@ locale::operator()(const basic_string<_CharT, _Traits, _Allocator>& __x, class _LIBCPP_TYPE_VIS ctype_base { public: -#if defined(__GLIBC__) +#if defined(_LIBCPP_PROVIDES_DEFAULT_RUNE_TABLE) + typedef unsigned long mask; + static const mask space = 1<<0; + static const mask print = 1<<1; + static const mask cntrl = 1<<2; + static const mask upper = 1<<3; + static const mask lower = 1<<4; + static const mask alpha = 1<<5; + static const mask digit = 1<<6; + static const mask punct = 1<<7; + static const mask xdigit = 1<<8; + static const mask blank = 1<<9; +#if defined(__BIONIC__) + // Historically this was a part of regex_traits rather than ctype_base. The + // historical value of the constant is preserved for ABI compatibility. + static const mask __regex_word = 0x8000; +#else + static const mask __regex_word = 1<<10; +#endif // defined(__BIONIC__) +#elif defined(__GLIBC__) typedef unsigned short mask; static const mask space = _ISspace; static const mask print = _ISprint; @@ -358,7 +447,12 @@ public: static const mask punct = _ISpunct; static const mask xdigit = _ISxdigit; static const mask blank = _ISblank; -#elif defined(_WIN32) +#if defined(__mips__) + static const mask __regex_word = static_cast(_ISbit(15)); +#else + static const mask __regex_word = 0x80; +#endif +#elif defined(_LIBCPP_MSVCRT_LIKE) typedef unsigned short mask; static const mask space = _SPACE; static const mask print = _BLANK|_PUNCT|_ALPHA|_DIGIT; @@ -370,6 +464,7 @@ public: static const mask punct = _PUNCT; static const mask xdigit = _HEX; static const mask blank = _BLANK; + static const mask __regex_word = 0x80; # define _LIBCPP_CTYPE_MASK_IS_COMPOSITE_PRINT #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__EMSCRIPTEN__) || defined(__NetBSD__) # ifdef __APPLE__ @@ -391,8 +486,12 @@ public: # if defined(__NetBSD__) static const mask blank = _CTYPE_BL; + // NetBSD defines classes up to 0x2000 + // see sys/ctype_bits.h, _CTYPE_Q + static const mask __regex_word = 0x8000; # else static const mask blank = _CTYPE_B; + static const mask __regex_word = 0x80; # endif #elif defined(__sun__) || defined(_AIX) typedef unsigned int mask; @@ -406,6 +505,7 @@ public: static const mask punct = _ISPUNCT; static const mask xdigit = _ISXDIGIT; static const mask blank = _ISBLANK; + static const mask __regex_word = 0x80; #elif defined(_NEWLIB_VERSION) // Same type as Newlib's _ctype_ array in newlib/libc/include/ctype.h. typedef char mask; @@ -419,29 +519,20 @@ public: static const mask punct = _P; static const mask xdigit = _X | _N; static const mask blank = _B; + static const mask __regex_word = 0x80; # define _LIBCPP_CTYPE_MASK_IS_COMPOSITE_PRINT # define _LIBCPP_CTYPE_MASK_IS_COMPOSITE_ALPHA # define _LIBCPP_CTYPE_MASK_IS_COMPOSITE_XDIGIT #else - typedef unsigned long mask; - static const mask space = 1<<0; - static const mask print = 1<<1; - static const mask cntrl = 1<<2; - static const mask upper = 1<<3; - static const mask lower = 1<<4; - static const mask alpha = 1<<5; - static const mask digit = 1<<6; - static const mask punct = 1<<7; - static const mask xdigit = 1<<8; - static const mask blank = 1<<9; +# error unknown rune table for this platform -- do you mean to define _LIBCPP_PROVIDES_DEFAULT_RUNE_TABLE? #endif static const mask alnum = alpha | digit; static const mask graph = alnum | punct; - _LIBCPP_ALWAYS_INLINE ctype_base() {} + _LIBCPP_INLINE_VISIBILITY ctype_base() {} }; -template class _LIBCPP_TYPE_VIS_ONLY ctype; +template class _LIBCPP_TEMPLATE_VIS ctype; template <> class _LIBCPP_TYPE_VIS ctype @@ -451,77 +542,77 @@ class _LIBCPP_TYPE_VIS ctype public: typedef wchar_t char_type; - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY explicit ctype(size_t __refs = 0) : locale::facet(__refs) {} - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY bool is(mask __m, char_type __c) const { return do_is(__m, __c); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* is(const char_type* __low, const char_type* __high, mask* __vec) const { return do_is(__low, __high, __vec); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* scan_is(mask __m, const char_type* __low, const char_type* __high) const { return do_scan_is(__m, __low, __high); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* scan_not(mask __m, const char_type* __low, const char_type* __high) const { return do_scan_not(__m, __low, __high); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY char_type toupper(char_type __c) const { return do_toupper(__c); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* toupper(char_type* __low, const char_type* __high) const { return do_toupper(__low, __high); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY char_type tolower(char_type __c) const { return do_tolower(__c); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* tolower(char_type* __low, const char_type* __high) const { return do_tolower(__low, __high); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY char_type widen(char __c) const { return do_widen(__c); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char* widen(const char* __low, const char* __high, char_type* __to) const { return do_widen(__low, __high, __to); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY char narrow(char_type __c, char __dfault) const { return do_narrow(__c, __dfault); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* narrow(const char_type* __low, const char_type* __high, char __dfault, char* __to) const { return do_narrow(__low, __high, __dfault, __to); @@ -554,15 +645,15 @@ class _LIBCPP_TYPE_VIS ctype public: typedef char char_type; - explicit ctype(const mask* __tab = 0, bool __del = false, size_t __refs = 0); + explicit ctype(const mask* __tab = nullptr, bool __del = false, size_t __refs = 0); - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY bool is(mask __m, char_type __c) const { return isascii(__c) ? (__tab_[static_cast(__c)] & __m) !=0 : false; } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* is(const char_type* __low, const char_type* __high, mask* __vec) const { for (; __low != __high; ++__low, ++__vec) @@ -570,7 +661,7 @@ public: return __low; } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* scan_is (mask __m, const char_type* __low, const char_type* __high) const { for (; __low != __high; ++__low) @@ -579,7 +670,7 @@ public: return __low; } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* scan_not(mask __m, const char_type* __low, const char_type* __high) const { for (; __low != __high; ++__low) @@ -588,49 +679,49 @@ public: return __low; } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY char_type toupper(char_type __c) const { return do_toupper(__c); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* toupper(char_type* __low, const char_type* __high) const { return do_toupper(__low, __high); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY char_type tolower(char_type __c) const { return do_tolower(__c); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char_type* tolower(char_type* __low, const char_type* __high) const { return do_tolower(__low, __high); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY char_type widen(char __c) const { return do_widen(__c); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char* widen(const char* __low, const char* __high, char_type* __to) const { return do_widen(__low, __high, __to); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY char narrow(char_type __c, char __dfault) const { return do_narrow(__c, __dfault); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY const char* narrow(const char_type* __low, const char_type* __high, char __dfault, char* __to) const { return do_narrow(__low, __high, __dfault, __to); @@ -643,7 +734,7 @@ public: #else static const size_t table_size = 256; // FIXME: Don't hardcode this. #endif - _LIBCPP_ALWAYS_INLINE const mask* table() const _NOEXCEPT {return __tab_;} + _LIBCPP_INLINE_VISIBILITY const mask* table() const _NOEXCEPT {return __tab_;} static const mask* classic_table() _NOEXCEPT; #if defined(__GLIBC__) || defined(__EMSCRIPTEN__) static const int* __classic_upper_table() _NOEXCEPT; @@ -668,7 +759,7 @@ protected: // template class ctype_byname; -template class _LIBCPP_TYPE_VIS_ONLY ctype_byname; +template class _LIBCPP_TEMPLATE_VIS ctype_byname; template <> class _LIBCPP_TYPE_VIS ctype_byname @@ -823,13 +914,13 @@ tolower(_CharT __c, const locale& __loc) class _LIBCPP_TYPE_VIS codecvt_base { public: - _LIBCPP_ALWAYS_INLINE codecvt_base() {} + _LIBCPP_INLINE_VISIBILITY codecvt_base() {} enum result {ok, partial, error, noconv}; }; // template class codecvt; -template class _LIBCPP_TYPE_VIS_ONLY codecvt; +template class _LIBCPP_TEMPLATE_VIS codecvt; // template <> class codecvt @@ -843,11 +934,11 @@ public: typedef char extern_type; typedef mbstate_t state_type; - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY explicit codecvt(size_t __refs = 0) : locale::facet(__refs) {} - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const @@ -855,14 +946,14 @@ public: return do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_unshift(__st, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const @@ -870,25 +961,25 @@ public: return do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int encoding() const _NOEXCEPT { return do_encoding(); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY bool always_noconv() const _NOEXCEPT { return do_always_noconv(); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const { return do_length(__st, __frm, __end, __mx); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int max_length() const _NOEXCEPT { return do_max_length(); @@ -897,7 +988,7 @@ public: static locale::id id; protected: - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY explicit codecvt(const char*, size_t __refs = 0) : locale::facet(__refs) {} @@ -932,7 +1023,7 @@ public: explicit codecvt(size_t __refs = 0); - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const @@ -940,14 +1031,14 @@ public: return do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_unshift(__st, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const @@ -955,25 +1046,25 @@ public: return do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int encoding() const _NOEXCEPT { return do_encoding(); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY bool always_noconv() const _NOEXCEPT { return do_always_noconv(); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const { return do_length(__st, __frm, __end, __mx); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int max_length() const _NOEXCEPT { return do_max_length(); @@ -1000,10 +1091,10 @@ protected: virtual int do_max_length() const _NOEXCEPT; }; -// template <> class codecvt +// template <> class codecvt // deprecated in C++20 template <> -class _LIBCPP_TYPE_VIS codecvt +class _LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_TYPE_VIS codecvt : public locale::facet, public codecvt_base { @@ -1012,11 +1103,11 @@ public: typedef char extern_type; typedef mbstate_t state_type; - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY explicit codecvt(size_t __refs = 0) : locale::facet(__refs) {} - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const @@ -1024,14 +1115,14 @@ public: return do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_unshift(__st, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const @@ -1039,25 +1130,25 @@ public: return do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int encoding() const _NOEXCEPT { return do_encoding(); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY bool always_noconv() const _NOEXCEPT { return do_always_noconv(); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const { return do_length(__st, __frm, __end, __mx); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int max_length() const _NOEXCEPT { return do_max_length(); @@ -1066,7 +1157,7 @@ public: static locale::id id; protected: - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY explicit codecvt(const char*, size_t __refs = 0) : locale::facet(__refs) {} @@ -1086,10 +1177,100 @@ protected: virtual int do_max_length() const _NOEXCEPT; }; -// template <> class codecvt +#ifndef _LIBCPP_NO_HAS_CHAR8_T + +// template <> class codecvt // C++20 template <> -class _LIBCPP_TYPE_VIS codecvt +class _LIBCPP_TYPE_VIS codecvt + : public locale::facet, + public codecvt_base +{ +public: + typedef char16_t intern_type; + typedef char8_t extern_type; + typedef mbstate_t state_type; + + _LIBCPP_INLINE_VISIBILITY + explicit codecvt(size_t __refs = 0) + : locale::facet(__refs) {} + + _LIBCPP_INLINE_VISIBILITY + result out(state_type& __st, + const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, + extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const + { + return do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); + } + + _LIBCPP_INLINE_VISIBILITY + result unshift(state_type& __st, + extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const + { + return do_unshift(__st, __to, __to_end, __to_nxt); + } + + _LIBCPP_INLINE_VISIBILITY + result in(state_type& __st, + const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, + intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const + { + return do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); + } + + _LIBCPP_INLINE_VISIBILITY + int encoding() const _NOEXCEPT + { + return do_encoding(); + } + + _LIBCPP_INLINE_VISIBILITY + bool always_noconv() const _NOEXCEPT + { + return do_always_noconv(); + } + + _LIBCPP_INLINE_VISIBILITY + int length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const + { + return do_length(__st, __frm, __end, __mx); + } + + _LIBCPP_INLINE_VISIBILITY + int max_length() const _NOEXCEPT + { + return do_max_length(); + } + + static locale::id id; + +protected: + _LIBCPP_INLINE_VISIBILITY + explicit codecvt(const char*, size_t __refs = 0) + : locale::facet(__refs) {} + + ~codecvt(); + + virtual result do_out(state_type& __st, + const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, + extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; + virtual result do_in(state_type& __st, + const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, + intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const; + virtual result do_unshift(state_type& __st, + extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; + virtual int do_encoding() const _NOEXCEPT; + virtual bool do_always_noconv() const _NOEXCEPT; + virtual int do_length(state_type&, const extern_type* __frm, const extern_type* __end, size_t __mx) const; + virtual int do_max_length() const _NOEXCEPT; +}; + +#endif + +// template <> class codecvt // deprecated in C++20 + +template <> +class _LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_TYPE_VIS codecvt : public locale::facet, public codecvt_base { @@ -1098,11 +1279,11 @@ public: typedef char extern_type; typedef mbstate_t state_type; - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY explicit codecvt(size_t __refs = 0) : locale::facet(__refs) {} - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const @@ -1110,14 +1291,14 @@ public: return do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_unshift(__st, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY result in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const @@ -1125,25 +1306,25 @@ public: return do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int encoding() const _NOEXCEPT { return do_encoding(); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY bool always_noconv() const _NOEXCEPT { return do_always_noconv(); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const { return do_length(__st, __frm, __end, __mx); } - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY int max_length() const _NOEXCEPT { return do_max_length(); @@ -1152,7 +1333,7 @@ public: static locale::id id; protected: - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY explicit codecvt(const char*, size_t __refs = 0) : locale::facet(__refs) {} @@ -1172,36 +1353,130 @@ protected: virtual int do_max_length() const _NOEXCEPT; }; +#ifndef _LIBCPP_NO_HAS_CHAR8_T + +// template <> class codecvt // C++20 + +template <> +class _LIBCPP_TYPE_VIS codecvt + : public locale::facet, + public codecvt_base +{ +public: + typedef char32_t intern_type; + typedef char8_t extern_type; + typedef mbstate_t state_type; + + _LIBCPP_INLINE_VISIBILITY + explicit codecvt(size_t __refs = 0) + : locale::facet(__refs) {} + + _LIBCPP_INLINE_VISIBILITY + result out(state_type& __st, + const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, + extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const + { + return do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); + } + + _LIBCPP_INLINE_VISIBILITY + result unshift(state_type& __st, + extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const + { + return do_unshift(__st, __to, __to_end, __to_nxt); + } + + _LIBCPP_INLINE_VISIBILITY + result in(state_type& __st, + const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, + intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const + { + return do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); + } + + _LIBCPP_INLINE_VISIBILITY + int encoding() const _NOEXCEPT + { + return do_encoding(); + } + + _LIBCPP_INLINE_VISIBILITY + bool always_noconv() const _NOEXCEPT + { + return do_always_noconv(); + } + + _LIBCPP_INLINE_VISIBILITY + int length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const + { + return do_length(__st, __frm, __end, __mx); + } + + _LIBCPP_INLINE_VISIBILITY + int max_length() const _NOEXCEPT + { + return do_max_length(); + } + + static locale::id id; + +protected: + _LIBCPP_INLINE_VISIBILITY + explicit codecvt(const char*, size_t __refs = 0) + : locale::facet(__refs) {} + + ~codecvt(); + + virtual result do_out(state_type& __st, + const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, + extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; + virtual result do_in(state_type& __st, + const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, + intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const; + virtual result do_unshift(state_type& __st, + extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; + virtual int do_encoding() const _NOEXCEPT; + virtual bool do_always_noconv() const _NOEXCEPT; + virtual int do_length(state_type&, const extern_type* __frm, const extern_type* __end, size_t __mx) const; + virtual int do_max_length() const _NOEXCEPT; +}; + +#endif + #if !defined(_LIBCPP_SGX_CONFIG) // template class codecvt_byname template -class _LIBCPP_TYPE_VIS_ONLY codecvt_byname +class _LIBCPP_TEMPLATE_VIS codecvt_byname : public codecvt<_InternT, _ExternT, _StateT> { public: - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY explicit codecvt_byname(const char* __nm, size_t __refs = 0) : codecvt<_InternT, _ExternT, _StateT>(__nm, __refs) {} - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY explicit codecvt_byname(const string& __nm, size_t __refs = 0) : codecvt<_InternT, _ExternT, _StateT>(__nm.c_str(), __refs) {} protected: ~codecvt_byname(); }; +_LIBCPP_SUPPRESS_DEPRECATED_PUSH template codecvt_byname<_InternT, _ExternT, _StateT>::~codecvt_byname() { } +_LIBCPP_SUPPRESS_DEPRECATED_POP -_LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS codecvt_byname) -_LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS codecvt_byname) -_LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS codecvt_byname) -_LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS codecvt_byname) +_LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname) +_LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname) +_LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname) // deprecated in C++20 +_LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname) // deprecated in C++20 +#ifndef _LIBCPP_NO_HAS_CHAR8_T +_LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname) // C++20 +_LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname) // C++20 +#endif #endif - -_LIBCPP_FUNC_VIS void __throw_runtime_error(const char*); template struct __narrow_to_utf8 @@ -1215,7 +1490,7 @@ template <> struct __narrow_to_utf8<8> { template - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY _OutputIterator operator()(_OutputIterator __s, const _CharT* __wb, const _CharT* __we) const { @@ -1225,17 +1500,19 @@ struct __narrow_to_utf8<8> } }; +_LIBCPP_SUPPRESS_DEPRECATED_PUSH template <> -struct __narrow_to_utf8<16> +struct _LIBCPP_TEMPLATE_VIS __narrow_to_utf8<16> : public codecvt { - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY __narrow_to_utf8() : codecvt(1) {} +_LIBCPP_SUPPRESS_DEPRECATED_POP - ~__narrow_to_utf8(); + _LIBCPP_EXPORTED_FROM_ABI ~__narrow_to_utf8(); template - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY _OutputIterator operator()(_OutputIterator __s, const _CharT* __wb, const _CharT* __we) const { @@ -1259,17 +1536,19 @@ struct __narrow_to_utf8<16> } }; +_LIBCPP_SUPPRESS_DEPRECATED_PUSH template <> -struct __narrow_to_utf8<32> +struct _LIBCPP_TEMPLATE_VIS __narrow_to_utf8<32> : public codecvt { - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY __narrow_to_utf8() : codecvt(1) {} +_LIBCPP_SUPPRESS_DEPRECATED_POP - ~__narrow_to_utf8(); + _LIBCPP_EXPORTED_FROM_ABI ~__narrow_to_utf8(); template - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY _OutputIterator operator()(_OutputIterator __s, const _CharT* __wb, const _CharT* __we) const { @@ -1305,7 +1584,7 @@ template <> struct __widen_from_utf8<8> { template - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY _OutputIterator operator()(_OutputIterator __s, const char* __nb, const char* __ne) const { @@ -1315,17 +1594,19 @@ struct __widen_from_utf8<8> } }; +_LIBCPP_SUPPRESS_DEPRECATED_PUSH template <> -struct __widen_from_utf8<16> +struct _LIBCPP_TEMPLATE_VIS __widen_from_utf8<16> : public codecvt { - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY __widen_from_utf8() : codecvt(1) {} +_LIBCPP_SUPPRESS_DEPRECATED_POP - ~__widen_from_utf8(); + _LIBCPP_EXPORTED_FROM_ABI ~__widen_from_utf8(); template - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY _OutputIterator operator()(_OutputIterator __s, const char* __nb, const char* __ne) const { @@ -1342,24 +1623,26 @@ struct __widen_from_utf8<16> if (__r == codecvt_base::error || __nn == __nb) __throw_runtime_error("locale not supported"); for (const char16_t* __p = __buf; __p < __bn; ++__p, ++__s) - *__s = (wchar_t)*__p; + *__s = *__p; __nb = __nn; } return __s; } }; +_LIBCPP_SUPPRESS_DEPRECATED_PUSH template <> -struct __widen_from_utf8<32> +struct _LIBCPP_TEMPLATE_VIS __widen_from_utf8<32> : public codecvt { - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY __widen_from_utf8() : codecvt(1) {} +_LIBCPP_SUPPRESS_DEPRECATED_POP - ~__widen_from_utf8(); + _LIBCPP_EXPORTED_FROM_ABI ~__widen_from_utf8(); template - _LIBCPP_ALWAYS_INLINE + _LIBCPP_INLINE_VISIBILITY _OutputIterator operator()(_OutputIterator __s, const char* __nb, const char* __ne) const { @@ -1376,7 +1659,7 @@ struct __widen_from_utf8<32> if (__r == codecvt_base::error || __nn == __nb) __throw_runtime_error("locale not supported"); for (const char32_t* __p = __buf; __p < __bn; ++__p, ++__s) - *__s = (wchar_t)*__p; + *__s = *__p; __nb = __nn; } return __s; @@ -1386,7 +1669,7 @@ struct __widen_from_utf8<32> #if !defined(_LIBCPP_SGX_CONFIG) // template class numpunct -template class _LIBCPP_TYPE_VIS_ONLY numpunct; +template class _LIBCPP_TEMPLATE_VIS numpunct; template <> class _LIBCPP_TYPE_VIS numpunct @@ -1398,11 +1681,11 @@ public: explicit numpunct(size_t __refs = 0); - _LIBCPP_ALWAYS_INLINE char_type decimal_point() const {return do_decimal_point();} - _LIBCPP_ALWAYS_INLINE char_type thousands_sep() const {return do_thousands_sep();} - _LIBCPP_ALWAYS_INLINE string grouping() const {return do_grouping();} - _LIBCPP_ALWAYS_INLINE string_type truename() const {return do_truename();} - _LIBCPP_ALWAYS_INLINE string_type falsename() const {return do_falsename();} + _LIBCPP_INLINE_VISIBILITY char_type decimal_point() const {return do_decimal_point();} + _LIBCPP_INLINE_VISIBILITY char_type thousands_sep() const {return do_thousands_sep();} + _LIBCPP_INLINE_VISIBILITY string grouping() const {return do_grouping();} + _LIBCPP_INLINE_VISIBILITY string_type truename() const {return do_truename();} + _LIBCPP_INLINE_VISIBILITY string_type falsename() const {return do_falsename();} static locale::id id; @@ -1429,11 +1712,11 @@ public: explicit numpunct(size_t __refs = 0); - _LIBCPP_ALWAYS_INLINE char_type decimal_point() const {return do_decimal_point();} - _LIBCPP_ALWAYS_INLINE char_type thousands_sep() const {return do_thousands_sep();} - _LIBCPP_ALWAYS_INLINE string grouping() const {return do_grouping();} - _LIBCPP_ALWAYS_INLINE string_type truename() const {return do_truename();} - _LIBCPP_ALWAYS_INLINE string_type falsename() const {return do_falsename();} + _LIBCPP_INLINE_VISIBILITY char_type decimal_point() const {return do_decimal_point();} + _LIBCPP_INLINE_VISIBILITY char_type thousands_sep() const {return do_thousands_sep();} + _LIBCPP_INLINE_VISIBILITY string grouping() const {return do_grouping();} + _LIBCPP_INLINE_VISIBILITY string_type truename() const {return do_truename();} + _LIBCPP_INLINE_VISIBILITY string_type falsename() const {return do_falsename();} static locale::id id; @@ -1452,7 +1735,7 @@ protected: // template class numpunct_byname -template class _LIBCPP_TYPE_VIS_ONLY numpunct_byname; +template class _LIBCPP_TEMPLATE_VIS numpunct_byname; template <> class _LIBCPP_TYPE_VIS numpunct_byname @@ -1493,5 +1776,4 @@ private: _LIBCPP_END_NAMESPACE_STD - #endif // _LIBCPP___LOCALE diff --git a/sdk/tlibcxx/include/__memory/allocator_traits.h b/sdk/tlibcxx/include/__memory/allocator_traits.h new file mode 100644 index 00000000..9443f61b --- /dev/null +++ b/sdk/tlibcxx/include/__memory/allocator_traits.h @@ -0,0 +1,401 @@ +// -*- C++ -*- +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___MEMORY_ALLOCATOR_TRAITS_H +#define _LIBCPP___MEMORY_ALLOCATOR_TRAITS_H + +#include <__config> +#include <__memory/base.h> +#include <__memory/pointer_traits.h> +#include + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +#pragma GCC system_header +#endif + +_LIBCPP_PUSH_MACROS +#include <__undef_macros> + +_LIBCPP_BEGIN_NAMESPACE_STD + +#define _LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(NAME, PROPERTY) \ + template struct NAME : false_type { }; \ + template struct NAME<_Tp, typename __void_t::type> : true_type { } + +// __pointer +_LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_pointer, pointer); +template ::type, + bool = __has_pointer<_RawAlloc>::value> +struct __pointer { + using type _LIBCPP_NODEBUG_TYPE = typename _RawAlloc::pointer; +}; +template +struct __pointer<_Tp, _Alloc, _RawAlloc, false> { + using type _LIBCPP_NODEBUG_TYPE = _Tp*; +}; + +// __const_pointer +_LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_const_pointer, const_pointer); +template ::value> +struct __const_pointer { + using type _LIBCPP_NODEBUG_TYPE = typename _Alloc::const_pointer; +}; +template +struct __const_pointer<_Tp, _Ptr, _Alloc, false> { +#ifdef _LIBCPP_CXX03_LANG + using type = typename pointer_traits<_Ptr>::template rebind::other; +#else + using type _LIBCPP_NODEBUG_TYPE = typename pointer_traits<_Ptr>::template rebind; +#endif +}; + +// __void_pointer +_LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_void_pointer, void_pointer); +template ::value> +struct __void_pointer { + using type _LIBCPP_NODEBUG_TYPE = typename _Alloc::void_pointer; +}; +template +struct __void_pointer<_Ptr, _Alloc, false> { +#ifdef _LIBCPP_CXX03_LANG + using type _LIBCPP_NODEBUG_TYPE = typename pointer_traits<_Ptr>::template rebind::other; +#else + using type _LIBCPP_NODEBUG_TYPE = typename pointer_traits<_Ptr>::template rebind; +#endif +}; + +// __const_void_pointer +_LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_const_void_pointer, const_void_pointer); +template ::value> +struct __const_void_pointer { + using type _LIBCPP_NODEBUG_TYPE = typename _Alloc::const_void_pointer; +}; +template +struct __const_void_pointer<_Ptr, _Alloc, false> { +#ifdef _LIBCPP_CXX03_LANG + using type _LIBCPP_NODEBUG_TYPE = typename pointer_traits<_Ptr>::template rebind::other; +#else + using type _LIBCPP_NODEBUG_TYPE = typename pointer_traits<_Ptr>::template rebind; +#endif +}; + +// __size_type +_LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_size_type, size_type); +template ::value> +struct __size_type : make_unsigned<_DiffType> { }; +template +struct __size_type<_Alloc, _DiffType, true> { + using type _LIBCPP_NODEBUG_TYPE = typename _Alloc::size_type; +}; + +// __alloc_traits_difference_type +_LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_alloc_traits_difference_type, difference_type); +template ::value> +struct __alloc_traits_difference_type { + using type _LIBCPP_NODEBUG_TYPE = typename pointer_traits<_Ptr>::difference_type; +}; +template +struct __alloc_traits_difference_type<_Alloc, _Ptr, true> { + using type _LIBCPP_NODEBUG_TYPE = typename _Alloc::difference_type; +}; + +// __propagate_on_container_copy_assignment +_LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_propagate_on_container_copy_assignment, propagate_on_container_copy_assignment); +template ::value> +struct __propagate_on_container_copy_assignment : false_type { }; +template +struct __propagate_on_container_copy_assignment<_Alloc, true> { + using type _LIBCPP_NODEBUG_TYPE = typename _Alloc::propagate_on_container_copy_assignment; +}; + +// __propagate_on_container_move_assignment +_LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_propagate_on_container_move_assignment, propagate_on_container_move_assignment); +template ::value> +struct __propagate_on_container_move_assignment : false_type { }; +template +struct __propagate_on_container_move_assignment<_Alloc, true> { + using type _LIBCPP_NODEBUG_TYPE = typename _Alloc::propagate_on_container_move_assignment; +}; + +// __propagate_on_container_swap +_LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_propagate_on_container_swap, propagate_on_container_swap); +template ::value> +struct __propagate_on_container_swap : false_type { }; +template +struct __propagate_on_container_swap<_Alloc, true> { + using type _LIBCPP_NODEBUG_TYPE = typename _Alloc::propagate_on_container_swap; +}; + +// __is_always_equal +_LIBCPP_ALLOCATOR_TRAITS_HAS_XXX(__has_is_always_equal, is_always_equal); +template ::value> +struct __is_always_equal : is_empty<_Alloc> { }; +template +struct __is_always_equal<_Alloc, true> { + using type _LIBCPP_NODEBUG_TYPE = typename _Alloc::is_always_equal; +}; + +// __allocator_traits_rebind +_LIBCPP_SUPPRESS_DEPRECATED_PUSH +template +struct __has_rebind_other : false_type { }; +template +struct __has_rebind_other<_Tp, _Up, typename __void_t< + typename _Tp::template rebind<_Up>::other +>::type> : true_type { }; + +template ::value> +struct __allocator_traits_rebind { + using type _LIBCPP_NODEBUG_TYPE = typename _Tp::template rebind<_Up>::other; +}; +template