Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ch 6.3.3 eprintln! macro in alloc produces endless alloc loop #119

Open
MichaPau opened this issue Oct 19, 2024 · 1 comment
Open

ch 6.3.3 eprintln! macro in alloc produces endless alloc loop #119

MichaPau opened this issue Oct 19, 2024 · 1 comment

Comments

@MichaPau
Copy link

Running the graphical application to create and destroy objects on the heap (Listing 6.9)
creates an endless loop. (ManjaroLinux release: 24.1.1; rustc 1.81.0).

and stops with the error : 'cargo run' terminated by signal SIGSEGV (Address boundary error)

this happens when using a macro like eprintln! or format! etc.
println! makes the application hang.

With the help from https://users.rust-lang.org (link below) I found a workaround using extern "C" printf:

extern "C" {
    fn printf(format: *const c_char, ...) -> c_int;
}
struct MyAllocator;


unsafe impl GlobalAlloc for MyAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        
        let start = Instant::now();
        let ptr = System.alloc(layout);
        let end = Instant::now();
        let ellapsed = end - start;
        let ellapsed_value = ellapsed.as_nanos();
        let v = layout.size();
        
        //eprint!("{}\t{}", v, ellapsed_value);
        let format: *const c_char = c"%d\t%d \n".as_ptr().cast();
        let _ = printf(format, v, ellapsed_value);

        ptr
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        System.dealloc(ptr, layout)
    }
}

This works on my system. I don't know if it's still possible that it allocates on the heap for others.

Link to the issue on rust-org

@niall-byrne
Copy link

niall-byrne commented Nov 25, 2024

I ran into a similar problem using rustc 1.82.0 (f6e511eec 2024-10-15).

The code would not execute, instead reporting:

fatal runtime error: the global allocator may not use TLS with destructors
Abort trap: 6

Removing the macro call to eprintln! resolved it, so I ended up following the same wormhole to create a C logger:

extern "C" {
  fn printf(_: *const core::ffi::c_char, ...) -> core::ffi::c_int;
}

fn log(bytes_requested: usize, time_taken: u128) {
  let fmt_ptr = b"%u, %u\n\0".as_ptr().cast();

  unsafe {
    printf(fmt_ptr, bytes_requested, time_taken);
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants