Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust debug library with GDB

I have a lib within /src/lib.rs. This I want to prepare for debugging with GDB.

rustc -g --crate-type lib libr.rs

Is the way searching told me how to do it. The output file has the following name liblib.rlib

Now running GDB - executing file lib.rs tells me it is not in a executable format and the same with the weird file liblib.rlib. I know that it is not an executable - but also I do not know any alternative file which I can start.

So how can I start debugging a lib in Rust now?

like image 623
xetra11 Avatar asked Jun 14 '16 12:06

xetra11


Video Answer


1 Answers

You cannot debug anything but an executable. Debuggers work by inspecting the memory of a running process; without a executable, you cannot have a process.

Assuming these two files:

src/lib.rs

pub fn add_one(i: u8) -> u8 {
    i + 2
}

#[test]
fn inline_test() {
    assert_eq!(2, foo::add_one(1));
}

tests/awesome.rs

extern crate foo;

#[test]
fn a_test() {
    assert_eq!(6, foo::add_one(5));
}

When you run cargo build or cargo test, test binaries will be created in the target/debug/ directory. In this case, there is one binary called foo-69521add8c82059a and one called awesome-4a24b21e22bc042a. Running either program runs that set of tests. All Rust tests work like this - an executable of some kind is generated and running it (perhaps with the right set of command line flags) will execute the test.

This executable is what you need to debug in GDB or LLDB:

$ rust-lldb target/debug/awesome-4a24b21e22bc042a

(lldb) br set -r '.*add_one.*'
(lldb) r
Process 59413 launched: '/private/tmp/foo/target/debug/awesome-4a24b21e22bc042a' (x86_64)

running 1 test
Process 59413 stopped
* thread #2: tid = 0xe9637, 0x0000000100038a3e awesome-4a24b21e22bc042a`foo::add_one::ha28bd7bf9dda9f1d + 14 at lib.rs:2, name = 'a_test', stop reason = breakpoint 1.1
    frame #0: 0x0000000100038a3e awesome-4a24b21e22bc042a`foo::add_one::ha28bd7bf9dda9f1d + 14 at lib.rs:2
   1    pub fn add_one(i: u8) -> u8 {
-> 2        i + 2
   3    }

rustc -g --crate-type lib libr.rs

This avoids using Cargo, which most people are not going to want to do. The important aspect of this line is the -g flag, which instructs the compiler to add debugging information. cargo build or cargo test compile in debugging mode by default. You can also build your tests in release mode.

like image 156
Shepmaster Avatar answered Sep 17 '22 15:09

Shepmaster