Skip to content

Place &str in specific linker sections #70239

Open
@korken89

Description

@korken89

In the usecase I am working on I want to store the string from core::any::type_name in a specific linker section to create an instrumentation tool for Embedded Rust micro controllers.
If the string is placed in .rodata it does not affect the tool, but when having only a few kB of memory storing these strings in the actual micro controller is a huge price to pay.
Rather only the generated ELF file, which the host can read, should have this info (i.e. in an INFO marked section).

As it is today one can place variables in specific sections as:

#[link_section = ".my_section"]
static S: u32 = 2; 

However, this is not possible for &str, the following:

#[link_section = ".my_section"]
static S: &str = "test"; 

Will place the string itself in .rodata, while placing the pointer and length in the section .my_section.
The recommended solution is to place the string in an array using something similar to the following:

union Transmute<T: Copy, U: Copy> {
    from: T,
    to: U,
}

const TN: &'static str = "my string";

#[link_section = ".my_section"]
static S: [u8; TN.as_bytes().len()] = unsafe {
    *Transmute::<*const [u8; TN.as_bytes().len()], &[u8; TN.as_bytes().len()]> {
        from: TN.as_ptr() as *const [u8; TN.as_bytes().len()],
    }
    .to
};

However this does not work on strings given from (non-const-fn) functions such as core::any::type_name, and the function take no arguments so the string must be coming from a literal somewhere.
Is there a way to make the strings from core::any::type_name (or similar functions) be placed in a specific linker section?
As the string is being placed in .rodata something is controlling this placement, I simply wish to change this.

The method stated above works in nightly, as one can use the #![feature(const_type_name)] feature to get the string as a const-fn. However I am unable to reproduce this in any way using stable rust.
Example playground of the nightly version: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=d5f5c7fbe90194640bd1918cc068c2db

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-linkageArea: linking into static, shared libraries and binariesC-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions