Skip to content

rs: add DisasmBuffer api to reuse the cs_insn allocation further #186

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

jiegec
Copy link
Contributor

@jiegec jiegec commented Jul 24, 2025

Add DisasmBuffer struct to wrap cs_insn allocation. It calls cs_free when dropped.
Add disasm_iter_with_buffer, create_buffer and into_buffer functions to ease buffer reuse.
The other disasm* functions are not removed yet.

@jiegec jiegec requested a review from tmfink July 24, 2025 07:34
&'cs self,
code: &'buf [u8],
addr: u64,
buffer: DisasmBuffer<'cs>,
Copy link
Contributor Author

@jiegec jiegec Jul 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A possible alternative to this is to add another lifetime and use mutable reference to access DisasmBuffer: &mut DisasmBuffer. So into_buffer is no longer needed (but relying on dropping the iterator upon reuse). But the user must hold DisasmBuffer in a variable then. I am not sure which is better.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need to take a &mut DisasmBuffer here to ensure there is exclusive access and to allow reuse:

We want to make sure the following is prevented:

let buffer = ...;
let mut insn_iter1 = cs.disasm_iter_with_buffer(code1, addr1, &mut buffer);
// unsound since we are mutating buffer from different iterators
let mut insn_iter2 = cs.disasm_iter_with_buffer(code2, addr1, &mut buffer);
let insn1 = insn_iter1.next().unwrap();
let insn2 = insn_iter2.next().unwrap();
let insn3 = insn_iter1.next().unwrap();

While still allowing:

let buffer = ...;
for code in [code1, code2, code3] {
    let mut insn_iter = cs.disasm_iter_with_buffer(code2, addr1, &mut buffer);
    let insn = insn_iter.next().unwrap();
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated.

@jiegec jiegec force-pushed the disasm-buffer branch 4 times, most recently from 88b7813 to 91ab670 Compare July 25, 2025 02:47
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.

2 participants