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

Support to pass unicorn handle to rust through FFI #1545

Merged
merged 2 commits into from
Feb 2, 2022

Conversation

bet4it
Copy link
Contributor

@bet4it bet4it commented Jan 22, 2022

After this PR, we can do something likes this:
C code:

#include <unicorn/unicorn.h>
#include "rust_ffi.h"

int main()
{
	uc_engine *uc;
	int val = 0;
	uc_open(UC_ARCH_ARM, UC_MODE_ARM, &uc);
	rust_ffi(uc);
	uc_reg_read(uc, UC_ARM_REG_R0, &val);
	printf("R0: %d\n", val);
	uc_close(uc);
	return 0;
}

Rust code:

#![allow(non_camel_case_types)]

use std::ffi::c_void;
use std::convert::TryFrom;
pub type uc_handle = *mut c_void;
use unicorn_engine::Unicorn;
use unicorn_engine::RegisterARM;

#[no_mangle]
pub extern "C" fn rust_ffi(handle: uc_handle) {
    if let Ok(mut unicorn) = Unicorn::try_from(handle) {
        assert_eq!(unicorn.reg_write(RegisterARM::R0, 1234), Ok(()));
    } else {
        panic!("Failed convert handle to Unicorn")
    }
}

I think this PR is only meaningful after #1511 is merged, otherwise the memory layout of uc_engine may be different between Rust and C.

@bet4it
Copy link
Contributor Author

bet4it commented Jan 22, 2022

@domenukk What do you think of it?

@domenukk
Copy link
Contributor

Makes sense. Although I'd call the fn from_uc_ptr or from_handle and it needs to be declared unsafe (as you can shoot yourself in the foot).

You can also consider exposing the handle so you can do the inverse, calling a c fn with uc handle from rust.

Plus maybe make the fn take a void ptr? Just a thought

@bet4it
Copy link
Contributor Author

bet4it commented Jan 23, 2022

Makes sense. Although I'd call the fn from_uc_ptr or from_handle and it needs to be declared unsafe (as you can shoot yourself in the foot).

I rewrite it with the TryFrom trait now. But I don't know how to declare unsafe on try_from😅

You can also consider exposing the handle so you can do the inverse, calling a c fn with uc handle from rust.

Done

Plus maybe make the fn take a void ptr? Just a thought

uc_handle and void ptr is totally the same thing:

pub type uc_handle = *mut c_void;

@wtdcode wtdcode merged commit 236848a into unicorn-engine:dev Feb 2, 2022
@bet4it bet4it deleted the rust_ffi branch February 3, 2022 01:20
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

Successfully merging this pull request may close these issues.

3 participants