Skip to content

ffi::CString::new(string-literal) is suboptimal #35838

Closed
@glandium

Description

@glandium

I noticed this while doing some ltrace using alloc_system on my panicking program. A small test case is

#![feature(alloc_system)]
extern crate alloc_system;
fn main() {
    panic!();
}

What I noticed is the following pattern:

  • ptr = malloc(14)
  • memcpy(ptr, "RUST_BACKTRACE", 14)
  • memchr("RUST_BACKTRACE", '\0', 14)
  • ptr = realloc(ptr, 28)
  • ptr = realloc(ptr, 15)
    (not in ltrace, but likely: ptr[15] = '\0')

If realloc is not in-place, that's 3 copies of the string, and 3 allocations.

This all stems from the use of env::var_os("RUST_BACKTRACE") in librustc_driver/lib.rs, which ends up doing ffi::CString::new("RUST_BACKTRACE") (and indeed replacing panic!() in the test case above with that ffi::CString::new call yields the same copy/alloc pattern.

Ironically, the "RUST_BACKTRACE" static string which is copied the first time, is already null terminated in the executable binary's rodata section.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.I-slowIssue: Problems and improvements with respect to performance of generated code.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions