Skip to main content

rustc_codegen_llvm/
common.rs

1//! Code that is useful in various codegen modules.
2
3use std::borrow::Borrow;
4
5use libc::{c_char, c_uint};
6use rustc_abi::Primitive::Pointer;
7use rustc_abi::{self as abi, ExternAbi, HasDataLayout as _};
8use rustc_ast::Mutability;
9use rustc_codegen_ssa::common::TypeKind;
10use rustc_codegen_ssa::traits::*;
11use rustc_data_structures::stable_hash::{StableHash, StableHasher};
12use rustc_hashes::Hash128;
13use rustc_hir::def::DefKind;
14use rustc_hir::def_id::DefId;
15use rustc_middle::bug;
16use rustc_middle::mir::interpret::{GlobalAlloc, PointerArithmetic, Scalar};
17use rustc_middle::ty::{Instance, TyCtxt};
18use rustc_session::cstore::DllImport;
19use rustc_target::spec::LlvmAbi;
20use tracing::debug;
21
22use crate::consts::{IsInitOrFini, IsStatic, const_alloc_to_llvm};
23pub(crate) use crate::context::CodegenCx;
24use crate::context::{GenericCx, SCx};
25use crate::llvm::{
26    self, BasicBlock, ConstantInt, FALSE, TRUE, ToLlvmBool, Type, Value, const_ptr_auth,
27};
28
29#[inline]
30pub(crate) fn pauth_fn_attrs() -> &'static [&'static str] {
31    // FIXME(jchlanda) This is not an exhaustive list of all `ptrauth`-related attributes, but only
32    // those currently supported. The list is expected to grow as additional functionality is
33    // implemented, particularly for C++ interoperability.
34    &[
35        "aarch64-jump-table-hardening",
36        "ptrauth-indirect-gotos",
37        "ptrauth-calls",
38        "ptrauth-returns",
39        "ptrauth-auth-traps",
40    ]
41}
42
43pub(crate) fn maybe_sign_fn_ptr<'ll, 'tcx>(
44    cx: &CodegenCx<'ll, '_>,
45    instance: Instance<'tcx>,
46    llfn: &'ll llvm::Value,
47    pac: PacMetadata,
48) -> &'ll llvm::Value {
49    if cx.sess().target.llvm_abiname != LlvmAbi::Pauthtest {
50        return llfn;
51    }
52
53    // Only free functions or methods
54    let def_id = instance.def_id();
55    if !#[allow(non_exhaustive_omitted_patterns)] match cx.tcx.def_kind(def_id) {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(cx.tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
56        return llfn;
57    }
58    // Only C ABI
59    let abi = cx.tcx.fn_sig(def_id).skip_binder().abi();
60    if !#[allow(non_exhaustive_omitted_patterns)] match abi {
    ExternAbi::C { .. } | ExternAbi::System { .. } => true,
    _ => false,
}matches!(abi, ExternAbi::C { .. } | ExternAbi::System { .. }) {
61        return llfn;
62    }
63    // Ignore LLVM intrinsics
64    if llvm::get_value_name(llfn).starts_with(b"llvm.") {
65        return llfn;
66    }
67    if Some(def_id) == cx.tcx.lang_items().eh_personality() {
68        return llfn;
69    }
70
71    let addr_diversity = match pac.addr_diversity {
72        AddressDiversity::None => None,
73        AddressDiversity::Real => Some(llfn),
74        AddressDiversity::Synthetic(val) => {
75            let llval = cx.const_u64(val);
76            let llty = cx.val_ty(llfn);
77            Some(unsafe { llvm::LLVMConstIntToPtr(llval, llty) })
78        }
79    };
80    const_ptr_auth(llfn, pac.key, pac.disc, addr_diversity)
81}
82
83/*
84* A note on nomenclature of linking: "extern", "foreign", and "upcall".
85*
86* An "extern" is an LLVM symbol we wind up emitting an undefined external
87* reference to. This means "we don't have the thing in this compilation unit,
88* please make sure you link it in at runtime". This could be a reference to
89* C code found in a C library, or rust code found in a rust crate.
90*
91* Most "externs" are implicitly declared (automatically) as a result of a
92* user declaring an extern _module_ dependency; this causes the rust driver
93* to locate an extern crate, scan its compilation metadata, and emit extern
94* declarations for any symbols used by the declaring crate.
95*
96* A "foreign" is an extern that references C (or other non-rust ABI) code.
97* There is no metadata to scan for extern references so in these cases either
98* a header-digester like bindgen, or manual function prototypes, have to
99* serve as declarators. So these are usually given explicitly as prototype
100* declarations, in rust code, with ABI attributes on them noting which ABI to
101* link via.
102*
103* An "upcall" is a foreign call generated by the compiler (not corresponding
104* to any user-written call in the code) into the runtime library, to perform
105* some helper task such as bringing a task to life, allocating memory, etc.
106*
107*/
108
109/// A structure representing an active landing pad for the duration of a basic
110/// block.
111///
112/// Each `Block` may contain an instance of this, indicating whether the block
113/// is part of a landing pad or not. This is used to make decision about whether
114/// to emit `invoke` instructions (e.g., in a landing pad we don't continue to
115/// use `invoke`) and also about various function call metadata.
116///
117/// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
118/// just a bunch of `None` instances (not too interesting), but for MSVC
119/// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
120/// When inside of a landing pad, each function call in LLVM IR needs to be
121/// annotated with which landing pad it's a part of. This is accomplished via
122/// the `OperandBundleDef` value created for MSVC landing pads.
123pub(crate) struct Funclet<'ll> {
124    cleanuppad: &'ll Value,
125    operand: llvm::OperandBundleBox<'ll>,
126}
127
128impl<'ll> Funclet<'ll> {
129    pub(crate) fn new(cleanuppad: &'ll Value) -> Self {
130        Funclet { cleanuppad, operand: llvm::OperandBundleBox::new("funclet", &[cleanuppad]) }
131    }
132
133    pub(crate) fn cleanuppad(&self) -> &'ll Value {
134        self.cleanuppad
135    }
136
137    pub(crate) fn bundle(&self) -> &llvm::OperandBundle<'ll> {
138        self.operand.as_ref()
139    }
140}
141
142impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericCx<'ll, CX> {
143    // FIXME(eddyb) replace this with a `Function` "subclass" of `Value`.
144    type Function = &'ll Value;
145    type BasicBlock = &'ll BasicBlock;
146    type Funclet = Funclet<'ll>;
147
148    type Value = &'ll Value;
149    type Type = &'ll Type;
150    type FunctionSignature = &'ll Type;
151
152    type DIScope = &'ll llvm::debuginfo::DIScope;
153    type DILocation = &'ll llvm::debuginfo::DILocation;
154    type DIVariable = &'ll llvm::debuginfo::DIVariable;
155}
156
157impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
158    pub(crate) fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
159        let len = u64::try_from(elts.len()).expect("LLVMConstArray2 elements len overflow");
160        unsafe { llvm::LLVMConstArray2(ty, elts.as_ptr(), len) }
161    }
162
163    pub(crate) fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
164        bytes_in_context(self.llcx(), bytes)
165    }
166
167    pub(crate) fn null_terminate_const_bytes(&self, bytes: &[u8]) -> &'ll Value {
168        null_terminate_bytes_in_context(self.llcx(), bytes)
169    }
170
171    pub(crate) fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
172        unsafe {
173            let idx = c_uint::try_from(idx).expect("LLVMGetAggregateElement index overflow");
174            let r = llvm::LLVMGetAggregateElement(v, idx).unwrap();
175
176            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/common.rs:176",
                        "rustc_codegen_llvm::common", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/common.rs"),
                        ::tracing_core::__macro_support::Option::Some(176u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::common"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("const_get_elt(v={0:?}, idx={1}, r={2:?})",
                                                    v, idx, r) as &dyn Value))])
            });
    } else { ; }
};debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
177
178            r
179        }
180    }
181
182    pub(crate) fn const_null(&self, t: &'ll Type) -> &'ll Value {
183        unsafe { llvm::LLVMConstNull(t) }
184    }
185
186    pub(crate) fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
187        struct_in_context(self.llcx(), elts, packed)
188    }
189}
190
191impl<'ll, 'tcx> ConstCodegenMethods for CodegenCx<'ll, 'tcx> {
192    fn const_null(&self, t: &'ll Type) -> &'ll Value {
193        unsafe { llvm::LLVMConstNull(t) }
194    }
195
196    fn const_undef(&self, t: &'ll Type) -> &'ll Value {
197        unsafe { llvm::LLVMGetUndef(t) }
198    }
199
200    fn const_poison(&self, t: &'ll Type) -> &'ll Value {
201        unsafe { llvm::LLVMGetPoison(t) }
202    }
203
204    fn const_bool(&self, val: bool) -> &'ll Value {
205        self.const_uint(self.type_i1(), val as u64)
206    }
207
208    fn const_i8(&self, i: i8) -> &'ll Value {
209        self.const_int(self.type_i8(), i as i64)
210    }
211
212    fn const_i16(&self, i: i16) -> &'ll Value {
213        self.const_int(self.type_i16(), i as i64)
214    }
215
216    fn const_i32(&self, i: i32) -> &'ll Value {
217        self.const_int(self.type_i32(), i as i64)
218    }
219
220    fn const_i64(&self, i: i64) -> &'ll Value {
221        self.const_int(self.type_i64(), i as i64)
222    }
223
224    fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
225        if true {
    if !(self.type_kind(t) == TypeKind::Integer) {
        {
            ::core::panicking::panic_fmt(format_args!("only allows integer types in const_int"));
        }
    };
};debug_assert!(
226            self.type_kind(t) == TypeKind::Integer,
227            "only allows integer types in const_int"
228        );
229        unsafe { llvm::LLVMConstInt(t, i as u64, TRUE) }
230    }
231
232    fn const_u8(&self, i: u8) -> &'ll Value {
233        self.const_uint(self.type_i8(), i as u64)
234    }
235
236    fn const_u32(&self, i: u32) -> &'ll Value {
237        self.const_uint(self.type_i32(), i as u64)
238    }
239
240    fn const_u64(&self, i: u64) -> &'ll Value {
241        self.const_uint(self.type_i64(), i)
242    }
243
244    fn const_u128(&self, i: u128) -> &'ll Value {
245        self.const_uint_big(self.type_i128(), i)
246    }
247
248    fn const_usize(&self, i: u64) -> &'ll Value {
249        let bit_size = self.data_layout().pointer_size().bits();
250        if bit_size < 64 {
251            // make sure it doesn't overflow
252            if !(i < (1 << bit_size)) {
    ::core::panicking::panic("assertion failed: i < (1 << bit_size)")
};assert!(i < (1 << bit_size));
253        }
254
255        self.const_uint(self.isize_ty, i)
256    }
257
258    fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
259        if true {
    if !(self.type_kind(t) == TypeKind::Integer) {
        {
            ::core::panicking::panic_fmt(format_args!("only allows integer types in const_uint"));
        }
    };
};debug_assert!(
260            self.type_kind(t) == TypeKind::Integer,
261            "only allows integer types in const_uint"
262        );
263        unsafe { llvm::LLVMConstInt(t, i, FALSE) }
264    }
265
266    fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
267        if true {
    if !(self.type_kind(t) == TypeKind::Integer) {
        {
            ::core::panicking::panic_fmt(format_args!("only allows integer types in const_uint_big"));
        }
    };
};debug_assert!(
268            self.type_kind(t) == TypeKind::Integer,
269            "only allows integer types in const_uint_big"
270        );
271        unsafe {
272            let words = [u as u64, (u >> 64) as u64];
273            llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
274        }
275    }
276
277    fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
278        unsafe { llvm::LLVMConstReal(t, val) }
279    }
280
281    fn const_str(&self, s: &str) -> (&'ll Value, &'ll Value) {
282        let mut const_str_cache = self.const_str_cache.borrow_mut();
283        let str_global = const_str_cache.get(s).copied().unwrap_or_else(|| {
284            let sc = self.const_bytes(s.as_bytes());
285            let sym = self.generate_local_symbol_name("str");
286            let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| {
287                ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        sym));bug!("symbol `{}` is already defined", sym);
288            });
289            llvm::set_initializer(g, sc);
290
291            llvm::set_global_constant(g, true);
292            llvm::set_unnamed_address(g, llvm::UnnamedAddr::Global);
293
294            llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
295            // Cast to default address space if globals are in a different addrspace
296            let g = self.const_pointercast(g, self.type_ptr());
297            const_str_cache.insert(s.to_owned(), g);
298            g
299        });
300        let len = s.len();
301        (str_global, self.const_usize(len as u64))
302    }
303
304    fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
305        struct_in_context(self.llcx, elts, packed)
306    }
307
308    fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
309        let len = c_uint::try_from(elts.len()).expect("LLVMConstVector elements len overflow");
310        unsafe { llvm::LLVMConstVector(elts.as_ptr(), len) }
311    }
312
313    fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
314        try_as_const_integral(v).and_then(|v| unsafe {
315            let mut i = 0u64;
316            let success = llvm::LLVMRustConstIntGetZExtValue(v, &mut i);
317            success.then_some(i)
318        })
319    }
320
321    fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
322        try_as_const_integral(v).and_then(|v| unsafe {
323            let (mut lo, mut hi) = (0u64, 0u64);
324            let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
325            success.then_some(hi_lo_to_u128(lo, hi))
326        })
327    }
328
329    fn scalar_to_backend_with_pac(
330        &self,
331        cv: Scalar,
332        layout: abi::Scalar,
333        llty: &'ll Type,
334        pac: Option<PacMetadata>,
335    ) -> &'ll Value {
336        let bitsize = if layout.is_bool() { 1 } else { layout.size(self).bits() };
337        match cv {
338            Scalar::Int(int) => {
339                let data = int.to_bits(layout.size(self));
340                let llval = self.const_uint_big(self.type_ix(bitsize), data);
341                if #[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
    Pointer(_) => true,
    _ => false,
}matches!(layout.primitive(), Pointer(_)) {
342                    unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
343                } else {
344                    self.const_bitcast(llval, llty)
345                }
346            }
347            Scalar::Ptr(ptr, _size) => {
348                let (prov, offset) = ptr.prov_and_relative_offset();
349                let global_alloc = self.tcx.global_alloc(prov.alloc_id());
350                let base_addr = match global_alloc {
351                    GlobalAlloc::Memory(alloc) => {
352                        // For ZSTs directly codegen an aligned pointer.
353                        // This avoids generating a zero-sized constant value and actually needing a
354                        // real address at runtime.
355                        if alloc.inner().len() == 0 {
356                            let val = alloc.inner().align.bytes().wrapping_add(offset.bytes());
357                            let llval = self.const_usize(self.tcx.truncate_to_target_usize(val));
358                            return if #[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
    Pointer(_) => true,
    _ => false,
}matches!(layout.primitive(), Pointer(_)) {
359                                unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
360                            } else {
361                                self.const_bitcast(llval, llty)
362                            };
363                        } else {
364                            let init = const_alloc_to_llvm(
365                                self,
366                                alloc.inner(),
367                                IsStatic::No,
368                                IsInitOrFini::No,
369                            );
370                            let alloc = alloc.inner();
371                            let value = match alloc.mutability {
372                                Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
373                                _ => self.static_addr_of_impl(init, alloc.align, None),
374                            };
375                            if !self.sess().fewer_names() && llvm::get_value_name(value).is_empty()
376                            {
377                                let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
378                                    let mut hasher = StableHasher::new();
379                                    alloc.stable_hash(&mut hcx, &mut hasher);
380                                    hasher.finish::<Hash128>()
381                                });
382                                llvm::set_value_name(
383                                    value,
384                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("alloc_{0:032x}", hash))
    })format!("alloc_{hash:032x}").as_bytes(),
385                                );
386                            }
387                            value
388                        }
389                    }
390                    GlobalAlloc::Function { instance, .. } => self.get_fn_addr(instance, pac),
391                    GlobalAlloc::VTable(ty, dyn_ty) => {
392                        let alloc = self
393                            .tcx
394                            .global_alloc(self.tcx.vtable_allocation((
395                                ty,
396                                dyn_ty.principal().map(|principal| {
397                                    self.tcx.instantiate_bound_regions_with_erased(principal)
398                                }),
399                            )))
400                            .unwrap_memory();
401                        let init = const_alloc_to_llvm(
402                            self,
403                            alloc.inner(),
404                            IsStatic::No,
405                            IsInitOrFini::No,
406                        );
407                        self.static_addr_of_impl(init, alloc.inner().align, None)
408                    }
409                    GlobalAlloc::Static(def_id) => {
410                        if !self.tcx.is_static(def_id) {
    ::core::panicking::panic("assertion failed: self.tcx.is_static(def_id)")
};assert!(self.tcx.is_static(def_id));
411                        if !!self.tcx.is_thread_local_static(def_id) {
    ::core::panicking::panic("assertion failed: !self.tcx.is_thread_local_static(def_id)")
};assert!(!self.tcx.is_thread_local_static(def_id));
412                        self.get_static(def_id)
413                    }
414                    GlobalAlloc::TypeId { .. } => {
415                        // Drop the provenance, the offset contains the bytes of the hash
416                        let llval = self.const_usize(offset.bytes());
417                        return unsafe { llvm::LLVMConstIntToPtr(llval, llty) };
418                    }
419                };
420                let base_addr_space = global_alloc.address_space(self);
421                let llval = unsafe {
422                    llvm::LLVMConstInBoundsGEP2(
423                        self.type_i8(),
424                        // Cast to the required address space if necessary
425                        self.const_pointercast(base_addr, self.type_ptr_ext(base_addr_space)),
426                        &self.const_usize(offset.bytes()),
427                        1,
428                    )
429                };
430                if !#[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
    Pointer(_) => true,
    _ => false,
}matches!(layout.primitive(), Pointer(_)) {
431                    unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
432                } else {
433                    self.const_bitcast(llval, llty)
434                }
435            }
436        }
437    }
438
439    fn const_ptr_byte_offset(&self, base_addr: Self::Value, offset: abi::Size) -> Self::Value {
440        unsafe {
441            llvm::LLVMConstInBoundsGEP2(
442                self.type_i8(),
443                base_addr,
444                &self.const_usize(offset.bytes()),
445                1,
446            )
447        }
448    }
449}
450
451/// Get the [LLVM type][Type] of a [`Value`].
452pub(crate) fn val_ty(v: &Value) -> &Type {
453    unsafe { llvm::LLVMTypeOf(v) }
454}
455
456pub(crate) fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
457    unsafe {
458        let ptr = bytes.as_ptr() as *const c_char;
459        llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), TRUE)
460    }
461}
462
463pub(crate) fn null_terminate_bytes_in_context<'ll>(
464    llcx: &'ll llvm::Context,
465    bytes: &[u8],
466) -> &'ll Value {
467    unsafe {
468        let ptr = bytes.as_ptr() as *const c_char;
469        llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), FALSE)
470    }
471}
472
473pub(crate) fn named_struct<'ll>(ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
474    let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
475    unsafe { llvm::LLVMConstNamedStruct(ty, elts.as_ptr(), len) }
476}
477
478fn struct_in_context<'ll>(
479    llcx: &'ll llvm::Context,
480    elts: &[&'ll Value],
481    packed: bool,
482) -> &'ll Value {
483    let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
484    unsafe { llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), len, packed.to_llvm_bool()) }
485}
486
487#[inline]
488fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
489    ((hi as u128) << 64) | (lo as u128)
490}
491
492fn try_as_const_integral(v: &Value) -> Option<&ConstantInt> {
493    unsafe { llvm::LLVMIsAConstantInt(v) }
494}
495
496pub(crate) fn get_dllimport<'tcx>(
497    tcx: TyCtxt<'tcx>,
498    id: DefId,
499    name: &str,
500) -> Option<&'tcx DllImport> {
501    tcx.native_library(id)
502        .and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
503}
504
505/// Extension trait for explicit casts to `*const c_char`.
506pub(crate) trait AsCCharPtr {
507    /// Equivalent to `self.as_ptr().cast()`, but only casts to `*const c_char`.
508    fn as_c_char_ptr(&self) -> *const c_char;
509}
510
511impl AsCCharPtr for str {
512    fn as_c_char_ptr(&self) -> *const c_char {
513        self.as_ptr().cast()
514    }
515}
516
517impl AsCCharPtr for [u8] {
518    fn as_c_char_ptr(&self) -> *const c_char {
519        self.as_ptr().cast()
520    }
521}