Skip to content

Commit

Permalink
Use cstr! macro.
Browse files Browse the repository at this point in the history
  • Loading branch information
reitermarkus committed Oct 12, 2022
1 parent 3697b4d commit 7b9f9e5
Show file tree
Hide file tree
Showing 15 changed files with 22 additions and 68 deletions.
11 changes: 0 additions & 11 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1023,16 +1023,6 @@ dependencies = [
"winapi",
]

[[package]]
name = "cstr"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c11a39d776a3b35896711da8a04dc1835169dcd36f710878187637314e47941b"
dependencies = [
"proc-macro2",
"quote",
]

[[package]]
name = "curl"
version = "0.4.43"
Expand Down Expand Up @@ -3275,7 +3265,6 @@ name = "rustc_codegen_llvm"
version = "0.0.0"
dependencies = [
"bitflags",
"cstr",
"libc",
"measureme",
"object 0.29.0",
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_codegen_llvm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ test = false

[dependencies]
bitflags = "1.0"
cstr = "0.2"
libc = "0.2"
measureme = "10.0.0"
object = { version = "0.29.0", default-features = false, features = ["std", "read_core", "archive", "coff", "elf", "macho", "pe"] }
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_codegen_llvm/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ use crate::context::CodegenCx;
use crate::llvm;
use crate::value::Value;

use cstr::cstr;

use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
use rustc_codegen_ssa::mono_item::MonoItemExt;
use rustc_codegen_ssa::traits::*;
Expand All @@ -34,6 +32,7 @@ use rustc_session::config::DebugInfo;
use rustc_span::symbol::Symbol;
use rustc_target::spec::SanitizerSet;

use std::ffi::cstr;
use std::time::Instant;

pub struct ValueIter<'ll> {
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_codegen_llvm/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use crate::llvm::{self, AtomicOrdering, AtomicRmwBinOp, BasicBlock};
use crate::type_::Type;
use crate::type_of::LayoutLlvmExt;
use crate::value::Value;
use cstr::cstr;
use libc::{c_char, c_uint};
use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind};
use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
Expand All @@ -23,7 +22,7 @@ use rustc_span::Span;
use rustc_target::abi::{self, call::FnAbi, Align, Size, WrappingRange};
use rustc_target::spec::{HasTargetSpec, Target};
use std::borrow::Cow;
use std::ffi::CStr;
use std::ffi::{cstr, CStr};
use std::iter;
use std::ops::Deref;
use std::ptr;
Expand All @@ -44,7 +43,7 @@ impl Drop for Builder<'_, '_, '_> {
}

// FIXME(eddyb) use a checked constructor when they become `const fn`.
const EMPTY_C_STR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"\0") };
const EMPTY_C_STR: &CStr = cstr!();

/// Empty string, to be used where LLVM expects an instruction name, indicating
/// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use crate::llvm_util;
use crate::type_::Type;
use crate::type_of::LayoutLlvmExt;
use crate::value::Value;
use cstr::cstr;
use libc::c_uint;
use rustc_codegen_ssa::traits::*;
use rustc_hir::def_id::DefId;
Expand All @@ -22,6 +21,7 @@ use rustc_middle::{bug, span_bug};
use rustc_target::abi::{
AddressSpace, Align, HasDataLayout, Primitive, Scalar, Size, WrappingRange,
};
use std::ffi::cstr;
use std::ops::Range;

pub fn const_alloc_to_llvm<'ll>(cx: &CodegenCx<'ll, '_>, alloc: ConstAllocation<'_>) -> &'ll Value {
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_codegen_llvm/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use crate::llvm_util;
use crate::type_::Type;
use crate::value::Value;

use cstr::cstr;
use rustc_codegen_ssa::base::wants_msvc_seh;
use rustc_codegen_ssa::traits::*;
use rustc_data_structures::base_n;
Expand All @@ -33,7 +32,7 @@ use rustc_target::spec::{HasTargetSpec, RelocModel, Target, TlsModel};
use smallvec::SmallVec;

use std::cell::{Cell, RefCell};
use std::ffi::CStr;
use std::ffi::{cstr, CStr};
use std::str;

/// There is one `CodegenCx` per compilation unit. Each one has its own LLVM
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ use crate::llvm::debuginfo::{
};
use crate::value::Value;

use cstr::cstr;
use rustc_codegen_ssa::debuginfo::type_names::cpp_like_debuginfo;
use rustc_codegen_ssa::debuginfo::type_names::VTableNameKind;
use rustc_codegen_ssa::traits::*;
Expand All @@ -45,6 +44,7 @@ use smallvec::smallvec;

use libc::{c_char, c_longlong, c_uint};
use std::borrow::Cow;
use std::ffi::cstr;
use std::fmt::{self, Write};
use std::hash::{Hash, Hasher};
use std::iter;
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_codegen_llvm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#![feature(let_chains)]
#![feature(extern_types)]
#![feature(once_cell)]
#![feature(cstr_macro)]
#![feature(iter_intersperse)]
#![recursion_limit = "256"]
#![allow(rustc::potential_query_instability)]
Expand Down
4 changes: 2 additions & 2 deletions library/core/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ impl fmt::Debug for CStr {
}
}

/// Converts a string or byte literal to a `&'static Cstr`.
/// Converts a `const` string or byte slice to a `&'static Cstr`.
///
/// # Examples
///
Expand Down Expand Up @@ -208,7 +208,7 @@ macro_rules! __cstr_macro_impl {
() => {
__cstr_macro_impl!("")
};
($s:literal) => {{
($s:expr) => {{
const BYTES: &[u8] = $crate::ffi::__cstr_macro_impl_as_bytes($s);
const BYTES_WITH_NUL: [u8; { BYTES.len() + 1 }] =
$crate::ffi::__cstr_macro_impl_to_bytes_with_nul(BYTES);
Expand Down
1 change: 1 addition & 0 deletions library/std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@
#![feature(maybe_uninit_uninit_array)]
#![feature(const_maybe_uninit_uninit_array)]
#![feature(const_waker)]
#![feature(cstr_macro)]
//
// Library features (alloc):
#![feature(alloc_layout_extra)]
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/sys/unix/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![allow(missing_docs, nonstandard_style)]

use crate::ffi::CStr;
use crate::ffi::cstr;
use crate::io::ErrorKind;

pub use self::rand::hashmap_random_keys;
Expand Down Expand Up @@ -75,7 +75,7 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
// thread-id for the main thread and so renaming the main thread will rename the
// process and we only want to enable this on platforms we've tested.
if cfg!(target_os = "macos") {
thread::Thread::set_name(&CStr::from_bytes_with_nul_unchecked(b"main\0"));
thread::Thread::set_name(cstr!("main"));
}

unsafe fn sanitize_standard_fds() {
Expand Down
6 changes: 3 additions & 3 deletions library/std/src/sys/windows/c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
#![cfg_attr(test, allow(dead_code))]
#![unstable(issue = "none", feature = "windows_c")]

use crate::ffi::CStr;
use crate::ffi::{cstr, CStr};
use crate::mem;
use crate::os::raw::{c_char, c_int, c_long, c_longlong, c_uint, c_ulong, c_ushort};
use crate::os::windows::io::{BorrowedHandle, HandleOrInvalid, HandleOrNull};
Expand Down Expand Up @@ -1245,7 +1245,7 @@ extern "system" {
// Functions that aren't available on every version of Windows that we support,
// but we still use them and just provide some form of a fallback implementation.
compat_fn_with_fallback! {
pub static KERNEL32: &CStr = ansi_str!("kernel32");
pub static KERNEL32: &CStr = cstr!("kernel32");

// >= Win10 1607
// https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreaddescription
Expand Down Expand Up @@ -1280,7 +1280,7 @@ compat_fn_optional! {
}

compat_fn_with_fallback! {
pub static NTDLL: &CStr = ansi_str!("ntdll");
pub static NTDLL: &CStr = cstr!("ntdll");

pub fn NtCreateFile(
FileHandle: *mut HANDLE,
Expand Down
42 changes: 5 additions & 37 deletions library/std/src/sys/windows/compat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
//! function is called. In the worst case, multiple threads may all end up
//! importing the same function unnecessarily.
use crate::ffi::{c_void, CStr};
use crate::ffi::{c_void, cstr, CStr};
use crate::ptr::NonNull;
use crate::sync::atomic::Ordering;
use crate::sys::c;
Expand Down Expand Up @@ -67,38 +67,6 @@ unsafe extern "C" fn init() {
load_synch_functions();
}

/// Helper macro for creating CStrs from literals and symbol names.
macro_rules! ansi_str {
(sym $ident:ident) => {{
#[allow(unused_unsafe)]
crate::sys::compat::const_cstr_from_bytes(concat!(stringify!($ident), "\0").as_bytes())
}};
($lit:literal) => {{ crate::sys::compat::const_cstr_from_bytes(concat!($lit, "\0").as_bytes()) }};
}

/// Creates a C string wrapper from a byte slice, in a constant context.
///
/// This is a utility function used by the [`ansi_str`] macro.
///
/// # Panics
///
/// Panics if the slice is not null terminated or contains nulls, except as the last item
pub(crate) const fn const_cstr_from_bytes(bytes: &'static [u8]) -> &'static CStr {
if !matches!(bytes.last(), Some(&0)) {
panic!("A CStr must be null terminated");
}
let mut i = 0;
// At this point `len()` is at least 1.
while i < bytes.len() - 1 {
if bytes[i] == 0 {
panic!("A CStr must not have interior nulls")
}
i += 1;
}
// SAFETY: The safety is ensured by the above checks.
unsafe { crate::ffi::CStr::from_bytes_with_nul_unchecked(bytes) }
}

/// Represents a loaded module.
///
/// Note that the modules std depends on must not be unloaded.
Expand Down Expand Up @@ -161,7 +129,7 @@ macro_rules! compat_fn_with_fallback {

fn load_from_module(module: Option<Module>) -> F {
unsafe {
static SYMBOL_NAME: &CStr = ansi_str!(sym $symbol);
static SYMBOL_NAME: &CStr = cstr!(stringify!($symbol));
if let Some(f) = module.and_then(|m| m.proc_address(SYMBOL_NAME)) {
PTR.store(f.as_ptr(), Ordering::Relaxed);
mem::transmute(f)
Expand Down Expand Up @@ -224,9 +192,9 @@ macro_rules! compat_fn_optional {
/// Load all needed functions from "api-ms-win-core-synch-l1-2-0".
pub(super) fn load_synch_functions() {
fn try_load() -> Option<()> {
const MODULE_NAME: &CStr = ansi_str!("api-ms-win-core-synch-l1-2-0");
const WAIT_ON_ADDRESS: &CStr = ansi_str!("WaitOnAddress");
const WAKE_BY_ADDRESS_SINGLE: &CStr = ansi_str!("WakeByAddressSingle");
const MODULE_NAME: &CStr = cstr!("api-ms-win-core-synch-l1-2-0");
const WAIT_ON_ADDRESS: &CStr = cstr!("WaitOnAddress");
const WAKE_BY_ADDRESS_SINGLE: &CStr = cstr!("WakeByAddressSingle");

// Try loading the library and all the required functions.
// If any step fails, then they all fail.
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/sys/windows/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![allow(missing_docs, nonstandard_style)]

use crate::ffi::{CStr, OsStr, OsString};
use crate::ffi::{cstr, OsStr, OsString};
use crate::io::ErrorKind;
use crate::mem::MaybeUninit;
use crate::os::windows::ffi::{OsStrExt, OsStringExt};
Expand Down Expand Up @@ -53,7 +53,7 @@ pub unsafe fn init(_argc: isize, _argv: *const *const u8, _sigpipe: u8) {

// Normally, `thread::spawn` will call `Thread::set_name` but since this thread already
// exists, we have to call it ourselves.
thread::Thread::set_name(&CStr::from_bytes_with_nul_unchecked(b"main\0"));
thread::Thread::set_name(cstr!("main"));
}

// SAFETY: must be called only once during runtime cleanup.
Expand Down
1 change: 0 additions & 1 deletion src/tools/tidy/src/deps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[
"crossbeam-epoch",
"crossbeam-utils",
"crypto-common",
"cstr",
"datafrog",
"difference",
"digest",
Expand Down

0 comments on commit 7b9f9e5

Please sign in to comment.