Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CI Cleanup + Code format #327

Merged
merged 5 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 27 additions & 8 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,19 @@ name: CI

on:
push:
paths-ignore:
- '*.md'
- 'LICENSE-APACHE'
- 'LICENSE-GPL'
branches:
- 'v0.*'
- staging
- trying
pull_request:
paths-ignore:
- '*.md'
- 'LICENSE-APACHE'
- 'LICENSE-GPL'
branches:
- mbedtls-3
- main
Expand Down Expand Up @@ -34,9 +42,6 @@ jobs:
- rust: stable
target: x86_64-pc-windows-msvc
os: windows-latest
- rust: stable
target: x86_64-pc-windows-msvc
os: windows-latest
- rust: stable
target: x86_64-pc-windows-msvc
os: windows-2019
Expand All @@ -53,7 +58,7 @@ jobs:
runs-on: ${{ matrix.os }}

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3

- name: Install qemu-user for aarch64 target
if: matrix.target == 'aarch64-unknown-linux-musl'
Expand All @@ -73,11 +78,10 @@ jobs:
key: ${{ matrix.rust }}

- name: Setup Rust toolchain
uses: actions-rs/toolchain@v1
uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ matrix.rust }}
target: ${{ matrix.target }}
override: true
targets: ${{ matrix.target }}

- name: Run tests
run: |
Expand All @@ -96,12 +100,27 @@ jobs:
AES_NI_SUPPORT: ${{ matrix.target == 'x86_64-unknown-linux-gnu' && 'true' || '' }}
shell: bash

fmt:
name: Rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
components: rustfmt
- name: Enforce formatting
run: |
cargo fmt --check -p mbedtls
cargo fmt --check -p mbedtls-platform-support
cargo fmt --check -p mbedtls-sys-auto
ci-success:
name: ci
if: always()
needs:
- test
runs-on: ubuntu-20.04
- fmt
runs-on: ubuntu-latest
steps:
- run: jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}'
- name: Done
Expand Down
10 changes: 6 additions & 4 deletions mbedtls-platform-support/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ fn main() {
let mut b = cc::Build::new();
b.include(env::var_os("DEP_MBEDTLS_INCLUDE").unwrap());
let config_file = format!(r#""{}""#, env::var("DEP_MBEDTLS_CONFIG_H").unwrap());
b.define("MBEDTLS_CONFIG_FILE",
Some(config_file.as_str()));

b.define("MBEDTLS_CONFIG_FILE", Some(config_file.as_str()));

b.file("src/rust_printf.c");
if sys_platform_components.get("c_compiler").map_or(false, |comps| comps.contains("freestanding")) {
if sys_platform_components
.get("c_compiler")
.map_or(false, |comps| comps.contains("freestanding"))
{
b.flag("-U_FORTIFY_SOURCE")
.define("_FORTIFY_SOURCE", Some("0"))
.flag("-ffreestanding");
Expand Down
48 changes: 27 additions & 21 deletions mbedtls-platform-support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ extern crate alloc as rust_alloc;
#[cfg(not(feature = "std"))]
mod alloc_prelude {
#![allow(unused)]
pub(crate) use rust_alloc::borrow::Cow;
pub(crate) use rust_alloc::borrow::ToOwned;
pub(crate) use rust_alloc::boxed::Box;
pub(crate) use rust_alloc::sync::Arc;
pub(crate) use rust_alloc::string::String;
pub(crate) use rust_alloc::string::ToString;
pub(crate) use rust_alloc::sync::Arc;
pub(crate) use rust_alloc::vec::Vec;
pub(crate) use rust_alloc::borrow::Cow;
}

pub mod self_test;
Expand All @@ -43,53 +43,59 @@ pub extern "C" fn mbedtls_aesni_has_support(_what: u32) -> i32 {
#[doc(hidden)]
#[no_mangle]
// needs to be pub for global visibility
pub extern "C" fn mbedtls_internal_aes_encrypt(_ctx: *mut mbedtls_sys::types::raw_types::c_void,
_input: *const u8,
_output: *mut u8) -> i32 {
pub extern "C" fn mbedtls_internal_aes_encrypt(
_ctx: *mut mbedtls_sys::types::raw_types::c_void,
_input: *const u8,
_output: *mut u8,
) -> i32 {
panic!("AES-NI support is forced but the T-tables code was invoked")
}

#[cfg(any(feature = "force_aesni_support", target_env = "sgx"))]
#[doc(hidden)]
#[no_mangle]
// needs to be pub for global visibility
pub extern "C" fn mbedtls_internal_aes_decrypt(_ctx: *mut mbedtls_sys::types::raw_types::c_void,
_input: *const u8,
_output: *mut u8) -> i32 {
pub extern "C" fn mbedtls_internal_aes_decrypt(
_ctx: *mut mbedtls_sys::types::raw_types::c_void,
_input: *const u8,
_output: *mut u8,
) -> i32 {
panic!("AES-NI support is forced but the T-tables code was invoked")
}


#[cfg(any(all(feature = "time", feature = "custom_gmtime_r"), sys_time_component = "custom"))]
#[doc(hidden)]
#[no_mangle]
// needs to be pub for global visibility
pub unsafe extern "C" fn mbedtls_platform_gmtime_r(tt: *const mbedtls_sys::types::time_t, tp: *mut mbedtls_sys::types::tm) -> *mut mbedtls_sys::types::tm {
pub unsafe extern "C" fn mbedtls_platform_gmtime_r(
tt: *const mbedtls_sys::types::time_t,
tp: *mut mbedtls_sys::types::tm,
) -> *mut mbedtls_sys::types::tm {
use chrono::prelude::*;

//0 means no TZ offset
let naive = if tp.is_null() {
return core::ptr::null_mut()
return core::ptr::null_mut();
} else {
match NaiveDateTime::from_timestamp_opt(*tt, 0) {
Some(t) => t,
None => return core::ptr::null_mut()
None => return core::ptr::null_mut(),
}
};
let utc = DateTime::<Utc>::from_utc(naive, Utc);

let tp = &mut *tp;
tp.tm_sec = utc.second() as i32;
tp.tm_min = utc.minute() as i32;
tp.tm_hour = utc.hour() as i32;
tp.tm_mday = utc.day() as i32;
tp.tm_mon = utc.month0() as i32;
tp.tm_year = match (utc.year() as i32).checked_sub(1900) {
tp.tm_sec = utc.second() as i32;
tp.tm_min = utc.minute() as i32;
tp.tm_hour = utc.hour() as i32;
tp.tm_mday = utc.day() as i32;
tp.tm_mon = utc.month0() as i32;
tp.tm_year = match (utc.year() as i32).checked_sub(1900) {
Some(year) => year,
None => return core::ptr::null_mut()
None => return core::ptr::null_mut(),
};
tp.tm_wday = utc.weekday().num_days_from_sunday() as i32;
tp.tm_yday = utc.ordinal0() as i32;
tp.tm_wday = utc.weekday().num_days_from_sunday() as i32;
tp.tm_yday = utc.ordinal0() as i32;
tp.tm_isdst = 0;

tp
Expand Down
41 changes: 22 additions & 19 deletions mbedtls-platform-support/src/self_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
//! Calling MbedTLS self test functions before they're enabled using the
//! `enable()` function here will result in a panic.
//!
//! Using this module in multithreaded or async environment will fail. The self
//! test functions rely on global variables to track operations and anything
//! non-self-test related operations will clobber these variables, resulting in
//! self test failures. Make sure no other code uses MbedTLS while running the
//! self tests. Multiple self test operations done simultaneously may also
//! Using this module in multithreaded or async environment will fail. The self
//! test functions rely on global variables to track operations and anything
//! non-self-test related operations will clobber these variables, resulting in
//! self test failures. Make sure no other code uses MbedTLS while running the
//! self tests. Multiple self test operations done simultaneously may also
//! return failures.

use mbedtls_sys::types::raw_types::{c_char, c_int};
Expand Down Expand Up @@ -55,9 +55,9 @@ pub unsafe extern "C" fn rand() -> c_int {

/// Set callback functions to enable the MbedTLS self tests.
///
/// `rand` only needs to be set on platforms that don't have a `rand()`
/// function in libc. `log` only needs to be set when using `no_std`, i.e.
/// the `std` feature of this create is not enabled. If neither function
/// `rand` only needs to be set on platforms that don't have a `rand()`
/// function in libc. `log` only needs to be set when using `no_std`, i.e.
/// the `std` feature of this create is not enabled. If neither function
/// needs to be set, you don't have to call `enable()`.
///
/// # Safety
Expand All @@ -66,10 +66,12 @@ pub unsafe extern "C" fn rand() -> c_int {
/// function in this module is called.
#[allow(unused)]
pub unsafe fn enable(rand: fn() -> c_int, log: Option<unsafe fn(*const c_char)>) {
#[cfg(any(not(feature = "std"), target_env = "sgx"))] {
#[cfg(any(not(feature = "std"), target_env = "sgx"))]
{
rand_f = Some(rand);
}
#[cfg(not(feature = "std"))] {
#[cfg(not(feature = "std"))]
{
log_f = log;
}
}
Expand All @@ -79,26 +81,27 @@ pub unsafe fn enable(rand: fn() -> c_int, log: Option<unsafe fn(*const c_char)>)
/// The caller needs to ensure this function is not called while any other
/// function in this module is called.
pub unsafe fn disable() {
#[cfg(any(not(feature = "std"), target_env = "sgx"))] {
#[cfg(any(not(feature = "std"), target_env = "sgx"))]
{
rand_f = None;
}
#[cfg(not(feature = "std"))] {
#[cfg(not(feature = "std"))]
{
log_f = None;
}
}

/// # Safety
///
///
/// The caller needs to ensure this function is not called while *any other*
/// MbedTLS function is called. See the module documentation for more
/// information.
pub use mbedtls_sys::{
aes_self_test as aes, arc4_self_test as arc4, aria_self_test as aria, base64_self_test as base64,
camellia_self_test as camellia, ccm_self_test as ccm, ctr_drbg_self_test as ctr_drbg,
camellia_self_test as camellia, ccm_self_test as ccm, cmac_self_test as cmac, ctr_drbg_self_test as ctr_drbg,
des_self_test as des, dhm_self_test as dhm, ecjpake_self_test as ecjpake, ecp_self_test as ecp,
entropy_self_test as entropy, gcm_self_test as gcm, hmac_drbg_self_test as hmac_drbg,
md2_self_test as md2, md4_self_test as md4, md5_self_test as md5, mpi_self_test as mpi,
pkcs5_self_test as pkcs5, ripemd160_self_test as ripemd160, rsa_self_test as rsa,
sha1_self_test as sha1, sha256_self_test as sha256, sha512_self_test as sha512,
x509_self_test as x509, xtea_self_test as xtea, nist_kw_self_test as nist_kw, cmac_self_test as cmac
entropy_self_test as entropy, gcm_self_test as gcm, hmac_drbg_self_test as hmac_drbg, md2_self_test as md2,
md4_self_test as md4, md5_self_test as md5, mpi_self_test as mpi, nist_kw_self_test as nist_kw, pkcs5_self_test as pkcs5,
ripemd160_self_test as ripemd160, rsa_self_test as rsa, sha1_self_test as sha1, sha256_self_test as sha256,
sha512_self_test as sha512, x509_self_test as x509, xtea_self_test as xtea,
};
18 changes: 8 additions & 10 deletions mbedtls-platform-support/src/threading.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,14 @@
#[cfg(not(feature = "std"))]
use crate::alloc_prelude::*;

// use cfg_if to ensure conditional compilation is compatible with v0.7 code
cfg_if::cfg_if! {
if #[cfg(any(all(feature = "spin_threading", not(feature = "rust_threading")), not(feature = "std")))] {
use spin::{Mutex, MutexGuard};
} else if #[cfg(any(feature = "rust_threading", feature = "std"))] {
use std::sync::{Mutex, MutexGuard};
} else {
{}
}
}
#[cfg(any(all(feature = "spin_threading", not(feature = "rust_threading")), not(feature = "std")))]
use spin::{Mutex, MutexGuard};

#[cfg(all(
not(any(all(feature = "spin_threading", not(feature = "rust_threading")), not(feature = "std"))),
any(feature = "rust_threading", feature = "std")
))]
use std::sync::{Mutex, MutexGuard};

use core::ptr;

Expand Down
48 changes: 30 additions & 18 deletions mbedtls-sys/build/bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,19 @@ struct MbedtlsParseCallbacks;

impl bindgen::callbacks::ParseCallbacks for MbedtlsParseCallbacks {
fn item_name(&self, original_item_name: &str) -> Option<String> {
Some(original_item_name.trim_start_matches("mbedtls_").trim_start_matches("MBEDTLS_").to_owned())
Some(
original_item_name
.trim_start_matches("mbedtls_")
.trim_start_matches("MBEDTLS_")
.to_owned(),
)
}

fn enum_variant_name(
&self,
_enum_name: Option<&str>,
original_variant_name: &str,
_variant_value: bindgen::callbacks::EnumVariantValue
_variant_value: bindgen::callbacks::EnumVariantValue,
) -> Option<String> {
self.item_name(original_variant_name)
}
Expand All @@ -39,7 +44,11 @@ impl bindgen::callbacks::ParseCallbacks for MbedtlsParseCallbacks {
}
}

fn blocklisted_type_implements_trait(&self, _name: &str, derive_trait: bindgen::callbacks::DeriveTrait) -> Option<bindgen::callbacks::ImplementsTrait> {
fn blocklisted_type_implements_trait(
&self,
_name: &str,
derive_trait: bindgen::callbacks::DeriveTrait,
) -> Option<bindgen::callbacks::ImplementsTrait> {
if derive_trait == bindgen::callbacks::DeriveTrait::Default {
Some(bindgen::callbacks::ImplementsTrait::Manually)
} else {
Expand All @@ -53,24 +62,29 @@ impl bindgen::callbacks::ParseCallbacks for MbedtlsParseCallbacks {
fn generate_deprecated_union_accessors(bindings: &str) -> String {
#[derive(Default)]
struct UnionImplBuilder {
impls: String
impls: String,
}

impl<'ast> syn::visit::Visit<'ast> for UnionImplBuilder {
fn visit_item_union(&mut self, i: &'ast syn::ItemUnion) {
let union_name = &i.ident;
let field_name = i.fields.named.iter().map(|field| field.ident.as_ref().unwrap());
let field_type = i.fields.named.iter().map(|field| &field.ty);
write!(self.impls, "{}", quote::quote! {
impl #union_name {
#(
#[deprecated]
pub unsafe fn #field_name(&mut self) -> *mut #field_type {
&mut self.#field_name
}
)*
write!(
self.impls,
"{}",
quote::quote! {
impl #union_name {
#(
#[deprecated]
pub unsafe fn #field_name(&mut self) -> *mut #field_type {
&mut self.#field_name
}
)*
}
}
}).unwrap();
)
.unwrap();
}
}

Expand Down Expand Up @@ -107,10 +121,7 @@ impl super::BuildConfig {
match output {
Ok(sysroot) => {
let path = std::str::from_utf8(&sysroot.stdout).expect("Malformed sysroot");
let trimmed_path = path
.strip_suffix("\r\n")
.or(path.strip_suffix("\n"))
.unwrap_or(&path);
let trimmed_path = path.strip_suffix("\r\n").or(path.strip_suffix("\n")).unwrap_or(&path);
cc.flag(&format!("--sysroot={}", trimmed_path));
}
_ => {} // skip toolchains without a configured sysroot
Expand Down Expand Up @@ -151,7 +162,8 @@ impl super::BuildConfig {
f.write_all(union_impls.as_bytes())?;
f.write_all(b"use crate::types::*;\n")?; // for FILE, time_t, etc.
Ok(())
}).expect("bindings.rs I/O error");
})
.expect("bindings.rs I/O error");

let mod_bindings = self.out_dir.join("mod-bindings.rs");
fs::write(mod_bindings, b"mod bindings;\n").expect("mod-bindings.rs I/O error");
Expand Down
Loading