Rollup merge of #132260 - Zalathar:type-safe-cast, r=compiler-errors

cg_llvm: Use a type-safe helper to cast `&str` and `&[u8]` to `*const c_char`

In `rustc_codegen_llvm` there are many uses of `.as_ptr().cast()` to convert a string or byte-slice to `*const c_char`, which then gets passed through FFI.

This works, but is fragile, because there's nothing constraining the pointer cast to actually be from `u8` to `c_char`. If the original value changes to something else that has an `as_ptr` method, or the context changes to expect something other than `c_char`, the cast will silently do the wrong thing.

By making the cast more explicit via a helper method, we can be sure that it will either perform the intended cast, or fail at compile time.
This commit is contained in:
Jubilee 2024-10-28 10:18:52 -07:00 committed by GitHub
commit bd43f8e9fd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 110 additions and 87 deletions

View File

@ -7,6 +7,7 @@
use rustc_middle::ty::TyCtxt; use rustc_middle::ty::TyCtxt;
use rustc_session::config::{DebugInfo, OomStrategy}; use rustc_session::config::{DebugInfo, OomStrategy};
use crate::common::AsCCharPtr;
use crate::llvm::{self, Context, False, Module, True, Type}; use crate::llvm::{self, Context, False, Module, True, Type};
use crate::{ModuleLlvm, attributes, debuginfo}; use crate::{ModuleLlvm, attributes, debuginfo};
@ -76,14 +77,14 @@ pub(crate) unsafe fn codegen(
unsafe { unsafe {
// __rust_alloc_error_handler_should_panic // __rust_alloc_error_handler_should_panic
let name = OomStrategy::SYMBOL; let name = OomStrategy::SYMBOL;
let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_ptr().cast(), name.len(), i8); let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_c_char_ptr(), name.len(), i8);
llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility())); llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility()));
let val = tcx.sess.opts.unstable_opts.oom.should_panic(); let val = tcx.sess.opts.unstable_opts.oom.should_panic();
let llval = llvm::LLVMConstInt(i8, val as u64, False); let llval = llvm::LLVMConstInt(i8, val as u64, False);
llvm::LLVMSetInitializer(ll_g, llval); llvm::LLVMSetInitializer(ll_g, llval);
let name = NO_ALLOC_SHIM_IS_UNSTABLE; let name = NO_ALLOC_SHIM_IS_UNSTABLE;
let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_ptr().cast(), name.len(), i8); let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_c_char_ptr(), name.len(), i8);
llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility())); llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility()));
let llval = llvm::LLVMConstInt(i8, 0, False); let llval = llvm::LLVMConstInt(i8, 0, False);
llvm::LLVMSetInitializer(ll_g, llval); llvm::LLVMSetInitializer(ll_g, llval);
@ -115,7 +116,7 @@ fn create_wrapper_function(
); );
let llfn = llvm::LLVMRustGetOrInsertFunction( let llfn = llvm::LLVMRustGetOrInsertFunction(
llmod, llmod,
from_name.as_ptr().cast(), from_name.as_c_char_ptr(),
from_name.len(), from_name.len(),
ty, ty,
); );
@ -137,7 +138,7 @@ fn create_wrapper_function(
} }
let callee = let callee =
llvm::LLVMRustGetOrInsertFunction(llmod, to_name.as_ptr().cast(), to_name.len(), ty); llvm::LLVMRustGetOrInsertFunction(llmod, to_name.as_c_char_ptr(), to_name.len(), ty);
if let Some(no_return) = no_return { if let Some(no_return) = no_return {
// -> ! DIFlagNoReturn // -> ! DIFlagNoReturn
attributes::apply_to_llfn(callee, llvm::AttributePlace::Function, &[no_return]); attributes::apply_to_llfn(callee, llvm::AttributePlace::Function, &[no_return]);

View File

@ -15,7 +15,7 @@
use tracing::debug; use tracing::debug;
use crate::builder::Builder; use crate::builder::Builder;
use crate::common::Funclet; use crate::common::{AsCCharPtr, Funclet};
use crate::context::CodegenCx; use crate::context::CodegenCx;
use crate::type_::Type; use crate::type_::Type;
use crate::type_of::LayoutLlvmExt; use crate::type_of::LayoutLlvmExt;
@ -420,7 +420,7 @@ fn codegen_global_asm(
unsafe { unsafe {
llvm::LLVMAppendModuleInlineAsm( llvm::LLVMAppendModuleInlineAsm(
self.llmod, self.llmod,
template_str.as_ptr().cast(), template_str.as_c_char_ptr(),
template_str.len(), template_str.len(),
); );
} }
@ -458,14 +458,14 @@ pub(crate) fn inline_asm_call<'ll>(
let fty = bx.cx.type_func(&argtys, output); let fty = bx.cx.type_func(&argtys, output);
unsafe { unsafe {
// Ask LLVM to verify that the constraints are well-formed. // Ask LLVM to verify that the constraints are well-formed.
let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr().cast(), cons.len()); let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_c_char_ptr(), cons.len());
debug!("constraint verification result: {:?}", constraints_ok); debug!("constraint verification result: {:?}", constraints_ok);
if constraints_ok { if constraints_ok {
let v = llvm::LLVMRustInlineAsm( let v = llvm::LLVMRustInlineAsm(
fty, fty,
asm.as_ptr().cast(), asm.as_c_char_ptr(),
asm.len(), asm.len(),
cons.as_ptr().cast(), cons.as_c_char_ptr(),
cons.len(), cons.len(),
volatile, volatile,
alignstack, alignstack,

View File

@ -25,6 +25,7 @@
use crate::back::write::{ use crate::back::write::{
self, CodegenDiagnosticsStage, DiagnosticHandlers, bitcode_section_name, save_temp_bitcode, self, CodegenDiagnosticsStage, DiagnosticHandlers, bitcode_section_name, save_temp_bitcode,
}; };
use crate::common::AsCCharPtr;
use crate::errors::{ use crate::errors::{
DynamicLinkingWithLTO, LlvmError, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib, LtoProcMacro, DynamicLinkingWithLTO, LlvmError, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib, LtoProcMacro,
}; };
@ -604,7 +605,7 @@ pub(crate) fn run_pass_manager(
unsafe { unsafe {
if !llvm::LLVMRustHasModuleFlag( if !llvm::LLVMRustHasModuleFlag(
module.module_llvm.llmod(), module.module_llvm.llmod(),
"LTOPostLink".as_ptr().cast(), "LTOPostLink".as_c_char_ptr(),
11, 11,
) { ) {
llvm::LLVMRustAddModuleFlagU32( llvm::LLVMRustAddModuleFlagU32(

View File

@ -34,6 +34,7 @@
use crate::back::profiling::{ use crate::back::profiling::{
LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback,
}; };
use crate::common::AsCCharPtr;
use crate::errors::{ use crate::errors::{
CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression, CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression,
WithLlvmError, WriteBytecode, WithLlvmError, WriteBytecode,
@ -596,9 +597,9 @@ pub(crate) unsafe fn llvm_optimize(
llvm_selfprofiler, llvm_selfprofiler,
selfprofile_before_pass_callback, selfprofile_before_pass_callback,
selfprofile_after_pass_callback, selfprofile_after_pass_callback,
extra_passes.as_ptr().cast(), extra_passes.as_c_char_ptr(),
extra_passes.len(), extra_passes.len(),
llvm_plugins.as_ptr().cast(), llvm_plugins.as_c_char_ptr(),
llvm_plugins.len(), llvm_plugins.len(),
) )
}; };
@ -1042,7 +1043,7 @@ unsafe fn embed_bitcode(
llvm::LLVMSetInitializer(llglobal, llconst); llvm::LLVMSetInitializer(llglobal, llconst);
let section = bitcode_section_name(cgcx); let section = bitcode_section_name(cgcx);
llvm::LLVMSetSection(llglobal, section.as_ptr().cast()); llvm::LLVMSetSection(llglobal, section.as_c_char_ptr());
llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage); llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
llvm::LLVMSetGlobalConstant(llglobal, llvm::True); llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
@ -1066,9 +1067,9 @@ unsafe fn embed_bitcode(
// We need custom section flags, so emit module-level inline assembly. // We need custom section flags, so emit module-level inline assembly.
let section_flags = if cgcx.is_pe_coff { "n" } else { "e" }; let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode); let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len()); llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_c_char_ptr(), asm.len());
let asm = create_section_with_flags_asm(".llvmcmd", section_flags, cmdline.as_bytes()); let asm = create_section_with_flags_asm(".llvmcmd", section_flags, cmdline.as_bytes());
llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len()); llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_c_char_ptr(), asm.len());
} }
} }
} }

View File

@ -392,3 +392,21 @@ pub(crate) fn get_dllimport<'tcx>(
tcx.native_library(id) tcx.native_library(id)
.and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name)) .and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
} }
/// Extension trait for explicit casts to `*const c_char`.
pub(crate) trait AsCCharPtr {
/// Equivalent to `self.as_ptr().cast()`, but only casts to `*const c_char`.
fn as_c_char_ptr(&self) -> *const c_char;
}
impl AsCCharPtr for str {
fn as_c_char_ptr(&self) -> *const c_char {
self.as_ptr().cast()
}
}
impl AsCCharPtr for [u8] {
fn as_c_char_ptr(&self) -> *const c_char {
self.as_ptr().cast()
}
}

View File

@ -19,7 +19,7 @@
}; };
use tracing::{debug, instrument, trace}; use tracing::{debug, instrument, trace};
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::errors::{ use crate::errors::{
InvalidMinimumAlignmentNotPowerOfTwo, InvalidMinimumAlignmentTooLarge, SymbolAlreadyDefined, InvalidMinimumAlignmentNotPowerOfTwo, InvalidMinimumAlignmentTooLarge, SymbolAlreadyDefined,
}; };
@ -400,7 +400,7 @@ fn codegen_static_item(&self, def_id: DefId) {
let new_g = llvm::LLVMRustGetOrInsertGlobal( let new_g = llvm::LLVMRustGetOrInsertGlobal(
self.llmod, self.llmod,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
val_llty, val_llty,
); );
@ -451,7 +451,7 @@ fn codegen_static_item(&self, def_id: DefId) {
if let Some(section) = attrs.link_section { if let Some(section) = attrs.link_section {
let section = llvm::LLVMMDStringInContext2( let section = llvm::LLVMMDStringInContext2(
self.llcx, self.llcx,
section.as_str().as_ptr().cast(), section.as_str().as_c_char_ptr(),
section.as_str().len(), section.as_str().len(),
); );
assert!(alloc.provenance().ptrs().is_empty()); assert!(alloc.provenance().ptrs().is_empty());
@ -462,7 +462,7 @@ fn codegen_static_item(&self, def_id: DefId) {
let bytes = let bytes =
alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()); alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
let alloc = let alloc =
llvm::LLVMMDStringInContext2(self.llcx, bytes.as_ptr().cast(), bytes.len()); llvm::LLVMMDStringInContext2(self.llcx, bytes.as_c_char_ptr(), bytes.len());
let data = [section, alloc]; let data = [section, alloc];
let meta = llvm::LLVMMDNodeInContext2(self.llcx, data.as_ptr(), data.len()); let meta = llvm::LLVMMDNodeInContext2(self.llcx, data.as_ptr(), data.len());
let val = llvm::LLVMMetadataAsValue(self.llcx, meta); let val = llvm::LLVMMetadataAsValue(self.llcx, meta);

View File

@ -29,6 +29,7 @@
use crate::back::write::to_llvm_code_model; use crate::back::write::to_llvm_code_model;
use crate::callee::get_fn; use crate::callee::get_fn;
use crate::common::AsCCharPtr;
use crate::debuginfo::metadata::apply_vcall_visibility_metadata; use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
use crate::llvm::{Metadata, MetadataType}; use crate::llvm::{Metadata, MetadataType};
use crate::type_::Type; use crate::type_::Type;
@ -231,7 +232,7 @@ pub(crate) unsafe fn create_module<'ll>(
// If we're normalizing integers with CFI, ensure LLVM generated functions do the same. // If we're normalizing integers with CFI, ensure LLVM generated functions do the same.
// See https://github.com/llvm/llvm-project/pull/104826 // See https://github.com/llvm/llvm-project/pull/104826
if sess.is_sanitizer_cfi_normalize_integers_enabled() { if sess.is_sanitizer_cfi_normalize_integers_enabled() {
let cfi_normalize_integers = c"cfi-normalize-integers".as_ptr().cast(); let cfi_normalize_integers = c"cfi-normalize-integers".as_ptr();
unsafe { unsafe {
llvm::LLVMRustAddModuleFlagU32( llvm::LLVMRustAddModuleFlagU32(
llmod, llmod,
@ -268,7 +269,7 @@ pub(crate) unsafe fn create_module<'ll>(
let pfe = let pfe =
PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry); PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry);
if pfe.prefix() > 0 { if pfe.prefix() > 0 {
let kcfi_offset = c"kcfi-offset".as_ptr().cast(); let kcfi_offset = c"kcfi-offset".as_ptr();
unsafe { unsafe {
llvm::LLVMRustAddModuleFlagU32( llvm::LLVMRustAddModuleFlagU32(
llmod, llmod,
@ -429,7 +430,7 @@ pub(crate) unsafe fn create_module<'ll>(
let name_metadata = unsafe { let name_metadata = unsafe {
llvm::LLVMMDStringInContext2( llvm::LLVMMDStringInContext2(
llcx, llcx,
rustc_producer.as_ptr().cast(), rustc_producer.as_c_char_ptr(),
rustc_producer.as_bytes().len(), rustc_producer.as_bytes().len(),
) )
}; };
@ -453,7 +454,7 @@ pub(crate) unsafe fn create_module<'ll>(
llmod, llmod,
llvm::LLVMModFlagBehavior::Error, llvm::LLVMModFlagBehavior::Error,
c"target-abi".as_ptr(), c"target-abi".as_ptr(),
llvm_abiname.as_ptr().cast(), llvm_abiname.as_c_char_ptr(),
llvm_abiname.len(), llvm_abiname.len(),
); );
} }
@ -474,7 +475,7 @@ pub(crate) unsafe fn create_module<'ll>(
// We already checked this during option parsing // We already checked this during option parsing
_ => unreachable!(), _ => unreachable!(),
}; };
unsafe { llvm::LLVMRustAddModuleFlagU32(llmod, behavior, key.as_ptr().cast(), *value) } unsafe { llvm::LLVMRustAddModuleFlagU32(llmod, behavior, key.as_c_char_ptr(), *value) }
} }
llmod llmod

View File

@ -14,7 +14,7 @@
use tracing::{debug, instrument}; use tracing::{debug, instrument};
use crate::builder::Builder; use crate::builder::Builder;
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::coverageinfo::map_data::FunctionCoverageCollector; use crate::coverageinfo::map_data::FunctionCoverageCollector;
use crate::llvm; use crate::llvm;
@ -236,7 +236,7 @@ fn create_pgo_func_name_var<'ll, 'tcx>(
unsafe { unsafe {
llvm::LLVMRustCoverageCreatePGOFuncNameVar( llvm::LLVMRustCoverageCreatePGOFuncNameVar(
llfn, llfn,
mangled_fn_name.as_ptr().cast(), mangled_fn_name.as_c_char_ptr(),
mangled_fn_name.len(), mangled_fn_name.len(),
) )
} }
@ -248,7 +248,7 @@ pub(crate) fn write_filenames_section_to_buffer<'a>(
) { ) {
let (pointers, lengths) = filenames let (pointers, lengths) = filenames
.into_iter() .into_iter()
.map(|s: &str| (s.as_ptr().cast(), s.len())) .map(|s: &str| (s.as_c_char_ptr(), s.len()))
.unzip::<_, _, Vec<_>, Vec<_>>(); .unzip::<_, _, Vec<_>, Vec<_>>();
unsafe { unsafe {
@ -291,7 +291,7 @@ pub(crate) fn write_mapping_to_buffer(
} }
pub(crate) fn hash_bytes(bytes: &[u8]) -> u64 { pub(crate) fn hash_bytes(bytes: &[u8]) -> u64 {
unsafe { llvm::LLVMRustCoverageHashByteArray(bytes.as_ptr().cast(), bytes.len()) } unsafe { llvm::LLVMRustCoverageHashByteArray(bytes.as_c_char_ptr(), bytes.len()) }
} }
pub(crate) fn mapping_version() -> u32 { pub(crate) fn mapping_version() -> u32 {

View File

@ -32,7 +32,7 @@
use super::utils::{ use super::utils::{
DIB, create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB, create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit,
}; };
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::metadata::type_map::build_type_with_children; use crate::debuginfo::metadata::type_map::build_type_with_children;
use crate::debuginfo::utils::{WidePtrKind, wide_pointer_kind}; use crate::debuginfo::utils::{WidePtrKind, wide_pointer_kind};
use crate::llvm::debuginfo::{ use crate::llvm::debuginfo::{
@ -190,7 +190,7 @@ fn build_pointer_or_reference_di_node<'ll, 'tcx>(
data_layout.pointer_size.bits(), data_layout.pointer_size.bits(),
data_layout.pointer_align.abi.bits() as u32, data_layout.pointer_align.abi.bits() as u32,
0, // Ignore DWARF address space. 0, // Ignore DWARF address space.
ptr_type_debuginfo_name.as_ptr().cast(), ptr_type_debuginfo_name.as_c_char_ptr(),
ptr_type_debuginfo_name.len(), ptr_type_debuginfo_name.len(),
) )
}; };
@ -348,7 +348,7 @@ fn build_subroutine_type_di_node<'ll, 'tcx>(
size, size,
align, align,
0, // Ignore DWARF address space. 0, // Ignore DWARF address space.
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
) )
}; };
@ -518,7 +518,7 @@ fn recursion_marker_type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll D
let name = "<recur_type>"; let name = "<recur_type>";
llvm::LLVMRustDIBuilderCreateBasicType( llvm::LLVMRustDIBuilderCreateBasicType(
DIB(cx), DIB(cx),
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
cx.tcx.data_layout.pointer_size.bits(), cx.tcx.data_layout.pointer_size.bits(),
DW_ATE_unsigned, DW_ATE_unsigned,
@ -640,14 +640,14 @@ fn alloc_new_file_metadata<'ll>(
unsafe { unsafe {
llvm::LLVMRustDIBuilderCreateFile( llvm::LLVMRustDIBuilderCreateFile(
DIB(cx), DIB(cx),
file_name.as_ptr().cast(), file_name.as_c_char_ptr(),
file_name.len(), file_name.len(),
directory.as_ptr().cast(), directory.as_c_char_ptr(),
directory.len(), directory.len(),
hash_kind, hash_kind,
hash_value.as_ptr().cast(), hash_value.as_c_char_ptr(),
hash_value.len(), hash_value.len(),
source.map_or(ptr::null(), |x| x.as_ptr().cast()), source.map_or(ptr::null(), |x| x.as_c_char_ptr()),
source.map_or(0, |x| x.len()), source.map_or(0, |x| x.len()),
) )
} }
@ -662,12 +662,12 @@ fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
llvm::LLVMRustDIBuilderCreateFile( llvm::LLVMRustDIBuilderCreateFile(
DIB(cx), DIB(cx),
file_name.as_ptr().cast(), file_name.as_c_char_ptr(),
file_name.len(), file_name.len(),
directory.as_ptr().cast(), directory.as_c_char_ptr(),
directory.len(), directory.len(),
llvm::ChecksumKind::None, llvm::ChecksumKind::None,
hash_value.as_ptr().cast(), hash_value.as_c_char_ptr(),
hash_value.len(), hash_value.len(),
ptr::null(), ptr::null(),
0, 0,
@ -788,7 +788,7 @@ fn build_basic_type_di_node<'ll, 'tcx>(
let ty_di_node = unsafe { let ty_di_node = unsafe {
llvm::LLVMRustDIBuilderCreateBasicType( llvm::LLVMRustDIBuilderCreateBasicType(
DIB(cx), DIB(cx),
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
cx.size_of(t).bits(), cx.size_of(t).bits(),
encoding, encoding,
@ -810,7 +810,7 @@ fn build_basic_type_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateTypedef( llvm::LLVMRustDIBuilderCreateTypedef(
DIB(cx), DIB(cx),
ty_di_node, ty_di_node,
typedef_name.as_ptr().cast(), typedef_name.as_c_char_ptr(),
typedef_name.len(), typedef_name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
0, 0,
@ -861,7 +861,7 @@ fn build_param_type_di_node<'ll, 'tcx>(
di_node: unsafe { di_node: unsafe {
llvm::LLVMRustDIBuilderCreateBasicType( llvm::LLVMRustDIBuilderCreateBasicType(
DIB(cx), DIB(cx),
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
Size::ZERO.bits(), Size::ZERO.bits(),
DW_ATE_unsigned, DW_ATE_unsigned,
@ -948,9 +948,9 @@ pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>(
unsafe { unsafe {
let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile( let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
debug_context.builder, debug_context.builder,
name_in_debuginfo.as_ptr().cast(), name_in_debuginfo.as_c_char_ptr(),
name_in_debuginfo.len(), name_in_debuginfo.len(),
work_dir.as_ptr().cast(), work_dir.as_c_char_ptr(),
work_dir.len(), work_dir.len(),
llvm::ChecksumKind::None, llvm::ChecksumKind::None,
ptr::null(), ptr::null(),
@ -963,7 +963,7 @@ pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>(
debug_context.builder, debug_context.builder,
DW_LANG_RUST, DW_LANG_RUST,
compile_unit_file, compile_unit_file,
producer.as_ptr().cast(), producer.as_c_char_ptr(),
producer.len(), producer.len(),
tcx.sess.opts.optimize != config::OptLevel::No, tcx.sess.opts.optimize != config::OptLevel::No,
c"".as_ptr(), c"".as_ptr(),
@ -971,7 +971,7 @@ pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>(
// NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
// put the path supplied to `MCSplitDwarfFile` into the debug info of the final // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
// output(s). // output(s).
split_name.as_ptr().cast(), split_name.as_c_char_ptr(),
split_name.len(), split_name.len(),
kind, kind,
0, 0,
@ -1022,7 +1022,7 @@ fn build_field_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateMemberType( llvm::LLVMRustDIBuilderCreateMemberType(
DIB(cx), DIB(cx),
owner, owner,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -1306,7 +1306,7 @@ fn build_generic_type_param_di_nodes<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateTemplateTypeParameter( llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
DIB(cx), DIB(cx),
None, None,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
actual_type_di_node, actual_type_di_node,
) )
@ -1382,9 +1382,9 @@ pub(crate) fn build_global_var_di_node<'ll>(
llvm::LLVMRustDIBuilderCreateStaticVariable( llvm::LLVMRustDIBuilderCreateStaticVariable(
DIB(cx), DIB(cx),
Some(var_scope), Some(var_scope),
var_name.as_ptr().cast(), var_name.as_c_char_ptr(),
var_name.len(), var_name.len(),
linkage_name.as_ptr().cast(), linkage_name.as_c_char_ptr(),
linkage_name.len(), linkage_name.len(),
file_metadata, file_metadata,
line_number, line_number,
@ -1602,9 +1602,9 @@ pub(crate) fn create_vtable_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateStaticVariable( llvm::LLVMRustDIBuilderCreateStaticVariable(
DIB(cx), DIB(cx),
NO_SCOPE_METADATA, NO_SCOPE_METADATA,
vtable_name.as_ptr().cast(), vtable_name.as_c_char_ptr(),
vtable_name.len(), vtable_name.len(),
linkage_name.as_ptr().cast(), linkage_name.as_c_char_ptr(),
linkage_name.len(), linkage_name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,

View File

@ -11,7 +11,7 @@
use rustc_target::abi::{Align, Endian, Size, TagEncoding, VariantIdx, Variants}; use rustc_target::abi::{Align, Endian, Size, TagEncoding, VariantIdx, Variants};
use smallvec::smallvec; use smallvec::smallvec;
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::metadata::enums::DiscrResult; use crate::debuginfo::metadata::enums::DiscrResult;
use crate::debuginfo::metadata::type_map::{self, Stub, UniqueTypeId}; use crate::debuginfo::metadata::type_map::{self, Stub, UniqueTypeId};
use crate::debuginfo::metadata::{ use crate::debuginfo::metadata::{
@ -359,7 +359,7 @@ fn build_single_variant_union_fields<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateStaticMemberType( llvm::LLVMRustDIBuilderCreateStaticMemberType(
DIB(cx), DIB(cx),
enum_type_di_node, enum_type_di_node,
TAG_FIELD_NAME.as_ptr().cast(), TAG_FIELD_NAME.as_c_char_ptr(),
TAG_FIELD_NAME.len(), TAG_FIELD_NAME.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -537,7 +537,7 @@ enum DiscrKind {
llvm::LLVMRustDIBuilderCreateStaticMemberType( llvm::LLVMRustDIBuilderCreateStaticMemberType(
DIB(cx), DIB(cx),
wrapper_struct_type_di_node, wrapper_struct_type_di_node,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -785,7 +785,7 @@ fn build_union_fields_for_direct_tag_enum_or_coroutine<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateMemberType( llvm::LLVMRustDIBuilderCreateMemberType(
DIB(cx), DIB(cx),
enum_type_di_node, enum_type_di_node,
field_name.as_ptr().cast(), field_name.as_c_char_ptr(),
field_name.len(), field_name.len(),
file_di_node, file_di_node,
line_number, line_number,

View File

@ -13,7 +13,7 @@
use super::type_map::{DINodeCreationResult, UniqueTypeId}; use super::type_map::{DINodeCreationResult, UniqueTypeId};
use super::{SmallVec, size_and_align_of}; use super::{SmallVec, size_and_align_of};
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::metadata::type_map::{self, Stub}; use crate::debuginfo::metadata::type_map::{self, Stub};
use crate::debuginfo::metadata::{ use crate::debuginfo::metadata::{
UNKNOWN_LINE_NUMBER, build_field_di_node, build_generic_type_param_di_nodes, type_di_node, UNKNOWN_LINE_NUMBER, build_field_di_node, build_generic_type_param_di_nodes, type_di_node,
@ -106,7 +106,7 @@ fn build_enumeration_type_di_node<'ll, 'tcx>(
let value = [value as u64, (value >> 64) as u64]; let value = [value as u64, (value >> 64) as u64];
Some(llvm::LLVMRustDIBuilderCreateEnumerator( Some(llvm::LLVMRustDIBuilderCreateEnumerator(
DIB(cx), DIB(cx),
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
value.as_ptr(), value.as_ptr(),
size.bits() as libc::c_uint, size.bits() as libc::c_uint,
@ -119,7 +119,7 @@ fn build_enumeration_type_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateEnumerationType( llvm::LLVMRustDIBuilderCreateEnumerationType(
DIB(cx), DIB(cx),
containing_scope, containing_scope,
type_name.as_ptr().cast(), type_name.as_c_char_ptr(),
type_name.len(), type_name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,

View File

@ -10,7 +10,7 @@
use rustc_target::abi::{Size, TagEncoding, VariantIdx, Variants}; use rustc_target::abi::{Size, TagEncoding, VariantIdx, Variants};
use smallvec::smallvec; use smallvec::smallvec;
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::metadata::type_map::{self, Stub, StubInfo, UniqueTypeId}; use crate::debuginfo::metadata::type_map::{self, Stub, StubInfo, UniqueTypeId};
use crate::debuginfo::metadata::{ use crate::debuginfo::metadata::{
DINodeCreationResult, NO_GENERICS, SmallVec, UNKNOWN_LINE_NUMBER, file_metadata, DINodeCreationResult, NO_GENERICS, SmallVec, UNKNOWN_LINE_NUMBER, file_metadata,
@ -244,7 +244,7 @@ fn build_enum_variant_part_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateVariantPart( llvm::LLVMRustDIBuilderCreateVariantPart(
DIB(cx), DIB(cx),
enum_type_di_node, enum_type_di_node,
variant_part_name.as_ptr().cast(), variant_part_name.as_c_char_ptr(),
variant_part_name.len(), variant_part_name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -253,7 +253,7 @@ fn build_enum_variant_part_di_node<'ll, 'tcx>(
DIFlags::FlagZero, DIFlags::FlagZero,
tag_member_di_node, tag_member_di_node,
create_DIArray(DIB(cx), &[]), create_DIArray(DIB(cx), &[]),
variant_part_unique_type_id_str.as_ptr().cast(), variant_part_unique_type_id_str.as_c_char_ptr(),
variant_part_unique_type_id_str.len(), variant_part_unique_type_id_str.len(),
) )
}, },
@ -327,7 +327,7 @@ fn build_discr_member_di_node<'ll, 'tcx>(
Some(llvm::LLVMRustDIBuilderCreateMemberType( Some(llvm::LLVMRustDIBuilderCreateMemberType(
DIB(cx), DIB(cx),
containing_scope, containing_scope,
tag_name.as_ptr().cast(), tag_name.as_c_char_ptr(),
tag_name.len(), tag_name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -399,7 +399,7 @@ fn build_enum_variant_member_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateVariantMemberType( llvm::LLVMRustDIBuilderCreateVariantMemberType(
DIB(cx), DIB(cx),
variant_part_di_node, variant_part_di_node,
variant_member_info.variant_name.as_ptr().cast(), variant_member_info.variant_name.as_c_char_ptr(),
variant_member_info.variant_name.len(), variant_member_info.variant_name.len(),
file_di_node, file_di_node,
line_number, line_number,

View File

@ -9,7 +9,7 @@
use rustc_target::abi::{Align, Size, VariantIdx}; use rustc_target::abi::{Align, Size, VariantIdx};
use super::{SmallVec, UNKNOWN_LINE_NUMBER, unknown_file_metadata}; use super::{SmallVec, UNKNOWN_LINE_NUMBER, unknown_file_metadata};
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::utils::{DIB, create_DIArray, debug_context}; use crate::debuginfo::utils::{DIB, create_DIArray, debug_context};
use crate::llvm::debuginfo::{DIFlags, DIScope, DIType}; use crate::llvm::debuginfo::{DIFlags, DIScope, DIType};
use crate::llvm::{self}; use crate::llvm::{self};
@ -191,7 +191,7 @@ pub(super) fn stub<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateStructType( llvm::LLVMRustDIBuilderCreateStructType(
DIB(cx), DIB(cx),
containing_scope, containing_scope,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -202,7 +202,7 @@ pub(super) fn stub<'ll, 'tcx>(
empty_array, empty_array,
0, 0,
vtable_holder, vtable_holder,
unique_type_id_str.as_ptr().cast(), unique_type_id_str.as_c_char_ptr(),
unique_type_id_str.len(), unique_type_id_str.len(),
) )
} }
@ -211,7 +211,7 @@ pub(super) fn stub<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateUnionType( llvm::LLVMRustDIBuilderCreateUnionType(
DIB(cx), DIB(cx),
containing_scope, containing_scope,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -220,7 +220,7 @@ pub(super) fn stub<'ll, 'tcx>(
flags, flags,
Some(empty_array), Some(empty_array),
0, 0,
unique_type_id_str.as_ptr().cast(), unique_type_id_str.as_c_char_ptr(),
unique_type_id_str.len(), unique_type_id_str.len(),
) )
}, },

View File

@ -31,7 +31,7 @@
use self::utils::{DIB, create_DIArray, is_node_local_to_unit}; use self::utils::{DIB, create_DIArray, is_node_local_to_unit};
use crate::abi::FnAbi; use crate::abi::FnAbi;
use crate::builder::Builder; use crate::builder::Builder;
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::llvm; use crate::llvm;
use crate::llvm::debuginfo::{ use crate::llvm::debuginfo::{
DIArray, DIBuilder, DIFile, DIFlags, DILexicalBlock, DILocation, DISPFlags, DIScope, DIType, DIArray, DIBuilder, DIFile, DIFlags, DILexicalBlock, DILocation, DISPFlags, DIScope, DIType,
@ -389,9 +389,9 @@ fn dbg_scope_fn(
llvm::LLVMRustDIBuilderCreateMethod( llvm::LLVMRustDIBuilderCreateMethod(
DIB(self), DIB(self),
containing_scope, containing_scope,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
linkage_name.as_ptr().cast(), linkage_name.as_c_char_ptr(),
linkage_name.len(), linkage_name.len(),
file_metadata, file_metadata,
loc.line, loc.line,
@ -406,9 +406,9 @@ fn dbg_scope_fn(
llvm::LLVMRustDIBuilderCreateFunction( llvm::LLVMRustDIBuilderCreateFunction(
DIB(self), DIB(self),
containing_scope, containing_scope,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
linkage_name.as_ptr().cast(), linkage_name.as_c_char_ptr(),
linkage_name.len(), linkage_name.len(),
file_metadata, file_metadata,
loc.line, loc.line,
@ -494,7 +494,7 @@ fn get_template_parameters<'ll, 'tcx>(
Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter( Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
DIB(cx), DIB(cx),
None, None,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
actual_type_metadata, actual_type_metadata,
)) ))
@ -635,7 +635,7 @@ fn create_dbg_var(
DIB(self), DIB(self),
dwarf_tag, dwarf_tag,
scope_metadata, scope_metadata,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
file_metadata, file_metadata,
loc.line, loc.line,

View File

@ -5,7 +5,7 @@
use rustc_middle::ty::{self, Instance}; use rustc_middle::ty::{self, Instance};
use super::utils::{DIB, debug_context}; use super::utils::{DIB, debug_context};
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::llvm; use crate::llvm;
use crate::llvm::debuginfo::DIScope; use crate::llvm::debuginfo::DIScope;
@ -36,7 +36,7 @@ pub(crate) fn item_namespace<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'l
llvm::LLVMRustDIBuilderCreateNameSpace( llvm::LLVMRustDIBuilderCreateNameSpace(
DIB(cx), DIB(cx),
parent_scope, parent_scope,
namespace_name_string.as_ptr().cast(), namespace_name_string.as_c_char_ptr(),
namespace_name_string.len(), namespace_name_string.len(),
false, // ExportSymbols (only relevant for C++ anonymous namespaces) false, // ExportSymbols (only relevant for C++ anonymous namespaces)
) )

View File

@ -20,6 +20,7 @@
use tracing::debug; use tracing::debug;
use crate::abi::{FnAbi, FnAbiLlvmExt}; use crate::abi::{FnAbi, FnAbiLlvmExt};
use crate::common::AsCCharPtr;
use crate::context::CodegenCx; use crate::context::CodegenCx;
use crate::llvm::AttributePlace::Function; use crate::llvm::AttributePlace::Function;
use crate::llvm::Visibility; use crate::llvm::Visibility;
@ -41,7 +42,7 @@ fn declare_raw_fn<'ll>(
) -> &'ll Value { ) -> &'ll Value {
debug!("declare_raw_fn(name={:?}, ty={:?})", name, ty); debug!("declare_raw_fn(name={:?}, ty={:?})", name, ty);
let llfn = unsafe { let llfn = unsafe {
llvm::LLVMRustGetOrInsertFunction(cx.llmod, name.as_ptr().cast(), name.len(), ty) llvm::LLVMRustGetOrInsertFunction(cx.llmod, name.as_c_char_ptr(), name.len(), ty)
}; };
llvm::SetFunctionCallConv(llfn, callconv); llvm::SetFunctionCallConv(llfn, callconv);
@ -68,7 +69,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
/// return its Value instead. /// return its Value instead.
pub(crate) fn declare_global(&self, name: &str, ty: &'ll Type) -> &'ll Value { pub(crate) fn declare_global(&self, name: &str, ty: &'ll Type) -> &'ll Value {
debug!("declare_global(name={:?})", name); debug!("declare_global(name={:?})", name);
unsafe { llvm::LLVMRustGetOrInsertGlobal(self.llmod, name.as_ptr().cast(), name.len(), ty) } unsafe { llvm::LLVMRustGetOrInsertGlobal(self.llmod, name.as_c_char_ptr(), name.len(), ty) }
} }
/// Declare a C ABI function. /// Declare a C ABI function.
@ -209,7 +210,7 @@ pub(crate) fn define_private_global(&self, ty: &'ll Type) -> &'ll Value {
/// Gets declared value by name. /// Gets declared value by name.
pub(crate) fn get_declared_value(&self, name: &str) -> Option<&'ll Value> { pub(crate) fn get_declared_value(&self, name: &str) -> Option<&'ll Value> {
debug!("get_declared_value(name={:?})", name); debug!("get_declared_value(name={:?})", name);
unsafe { llvm::LLVMRustGetNamedValue(self.llmod, name.as_ptr().cast(), name.len()) } unsafe { llvm::LLVMRustGetNamedValue(self.llmod, name.as_c_char_ptr(), name.len()) }
} }
/// Gets defined or externally defined (AvailableExternally linkage) value by /// Gets defined or externally defined (AvailableExternally linkage) value by

View File

@ -17,13 +17,13 @@
pub use self::Linkage::*; pub use self::Linkage::*;
pub use self::MetadataType::*; pub use self::MetadataType::*;
pub use self::RealPredicate::*; pub use self::RealPredicate::*;
pub use self::ffi::*;
use crate::common::AsCCharPtr;
pub mod archive_ro; pub mod archive_ro;
pub mod diagnostic; pub mod diagnostic;
mod ffi; mod ffi;
pub use self::ffi::*;
impl LLVMRustResult { impl LLVMRustResult {
pub fn into_result(self) -> Result<(), ()> { pub fn into_result(self) -> Result<(), ()> {
match self { match self {
@ -53,9 +53,9 @@ pub fn CreateAttrStringValue<'ll>(llcx: &'ll Context, attr: &str, value: &str) -
unsafe { unsafe {
LLVMCreateStringAttribute( LLVMCreateStringAttribute(
llcx, llcx,
attr.as_ptr().cast(), attr.as_c_char_ptr(),
attr.len().try_into().unwrap(), attr.len().try_into().unwrap(),
value.as_ptr().cast(), value.as_c_char_ptr(),
value.len().try_into().unwrap(), value.len().try_into().unwrap(),
) )
} }
@ -65,7 +65,7 @@ pub fn CreateAttrString<'ll>(llcx: &'ll Context, attr: &str) -> &'ll Attribute {
unsafe { unsafe {
LLVMCreateStringAttribute( LLVMCreateStringAttribute(
llcx, llcx,
attr.as_ptr().cast(), attr.as_c_char_ptr(),
attr.len().try_into().unwrap(), attr.len().try_into().unwrap(),
std::ptr::null(), std::ptr::null(),
0, 0,
@ -294,7 +294,7 @@ pub fn get_value_name(value: &Value) -> &[u8] {
/// Safe wrapper for `LLVMSetValueName2` from a byte slice /// Safe wrapper for `LLVMSetValueName2` from a byte slice
pub fn set_value_name(value: &Value, name: &[u8]) { pub fn set_value_name(value: &Value, name: &[u8]) {
unsafe { unsafe {
let data = name.as_ptr().cast(); let data = name.as_c_char_ptr();
LLVMSetValueName2(value, data, name.len()); LLVMSetValueName2(value, data, name.len());
} }
} }