1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16//! rustc demangle for Rust. 17 18#![feature(rustc_private)] 19extern crate rustc_demangle; 20 21use std::alloc::{GlobalAlloc, Layout, System}; 22use std::io::Write; 23use std::os::raw::{c_char}; 24use std::ptr; 25use std::result::Result::{Ok, Err}; 26 27/// # Safety 28/// 29/// C-style interface for demangling. 30#[no_mangle] 31pub unsafe extern "C" fn rustc_demangle(mangled: *const c_char) -> *mut c_char 32{ 33 if mangled.is_null() { 34 return ptr::null_mut(); 35 } 36 let mangled_str = match std::ffi::CStr::from_ptr(mangled).to_str() { 37 Ok(s) => s, 38 Err(_) => return ptr::null_mut(), 39 }; 40 41 match rustc_demangle::try_demangle(mangled_str) { 42 Ok(demangle) => { 43 let size = demangle.to_string().len(); 44 let out = unsafe { System.alloc_zeroed(Layout::from_size_align_unchecked(size, 1)) }; 45 if out.is_null() { 46 return ptr::null_mut(); 47 } 48 49 match write!(unsafe { std::slice::from_raw_parts_mut(out, size) }, "{:#}\0", demangle) { 50 Ok(_) => { 51 unsafe { std::slice::from_raw_parts_mut(out, size) }.as_mut_ptr() as *mut c_char 52 } 53 Err(_) => ptr::null_mut(), 54 } 55 } 56 Err(_) => ptr::null_mut(), 57 } 58} 59