
Shuu12121/CodeModernBERT-Owl-4.1
Fill-Mask
•
0.2B
•
Updated
•
102
code
stringlengths 40
729k
| docstring
stringlengths 22
46.3k
| func_name
stringlengths 1
97
| language
stringclasses 1
value | repo
stringlengths 6
48
| path
stringlengths 8
176
| url
stringlengths 47
228
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
pub fn validate_author(name: &str) -> anyhow::Result<()> {
let mut s = Scanner::new(name);
s.eat_until(|c| c == '<');
if s.eat_if('<') {
let contact = s.eat_until('>');
if let Some(handle) = contact.strip_prefix('@') {
validate_github_handle(handle).context("GitHub handle is invalid")?;
} else if contact.starts_with("http") {
validate_url(contact).context("URL is invalid")?;
} else {
let _addr: EmailAddress = contact.parse().context("email is invalid")?;
}
if !s.eat_if('>') {
bail!("expected '>'");
}
}
Ok(())
} | Validates the format of an author field. It can contain a name and, in angle
brackets, one of a URL, email or GitHub handle. | validate_author | rust | typst/packages | bundler/src/author.rs | https://github.com/typst/packages/blob/master/bundler/src/author.rs | Apache-2.0 |
fn is_legal_in_url(c: char) -> bool {
c.is_ascii_alphanumeric() || "-_.~:/?#[]@!$&'()*+,;=".contains(c)
} | Whether a character is legal in a URL. | is_legal_in_url | rust | typst/packages | bundler/src/author.rs | https://github.com/typst/packages/blob/master/bundler/src/author.rs | Apache-2.0 |
pub fn validate_category(category: &str) -> anyhow::Result<()> {
match category {
// Functional categories.
"components" => {}
"visualization" => {}
"model" => {}
"layout" => {}
"text" => {}
"languages" => {}
"scripting" => {}
"integration" => {}
"utility" => {}
"fun" => {}
// Publication categories.
"book" => {}
"report" => {}
"paper" => {}
"thesis" => {}
"poster" => {}
"flyer" => {}
"presentation" => {}
"cv" => {}
"office" => {}
_ => anyhow::bail!("unknown category"),
}
Ok(())
} | Validate that this is a Typst universe category. | validate_category | rust | typst/packages | bundler/src/categories.rs | https://github.com/typst/packages/blob/master/bundler/src/categories.rs | Apache-2.0 |
pub fn validate_discipline(discipline: &str) -> anyhow::Result<()> {
match discipline {
"agriculture" => {}
"anthropology" => {}
"archaeology" => {}
"architecture" => {}
"biology" => {}
"business" => {}
"chemistry" => {}
"communication" => {}
"computer-science" => {}
"design" => {}
"drawing" => {}
"economics" => {}
"education" => {}
"engineering" => {}
"environment" => {}
"fashion" => {}
"film" => {}
"geography" => {}
"geology" => {}
"history" => {}
"journalism" => {}
"law" => {}
"linguistics" => {}
"literature" => {}
"mathematics" => {}
"medicine" => {}
"music" => {}
"painting" => {}
"philosophy" => {}
"photography" => {}
"physics" => {}
"politics" => {}
"psychology" => {}
"sociology" => {}
"theater" => {}
"theology" => {}
"transportation" => {}
_ => anyhow::bail!("unknown discipline"),
}
Ok(())
} | Validate that this is a Typst universe discipline. | validate_discipline | rust | typst/packages | bundler/src/disciplines.rs | https://github.com/typst/packages/blob/master/bundler/src/disciplines.rs | Apache-2.0 |
fn parse_manifest(path: &Path, namespace: &str) -> anyhow::Result<PackageManifest> {
let src = fs::read_to_string(path.join("typst.toml"))?;
let manifest: PackageManifest = toml::from_str(&src)?;
let expected = format!(
"packages/{namespace}/{}/{}",
manifest.package.name, manifest.package.version
);
validate_no_unknown_fields(&manifest.unknown_fields, None)?;
validate_no_unknown_fields(&manifest.package.unknown_fields, Some("package"))?;
if path != Path::new(&expected) {
bail!("package directory name and manifest are mismatched");
}
if !is_ident(&manifest.package.name) {
bail!("package name is not a valid identifier");
}
for author in &manifest.package.authors {
validate_author(author).context("error while checking author name")?;
}
if manifest.package.description.is_none() {
bail!("package description is missing");
}
if manifest.package.categories.len() > 3 {
bail!("package can have at most 3 categories");
}
for category in &manifest.package.categories {
validate_category(category)?;
}
for discipline in &manifest.package.disciplines {
validate_discipline(discipline)?;
}
let Some(license) = &manifest.package.license else {
bail!("package license is missing");
};
let license =
spdx::Expression::parse(license).context("failed to parse SPDX license expression")?;
for requirement in license.requirements() {
let id = requirement
.req
.license
.id()
.context("license must not contain a referencer")?;
if !id.is_osi_approved() && !is_allowed_cc(id) {
bail!(
"license is neither OSI approved nor an allowed CC license: {}",
id.full_name
);
}
}
let entrypoint = path.join(manifest.package.entrypoint.as_str());
validate_typst_file(&entrypoint, "package entrypoint")?;
if let Some(template) = &manifest.template {
validate_no_unknown_fields(&template.unknown_fields, Some("template"))?;
if manifest.package.categories.is_empty() {
bail!("template packages must have at least one category");
}
let entrypoint = path
.join(template.path.as_str())
.join(template.entrypoint.as_str());
validate_typst_file(&entrypoint, "template entrypoint")?;
}
Ok(manifest)
} | Read and validate the package's manifest. | parse_manifest | rust | typst/packages | bundler/src/main.rs | https://github.com/typst/packages/blob/master/bundler/src/main.rs | Apache-2.0 |
fn read_readme(dir_path: &Path) -> anyhow::Result<String> {
fs::read_to_string(dir_path.join("README.md")).context("failed to read README.md")
} | Return the README file as a string. | read_readme | rust | typst/packages | bundler/src/main.rs | https://github.com/typst/packages/blob/master/bundler/src/main.rs | Apache-2.0 |
fn validate_archive(buf: &[u8]) -> anyhow::Result<()> {
let decompressed = flate2::read::GzDecoder::new(io::Cursor::new(&buf));
let mut tar = tar::Archive::new(decompressed);
for entry in tar.entries()? {
let _ = entry?;
}
Ok(())
} | Ensures that the archive can be decompressed and read. | validate_archive | rust | typst/packages | bundler/src/main.rs | https://github.com/typst/packages/blob/master/bundler/src/main.rs | Apache-2.0 |
fn write_archive(info: &PackageInfo, buf: &[u8], namespace_dir: &Path) -> anyhow::Result<()> {
let path = namespace_dir.join(format!("{}-{}.tar.gz", info.name, info.version));
fs::write(path, buf)?;
Ok(())
} | Write a compressed archive to the output directory. | write_archive | rust | typst/packages | bundler/src/main.rs | https://github.com/typst/packages/blob/master/bundler/src/main.rs | Apache-2.0 |
fn process_thumbnail(
path: &Path,
manifest: &PackageManifest,
template: &TemplateInfo,
namespace_dir: &Path,
) -> anyhow::Result<()> {
let original_path = path.join(template.thumbnail.as_str());
let thumb_dir = namespace_dir.join(THUMBS_DIR);
let filename = format!("{}-{}", manifest.package.name, manifest.package.version);
let hopefully_max_encoded_size = 1024 * 1024;
let extension = original_path
.extension()
.context("thumbnail has no extension")?
.to_ascii_lowercase();
if extension != "png" && extension != "webp" {
bail!("thumbnail must be a PNG or WebP image");
}
// Get file size.
let file_size = fs::metadata(&original_path)?.len() as usize;
if file_size > 3 * 1024 * 1024 {
bail!("thumbnail must be smaller than 3MB");
}
let mut image = image::open(&original_path)?;
// Ensure that the image has at least a certain minimum size.
let longest_edge = image.width().max(image.height());
if longest_edge < 1080 {
bail!("each thumbnail's longest edge must be at least 1080px long");
}
// We produce a full-size and a miniature thumbnail.
let thumbnail_path = thumb_dir.join(format!("{filename}.webp"));
let miniature_path = thumb_dir.join(format!("{filename}-small.webp"));
// Choose a fast filter for the miniature.
let miniature = image.resize(400, 400, FilterType::CatmullRom);
let miniature_buf = encode_webp(&miniature, 85)?;
fs::write(miniature_path, miniature_buf)?;
// Thumbnails that are WebP already and in the budget should be copied as-is.
if extension == "webp" && file_size < hopefully_max_encoded_size {
fs::copy(&original_path, thumbnail_path)?;
return Ok(());
}
// Try to encode as WebP without resizing. If that fits into the budget,
// we're done.
let mut quality = 98;
let buf = encode_webp(&image, quality)?;
if buf.len() < hopefully_max_encoded_size {
fs::write(&thumbnail_path, buf)?;
}
// We're still too big. Fix it.
if longest_edge <= 1920 {
// Resizing doesn't help. Reduce quality instead.
quality = 70;
} else {
image = image.resize(1920, 1920, FilterType::Lanczos3);
}
let buf = encode_webp(&image, quality)?;
fs::write(&thumbnail_path, buf)?;
Ok(())
} | Process the thumbnail image for a package and write it to the `dist`
directory in large and small version. | process_thumbnail | rust | typst/packages | bundler/src/main.rs | https://github.com/typst/packages/blob/master/bundler/src/main.rs | Apache-2.0 |
fn validate_typst_file(path: &Path, name: &str) -> anyhow::Result<()> {
if !path.exists() {
bail!("{name} is missing");
}
if path.extension().is_none_or(|ext| ext != "typ") {
bail!("{name} must have a .typ extension");
}
fs::read_to_string(path).context("failed to read {name} file")?;
Ok(())
} | Check that a Typst file exists, its name ends in `.typ`, and that it is valid
UTF-8. | validate_typst_file | rust | typst/packages | bundler/src/main.rs | https://github.com/typst/packages/blob/master/bundler/src/main.rs | Apache-2.0 |
fn is_ident(string: &str) -> bool {
let mut chars = string.chars();
chars
.next()
.is_some_and(|c| is_id_start(c) && chars.all(is_id_continue))
} | Whether a string is a valid Typst identifier. | is_ident | rust | typst/packages | bundler/src/main.rs | https://github.com/typst/packages/blob/master/bundler/src/main.rs | Apache-2.0 |
fn is_id_start(c: char) -> bool {
is_xid_start(c) || c == '_'
} | Whether a character can start an identifier. | is_id_start | rust | typst/packages | bundler/src/main.rs | https://github.com/typst/packages/blob/master/bundler/src/main.rs | Apache-2.0 |
fn is_id_continue(c: char) -> bool {
is_xid_continue(c) || c == '_' || c == '-'
} | Whether a character can continue an identifier. | is_id_continue | rust | typst/packages | bundler/src/main.rs | https://github.com/typst/packages/blob/master/bundler/src/main.rs | Apache-2.0 |
pub fn new(r2api: &mut R2Api, btor: Solver, blank: bool) -> Memory {
let segments = r2api.get_segments().unwrap();
let mut segs = Vec::with_capacity(64);
for seg in segments {
segs.push(MemorySegment {
name: seg.name,
addr: seg.vaddr,
size: seg.size,
read: seg.perm.contains('r'),
write: seg.perm.contains('w'),
exec: seg.perm.contains('x'),
init: true,
});
}
let endian = r2api.info.bin.endian.as_str();
let bin = &r2api.info.bin;
let bits = if bin.arch == "arm" && bin.bits == 16 {
32 // says "16" for 32 bit arm cuz thumb
} else {
bin.bits
};
//let heap_canary = Value::Symbolic(
// btor.bv("heap_canary", HEAP_CANARY_SIZE as u32), 0);
Memory {
solver: btor,
r2api: r2api.clone(),
mem: BTreeMap::new(),
heap: Heap::new(HEAP_START, HEAP_SIZE),
//heap_canary,
bits,
endian: Endian::from_string(endian),
segs,
blank,
}
} | Create a new Memory struct to hold memory values for symbolic execution | new | rust | aemmitt-ns/radius2 | radius/src/memory.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/memory.rs | MIT |
pub fn alloc(&mut self, length: &Value) -> u64 {
let len = length.as_u64().unwrap();
// aligning makes some runs take much longer wtaf
let len = len + if len % ALIGN != 0 { ALIGN - len % ALIGN } else { 0 };
let addr = self.heap.alloc(len);
//let canary = self.heap_canary.clone();
//self.write_value(addr, &canary, HEAP_CANARY_SIZE as usize);
addr
} | Allocate memory `length` bytes long. Returns the address of the allocation. | alloc | rust | aemmitt-ns/radius2 | radius/src/memory.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/memory.rs | MIT |
pub fn read_value(&mut self, addr: u64, length: usize) -> Value {
if length <= 32 {
let mut data: [Value; 32] = Default::default();
self.read(addr, length, &mut data[..length]);
self.pack(&data[..length])
} else {
let mut data = vec![Value::Concrete(0, 0); length];
self.read(addr, length, &mut data);
self.pack(&data)
}
} | read a Value of `length` bytes from memory at `addr` | read_value | rust | aemmitt-ns/radius2 | radius/src/memory.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/memory.rs | MIT |
pub fn write_value(&mut self, addr: u64, value: &Value, length: usize) {
if length <= 32 {
let mut data: [Value; 32] = Default::default();
self.unpack(value, length, &mut data[..length]);
self.write(addr, &mut data[..length])
} else {
let mut data = vec![Value::Concrete(0, 0); length];
self.unpack(value, length, &mut data);
self.write(addr, &mut data)
}
} | write a Value of `length` bytes to memory at `addr` | write_value | rust | aemmitt-ns/radius2 | radius/src/memory.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/memory.rs | MIT |
pub fn read(&mut self, addr: u64, length: usize, data: &mut [Value]) {
if length == 0 || data.len() == 0 {
return;
}
let make_sym = self.blank && !self.check_permission(addr, length as u64, 'i');
let size = READ_CACHE as u64;
let mask = -1i64 as u64 ^ (size - 1);
let not_mask = size - 1;
let chunks = (((addr & not_mask) + length as u64) / size) + 1;
let mut index = 0;
for count in 0..chunks {
let caddr = (addr & mask) + size * count;
let mut offset = (addr & not_mask) * (count == 0) as u64;
let mem = if let Some(m) = self.mem.get(&caddr) {
m
} else if make_sym {
let mut vals = Vec::with_capacity(READ_CACHE);
for i in 0..size {
let sym_name = format!("mem_{:08x}", caddr + i);
vals.push(Value::Symbolic(self.solver.bv(&sym_name, 8), 0));
}
self.mem.entry(caddr).or_insert(vals)
} else {
let bytes = self.r2api.read(caddr, READ_CACHE).unwrap();
// println!("{:x} {:?}", caddr, bytes);
let vals = bytes
.iter()
.map(|b| Value::Concrete(*b as u64, 0))
.collect();
self.mem.entry(caddr).or_insert(vals)
};
while index < length && offset < size && data.len() > index {
data[index] = mem[offset as usize].to_owned();
index += 1;
offset += 1;
}
}
} | read `length` bytes from memory at `addr` into `data` | read | rust | aemmitt-ns/radius2 | radius/src/memory.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/memory.rs | MIT |
pub fn write(&mut self, addr: u64, data: &mut [Value]) {
let length = data.len();
let size = READ_CACHE as u64;
let mask = -1i64 as u64 ^ (size - 1);
let not_mask = size - 1;
let chunks = (((addr & not_mask) + length as u64) / size) + 1;
let mut index = 0;
for count in 0..chunks {
let caddr = (addr & mask) + size * count;
let mut offset = (addr & not_mask) * (count == 0) as u64;
let mem = if let Some(m) = self.mem.get_mut(&caddr) {
m
} else {
let mut newmem = vec![Value::Concrete(0, 0); READ_CACHE];
// dont read if we are writing all
if addr % size != 0 || length % READ_CACHE != 0 {
self.read(caddr, READ_CACHE, &mut newmem);
}
self.mem.entry(caddr).or_insert(newmem)
};
while index < length && offset < size {
mem[offset as usize] = mem::take(&mut data[index]);
index += 1;
offset += 1;
}
}
} | write `length` bytes to memory at `addr` from `data` | write | rust | aemmitt-ns/radius2 | radius/src/memory.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/memory.rs | MIT |
pub fn pack(&self, data: &[Value]) -> Value {
let new_data = data;
let length = new_data.len();
let mut taint = 0;
if self.endian == Endian::Big {
let mut new_data = data.to_owned();
new_data.reverse();
}
// if length > 64 bits use sym to cheat
if length > 8 || new_data.iter().any(|x| x.is_symbolic()) {
// this value isn't used, idk
let mut sym_val = self.solver.bvv(0, 1);
for count in 0..length {
let datum = new_data.get(count).unwrap();
match &datum {
Value::Symbolic(val, t) => {
//let trans_val = self.solver.translate(val).unwrap();
if sym_val.get_width() == 1 {
sym_val = val.slice(7, 0);
} else {
sym_val = val.slice(7, 0).concat(&sym_val);
}
taint |= t;
}
Value::Concrete(val, t) => {
let new_val = self.solver.bvv(*val, 8);
if sym_val.get_width() == 1 {
sym_val = new_val;
} else {
sym_val = new_val.concat(&sym_val);
}
taint |= t;
}
}
}
Value::Symbolic(sym_val, taint)
} else {
let mut con_val: u64 = 0;
for (count, datum) in new_data.iter().enumerate() {
if let Value::Concrete(val, t) = datum {
con_val += val << (8 * count);
taint |= t;
}
}
Value::Concrete(con_val, taint)
}
} | Pack the bytes in `data` into a Value according to the endianness of the target | pack | rust | aemmitt-ns/radius2 | radius/src/memory.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/memory.rs | MIT |
pub fn unpack(&self, value: &Value, length: usize, data: &mut [Value]) {
//let mut data: Vec<Value> = Vec::with_capacity(length);
if length == 0 {
return;
}
match value {
Value::Concrete(val, t) => {
for count in 0..length {
// TODO fix this for >64 bit length
data[count] = Value::Concrete((val.wrapping_shr(8 * count as u32)) & 0xff, *t);
}
}
Value::Symbolic(val, t) => {
for count in 0..length {
//let trans_val = self.solver.translate(&val).unwrap();
let bv = val.slice(((count as u32) + 1) * 8 - 1, (count as u32) * 8);
data[count] = Value::Symbolic(bv, *t);
}
}
}
if self.endian == Endian::Big {
data.reverse();
}
//data
} | Unpack the Value into `length` bytes and store them in the `data` ref | unpack | rust | aemmitt-ns/radius2 | radius/src/memory.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/memory.rs | MIT |
pub fn print_instr(&self, state: &mut State, instr: &Instruction) {
if let Some(sim) = self.sims.get(&instr.offset) {
println!(
"\n0x{:08x} ( {} {} )\n",
instr.offset,
"simulated", sim.symbol.blue()
);
} else if !self.color {
println!(
"0x{:08x} {:<40} | {}",
instr.offset, instr.disasm, instr.esil
);
} else {
print!(
"{}",
state
.r2api
.cmd(&format!("pd 1 @ {}", instr.offset))
.unwrap()
);
}
} | print instruction if debug output is enabled | print_instr | rust | aemmitt-ns/radius2 | radius/src/processor.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/processor.rs | MIT |
pub fn optimize(&mut self, state: &mut State, prev_pc: u64, curr_instr: &InstructionEntry) {
let prev_instr = &self.instructions[&prev_pc];
if !prev_instr
.tokens
.contains(&Word::Operator(Operations::WeakEqual))
|| !curr_instr
.tokens
.contains(&Word::Operator(Operations::WeakEqual))
{
return;
}
let mut regs_read: Vec<usize> = Vec::with_capacity(16);
let mut regs_written: Vec<usize> = Vec::with_capacity(16);
let len = curr_instr.tokens.len();
for (i, word) in curr_instr.tokens.iter().enumerate() {
if let Word::Register(index) = word {
if i + 1 < len {
let next = &curr_instr.tokens[i + 1];
if let Word::Operator(op) = next {
match op {
Operations::WeakEqual | Operations::Equal => {
regs_written.push(*index);
}
_ => regs_read.push(*index),
}
} else {
regs_read.push(*index);
}
}
}
}
let mut remove: Vec<usize> = Vec::with_capacity(32);
for (i, word) in prev_instr.tokens.iter().enumerate() {
if let Word::Operator(op) = word {
if let Operations::NoOperation = op {
remove.push(i); // remove nops
} else if let Operations::WeakEqual = op {
let reg = &prev_instr.tokens[i - 1];
if let Word::Register(index) = reg {
if !regs_read.iter().any(|r| state.registers.is_sub(*r, *index))
&& regs_written
.iter()
.any(|r| state.registers.is_sub(*r, *index))
{
let val = &prev_instr.tokens[i - 2];
if let Word::Operator(op) = val {
match op {
Operations::Zero => remove.extend(vec![i - 2, i - 1, i]),
Operations::Carry => {
remove.extend(vec![i - 3, i - 2, i - 1, i])
}
Operations::Borrow => {
remove.extend(vec![i - 3, i - 2, i - 1, i])
}
Operations::Parity => remove.extend(vec![i - 2, i - 1, i]),
Operations::Overflow => {
remove.extend(vec![i - 3, i - 2, i - 1, i])
}
Operations::S => remove.extend(vec![i - 3, i - 2, i - 1, i]),
_ => {}
}
}
}
}
}
}
}
if !remove.is_empty() {
let mut mut_prev_instr = prev_instr.to_owned();
let mut new_tokens: Vec<Word> = Vec::with_capacity(128);
for (i, word) in prev_instr.tokens.iter().enumerate() {
if !remove.contains(&i) {
new_tokens.push(word.to_owned());
}
}
mut_prev_instr.tokens = new_tokens;
self.instructions.insert(prev_pc, mut_prev_instr);
}
} | removes words that weak set flag values that are never read, and words that are NOPs
really need to refactor this mess but every time i try it gets slower | optimize | rust | aemmitt-ns/radius2 | radius/src/processor.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/processor.rs | MIT |
pub fn step(&mut self, state: &mut State) -> Vec<State> {
self.steps += 1;
state.visit();
let pc_allocs = 32;
let pc_value = state.registers.get_pc();
if let Some(pc_val) = pc_value.as_u64() {
self.execute_instruction(state, pc_val);
} else {
panic!("got an unexpected sym PC: {:?}", pc_value);
}
let new_pc = state.registers.get_pc();
if self.force && !state.esil.pcs.is_empty() {
// we just use the pcs in state.esil.pcs
} else if let Some(pc) = new_pc.as_u64() {
state.esil.pcs.clear();
state.esil.pcs.push(pc);
} else {
let pc_val = new_pc.as_bv().unwrap();
if self.debug {
println!("\n{} : {:?}\n", "symbolic PC".red(), pc_val);
}
if DO_EVENT_HOOKS && state.has_event_hooks {
state.do_hooked(
&Event::SymbolicExec(EventTrigger::Before),
&EventContext::ExecContext(new_pc.clone(), vec![]),
);
}
if !self.lazy && !state.esil.pcs.is_empty() {
// testing sat without modelgen is a bit faster than evaluating
state.esil.pcs = state
.esil
.pcs
.clone()
.into_iter()
.filter(|x| state.check(&new_pc.eq(&vc(*x))))
.collect();
} else if state.esil.pcs.is_empty() {
let bps = self.breakpoints.clone();
state.esil.pcs = bps.into_iter()
.filter(|bp| state.check(&new_pc.eq(&vc(*bp))))
.collect();
if state.esil.pcs.is_empty() {
state.esil.pcs = state.evaluate_many(&pc_val);
}
}
if DO_EVENT_HOOKS && state.has_event_hooks {
state.do_hooked(
&Event::SymbolicExec(EventTrigger::After),
&EventContext::ExecContext(new_pc.clone(), state.esil.pcs.clone()),
);
}
}
if state.esil.pcs.len() > 1 || new_pc.as_u64().is_none() {
let mut states: Vec<State> = Vec::with_capacity(pc_allocs);
// this function is kind of a mess this should be refactored
if state.esil.pcs.is_empty() && new_pc.as_u64().is_none() {
state.set_inactive();
return states;
}
let last = state.esil.pcs.len() - 1;
for new_pc_val in &state.esil.pcs[..last] {
let mut new_state = state.clone();
if let Some(pc_val) = new_pc.as_bv() {
let a = pc_val._eq(&new_state.bvv(*new_pc_val, pc_val.get_width()));
new_state.solver.assert_bv(&a);
}
new_state.registers.set_pc(Value::Concrete(*new_pc_val, 0));
states.push(new_state);
}
let new_pc_val = state.esil.pcs[last];
if let Some(pc_val) = new_pc.as_bv() {
let pc_bv = pc_val;
let a = pc_bv._eq(&state.bvv(new_pc_val, pc_bv.get_width()));
state.solver.assert_bv(&a);
}
state.registers.set_pc(Value::Concrete(new_pc_val, 0));
states
} else if self.selfmodify {
let mut states: Vec<State> = Vec::with_capacity(pc_allocs);
// this is bad, 8 bytes is not enough, but this is what it is for now
let mem = state.memory_read_value(&new_pc, 8);
if let Value::Symbolic(bv, _t) = &mem {
let possible = state.evaluate_many(bv);
if !possible.is_empty() {
let last = possible.len() - 1;
for pos in &possible[..last] {
let mut new_state = state.clone();
new_state.assert(&mem.eq(&vc(*pos)));
states.push(new_state);
}
state.assert(&mem.eq(&vc(possible[last])));
}
}
states
} else {
vec![]
}
} | Take single step with the state provided | step | rust | aemmitt-ns/radius2 | radius/src/processor.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/processor.rs | MIT |
pub fn run(&mut self, state: State, mode: RunMode) -> Vec<State> {
// use binary heap as priority queue to prioritize states
// that have the lowest number of visits for the current PC
let mut states = BinaryHeap::new();
let mut results = vec![];
states.push(Rc::new(state));
// run until empty for single, until split for parallel
// or until every state is at the breakpoint for multiple
let split = mode == RunMode::Parallel;
let step = mode == RunMode::Step;
loop {
//println!("{} states", states.len());
if states.is_empty() {
if self.merges.is_empty() {
return results;
} else {
// pop one out of mergers
// let key = *self.merges.keys().next().unwrap();
// let mut merge = self.merges.remove(&key).unwrap();
let (_k, mut merge) = self.merges.pop_first().unwrap();
merge.status = StateStatus::PostMerge;
states.push(Rc::new(merge));
}
}
let mut current_rc = states.pop().unwrap();
let current_state = Rc::make_mut(&mut current_rc);
match current_state.status {
StateStatus::Active | StateStatus::PostMerge => {
let new_states = self.step(current_state);
// ugly but prevents lots of wasted effort, needs serious refactor
if current_state.status == StateStatus::Break && current_state.is_sat() {
if mode != RunMode::Multiple {
results.push(current_state.to_owned());
return results;
}
}
for mut state in new_states {
if state.status == StateStatus::Break && state.is_sat() {
if mode != RunMode::Multiple {
results.push(state.to_owned());
return results;
}
}
states.push(Rc::new(state));
}
states.push(current_rc);
}
StateStatus::Merge => {
self.merge(current_state.to_owned());
}
StateStatus::Break => {
if current_state.is_sat() {
results.push(current_state.to_owned());
if mode != RunMode::Multiple {
return results;
}
}
}
StateStatus::Crash(_addr, _len) => {
self.crashes.push(current_state.to_owned());
}
_ => {}
}
// single step mode always returns states
if step || (split && states.len() > 1) {
while let Some(mut state) = states.pop() {
results.push(Rc::make_mut(&mut state).to_owned());
}
return results;
}
}
} | run the state until completion based on mode | run | rust | aemmitt-ns/radius2 | radius/src/processor.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/processor.rs | MIT |
pub fn new<T: AsRef<str>>(filename: T) -> Self {
// no radius options and no r2 errors by default
Radius::new_with_options(Some(filename), &[])
} | Create a new Radius instance for the provided binary
## Arguments
* `filename` - path to the target binary
## Example
```
use radius2::radius::Radius;
let mut radius = Radius::new("/bin/sh");
``` | new | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn new_with_options<T: AsRef<str>>(filename: Option<T>, options: &[RadiusOption]) -> Self {
let mut argv = vec!["-2"];
let mut eval_max = 256;
let mut paths = vec![];
for o in options {
if let RadiusOption::R2Argument(arg) = o {
argv.push(*arg);
} else if let RadiusOption::EvalMax(m) = o {
eval_max = *m;
} else if let RadiusOption::LibPath(p) = o {
paths.push(p.to_owned());
}
}
let debug = options.contains(&RadiusOption::Debug(true));
let color = options.contains(&RadiusOption::ColorOutput(true));
let use_sims = !options.contains(&RadiusOption::Sims(false));
if !options.contains(&RadiusOption::LoadPlugins(true)) {
argv.push("-NN");
}
if debug && color {
// pretty print disasm + esil
argv.push("-e scr.color=3");
//argv.push("-e asm.cmt.esil=true");
argv.push("-e asm.lines=false");
argv.push("-e asm.emu=false");
argv.push("-e asm.xrefs=false");
argv.push("-e asm.functions=false");
}
let args = if !argv.is_empty() || filename.is_none() {
Some(argv)
} else {
None
};
let mut r2api = R2Api::new(filename, args);
r2api.set_option("io.cache", "true").unwrap();
// r2api.cmd("eco darkda").unwrap(); // i like darkda
let arch = &r2api.info.bin.arch;
// don't optimize dalvik & arm
let opt = !options.contains(&RadiusOption::Optimize(false))
&& arch.as_str() != "arm"
&& arch.as_str() != "dalvik";
let lazy = !options.contains(&RadiusOption::Lazy(false));
let force = options.contains(&RadiusOption::Force(true));
let topo = options.contains(&RadiusOption::Topological(true));
let check = options.contains(&RadiusOption::Permissions(true));
let sim_all = options.contains(&RadiusOption::SimAll(true));
let selfmod = options.contains(&RadiusOption::SelfModify(true));
let strict = options.contains(&RadiusOption::Strict(true));
let automerge = options.contains(&RadiusOption::AutoMerge(true));
let mut processor = Processor::new(selfmod, opt, debug, lazy, force, topo, automerge, color);
let processors = Arc::new(Mutex::new(vec![]));
if !options.contains(&RadiusOption::Syscalls(false)) {
let syscalls = r2api.get_syscalls().unwrap();
if let Some(sys) = syscalls.get(0) {
processor.traps.insert(sys.swi, indirect);
}
for sys in &syscalls {
processor.syscalls.insert(sys.num, sys.to_owned());
}
}
let _libs = if options.contains(&RadiusOption::LoadLibs(true)) {
r2api.load_libraries(&paths).unwrap()
} else {
vec![]
};
// this is weird, idk
if use_sims {
Radius::register_sims(&mut r2api, &mut processor, sim_all);
}
Radius {
r2api,
processor,
processors,
eval_max,
check,
debug,
strict,
}
} | Create a new Radius instance for the provided binary with a vec of `RadiusOption`
## Arguments
* `filename` - path to the target binary
* `options` - array of options to configure radius2
## Example
```
use radius2::radius::{Radius, RadiusOption};
let options = [RadiusOption::Optimize(false), RadiusOption::Sims(false)];
let mut radius = Radius::new_with_options(Some("/bin/sh"), &options);
``` | new_with_options | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn call_state(&mut self, addr: u64) -> State {
self.r2api.seek(addr);
self.r2api.init_vm();
let mut state = self.init_state();
state.memory.add_stack();
state.memory.add_heap();
state.memory.add_std_streams();
state
} | Initialized state at the provided function address with an initialized stack
(if applicable)
## Arguments
* `addr` - the address of the function
## Example
```
use radius2::radius::Radius;
let mut radius = Radius::new("/bin/sh");
let mut state = radius.call_state(0x004006fd);
``` | call_state | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn callsym_state<T: AsRef<str>>(&mut self, sym: T) -> State {
let addr = self.get_address(sym).unwrap_or_default();
self.call_state(addr)
} | Initialized state at the provided function name with an initialized stack
equivalent to `call_state(get_address(sym))`
## Arguments
* `sym` - the name of the function
## Example
```
use radius2::Radius;
let mut radius = Radius::new("/bin/sh");
let mut state = radius.callsym_state("printf");
``` | callsym_state | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn debug_state(&mut self, addr: u64, args: &[String]) -> State {
// set cache to false to set breakpoint
self.r2api.set_option("io.cache", "false").unwrap();
self.r2api.init_debug(addr, args);
self.init_state()
} | Initialize state from a debugger breakpoint
the program will block until bp is hit | debug_state | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn frida_state(&mut self, addr: u64) -> State {
self.r2api.seek(addr);
let mut state = self.init_state();
self.processor.fetch_instruction(&mut state, addr); // cache real instrs
let context = self.r2api.init_frida(addr).unwrap();
for reg in context.keys() {
if state.registers.regs.contains_key(reg) {
state.registers.set(reg, vc(context[reg]));
}
}
state
} | Initialize state from a frida hook
the program will block until the hook is hit | frida_state | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn entry_state(&mut self) -> State {
// get the entrypoint
let entrypoints = self.r2api.get_entrypoints().unwrap_or_default();
if !entrypoints.is_empty() {
self.r2api.seek(entrypoints[0].vaddr);
}
self.r2api.init_vm();
let mut state = self.init_state();
state.memory.add_stack();
state.memory.add_heap();
state.memory.add_std_streams();
let start_main_reloc = self.r2api.get_address("reloc.__libc_start_main").unwrap_or(0);
if start_main_reloc != 0 {
self.r2api.cmd("af").unwrap(); // analyze entrypoint
let callers = self.r2api.get_references(start_main_reloc).unwrap_or_default();
if !callers.is_empty() {
self.hook(callers[0].from, __libc_start_main);
}
}
state
} | Initialized state at the program entry point (the first if multiple).
## Example
```
use radius2::Radius;
let mut radius = Radius::new("/bin/sh");
let mut state = radius.entry_state();
``` | entry_state | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn set_argv_env(&mut self, state: &mut State, args: &[Value], env: &[Value]) {
// we write args to both regs and stack
// i think this is ok
let sp = state.registers.get_with_alias("SP");
let ptrlen = (state.memory.bits / 8) as usize;
let argc = Value::Concrete(args.len() as u64, 0);
state.memory_write_value(&sp, &argc, ptrlen);
state.registers.set_with_alias("A0", argc);
let types = ["argv", "env"];
let mut current = sp + Value::Concrete(ptrlen as u64, 0);
for (i, strings) in [args, env].iter().enumerate() {
state
.context
.insert(types[i].to_owned(), vec![current.clone()]);
let alias = format!("A{}", i + 1);
state.registers.set_with_alias(&alias, current.clone());
for string in strings.iter() {
let addr = state
.memory
.alloc(&Value::Concrete((string.size() / 8) as u64 + 1, 0));
state.memory_write_value(
&Value::Concrete(addr, 0),
string,
string.size() as usize / 8,
);
state.memory.write_value(
addr + (string.size() / 8) as u64,
&Value::Concrete(0, 0),
1,
);
state.memory_write_value(¤t, &Value::Concrete(addr, 0), ptrlen);
current = current + Value::Concrete(ptrlen as u64, 0);
}
state.memory_write_value(¤t, &Value::Concrete(0, 0), ptrlen);
current = current + Value::Concrete(ptrlen as u64, 0);
}
} | Set argv and env with arrays of values | set_argv_env | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn blank_state(&mut self) -> State {
State::new(
&mut self.r2api,
self.eval_max,
self.debug,
true,
self.check,
self.strict,
)
} | A "blank" state with uninitialized values set to be symbolic | blank_state | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn blank_call_state(&mut self, addr: u64) -> State {
self.r2api.seek(addr);
self.r2api.init_vm();
let mut state = self.blank_state();
let sp = self.r2api.get_register_value("SP").unwrap();
state
.registers
.set_with_alias("PC", Value::Concrete(addr, 0));
state.registers.set_with_alias("SP", Value::Concrete(sp, 0));
state.memory.add_stack();
state.memory.add_heap();
state.memory.add_std_streams();
state
} | A blank state except for PC and SP | blank_call_state | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn hook(&mut self, addr: u64, hook_callback: HookMethod) {
self.processor
.hooks
.entry(addr)
.or_insert(vec![])
.push(hook_callback);
} | Hook an address with a callback that is passed the `State`.
The return value of the callback specifies whether the hooked instruction should be executed or skipped
## Arguments
* `addr` - the address to hook
* `hook_callback` - the function to call once the address is reached
## Example
```
use radius2::{Radius, State, vc};
let mut radius = Radius::new("/bin/sh");
fn callback(state: &mut State) -> bool {
state.registers.set("rax", vc(0x1337));
true // do not skip instruction
}
radius.hook(0x400cb0, callback);
``` | hook | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn esil_hook(&mut self, addr: u64, esil: &str) {
self.processor
.esil_hooks
.entry(addr)
.or_insert(vec![])
.push(esil.to_owned());
} | Hook an address with an esil expression. The instruction
at the address is skipped if the last value on the stack is nonzero
## Arguments
* `addr` - the address to hook
* `esil` - the ESIL expression to evaluate | esil_hook | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn hook_symbol(&mut self, sym: &str, hook_callback: HookMethod) {
let addr = self.get_address(sym).unwrap();
self.hook(addr, hook_callback);
} | Hook a symbol with a callback that is passed each state that reaches it | hook_symbol | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn trap(&mut self, trap_num: u64, sim: SimMethod) {
self.processor.traps.insert(trap_num, sim);
} | Register a trap to call the provided `SimMethod` | trap | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn simulate(&mut self, addr: u64, sim: Sim) {
self.processor.sims.insert(addr, sim);
} | Register a `SimMethod` for the provided function address
## Arguments
* `addr` - address of the function to simulate (usually the PLT address)
* `sim` - Sim struct containing the function name, implementation, and arg count
## Example
```
use radius2::{Radius, State, Sim, Value, vc};
let mut radius = Radius::new("/bin/sh");
let scanf = radius.get_address("__isoc99_scanf").unwrap();
fn scanf_sim(state: &mut State, args: &[Value]) -> Value {
state.memory_write_value(&args[1], &vc(42), 8);
vc(1)
}
radius.simulate(scanf, Sim{
symbol: "scanf".to_owned(),
function: scanf_sim,
arguments: 2
});
``` | simulate | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn assign_sim(&mut self, addr: u64, name: &str) {
// TODO: get_sims should return a HashMap idk why it doesnt
get_sims()
.into_iter()
.find(|s| s.symbol == name)
.map(|s| self.simulate(addr, s));
} | assign an existing sim to an address (for static binaries) | assign_sim | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn avoid(&mut self, addrs: &[u64]) {
for addr in addrs {
self.processor.avoidpoints.insert(*addr);
}
} | Add addresses that will be avoided during execution. Any
`State` that reaches these addresses will be marked inactive
## Arguments
* `addrs` - slice of addresses to avoid during execution | avoid | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn get_steps(&self) -> u64 {
self.processor.steps
+ self
.processors
.lock()
.unwrap()
.iter()
.map(|p| p.steps)
.sum::<u64>()
} | Get total number of steps from all processors | get_steps | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn call_function(&mut self, sym: &str, state: State, args: Vec<Value>) -> Option<State> {
let addr = self.r2api.get_address(sym).unwrap_or_default();
self.call_address(addr, state, args)
} | Execute function and return the resulting state | call_function | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn call_address(&mut self, addr: u64, mut state: State, args: Vec<Value>) -> Option<State> {
state.set_args(args);
state.registers.set_pc(vc(addr));
let mut states = self.run_all(state);
let count = states.len();
if !states.is_empty() {
let mut end = states.remove(0);
for _ in 1..count {
end.merge(&mut states.remove(0));
}
Some(end)
} else {
None
}
} | Execute function at address and return the resulting state
if there are multiple result states, merge them all | call_address | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn run_until(&mut self, state: State, target: u64, avoid: &[u64]) -> Option<State> {
self.breakpoint(target);
self.avoid(avoid);
self.processor.run(state, RunMode::Single).pop()
} | Simple way to execute until a given target address while avoiding a vec of other addrs
## Arguments
* `state` - the program state to begin running from
* `target` - the goal address where execution should stop and return the result state
* `avoid` - slice of addresses to avoid, states that reach them will be marked inactive | run_until | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn run_all(&mut self, state: State) -> Vec<State> {
self.processor.run(state, RunMode::Multiple)
} | Execute until every state has reached an end and return active states | run_all | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn run(&mut self, state: State, _threads: usize) -> Option<State> {
// we are gonna scrap threads for now cuz theyre currently useless.
self.processor.run(state, RunMode::Single).pop()
} | Main run method, start or continue a symbolic execution
## Arguments
* `state` - the program state to begin executing from
* `threads` - number of threads (currently unused)
## Example
```
use radius2::Radius;
let mut radius = Radius::new("/bin/ls");
let state = radius.entry_state();
let new_state = radius.run(state, 1);
``` | run | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn write_string(&mut self, address: u64, string: &str) {
self.r2api
.write(address, string.chars().map(|c| c as u8).collect::<Vec<_>>())
} | Write string to binary / real memory | write_string | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn set_option(&mut self, key: &str, value: &str) {
self.r2api.set_option(key, value).unwrap();
} | Set radare2 option, equivalent to "e `key`=`value`" | set_option | rust | aemmitt-ns/radius2 | radius/src/radius.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/radius.rs | MIT |
pub fn new(
r2api: &mut R2Api,
eval_max: usize,
debug: bool,
blank: bool,
check: bool,
strict: bool,
) -> Self {
let esil_state = EsilState {
mode: ExecMode::Uncon,
prev_pc: Value::Concrete(0, 0),
previous: Value::Concrete(0, 0),
current: Value::Concrete(0, 0),
last_sz: 64,
stored_address: None,
temp1: vec![], // these instances are actually not used
temp2: vec![],
pcs: Vec::with_capacity(64),
};
let solver = Solver::new(eval_max);
let registers = Registers::new(r2api, solver.clone(), blank);
let memory = Memory::new(r2api, solver.clone(), blank);
State {
solver,
r2api: r2api.clone(),
info: r2api.info.clone(),
stack: Vec::with_capacity(128),
esil: esil_state,
condition: None,
registers,
memory,
filesystem: SimFilesytem::new(),
status: StateStatus::Active,
context: HashMap::new(),
taints: HashMap::new(),
hooks: HashMap::new(),
visits: HashMap::with_capacity(512),
backtrace: Vec::with_capacity(128),
pid: 1337, // sup3rh4x0r
blank,
debug,
check,
strict,
has_event_hooks: false,
}
} | Create a new state, should generally not be called directly | new | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn duplicate(&mut self) -> Self {
let solver = self.solver.duplicate();
let mut registers = self.registers.clone();
registers.solver = solver.clone();
registers.values = registers
.values
.iter()
.map(|r| solver.translate_value(r))
.collect();
let mut memory = self.memory.clone();
memory.solver = solver.clone();
let addrs = memory.addresses();
for addr in addrs {
let values = memory.mem.remove(&addr).unwrap();
memory.mem.insert(
addr,
values.iter().map(|v| solver.translate_value(&v)).collect(),
);
}
let mut context = HashMap::new();
for key in self.context.keys() {
let values = self.context.get(key).unwrap();
let new_values = values.iter().map(|v| solver.translate_value(v)).collect();
context.insert(key.to_owned(), new_values);
}
let mut filesystem = self.filesystem.clone();
for f in &mut filesystem.files {
let content = f.content.clone();
f.content = content.iter().map(|v| solver.translate_value(v)).collect();
}
let esil_state = EsilState {
mode: ExecMode::Uncon,
prev_pc: self.esil.prev_pc.clone(),
previous: vc(0),
current: vc(0),
last_sz: 64,
stored_address: None,
temp1: Vec::with_capacity(128),
temp2: Vec::with_capacity(128),
pcs: Vec::with_capacity(64),
};
State {
solver,
r2api: self.r2api.clone(),
info: self.info.clone(),
stack: Vec::with_capacity(128),
esil: esil_state,
condition: None,
registers,
memory,
filesystem,
status: self.status.clone(),
context,
taints: self.taints.clone(),
hooks: self.hooks.clone(),
visits: self.visits.clone(),
backtrace: self.backtrace.clone(),
pid: self.pid,
blank: self.blank,
debug: self.debug,
check: self.check,
strict: self.strict,
has_event_hooks: self.has_event_hooks,
}
} | duplicate state is different from clone as it creates
a duplicate solver instead of another reference to the old one | duplicate | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn memory_alloc(&mut self, length: &Value) -> Value {
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if length.is_symbolic() {
Event::SymbolicAlloc(EventTrigger::Before)
} else {
Event::Alloc(EventTrigger::Before)
};
self.do_hooked(&event, &EventContext::AllocContext(length.to_owned()));
}
let ret = self.memory.alloc_sym(length, &mut self.solver);
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if length.is_symbolic() {
Event::SymbolicAlloc(EventTrigger::After)
} else {
Event::Alloc(EventTrigger::After)
};
self.do_hooked(&event, &EventContext::AllocContext(length.to_owned()));
}
ret
} | Allocate a block of memory `length` bytes in size | memory_alloc | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn memory_free(&mut self, addr: &Value) -> Value {
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if addr.is_symbolic() {
Event::SymbolicFree(EventTrigger::Before)
} else {
Event::Free(EventTrigger::Before)
};
self.do_hooked(&event, &EventContext::FreeContext(addr.to_owned()));
}
if self.check && self.check_crash(addr, &vc(1), 'r') {
return vc(-1i64 as u64);
}
let ret = self.memory.free_sym(addr, &mut self.solver);
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if addr.is_symbolic() {
Event::SymbolicFree(EventTrigger::After)
} else {
Event::Free(EventTrigger::After)
};
self.do_hooked(&event, &EventContext::FreeContext(addr.to_owned()));
}
ret
} | Free a block of memory at `addr` | memory_free | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn memory_search(
&mut self,
addr: &Value,
needle: &Value,
length: &Value,
reverse: bool,
) -> Value {
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if addr.is_symbolic() || length.is_symbolic() {
Event::SymbolicSearch(EventTrigger::Before)
} else {
Event::Search(EventTrigger::Before)
};
self.do_hooked(
&event,
&EventContext::SearchContext(addr.to_owned(), needle.to_owned(), length.to_owned()),
);
}
if self.check && self.check_crash(addr, &vc(1), 'r') {
return vc(-1i64 as u64);
}
let ret = self
.memory
.search(addr, needle, length, reverse, &mut self.solver);
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if addr.is_symbolic() || length.is_symbolic() {
Event::SymbolicSearch(EventTrigger::After)
} else {
Event::Search(EventTrigger::After)
};
self.do_hooked(
&event,
&EventContext::SearchContext(addr.to_owned(), needle.to_owned(), length.to_owned()),
);
}
ret
} | Search for `needle` at the address `addr` for a maximum of `length` bytes
Returns a `Value` containing the **address** of the needle, not index | memory_search | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn memory_compare(&mut self, dst: &Value, src: &Value, length: &Value) -> Value {
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if dst.is_symbolic() || src.is_symbolic() || length.is_symbolic() {
Event::SymbolicCompare(EventTrigger::Before)
} else {
Event::Compare(EventTrigger::Before)
};
self.do_hooked(
&event,
&EventContext::CompareContext(dst.to_owned(), src.to_owned(), length.to_owned()),
);
}
if self.check && (self.check_crash(src, &vc(1), 'r') || self.check_crash(dst, &vc(1), 'r'))
{
return vc(-1i64 as u64);
}
let ret = self.memory.compare(dst, src, length, &mut self.solver);
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if dst.is_symbolic() || src.is_symbolic() || length.is_symbolic() {
Event::SymbolicCompare(EventTrigger::After)
} else {
Event::Compare(EventTrigger::After)
};
self.do_hooked(
&event,
&EventContext::CompareContext(dst.to_owned(), src.to_owned(), length.to_owned()),
);
}
ret
} | Compare memory at `dst` and `src` address up to `length` bytes.
This is akin to memcmp but will handle symbolic addrs and length | memory_compare | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn memory_strlen(&mut self, addr: &Value, length: &Value) -> Value {
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if addr.is_symbolic() || length.is_symbolic() {
Event::SymbolicStrlen(EventTrigger::Before)
} else {
Event::StringLength(EventTrigger::Before)
};
self.do_hooked(
&event,
&EventContext::StrlenContext(addr.to_owned(), length.to_owned()),
);
}
// eh don't use the length here
if self.check && self.check_crash(addr, &vc(1), 'r') {
return vc(-1i64 as u64);
}
let ret = self.memory.strlen(addr, length, &mut self.solver);
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if addr.is_symbolic() || length.is_symbolic() {
Event::SymbolicStrlen(EventTrigger::After)
} else {
Event::StringLength(EventTrigger::After)
};
self.do_hooked(
&event,
&EventContext::StrlenContext(addr.to_owned(), length.to_owned()),
);
}
ret
} | Get the length of the null terminated string at `addr` | memory_strlen | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn memory_move(&mut self, dst: &Value, src: &Value, length: &Value) {
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if dst.is_symbolic() || src.is_symbolic() || length.is_symbolic() {
Event::SymbolicMove(EventTrigger::Before)
} else {
Event::Move(EventTrigger::Before)
};
self.do_hooked(
&event,
&EventContext::MoveContext(dst.to_owned(), src.to_owned(), length.to_owned()),
);
}
if self.check && (self.check_crash(src, length, 'r') || self.check_crash(dst, length, 'w'))
{
return;
}
self.memory.memmove(dst, src, length, &mut self.solver);
if DO_EVENT_HOOKS && self.has_event_hooks {
let event = if dst.is_symbolic() || src.is_symbolic() || length.is_symbolic() {
Event::SymbolicMove(EventTrigger::After)
} else {
Event::Move(EventTrigger::After)
};
self.do_hooked(
&event,
&EventContext::MoveContext(dst.to_owned(), src.to_owned(), length.to_owned()),
);
}
} | Move `length` bytes from `src` to `dst` | memory_move | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn memory_read_string(&mut self, address: u64, length: usize) -> String {
self.memory.read_string(address, length, &mut self.solver)
} | Read a string from `address` up to `length` bytes long | memory_read_string | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn unpack(&self, data: &Value, length: usize) -> Vec<Value> {
let mut values = vec![Value::Concrete(0, 0); length];
self.memory.unpack(data, length, &mut values);
values
} | unpack `Value` into vector of bytes | unpack | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn apply(&mut self) {
let mut inds = Vec::with_capacity(256);
for reg in &self.registers.indexes {
if !inds.contains(®.value_index) {
inds.push(reg.value_index);
let rval = self.registers.values[reg.value_index].to_owned();
let r = self.solver.evalcon_to_u64(&rval).unwrap();
self.r2api.set_register_value(®.reg_info.name, r);
}
}
let mut bvals = vec![Value::Concrete(0, 0); READ_CACHE];
for addr in self.memory.addresses() {
self.memory.read(addr, READ_CACHE, &mut bvals);
let bytes: Vec<u8> = bvals
.iter()
.map(|bval| self.solver.evalcon_to_u64(&bval).unwrap() as u8)
.collect();
self.r2api.write(addr, bytes.clone());
}
// TODO: evaluate files and write to real FS? maybe a bad idea
} | Apply this state to the radare2 instance. This writes all the values
in the states memory back to the memory in r2 as well as the register
values, evaluating any symbolic expressions. | apply | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn constrain_with_state(&mut self, state: &Self) {
self.solver = state.solver.clone();
} | Use the constraints from the provided state. This is
useful for constraining the data in some initial
state with the assertions of some desired final state | constrain_with_state | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn bv(&self, s: &str, n: u32) -> BitVec {
self.solver.bv(s, n)
} | Create a bitvector from this states solver | bv | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn bvv(&self, v: u64, n: u32) -> BitVec {
self.solver.bvv(v, n)
} | Create a bitvector value from this states solver | bvv | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn concrete_value(&self, v: u64, n: u32) -> Value {
let mask = if n < 64 { (1 << n) - 1 } else { -1i64 as u64 };
Value::Concrete(v & mask, 0)
} | Create a `Value::Concrete` from a value `v` and bit width `n` | concrete_value | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn symbolic_value(&self, s: &str, n: u32) -> Value {
Value::Symbolic(self.bv(s, n), 0)
} | Create a `Value::Symbolic` from a name `s` and bit width `n` | symbolic_value | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn tainted_concrete_value(&mut self, t: &str, v: u64, n: u32) -> Value {
let mask = if n < 64 { (1 << n) - 1 } else { -1i64 as u64 };
let taint = self.get_tainted_identifier(t);
Value::Concrete(v & mask, taint)
} | Create a tainted `Value::Concrete` from a value `v` and bit width `n` | tainted_concrete_value | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn tainted_symbolic_value(&mut self, t: &str, s: &str, n: u32) -> Value {
let taint = self.get_tainted_identifier(t);
Value::Symbolic(self.bv(s, n), taint)
} | Create a tainted `Value::Symbolic` from a name `s` and bit width `n` | tainted_symbolic_value | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn get_tainted_identifier(&mut self, t: &str) -> u64 {
if let Some(taint) = self.taints.get(t) {
*taint
} else {
let index = self.taints.len();
if index < 64 {
let new_taint = 1 << index as u64;
self.taints.insert(t.to_owned(), new_taint);
new_taint
} else {
// no need to panic
println!("Max of 64 taints allowed!");
0
}
}
} | Get the numeric identifier for the given taint name | get_tainted_identifier | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn is_tainted_with(&mut self, value: &Value, taint: &str) -> bool {
(value.get_taint() & self.get_tainted_identifier(taint)) != 0
} | Check if the `value` is tainted with the given `taint` | is_tainted_with | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn constrain_bytes_bv(&mut self, bv: &BitVec, pattern: &str) {
if &pattern[..1] != "[" {
for (i, c) in pattern.chars().enumerate() {
self.assert_bv(
&bv.slice(8 * (i as u32 + 1) - 1, 8 * i as u32)
._eq(&self.bvv(c as u64, 8)),
);
}
} else {
let patlen = pattern.len();
let newpat = &pattern[1..patlen - 1];
let mut assertions = Vec::with_capacity(256);
for ind in 0..bv.get_width() / 8 {
assertions.clear();
let s = &bv.slice(8 * (ind + 1) - 1, 8 * ind);
let mut i = 0;
while i < patlen - 2 {
let c = newpat.as_bytes()[i] as u64;
if patlen > 4 && i < patlen - 4 && &newpat[i + 1..i + 2] == "-" {
let n = newpat.as_bytes()[i + 2] as u64;
i += 3;
assertions.push(s.ugte(&self.bvv(c, 8)).and(&s.ulte(&self.bvv(n, 8))));
} else {
i += 1;
assertions.push(s._eq(&self.bvv(c, 8)));
}
}
self.assert_bv(&self.solver.or_all(&assertions));
}
}
} | Constrain bytes of bitvector to be an exact string eg. "ABC"
or use "\[...\]" to match a simple pattern eg. "\[XYZa-z0-9\]" | constrain_bytes_bv | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn constrain_bytes(&mut self, bv: &Value, pattern: &str) {
if let Value::Symbolic(s, _) = bv {
self.constrain_bytes_bv(s, pattern)
}
} | Constrain bytes of bitvector to be an exact string eg. "ABC"
or use "\[...\]" to match a simple pattern eg. "\[XYZa-z0-9\]" | constrain_bytes | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn constrain_fd(&mut self, fd: usize, content: &str) {
let fbytes = self.dump_file(fd);
let fbv = self.pack(&fbytes);
self.constrain_bytes(&fbv, content);
} | Constrain bytes of file with file descriptor `fd` and pattern | constrain_fd | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn constrain_file(&mut self, path: &str, content: &str) {
if let Some(fd) = self.filesystem.getfd(path) {
self.constrain_fd(fd, content);
}
} | Constrain bytes of file at `path` with pattern | constrain_file | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn is_sat(&mut self) -> bool {
if self.solver.is_sat() {
true
} else {
self.status = StateStatus::Unsat;
false
}
} | Check if this state is satisfiable and mark the state `Unsat` if not | is_sat | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn set_status(&mut self, status: StateStatus) {
self.status = status;
} | Set status of state (active, inactive, merge, unsat...) | set_status | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn set_crash(&mut self, addr: u64, perm: char) {
self.set_status(StateStatus::Crash(addr, perm));
} | Convenience method to mark state crashed | set_crash | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn get_args(&mut self) -> Vec<Value> {
let pc = self.registers.get_pc().as_u64().unwrap();
let cc = self.r2api.get_cc(pc).unwrap_or_default();
let mut args = Vec::with_capacity(16);
if !cc.args.is_empty() {
for arg in &cc.args {
args.push(self.registers.get_with_alias(arg));
}
} else {
// read args from stack?
let mut sp = self.registers.get_with_alias("SP");
let length = self.memory.bits as usize / 8;
for _ in 0..8 {
// do 8 idk?
sp = sp + Value::Concrete(length as u64, 0);
let value = self.memory_read_value(&sp, length);
args.push(value);
}
}
args
} | Get the argument values for the current function | get_args | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn get_ret(&mut self) -> Value {
let pc = self.registers.get_pc().as_u64().unwrap();
let cc = self.r2api.get_cc(pc).unwrap_or_default();
self.registers.get(&cc.ret)
} | get the return value from the right register | get_ret | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn set_args(&mut self, mut values: Vec<Value>) {
let pc = self.registers.get_pc().as_u64().unwrap();
let cc = self.r2api.get_cc(pc).unwrap_or_default();
if !cc.args.is_empty() {
for arg in &cc.args {
if !values.is_empty() {
self.registers.set_with_alias(arg, values.remove(0));
}
}
} else {
// read args from stack?
let mut sp = self.registers.get_with_alias("SP");
let length = self.memory.bits as usize / 8;
for _ in 0..8 {
// do 8 idk?
sp = sp + Value::Concrete(length as u64, 0);
if !values.is_empty() {
self.memory_write_value(&sp, &values.remove(0), length);
}
}
}
} | Set the argument values for the current function | set_args | rust | aemmitt-ns/radius2 | radius/src/state.rs | https://github.com/aemmitt-ns/radius2/blob/master/radius/src/state.rs | MIT |
pub fn fluctuate_from_pattern(config_delay: Option<u32>, event_handle: Option<HANDLE>, pattern: [u8;2]) -> Result<(), String>
{
fluctuate_core(true, config_delay, event_handle, 0, Some(pattern))
} | Encrypt the whole PE. Use this function in order to specify a two bytes pattern that the library will look for to retrieve the module's base address. These two bytes replace
the classic MZ PE magic bytes, allowing you to remove PE headers to hide the pressence of the binary.
- config_delay: Number of seconds that the program will sleep for. If it is left to None, the timeout will be infinite.
For that option to work correctly, a valid event handle must be passed as an argument (event_handle), so the event can be
properly signaled to resume the execution. Otherwise, this function will never return.
- event_handle: The NtWaitForSingleObject function is used to delay execution. If this parameter is set to None
the function will automatically generate a new event to pass to NtWaitForSingleObject. If the caller wants to use a previously
created event, its handle can be passed using this argument.
- pattern: A two bytes pattern that will indicate the start of the PE in memory. The MZ magic bytes should be replaced by these two bytes. | fluctuate_from_pattern | rust | Kudaes/Shelter | src/lib.rs | https://github.com/Kudaes/Shelter/blob/master/src/lib.rs | Apache-2.0 |
pub fn fluctuate_from_address(config_delay: Option<u32>, event_handle: Option<HANDLE>, base_adress: usize) -> Result<(), String>
{
fluctuate_core(true, config_delay, event_handle, base_adress, None)
} | Encrypt the whole PE. Use this function in order to specify the base_address of the current PE, preventing the library from searching the MZ pattern.
- config_delay: Number of seconds that the program will sleep for. If it is left to None, the timeout will be infinite.
For that option to work correctly, a valid event handle must be passed as an argument (event_handle), so the event can be
properly signaled to resume the execution. Otherwise, this function will never return.
- event_handle: The NtWaitForSingleObject function is used to delay execution. If this parameter is set to None
the function will automatically generate a new event to pass to NtWaitForSingleObject. If the caller wants to use a previously
created event, its handle can be passed using this argument.
- base_address: This is the PE base address. | fluctuate_from_address | rust | Kudaes/Shelter | src/lib.rs | https://github.com/Kudaes/Shelter/blob/master/src/lib.rs | Apache-2.0 |
pub fn fluctuate(config_encryptall: bool, config_delay: Option<u32>, event_handle: Option<HANDLE>) -> Result<(), String>
{
fluctuate_core(config_encryptall, config_delay, event_handle, 0, None)
} | Encrypt either the current memory region or the whole PE.
- config_encryptall: Encrypt all sections from the PE or just the current memory region where the main program resides.
Keep in mind that, to be able to encrypt all sections, PE's magic bytes shouldn't be stripped.
For more information check out the implementation of get_pe_baseaddress function. If the header is not
found, the configuration will automatically change to encrypt only current memory region.
- config_delay: Number of seconds that the program will sleep for. If it is left to None, the timeout will be infinite.
For that option to work correctly, a valid event handle must be passed as an argument (event_handle), so the event can be
properly signaled to resume the execution. Otherwise, this function will never return.
- event_handle: The NtWaitForSingleObject function is used to delay execution. If this parameter is set to None
the function will automatically generate a new event to pass to NtWaitForSingleObject. If the caller wants to use a previously
created event, its handle can be passed using this argument. | fluctuate | rust | Kudaes/Shelter | src/lib.rs | https://github.com/Kudaes/Shelter/blob/master/src/lib.rs | Apache-2.0 |
fn get_pe_metadata (module_ptr: *const u8) -> Result<PeMetadata,String> {
let mut pe_metadata= PeMetadata::default();
unsafe {
let e_lfanew = *((module_ptr as u64 + 0x3C) as *const u32);
pe_metadata.image_file_header = *((module_ptr as u64 + e_lfanew as u64 + 0x4) as *mut ImageFileHeader);
let opt_header: *const u16 = (module_ptr as u64 + e_lfanew as u64 + 0x18) as *const u16;
let pe_arch = *(opt_header);
if pe_arch == 0x010B
{
pe_metadata.is_32_bit = true;
let opt_header_content: *const IMAGE_OPTIONAL_HEADER32 = std::mem::transmute(opt_header);
pe_metadata.opt_header_32 = *opt_header_content;
}
else if pe_arch == 0x020B
{
pe_metadata.is_32_bit = false;
let opt_header_content: *const ImageOptionalHeader64 = std::mem::transmute(opt_header);
pe_metadata.opt_header_64 = *opt_header_content;
}
else
{
return Err(lc!("[x] Invalid magic value."));
}
let mut sections: Vec<IMAGE_SECTION_HEADER> = vec![];
for i in 0..pe_metadata.image_file_header.number_of_sections
{
let section_ptr = (opt_header as u64 + pe_metadata.image_file_header.size_of_optional_header as u64 + (i * 0x28) as u64) as *const u8;
let section_ptr: *const IMAGE_SECTION_HEADER = std::mem::transmute(section_ptr);
sections.push(*section_ptr);
}
pe_metadata.sections = sections;
Ok(pe_metadata)
}
} | Retrieves PE headers information from the module base address.
It will return either a dinvoke_rs::data::PeMetada struct containing the PE
metadata or a String with a descriptive error message.
# Examples
```
use std::fs;
let file_content = fs::read("c:\\windows\\system32\\ntdll.dll").expect("[x] Error opening the specified file.");
let file_content_ptr = file_content.as_ptr();
let result = manualmap::get_pe_metadata(file_content_ptr);
``` | get_pe_metadata | rust | Kudaes/Shelter | src/lib.rs | https://github.com/Kudaes/Shelter/blob/master/src/lib.rs | Apache-2.0 |
async fn interaction_handler<F>(
req: Request<Incoming>,
f: impl Fn(Box<CommandData>) -> F,
) -> anyhow::Result<Response<Full<Bytes>>>
where
F: Future<Output = anyhow::Result<InteractionResponse>>,
{
// Check that the method used is a POST, all other methods are not allowed.
if req.method() != Method::POST {
return Ok(Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED)
.body(Full::default())?);
}
// Check if the path the request is sent to is the root of the domain.
//
// This filter is for the purposes of this example. The user may filter by
// any path they choose.
if req.uri().path() != "/" {
return Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Full::default())?);
}
// Extract the timestamp header for use later to check the signature.
let timestamp = if let Some(ts) = req.headers().get("x-signature-timestamp") {
ts.to_owned()
} else {
return Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Full::default())?);
};
// Extract the signature to check against.
let signature = if let Some(hex_sig) = req
.headers()
.get("x-signature-ed25519")
.and_then(|v| v.to_str().ok())
{
hex_sig.parse().unwrap()
} else {
return Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Full::default())?);
};
// Fetch the whole body of the request as that is needed to check the
// signature against.
let whole_body = req.collect().await?.to_bytes();
// Check if the signature matches and else return a error response.
if PUB_KEY
.verify(
[timestamp.as_bytes(), &whole_body].concat().as_ref(),
&signature,
)
.is_err()
{
return Ok(Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Full::default())?);
}
// Deserialize the body into a interaction.
let interaction = serde_json::from_slice::<Interaction>(&whole_body)?;
match interaction.kind {
// Return a Pong if a Ping is received.
InteractionType::Ping => {
let response = InteractionResponse {
kind: InteractionResponseType::Pong,
data: None,
};
let json = serde_json::to_vec(&response)?;
Ok(Response::builder()
.status(StatusCode::OK)
.header(CONTENT_TYPE, "application/json")
.body(json.into())?)
}
// Respond to a slash command.
InteractionType::ApplicationCommand => {
// Run the handler to gain a response.
let data = match interaction.data {
Some(InteractionData::ApplicationCommand(data)) => Some(data),
_ => None,
}
.expect("`InteractionType::ApplicationCommand` has data");
let response = f(data).await?;
// Serialize the response and return it back to Discord.
let json = serde_json::to_vec(&response)?;
Ok(Response::builder()
.header(CONTENT_TYPE, "application/json")
.status(StatusCode::OK)
.body(json.into())?)
}
// Unhandled interaction types.
_ => Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Full::default())?),
}
} | Main request handler which will handle checking the signature.
Responses are made by giving a function that takes a Interaction and returns
a InteractionResponse or a error. | interaction_handler | rust | twilight-rs/twilight | examples/model-webhook-slash.rs | https://github.com/twilight-rs/twilight/blob/master/examples/model-webhook-slash.rs | ISC |
async fn handler(data: Box<CommandData>) -> anyhow::Result<InteractionResponse> {
match data.name.as_ref() {
"vroom" => vroom(data).await,
"debug" => debug(data).await,
_ => debug(data).await,
}
} | Interaction handler that matches on the name of the interaction that
have been dispatched from Discord. | handler | rust | twilight-rs/twilight | examples/model-webhook-slash.rs | https://github.com/twilight-rs/twilight/blob/master/examples/model-webhook-slash.rs | ISC |
async fn debug(data: Box<CommandData>) -> anyhow::Result<InteractionResponse> {
Ok(InteractionResponse {
kind: InteractionResponseType::ChannelMessageWithSource,
data: Some(InteractionResponseData {
content: Some(format!("```rust\n{data:?}\n```")),
..Default::default()
}),
})
} | Example of a handler that returns the formatted version of the interaction. | debug | rust | twilight-rs/twilight | examples/model-webhook-slash.rs | https://github.com/twilight-rs/twilight/blob/master/examples/model-webhook-slash.rs | ISC |
async fn vroom(_: Box<CommandData>) -> anyhow::Result<InteractionResponse> {
Ok(InteractionResponse {
kind: InteractionResponseType::ChannelMessageWithSource,
data: Some(InteractionResponseData {
content: Some("Vroom vroom".to_owned()),
..Default::default()
}),
})
} | Example of interaction that responds with a message saying "Vroom vroom". | vroom | rust | twilight-rs/twilight | examples/model-webhook-slash.rs | https://github.com/twilight-rs/twilight/blob/master/examples/model-webhook-slash.rs | ISC |
pub const fn new() -> Self {
Self(Config::new(), PhantomData)
} | Creates a builder to configure and construct an [`InMemoryCache`]. | new | rust | twilight-rs/twilight | twilight-cache-inmemory/src/builder.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/builder.rs | ISC |
pub const fn resource_types(mut self, resource_types: ResourceType) -> Self {
self.0.resource_types = resource_types;
self
} | Sets the list of resource types for the cache to handle.
Defaults to all types. | resource_types | rust | twilight-rs/twilight | twilight-cache-inmemory/src/builder.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/builder.rs | ISC |
pub const fn message_cache_size(mut self, message_cache_size: usize) -> Self {
self.0.message_cache_size = message_cache_size;
self
} | Sets the number of messages to cache per channel.
Defaults to 100. | message_cache_size | rust | twilight-rs/twilight | twilight-cache-inmemory/src/builder.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/builder.rs | ISC |
pub const fn new() -> Self {
Self {
resource_types: ResourceType::all(),
message_cache_size: 100,
}
} | Create a new default configuration.
Refer to individual getters for their defaults. | new | rust | twilight-rs/twilight | twilight-cache-inmemory/src/config.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/config.rs | ISC |
pub fn message_cache_size_mut(&mut self) -> &mut usize {
&mut self.message_cache_size
} | Returns a mutable reference to the message cache size. | message_cache_size_mut | rust | twilight-rs/twilight | twilight-cache-inmemory/src/config.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/config.rs | ISC |
pub fn resource_types_mut(&mut self) -> &mut ResourceType {
&mut self.resource_types
} | Returns a mutable reference to the resource types enabled. | resource_types_mut | rust | twilight-rs/twilight | twilight-cache-inmemory/src/config.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/config.rs | ISC |
pub fn members(
&self,
) -> ResourceIter<'a, (Id<GuildMarker>, Id<UserMarker>), CacheModels::Member> {
ResourceIter::new(self.0.members.iter())
} | Create an iterator over the members across all guilds in the cache. | members | rust | twilight-rs/twilight | twilight-cache-inmemory/src/iter.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/iter.rs | ISC |
pub fn presences(
&self,
) -> ResourceIter<'a, (Id<GuildMarker>, Id<UserMarker>), CacheModels::Presence> {
ResourceIter::new(self.0.presences.iter())
} | Create an iterator over the presences in the cache. | presences | rust | twilight-rs/twilight | twilight-cache-inmemory/src/iter.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/iter.rs | ISC |
pub fn stage_instances(
&self,
) -> ResourceIter<'a, Id<StageMarker>, GuildResource<CacheModels::StageInstance>> {
ResourceIter::new(self.0.stage_instances.iter())
} | Create an iterator over the stage instances in the cache. | stage_instances | rust | twilight-rs/twilight | twilight-cache-inmemory/src/iter.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/iter.rs | ISC |
pub fn stickers(
&self,
) -> ResourceIter<'a, Id<StickerMarker>, GuildResource<CacheModels::Sticker>> {
ResourceIter::new(self.0.stickers.iter())
} | Create an iterator over the stickers in the cache. | stickers | rust | twilight-rs/twilight | twilight-cache-inmemory/src/iter.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/iter.rs | ISC |
pub fn voice_states(
&self,
) -> ResourceIter<'a, (Id<GuildMarker>, Id<UserMarker>), CacheModels::VoiceState> {
ResourceIter::new(self.0.voice_states.iter())
} | Create an iterator over the voice states in the cache. | voice_states | rust | twilight-rs/twilight | twilight-cache-inmemory/src/iter.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/iter.rs | ISC |
pub fn channel_messages(
&self,
channel_id: Id<ChannelMarker>,
) -> Option<Reference<'_, Id<ChannelMarker>, VecDeque<Id<MessageMarker>>>> {
self.channel_messages.get(&channel_id).map(Reference::new)
} | Gets the set of messages in a channel.
This requires the [`DIRECT_MESSAGES`] or [`GUILD_MESSAGES`] intents.
[`DIRECT_MESSAGES`]: ::twilight_model::gateway::Intents::DIRECT_MESSAGES
[`GUILD_MESSAGES`]: ::twilight_model::gateway::Intents::GUILD_MESSAGES | channel_messages | rust | twilight-rs/twilight | twilight-cache-inmemory/src/lib.rs | https://github.com/twilight-rs/twilight/blob/master/twilight-cache-inmemory/src/lib.rs | ISC |
This dataset contains Rust functions and methods paired with their documentation comments, extracted from open-source Rust repositories on GitHub. It is formatted similarly to the CodeSearchNet challenge dataset.
Each entry includes:
code
: The source code of a rust function or method.docstring
: The docstring or Javadoc associated with the function/method.func_name
: The name of the function/method.language
: The programming language (always "rust").repo
: The GitHub repository from which the code was sourced (e.g., "owner/repo").path
: The file path within the repository where the function/method is located.url
: A direct URL to the function/method's source file on GitHub (approximated to master/main branch).license
: The SPDX identifier of the license governing the source repository (e.g., "MIT", "Apache-2.0").
Additional metrics if available (from Lizard tool):ccn
: Cyclomatic Complexity Number.params
: Number of parameters of the function/method.nloc
: Non-commenting lines of code.token_count
: Number of tokens in the function/method.The dataset is divided into the following splits:
train
: 735,617 examplesvalidation
: 8,984 examplestest
: 9,920 examplesThe data was collected by:
.rs
) using tree-sitter to extract functions/methods and their docstrings/Javadoc.lizard
tool to calculate code metrics (CCN, NLOC, params).This dataset can be used for tasks such as:
The code examples within this dataset are sourced from repositories with permissive licenses (typically MIT, Apache-2.0, BSD).
Each sample includes its original license information in the license
field.
The dataset compilation itself is provided under a permissive license (e.g., MIT or CC-BY-SA-4.0),
but users should respect the original licenses of the underlying code.
from datasets import load_dataset
# Load the dataset
dataset = load_dataset("Shuu12121/rust-treesitter-filtered-datasetsV2")
# Access a split (e.g., train)
train_data = dataset["train"]
# Print the first example
print(train_data[0])