use std::collections::{BTreeMap, BTreeSet};
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::thread;
use binbun_decompile::data::Data;
use binbun_decompile::lower::{self as lowering, Context, Facts, Found, Interface};
use binbun_decompile::prototype::Prototypes;
use binbun_decompile::typing::Summary;
use binbun_loader::Image;
use binbun_semantics::core::pass::PassStats;
use binbun_ssa::constant::Constants;
use binbun_ssa::graph::Dominators;
use binbun_ssa::ir::Function;
use binbun_ssa::stack::Stack;
use super::callers::Callers;
use super::{Prepared, decompile_l1, with_context};
use crate::cfg::{FunctionId, Program};
use crate::summary::{Summaries, callees_first};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Interfaces {
pub interfaces: BTreeMap<u64, Interface>,
pub functions: BTreeSet<u64>,
pub callers: Callers,
}
impl Interfaces {
pub(crate) fn of(program: &Program, callers: &Callers) -> Self {
Self {
interfaces: callers.interfaces.clone(),
functions: program.functions.iter().map(|(_, f)| f.entry).collect(),
callers: callers.clone(),
}
}
}
pub fn stream(
image: &Image<'_>,
program: &Program,
summaries: &Summaries,
read: &Callers,
disabled: &[String],
mut ready: impl FnMut(FunctionId, Result<Prepared, String>, &Interfaces),
) {
let known = Interfaces::of(program, read);
let order = callees_first(program);
lifted(
image,
program,
&order,
summaries,
disabled,
1,
|id, prepared| {
ready(id, prepared, &known);
},
);
}
#[expect(
clippy::too_many_arguments,
reason = "what decompilation reads of the program, and how to share the work"
)]
pub fn stream_parallel<T: Send>(
image: &Image<'_>,
program: &Program,
summaries: &Summaries,
read: &Callers,
disabled: &[String],
threads: usize,
work: impl Fn(FunctionId, Result<Prepared, String>, &Interfaces) -> T + Sync,
mut ready: impl FnMut(T),
) {
if threads <= 1 {
stream(
image,
program,
summaries,
read,
disabled,
|id, prepared, known| {
ready(work(id, prepared, known));
},
);
return;
}
let known = Interfaces::of(program, read);
let order = callees_first(program);
let (jobs, queue) = mpsc::sync_channel::<Job>(threads.saturating_mul(2));
let queue = Arc::new(Mutex::new(queue));
let (done, results) = mpsc::channel();
thread::scope(|scope| {
for _ in 0..threads {
let (queue, done, known, work) = (Arc::clone(&queue), done.clone(), &known, &work);
scope.spawn(move || {
while let Some(job) = next(&queue) {
let prepared = job.prepared.map(Moved::prepared);
if done.send((job.at, work(job.id, prepared, known))).is_err() {
break;
}
}
});
}
drop((queue, done));
let mut in_order = InOrder::default();
let mut at = 0;
lifted(
image,
program,
&order,
summaries,
disabled,
threads,
|id, prepared| {
let job = Job {
at,
id,
prepared: prepared.map(Moved::new),
};
at += 1;
let _ = jobs.send(job);
for (at, result) in results.try_iter() {
in_order.add(at, result, &mut ready);
}
},
);
drop(jobs);
for (at, result) in results {
in_order.add(at, result, &mut ready);
}
});
}
struct Job {
at: usize,
id: FunctionId,
prepared: Result<Moved, String>,
}
pub(super) struct Moved {
l1: Function,
passes: Vec<(&'static str, PassStats)>,
analyses: Vec<(&'static str, usize)>,
constants: Constants,
stack: Stack,
dominators: Dominators,
}
impl Moved {
pub(super) fn new(prepared: Prepared) -> Self {
let Prepared {
l1,
facts,
passes,
analyses,
} = prepared;
let Facts {
constants,
stack,
dominators,
..
} = facts;
Self {
l1,
passes,
analyses,
constants: Rc::unwrap_or_clone(constants),
stack: Rc::unwrap_or_clone(stack),
dominators: Rc::unwrap_or_clone(dominators),
}
}
pub(super) fn prepared(self) -> Prepared {
Prepared {
l1: self.l1,
facts: Facts::new(
Rc::new(self.constants),
Rc::new(self.stack),
Rc::new(self.dominators),
),
passes: self.passes,
analyses: self.analyses,
}
}
}
fn next(queue: &Mutex<Receiver<Job>>) -> Option<Job> {
queue
.lock()
.unwrap_or_else(PoisonError::into_inner)
.recv()
.ok()
}
pub(super) fn lifted(
image: &Image<'_>,
program: &Program,
order: &[FunctionId],
summaries: &Summaries,
disabled: &[String],
threads: usize,
mut visit: impl FnMut(FunctionId, Result<Prepared, String>),
) {
if threads <= 1 {
for &id in order {
visit(id, decompile_l1(image, program, id, summaries, disabled));
}
return;
}
let ahead = threads.saturating_mul(AHEAD);
let taken = AtomicUsize::new(0);
let window = Window::default();
let (done, results) = mpsc::channel();
thread::scope(|scope| {
for _ in 0..threads {
let (taken, window, done) = (&taken, &window, done.clone());
scope.spawn(move || {
let _stop = Stop(window);
loop {
let at = taken.fetch_add(1, Ordering::Relaxed);
let Some(&id) = order.get(at) else {
break;
};
if !window.wait(at.saturating_sub(ahead)) {
break;
}
let prepared = decompile_l1(image, program, id, summaries, disabled);
if done.send((at, prepared.map(Moved::new))).is_err() {
break;
}
}
});
}
drop(done);
let _stop = Stop(&window);
let mut waiting = BTreeMap::new();
for (at, &id) in order.iter().enumerate() {
let prepared = loop {
if let Some(prepared) = waiting.remove(&at) {
break prepared;
}
let Ok((place, prepared)) = results.recv() else {
return;
};
waiting.insert(place, prepared);
};
visit(id, prepared.map(Moved::prepared));
window.advance(at + 1);
}
});
}
const AHEAD: usize = 4;
#[derive(Default)]
struct Window {
state: Mutex<(usize, bool)>,
changed: Condvar,
}
impl Window {
fn wait(&self, visited: usize) -> bool {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
while state.0 < visited && !state.1 {
state = self
.changed
.wait(state)
.unwrap_or_else(PoisonError::into_inner);
}
!state.1
}
fn advance(&self, visited: usize) {
self.state.lock().unwrap_or_else(PoisonError::into_inner).0 = visited;
self.changed.notify_all();
}
}
struct Stop<'w>(&'w Window);
impl Drop for Stop<'_> {
fn drop(&mut self) {
if thread::panicking() {
self.0
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.1 = true;
self.0.changed.notify_all();
}
}
}
struct InOrder<T> {
next: usize,
waiting: BTreeMap<usize, T>,
}
impl<T> Default for InOrder<T> {
fn default() -> Self {
Self {
next: 0,
waiting: BTreeMap::new(),
}
}
}
impl<T> InOrder<T> {
fn add(&mut self, at: usize, result: T, ready: &mut impl FnMut(T)) {
self.waiting.insert(at, result);
while let Some(result) = self.waiting.remove(&self.next) {
ready(result);
self.next += 1;
}
}
}
pub(super) fn interface(
image: &Image<'_>,
prepared: &Prepared,
prototypes: &dyn Prototypes,
data: &dyn Data,
known: &Interfaces,
) -> Result<Found, String> {
with_context(
image,
prepared.l1.entry,
known,
prototypes,
data,
|context| {
lowering::interface(&prepared.l1, &prepared.facts, context).map_err(|e| e.to_string())
},
)
}
pub(super) fn summarise(
image: &Image<'_>,
prepared: &Prepared,
prototypes: &dyn Prototypes,
data: &dyn Data,
known: &Interfaces,
) -> Result<(Found, Option<Summary>), String> {
with_context(
image,
prepared.l1.entry,
known,
prototypes,
data,
|context| {
let (mut found, summary) = lowering::summarise(&prepared.l1, &prepared.facts, context)
.map_err(|e| e.to_string())?;
if found.unsettled_futex && !context.assume_futex {
let assumed = Context {
assume_futex: true,
..*context
};
found.assumed = lowering::interface(&prepared.l1, &prepared.facts, &assumed)
.ok()
.map(Box::new);
}
Ok((found, summary))
},
)
}