diff --git a/README.md b/README.md index 483084de..0fc9a4b7 100644 --- a/README.md +++ b/README.md @@ -857,6 +857,10 @@ Matching, body/override precedence and disabling rules are specified in ## SQLite database schema +A callable constructed by `std::bind` can appear as a `Bound` location in +debug exports. Its argument-flow rows are attached to the call site that +invokes it. See [Bound callables](docs/IR.md#bound-callables). + Minimal and full databases record indirect callee and return-destination variable IDs in `call_sites.callee_var` and `call_sites.return_dst`. Export uses indexed SQLite joins for indirect-return provenance, building the required diff --git a/crates/trace-analysis/src/constraints.rs b/crates/trace-analysis/src/constraints.rs index f8cd6cb6..004ae7ed 100644 --- a/crates/trace-analysis/src/constraints.rs +++ b/crates/trace-analysis/src/constraints.rs @@ -72,11 +72,14 @@ pub struct CallGraphEdge { pub resolution: ResolutionKind, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct ArgFlowEdge { pub call_site: trace_ir::CallSiteId, pub arg_index: u32, pub actual_var: Option, + /// The address temporary passed for a source argument such as `&x`. + /// The row still names `x` as its actual variable. + pub actual_address: Option, pub actual_fn: Option, pub formal: VarId, } @@ -95,6 +98,10 @@ pub enum LocKind { Function, /// Interned C string literal (value in `AbstractLocation.desc`). StringLit, + /// A callable `std::bind` built: a function value naming the function it + /// wraps (`Pag::bound_callables` holds its receiver and bound + /// arguments). See docs/IR.md, "Bound callables". + Bound, } #[derive(Debug, Clone)] diff --git a/crates/trace-analysis/src/memory.rs b/crates/trace-analysis/src/memory.rs index 204a5681..00f0b864 100644 --- a/crates/trace-analysis/src/memory.rs +++ b/crates/trace-analysis/src/memory.rs @@ -96,7 +96,10 @@ fn collect_cells<'a>( let mut unfoldable = 0usize; for &loc in targets { let loc_kind = pag.locations[loc.0 as usize].kind; - if matches!(loc_kind, LocKind::Function | LocKind::StringLit) { + if matches!( + loc_kind, + LocKind::Function | LocKind::Bound | LocKind::StringLit + ) { continue; } cells.push(loc); diff --git a/crates/trace-analysis/src/pag.rs b/crates/trace-analysis/src/pag.rs index 3ccb9008..93f9c039 100644 --- a/crates/trace-analysis/src/pag.rs +++ b/crates/trace-analysis/src/pag.rs @@ -5,10 +5,21 @@ use indexmap::IndexMap; use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet}; use std::sync::Arc; use trace_ir::{ - CallSite, ContainerOwner, FieldId, FlowConstraint, FnId, LocId, PagNodeId, Program, ReturnFlow, - StorageClass, TargetId, TypeDesc, TypeId, VarId, + BindTarget, BoundArg, CallSite, ContainerOwner, FieldId, FlowConstraint, FnId, LocId, + PagNodeId, Program, ReturnFlow, StorageClass, TargetId, TypeDesc, TypeId, VarId, }; +/// What a `Bound` location binds ([`Pag::bound_callables`]): the callable +/// `std::bind` built, as lowering read it off the bind expression +/// (docs/IR.md, "Bound callables"). +#[derive(Debug, Clone)] +pub struct BoundCallable { + /// The object bound as a member function's implicit `this`. + pub receiver: Option, + /// One entry per bound argument, in the order written. + pub args: Vec, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum PagNodeKind { Var(VarId), @@ -128,6 +139,14 @@ pub struct Pag { pub indices: SolverIndices, /// Call results produced by `return_field`, for transitive return expansion. return_field_values: FxHashSet, + /// Each `Bound` location's binding, by location: the function it wraps, + /// with the receiver and arguments `std::bind` holds for it + /// (docs/IR.md, "Bound callables"). Empty unless the program binds. + pub bound_callables: FxHashMap, + /// Variable-target binding facts to revisit as the source gains functions. + pub(crate) bind_sources: FxHashMap>, + /// Each binding fact's realized locations, in discovery order. + bound_origins: FxHashMap>, } impl Pag { @@ -815,7 +834,7 @@ impl Pag { fn build_flow_constraints(&mut self, program: &Program, models: &ModelLookup) { let mut container_elements = FxHashMap::default(); - for flow in &program.flow { + for (index, flow) in program.flow.iter().enumerate() { match flow { FlowConstraint::Copy { dst, src } => { let dst_n = self.var_node_id(*dst); @@ -1058,6 +1077,13 @@ impl Pag { let src_n = self.var_node_id(*src); self.add_unwrap(dst_n, src_n); } + FlowConstraint::BindCallable { target, .. } => match *target { + BindTarget::Function(callee) => self.materialize_binding(program, flow, callee), + BindTarget::Value(var) => { + let source = self.var_node_id(var); + self.bind_sources.entry(source).or_default().push(index); + } + }, } } self.expand_call_site_returns(program, models); @@ -1550,16 +1576,74 @@ impl Pag { /// address the actual temporary holds. pub fn argument_var(&self, cs: &trace_ir::CallSite, idx: u32) -> Option { let actual = cs.var_args.iter().find(|(j, _)| *j == idx)?.1; - let addressed = cs - .addr_of_args() - .contains(&idx) + Some(self.argument_var_for_value(actual, cs.addr_of_args().contains(&idx))) + } + + /// The source variable denoted by a collected argument value. + pub(crate) fn argument_var_for_value(&self, actual: VarId, addr_of: bool) -> VarId { + addr_of .then(|| { self.var_node .get(&actual) .and_then(|&n| self.addressed_var(n)) }) - .flatten(); - Some(addressed.unwrap_or(actual)) + .flatten() + .unwrap_or(actual) + } + + /// Each realized target of this exact binding fact, including those + /// discovered during solve. Configuration alternatives can share a destination. + pub fn bound_locations(&self, fact: &FlowConstraint) -> &[PagNodeId] { + self.bound_origins.get(fact).map_or(&[], Vec::as_slice) + } + + pub(crate) fn materialize_binding( + &mut self, + program: &Program, + fact: &FlowConstraint, + callee: FnId, + ) { + let FlowConstraint::BindCallable { dst, args, .. } = fact else { + unreachable!("binding index must name a BindCallable"); + }; + let function = program.symbols.function(callee); + if !function.pack_positions.is_empty() + || self.bound_locations(fact).iter().any(|node| { + let PagNodeKind::Loc(loc) = self.nodes[node.0 as usize].kind else { + unreachable!("binding origin must name a location"); + }; + self.locations[loc.0 as usize].fn_id == Some(callee) + }) + { + return; + } + let mut args = args.clone(); + let member = program.symbols.is_member_function(callee) && !function.is_static_member; + let receiver = member.then(|| match args.first().copied() { + Some(BoundArg::Pack(var)) => BoundArg::Stored(var), + Some(_) => args.remove(0), + None => BoundArg::Opaque, + }); + let loc = LocId(self.locations.len() as u32); + self.alloc_loc(AbstractLocation { + id: loc, + kind: LocKind::Bound, + var: None, + fn_id: Some(callee), + field: None, + type_id: program.types.unknown(), + desc: function.name.clone(), + }); + self.set_location_target(loc, program.symbols.variable(*dst).target); + self.bound_callables + .insert(loc, BoundCallable { receiver, args }); + let dst = self.var_node_id(*dst); + let location = self.loc_node[&loc]; + self.bound_origins + .entry(fact.clone()) + .or_default() + .push(location); + self.add_addr_of(dst, location); } pub fn call_target_node(&mut self, cs: trace_ir::CallSiteId) -> PagNodeId { diff --git a/crates/trace-analysis/src/solver.rs b/crates/trace-analysis/src/solver.rs index 054c9dcb..86c0ec6c 100644 --- a/crates/trace-analysis/src/solver.rs +++ b/crates/trace-analysis/src/solver.rs @@ -3,14 +3,18 @@ use crate::constraints::{ }; use crate::contexts::{self, ContextStart, ExecutionContext}; use crate::memory::MemoryAccess; -use crate::pag::{Pag, PagNodeKind, SolverIndices}; +use crate::pag::{BoundCallable, Pag, PagNodeKind, SolverIndices}; use crate::summaries::{ class_type, is_value_of, ArgType, ContextKind, Effect, EffectGroup, FnModelSet, InvokeArgs, ModelLookup, }; use indexmap::{IndexMap, IndexSet}; use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet}; -use trace_ir::{CallSiteId, FnId, LocId, PagNodeId, Program, StorageClass, TargetId, VarId}; +use std::sync::Arc; +use trace_ir::{ + BoundArg, CallSite, CallSiteDetails, CallSiteId, FnId, LocId, PagNodeId, Program, StorageClass, + TargetId, VarId, +}; /// Sentinel `CallSiteId` used for synthetic IPC bridge call edges. Real call /// sites are allocated sequentially from `0`; this value marks an edge that @@ -135,9 +139,9 @@ pub struct AnalysisResult { /// Arguments a modelled callee forwards to a callback (`invoke`), by /// call site and callback: each `(formal index, argument position)` wired. pub forwarded_arg_flow: ForwardedArgFlow, - /// Applied `clears` effects: `(call site, cleared parameter index)`. + /// Applied `clears` effects: `(call site, cleared parameter index, actual)`. /// Exported as terminator nodes/edges in the flow graph. - pub terminator_events: Vec<(CallSiteId, u32)>, + pub terminator_events: Vec<(CallSiteId, u32, VarId)>, /// Where threads, tasks and IPC requests start running code: one per /// resolved callback invocation, then one per IPC stub handler /// (`docs/MODELS.md`, "Execution contexts"). @@ -170,6 +174,7 @@ pub fn analyze_with_options(program: &Program, opts: AnalyzeOptions) -> (Pag, An opts.solve_budget_pops, opts.solve_budget_secs, ); + let bound_args = std::mem::take(&mut result.arg_flow_edges); extract_arg_flow( program, &pag, @@ -178,6 +183,14 @@ pub fn analyze_with_options(program: &Program, opts: AnalyzeOptions) -> (Pag, An &result.forwarded_arg_flow, &mut result.arg_flow_edges, ); + if !bound_args.is_empty() { + let bound_sites: FxHashSet<_> = bound_args.iter().map(|row| row.call_site).collect(); + let mut seen = FxHashSet::default(); + result.arg_flow_edges.extend(bound_args); + result + .arg_flow_edges + .retain(|row| !bound_sites.contains(&row.call_site) || seen.insert(row.clone())); + } (pag, result) } @@ -283,9 +296,9 @@ struct SolverState { cell_owner: FxHashMap, /// What [`wire_callback`] wired, for the arg-flow rows. forwarded_arg_flow: ForwardedArgFlow, - /// `(call site, parameter)` terminator events already recorded, so each - /// is recorded once without scanning the event list. - terminators_seen: FxHashSet<(CallSiteId, u32)>, + bound_arg_flow: Vec, + /// Cleared actuals already recorded at a call site's model parameter. + terminators_seen: FxHashSet<(CallSiteId, u32, VarId)>, /// Membership bits mirroring the large `pts` and `memory_pts` sets /// ([`LocBits`]): the sets stay the storage and the iteration order, /// the bits only answer "already held" without hashing. @@ -988,9 +1001,13 @@ fn solve( } let mut call_edges: Vec = Vec::new(); - let mut resolved_indirect: FxHashMap> = FxHashMap::default(); + // One edge per target, with ordinary function values wired separately + // from each bound location that reaches that target. + let mut resolved_indirect = IndirectTargets::default(); + let mut wired_bindings = FxHashSet::default(); let mut wired_arg_flow: FxHashSet<(CallSiteId, u32, FnId)> = FxHashSet::default(); - let mut terminator_events: Vec<(CallSiteId, u32)> = Vec::new(); + let mut terminator_events = Vec::new(); + let mut bound_model_sites = BoundModelSites::default(); let invoked = invoked_params(program, models); let mut invoke_watch = InvokeWatch::default(); @@ -1071,7 +1088,7 @@ fn solve( program, &mut st, &mut scratch, - cs, + &InvocationSite::source(cs), invoked.get(&callee), &mut invoke_watch, ); @@ -1121,7 +1138,16 @@ fn solve( // `Some(&str)` describes which budget stopped the solve, for the stderr // message and the exported diagnostic. let mut stopped_by: Option<&'static str> = None; - while let Some(node) = st.worklist.pop() { + loop { + let node = if let Some(node) = st.worklist.pop() { + node + } else { + // Once propagation settles, activate zero-argument models + // whose callback variables actually acquired a bound value. + invoke_watch.activate_empty(pag, program, &mut st, &mut scratch); + let Some(node) = st.worklist.pop() else { break }; + node + }; st.queued.remove(&node); // A budget of N allows exactly N pops of work: the (N+1)-th node is // popped off the worklist and dropped unprocessed, and `pops` keeps @@ -1185,6 +1211,24 @@ fn solve( for &loc in delta.iter() { st.delta_pending.remove(&(node, loc)); } + if !pag.bind_sources.is_empty() && !delta.is_empty() { + if let Some(facts) = pag.bind_sources.get(&node).cloned() { + let before = pag.constraints.len(); + for &loc in delta.iter() { + let location = &pag.locations[loc.0 as usize]; + if location.kind == LocKind::Function { + if let Some(callee) = location.fn_id { + for &fact in &facts { + pag.materialize_binding(program, &program.flow[fact], callee); + } + } + } + } + if before != pag.constraints.len() { + activate_new_constraints(pag, program, &mut st, &mut scratch, before); + } + } + } if delta.is_empty() { // First touch with no pointees: apply constraints whose effect // does not depend on points-to content (addr-of seeding and the @@ -1559,13 +1603,25 @@ fn solve( let caller_target = program.symbols.function(cs.caller).target; for &loc in delta.iter() { if let Some(fn_id) = fn_for_loc(pag, loc) { - if cs.args_bound_past_this { - new_callees.extend(member_pointer_targets( - program, - cs, - fn_id, - pag.is_reinterpreted_location(loc), - )); + if pag.locations[loc.0 as usize].kind == LocKind::Bound { + if wired_bindings.insert((cs.id, loc)) { + new_callees.extend( + reached_definitions(program, fn_id, caller_target) + .into_iter() + .map(|callee| (callee, Some(loc))), + ); + } + } else if cs.args_bound_past_this { + new_callees.extend( + member_pointer_targets( + program, + cs, + fn_id, + pag.is_reinterpreted_location(loc), + ) + .into_iter() + .map(|callee| (callee, None)), + ); } else { if pag.is_reinterpreted_location(loc) && cs.callee_var.is_some_and(|var| { @@ -1584,20 +1640,69 @@ fn solve( { continue; } - new_callees.extend(reached_definitions(program, fn_id, caller_target)); + new_callees.extend( + reached_definitions(program, fn_id, caller_target) + .into_iter() + .map(|callee| (callee, None)), + ); } } } let prev = resolved_indirect.entry(cs_id).or_default(); - for callee in new_callees { - if !prev.contains(&callee) { - prev.push(callee); - call_edges.push(CallGraphEdge { - call_site: cs.id, - caller: cs.caller, + for (callee, bound_loc) in new_callees { + let ordinary = bound_loc.is_none(); + let (new_edge, wire_ordinary) = if let Some((_, wired)) = + prev.iter_mut().find(|(target, _)| *target == callee) + { + (false, ordinary && !std::mem::replace(wired, true)) + } else { + prev.push((callee, ordinary)); + (true, ordinary) + }; + if let Some(loc) = bound_loc { + let binding = pag.bound_callables[&loc].clone(); + wire_bound_callable( + pag, + program, + &mut st, + &mut scratch, + &InvocationSite::source(cs), callee, - resolution: ResolutionKind::Indirect, - }); + &binding, + |position| invoke_site_index(cs, position), + ); + let name = &program.symbols.function(callee).name; + let invokes = invoked.get(&callee); + if invokes.is_some() || models.model(name, EffectGroup::Args).is_some() { + let site = compose_bound_site(program, cs, callee, &binding); + apply_fn_model( + pag, + program, + &mut st, + &mut scratch, + site.arguments(), + name, + models, + &mut terminator_events, + ); + if invokes.is_some() { + wire_invocations( + pag, + program, + &mut st, + &mut scratch, + &site, + invokes, + &mut invoke_watch, + ); + bound_model_sites + .entry((cs.id, callee)) + .or_default() + .push(site); + } + } + } + if wire_ordinary { wire_params( pag, program, @@ -1607,6 +1712,14 @@ fn solve( &mut scratch, &mut wired_arg_flow, ); + } + if new_edge { + call_edges.push(CallGraphEdge { + call_site: cs.id, + caller: cs.caller, + callee, + resolution: ResolutionKind::Indirect, + }); // Expand return flows from the callee into the // `CallReturnIndirect` destination so the return // value reaches the assignment LHS (e.g. @@ -1628,7 +1741,7 @@ fn solve( models, &mut visited, ); - activate_return_constraints( + activate_new_constraints( pag, program, &mut st, @@ -1648,14 +1761,10 @@ fn solve( models, &mut FxHashSet::default(), ); - activate_return_constraints( - pag, - program, - &mut st, - &mut scratch, - before, - ); + activate_new_constraints(pag, program, &mut st, &mut scratch, before); } + } + if wire_ordinary { apply_fn_model( pag, program, @@ -1671,7 +1780,7 @@ fn solve( program, &mut st, &mut scratch, - cs, + &InvocationSite::source(cs), invoked.get(&callee), &mut invoke_watch, ); @@ -1684,21 +1793,29 @@ fn solve( // the arguments the callee forwards reach its parameters. // Nearly always empty: no lookup per pop for a program that hands // no callback variable to a forwarding model. - if let Some(watchers) = (!invoke_watch.is_empty()) - .then(|| invoke_watch.get(&node)) + if let Some(watchers) = (!invoke_watch.by_node.is_empty()) + .then(|| invoke_watch.by_node.get(&node)) .flatten() { - let gained: Vec = delta.iter().filter_map(|&l| fn_for_loc(pag, l)).collect(); for (cs, invoked) in watchers { - for &callback in &gained { - wire_callback(pag, program, &mut st, &mut scratch, cs, callback, invoked); + for &loc in delta.iter() { + wire_callback(pag, program, &mut st, &mut scratch, cs, loc, invoked); } } } } - let (callbacks, invocations) = callback_edges(program, pag, &st, &invoked, &call_edges); + let (callbacks, invocations) = callback_edges( + program, + pag, + &st, + &invoked, + &call_edges, + &resolved_indirect, + &bound_model_sites, + ); call_edges.extend(callbacks); + drop(bound_model_sites); // Emit synthetic call edges for IPC proxy→stub bridges detected at PAG // build. These connect the proxy method to the stub handler it would @@ -1737,6 +1854,17 @@ fn solve( ) }); let forwarded_arg_flow = std::mem::take(&mut st.forwarded_arg_flow); + let mut bound_arg_flow = std::mem::take(&mut st.bound_arg_flow); + bound_arg_flow.sort_unstable_by_key(|edge| { + ( + edge.call_site, + edge.arg_index, + edge.formal, + edge.actual_var, + edge.actual_address, + edge.actual_fn, + ) + }); let memory_accesses = crate::memory::memory_accesses(pag, &st.pts, &st.designated); let points_to = if retain_points_to { std::mem::take(&mut st.pts).into_iter().collect() @@ -1749,6 +1877,7 @@ fn solve( drop(invoke_watch); drop(invoked); drop(resolved_indirect); + drop(wired_bindings); drop(unwrap_memo); drop(new_in_order); drop(scratch); @@ -1792,7 +1921,7 @@ fn solve( AnalysisResult { points_to, call_edges, - arg_flow_edges: Vec::new(), + arg_flow_edges: bound_arg_flow, wired_arg_flow, forwarded_arg_flow, terminator_events, @@ -1827,7 +1956,7 @@ fn apply_fn_model( cs: &trace_ir::CallSite, callee_name: &str, models: &ModelLookup, - terminator_events: &mut Vec<(CallSiteId, u32)>, + terminator_events: &mut Vec<(CallSiteId, u32, VarId)>, ) { let Some(model) = models.model(callee_name, EffectGroup::Args) else { return; @@ -1951,8 +2080,8 @@ fn apply_fn_model( } } Effect::Clears { param } => { - if arg_node(pag, *param).is_some() { - let event = (cs.id, *param); + if let Some(actual) = pag.argument_var(cs, *param) { + let event = (cs.id, *param, actual); if st.terminators_seen.insert(event) { terminator_events.push(event); } @@ -1992,9 +2121,9 @@ fn wire_epoll_copy( } } -/// A callee may resolve after a returned value's source has already settled. -/// Replay those facts through the newly indexed edges as well as future deltas. -fn activate_return_constraints( +/// A solver-created edge may have a settled source. Replay its existing +/// values and index the edge for future deltas. +fn activate_new_constraints( pag: &mut Pag, program: &Program, st: &mut SolverState, @@ -2025,7 +2154,10 @@ fn unwrap_admits( pointee: trace_ir::TypeId, ) -> bool { let loc = &pag.locations[loc.0 as usize]; - if matches!(loc.kind, LocKind::Function | LocKind::StringLit) { + if matches!( + loc.kind, + LocKind::Function | LocKind::Bound | LocKind::StringLit + ) { return false; } *memo @@ -2604,7 +2736,7 @@ fn wire_params( st, scratch, Some, - |st, formal, arg| { + |_, st, formal, arg| { if formal == arg { wired.insert((cs.id, formal, callee)); } else { @@ -2645,7 +2777,7 @@ fn recorded_position(program: &Program, cs: &trace_ir::CallSite, idx: u32) -> Op } /// Wire `cs`'s actuals into `callee`'s formals: formal `i` takes what the site -/// records at position `actual_of(i)`, and `on_wired(st, i, at)` records each +/// records at position `actual_of(i)`, and `on_wired` records each /// formal that took something and the position it was recorded at, for the /// arg-flow rows. An ordinary call passes position `i` to formal `i`; a /// callback a model invokes takes the positions the model forwards; a pack @@ -2660,7 +2792,7 @@ fn wire_actuals( st: &mut SolverState, scratch: &mut Scratch, actual_of: impl Fn(u32) -> Option, - mut on_wired: impl FnMut(&mut SolverState, u32, u32), + mut on_wired: impl FnMut(&Pag, &mut SolverState, u32, u32), ) { let callee_fn = program.symbols.function(callee); let this = u32::from(program.symbols.has_this_param(callee)); @@ -2751,39 +2883,11 @@ fn wire_one( formal: VarId, formal_idx: u32, at: u32, - on_wired: &mut impl FnMut(&mut SolverState, u32, u32), + on_wired: &mut impl FnMut(&Pag, &mut SolverState, u32, u32), ) { let mut wired = false; for &(_, actual) in cs.var_args.iter().filter(|(j, _)| *j == at) { - let formal_node = pag.var_node.get(&formal).copied().expect("formal var node"); - let actual_node = pag.var_node.get(&actual).copied().expect("actual var node"); - // Persistent copy constraint: the actual's points-to may still be - // growing when the edge is first discovered (direct sites are - // wired before the first propagation round). A one-shot snapshot - // here loses interprocedural flow (observed as missed indirect - // targets passed through parameters). Scalars cannot contribute - // pointees and are skipped to bound constraint volume. - let actual_pointee = var_may_hold_pointee(program, actual); - let formal_pointee = var_may_hold_pointee(program, formal); - // Erasure can hide a callback slot or aggregate, but a known scalar - // buffer on either side still cannot carry callable contents. - let carries_pointee = (actual_pointee || var_is_opaque_pointer(program, actual)) - && (formal_pointee || var_is_opaque_pointer(program, formal)); - if carries_pointee && st.wired_copies.insert((actual_node, formal_node)) { - ensure_param_copy(pag, st, actual_node, formal_node); - } - if let Some(actual_pts) = st.pts.get(&actual_node) { - // Snapshotted rather than cloned: this used to copy the - // actual's whole points-to set once per wired argument. - scratch.wire_src.clear(); - scratch.wire_src.extend(actual_pts.iter().copied()); - propagate_locs( - st, - &mut scratch.fresh, - formal_node, - scratch.wire_src.iter().copied(), - ); - } + wire_var_actual(pag, program, st, scratch, formal, actual); wired = true; } // A name with overloads passes each one it may mean; an expansion's @@ -2799,10 +2903,150 @@ fn wire_one( wired = true; } if wired { - on_wired(st, formal_idx, at); + on_wired(pag, st, formal_idx, at); } } +/// Connect an actual variable to a formal and replay its current value. +fn wire_var_actual( + pag: &mut Pag, + program: &Program, + st: &mut SolverState, + scratch: &mut Scratch, + formal: VarId, + actual: VarId, +) { + let formal_node = pag.var_node.get(&formal).copied().expect("formal var node"); + let actual_node = pag.var_node.get(&actual).copied().expect("actual var node"); + // Persistent copy constraint: the actual's points-to may still be + // growing when the edge is first discovered (direct sites are + // wired before the first propagation round). A one-shot snapshot + // here loses interprocedural flow (observed as missed indirect + // targets passed through parameters). Scalars cannot contribute + // pointees and are skipped to bound constraint volume. + let actual_pointee = var_may_hold_pointee(program, actual); + let formal_pointee = var_may_hold_pointee(program, formal); + // Erasure can hide a callback slot or aggregate, but a known scalar + // buffer on either side still cannot carry callable contents. + let carries_pointee = (actual_pointee || var_is_opaque_pointer(program, actual)) + && (formal_pointee || var_is_opaque_pointer(program, formal)); + if carries_pointee && st.wired_copies.insert((actual_node, formal_node)) { + ensure_param_copy(pag, st, actual_node, formal_node); + } + if let Some(actual_pts) = st.pts.get(&actual_node) { + // Snapshotted rather than cloned: this used to copy the + // actual's whole points-to set once per wired argument. + scratch.wire_src.clear(); + scratch.wire_src.extend(actual_pts.iter().copied()); + propagate_locs( + st, + &mut scratch.fresh, + formal_node, + scratch.wire_src.iter().copied(), + ); + } +} + +#[allow(clippy::too_many_arguments)] +fn wire_bound_callable( + pag: &mut Pag, + program: &Program, + st: &mut SolverState, + scratch: &mut Scratch, + site: &InvocationSite<'_>, + callee: FnId, + binding: &BoundCallable, + invocation_position: impl Fn(u32) -> Option, +) { + let cs = site.arguments(); + let function = program.symbols.function(callee); + let bindings = bound_slots(program, callee, binding); + for (i, (&formal, bound)) in function.params.iter().zip(bindings).enumerate() { + let index = i as u32; + let (actual_var, actual_address, actual_fn) = match bound { + BoundArg::Stored(var) + | BoundArg::AddressOf(var) + | BoundArg::MemberAddress(var) + | BoundArg::Pack(var) => { + wire_var_actual(pag, program, st, scratch, formal, var); + let addr_of = matches!(bound, BoundArg::AddressOf(_)); + ( + Some(pag.argument_var_for_value(var, addr_of)), + addr_of.then_some(var), + None, + ) + } + BoundArg::Function(function) => { + if let Some(&loc) = pag.fn_locations.get(&function) { + add_pts(st, pag.var_node[&formal], loc); + } + (None, None, Some(function)) + } + BoundArg::Placeholder(n) => { + if let Some(at) = n + .checked_sub(1) + .and_then(&invocation_position) + .and_then(|at| recorded_position(program, cs, at)) + { + wire_one( + pag, + program, + cs, + st, + scratch, + formal, + index, + at, + &mut |pag, st, formal, arg| { + record_model_forwarded(program, pag, st, site, callee, formal, arg); + }, + ); + } + continue; + } + BoundArg::Opaque => continue, + }; + st.bound_arg_flow.push(ArgFlowEdge { + call_site: cs.id, + arg_index: index, + actual_var, + actual_address, + actual_fn, + formal, + }); + } +} + +fn bound_slots<'a>( + program: &Program, + target: FnId, + binding: &'a BoundCallable, +) -> impl Iterator + 'a { + let receiver = binding.receiver.or_else(|| { + program + .symbols + .has_this_param(target) + .then_some(BoundArg::Opaque) + }); + let (fixed, pack) = match binding.args.split_last() { + Some((BoundArg::Pack(var), fixed)) => (fixed, Some(BoundArg::Stored(*var))), + _ => (binding.args.as_slice(), None), + }; + let count = pack.map_or(0, |_| { + let f = program.symbols.function(target); + let this = usize::from(receiver.is_some()); + let declared = f.explicit_arity.map_or(0, |arity| arity as usize + this); + f.params + .len() + .max(declared) + .saturating_sub(this + fixed.len()) + }); + receiver.into_iter().chain(fixed.iter().copied()).chain( + pack.into_iter() + .flat_map(move |arg| std::iter::repeat_n(arg, count)), + ) +} + fn add_pts(st: &mut SolverState, node: PagNodeId, loc: LocId) { let inserted = { let entry = st.pts.entry(node).or_default(); @@ -2837,10 +3081,180 @@ struct Invoked<'m> { /// The `invoke` effects of one modelled callee. type Invocations<'m> = Vec>; +/// The arguments a model sees, together with the original source site. +/// Composed arguments are shared by propagation and the callback edge pass. +#[derive(Clone)] +struct InvocationSite<'m> { + source: &'m CallSite, + composed: Option>, +} + +struct ComposedArguments { + /// Solver-local copy. Its identity still names the original call site. + call: CallSite, + /// Positions to report at the source site when the model forwards values. + source_positions: Vec, +} + +impl<'m> InvocationSite<'m> { + fn source(source: &'m CallSite) -> Self { + Self { + source, + composed: None, + } + } + + fn arguments(&self) -> &CallSite { + self.composed + .as_ref() + .map_or(self.source, |args| &args.call) + } + + fn same_call(&self, other: &Self) -> bool { + self.source.id == other.source.id + && match (&self.composed, &other.composed) { + (None, None) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + _ => false, + } + } +} + +fn compose_bound_site<'m>( + program: &Program, + source: &'m CallSite, + target: FnId, + binding: &BoundCallable, +) -> InvocationSite<'m> { + let mut call = source.clone(); + call.var_args.clear(); + let mut fn_args = Vec::new(); + let mut addr_of_args = Vec::new(); + let mut addr_of_member_args = Vec::new(); + let mut source_positions = Vec::new(); + for (index, arg) in bound_slots(program, target, binding).enumerate() { + let index = index as u32; + let mut position = index; + match arg { + BoundArg::Stored(var) | BoundArg::Pack(var) => call.var_args.push((index, var)), + BoundArg::AddressOf(var) => { + call.var_args.push((index, var)); + addr_of_args.push(index); + } + BoundArg::MemberAddress(var) => { + call.var_args.push((index, var)); + addr_of_member_args.push(index); + } + BoundArg::Function(f) => fn_args.push((index, f)), + BoundArg::Placeholder(n) => { + if let Some(at) = n + .checked_sub(1) + .and_then(|i| invoke_site_index(source, i)) + .and_then(|i| recorded_position(program, source, i)) + { + position = at; + call.var_args + .extend(args_at(&source.var_args, at).map(|v| (index, v))); + fn_args.extend(args_at(source.fn_args(), at).map(|f| (index, f))); + if source.addr_of_args().contains(&at) { + addr_of_args.push(index); + } + if source.addr_of_member_args().contains(&at) { + addr_of_member_args.push(index); + } + } + } + BoundArg::Opaque => {} + } + source_positions.push(position); + } + call.args_bound_past_this = + binding.receiver.is_some() || program.symbols.has_this_param(target); + call.receiver = binding + .receiver + .and_then(|_| args_at(&call.var_args, 0).next()); + call.details = CallSiteDetails::boxed(fn_args, addr_of_member_args, addr_of_args, None); + InvocationSite { + source, + composed: Some(Arc::new(ComposedArguments { + call, + source_positions, + })), + } +} + +fn record_model_forwarded( + program: &Program, + pag: &Pag, + st: &mut SolverState, + site: &InvocationSite<'_>, + callee: FnId, + formal: u32, + arg: u32, +) { + if let Some(composed) = &site.composed { + // These positions name the composed argument list. Export its actual + // value at the source site instead of reading that site's raw args. + append_argument_rows( + pag, + &composed.call, + arg, + composed.source_positions[arg as usize], + program.symbols.function(callee).params[formal as usize], + &mut st.bound_arg_flow, + ); + } else { + record_forwarded(st, site.source.id, callee, (formal, arg)); + } +} + /// Callback variables handed to a modelled callee that forwards arguments, /// by PAG node, with the call sites that hand them over: a function reaching /// such a variable is wired like an indirect call's target. -type InvokeWatch<'m> = FxHashMap)>>; +type InvocationWatchers<'m> = FxHashMap, Invoked<'m>)>>; + +#[derive(Default)] +struct InvokeWatch<'m> { + by_node: InvocationWatchers<'m>, + // Zero-argument effects need a watcher only for a variable that holds + // a bound value. Until then, keep one entry for the call and effect. + awaiting_bound: Vec<(InvocationSite<'m>, Invoked<'m>)>, +} + +impl InvokeWatch<'_> { + fn activate_empty( + &mut self, + pag: &mut Pag, + program: &Program, + st: &mut SolverState, + scratch: &mut Scratch, + ) { + if pag.bound_callables.is_empty() { + return; + } + for (site, invoked) in &self.awaiting_bound { + let cs = site.arguments(); + let Some(index) = invoke_site_index(cs, invoked.param) else { + continue; + }; + for var in args_at(&cs.var_args, index) { + watch_invocation_variable( + pag, + program, + st, + scratch, + site, + invoked, + var, + &mut self.by_node, + ); + } + } + } +} +type BoundModelSites<'m> = FxHashMap<(CallSiteId, FnId), Vec>>; +/// Each target and whether an ordinary function value also reaches it. +type IndirectTargets = FxHashMap>; /// The callees a model says may invoke a callback argument, with the argument /// positions it names (`docs/MODELS.md`, "Function models"). Read off the @@ -2959,18 +3373,19 @@ fn args_at(args: &[(u32, T)], index: u32) -> impl Iterator + .map(|(_, v)| *v) } -/// The functions variable `var` may hold, in its points-to set's order. -fn held_functions<'a>( +/// The callable values a variable may hold, in its points-to set's order. +fn held_callables<'a>( pag: &'a Pag, st: &'a SolverState, var: VarId, -) -> impl Iterator + 'a { +) -> impl Iterator + 'a { pag.var_node .get(&var) .and_then(|node| st.pts.get(node)) .into_iter() .flatten() - .filter_map(|loc| fn_for_loc(pag, *loc)) + .copied() + .filter(|&loc| fn_for_loc(pag, loc).is_some()) } /// Whether this call site hands one of the caller's own modelled callback @@ -3007,6 +3422,14 @@ const RECEIVER_SKIPS: usize = 2; /// The supplied values that may lead forwarded arguments: none or one. const LEADS: usize = 2; +/// A known type selects the applicable lead. An unknown type admits both. +fn supplied_leads(supplied: Option) -> [Option; LEADS] { + [ + (supplied != Some(true)).then_some(0), + (supplied != Some(false)).then_some(1), + ] +} + /// The ways a callback can take forwarded arguments ([`invoke_alignments`]), /// in the order first found, each once: one per receiver skip and supplied /// lead at most. Skipping no receiver behind a supplied value and skipping @@ -3066,10 +3489,7 @@ fn invoke_alignments( var_is_value_of(program, formal, class) }) }); - [ - (supplied != Some(true)).then_some(0), - (supplied != Some(false)).then_some(1), - ] + supplied_leads(supplied) }; // The ways among `typed` that `fits` has room for. A callable that takes // the supplied value but has no room for it ahead of the arguments is @@ -3143,6 +3563,30 @@ fn invoke_alignments( Alignments::from_grid(grid) } +/// The supplied value, if present, reaches the formals fed by `_1`. +/// Its slot shifts every later placeholder even though it has no IR value. +fn bound_invoke_alignments( + program: &Program, + target: FnId, + binding: &BoundCallable, + invoked: &Invoked, +) -> Alignments { + let supplied = invoked.supplies.map_or(Some(false), |name| { + let class = class_type(name); + let mut consumers = program + .symbols + .function(target) + .params + .iter() + .zip(bound_slots(program, target, binding)) + .filter(|(_, arg)| *arg == BoundArg::Placeholder(1)) + .map(|(&formal, _)| var_is_value_of(program, formal, &class)); + let first = consumers.next().flatten()?; + consumers.all(|value| value == Some(first)).then_some(first) + }); + Alignments::from_grid([supplied_leads(supplied), [None; LEADS]]) +} + /// The definitions a callback handed over as `callback` runs when a model /// invokes it with `args` at `cs`: those an indirect call from the caller /// reaches ([`reached_definitions`]) that can take the arguments, each with @@ -3151,15 +3595,23 @@ fn invoke_targets<'a>( program: &'a Program, cs: &'a trace_ir::CallSite, callback: FnId, + bound: Option<&'a BoundCallable>, invoked: &'a Invoked<'a>, ) -> impl Iterator + 'a { let caller_target = program.symbols.function(cs.caller).target; - reached_definitions(program, callback, caller_target) - .into_iter() - .filter_map(move |target| { - let alignments = invoke_alignments(program, cs, target, invoked); - (alignments.len > 0).then_some((target, alignments)) - }) + let targets = if bound.is_some() && invoked.model == "std::packaged_task::packaged_task" { + Vec::new() + } else { + reached_definitions(program, callback, caller_target) + }; + targets.into_iter().filter_map(move |target| { + let alignments = if let Some(binding) = bound { + bound_invoke_alignments(program, target, binding, invoked) + } else { + invoke_alignments(program, cs, target, invoked) + }; + (alignments.len > 0).then_some((target, alignments)) + }) } /// Parameter wiring for the callbacks handed to a modelled callee at `cs` @@ -3174,40 +3626,84 @@ fn wire_invocations<'m>( program: &Program, st: &mut SolverState, scratch: &mut Scratch, - cs: &'m trace_ir::CallSite, + site: &InvocationSite<'m>, invocations: Option<&Invocations<'m>>, watch: &mut InvokeWatch<'m>, ) { + let cs = site.arguments(); for &invoked in invocations.into_iter().flatten() { - if invoked.args.is_empty() || !invocation_applies(program, cs, &invoked) { + let empty = invoked.args.is_empty(); + if (empty && pag.bound_callables.is_empty() && pag.bind_sources.is_empty()) + || !invocation_applies(program, cs, &invoked) + { continue; } let Some(index) = invoke_site_index(cs, invoked.param) else { continue; }; + if empty { + if args_at(&cs.var_args, index).next().is_some() { + watch.awaiting_bound.push((site.clone(), invoked)); + } + continue; + } for callback in args_at(cs.fn_args(), index) { - wire_callback(pag, program, st, scratch, cs, callback, &invoked); + if let Some(&loc) = pag.fn_locations.get(&callback) { + wire_callback(pag, program, st, scratch, site, loc, &invoked); + } } for var in args_at(&cs.var_args, index) { - let Some(&node) = pag.var_node.get(&var) else { - continue; - }; - let watchers = watch.entry(node).or_default(); - if watchers.iter().any(|&(c, w)| c.id == cs.id && w == invoked) { - continue; - } - watchers.push((cs, invoked)); - // A settled variable never pops again: wire what it holds now, - // in an order its hash set does not decide. - let mut held: Vec = held_functions(pag, st, var).collect(); - held.sort_unstable(); - for callback in held { - wire_callback(pag, program, st, scratch, cs, callback, &invoked); - } + watch_invocation_variable( + pag, + program, + st, + scratch, + site, + &invoked, + var, + &mut watch.by_node, + ); } } } +#[allow(clippy::too_many_arguments)] +fn watch_invocation_variable<'m>( + pag: &mut Pag, + program: &Program, + st: &mut SolverState, + scratch: &mut Scratch, + site: &InvocationSite<'m>, + invoked: &Invoked<'m>, + var: VarId, + watch: &mut InvocationWatchers<'m>, +) { + let Some(&node) = pag.var_node.get(&var) else { + return; + }; + let empty = invoked.args.is_empty(); + if empty && !held_callables(pag, st, var).any(|loc| pag.bound_callables.contains_key(&loc)) { + return; + } + let watchers = watch.entry(node).or_default(); + if watchers + .iter() + .any(|(other, effect)| *effect == *invoked && site.same_call(other)) + { + return; + } + watchers.push((site.clone(), *invoked)); + // A settled variable never pops again. Wire its current values in a + // stable order, then let the watcher handle future deltas. + let mut held: Vec<_> = held_callables(pag, st, var) + .filter(|loc| !empty || pag.bound_callables.contains_key(loc)) + .collect(); + held.sort_unstable_by_key(|&loc| (fn_for_loc(pag, loc), loc)); + for loc in held { + wire_callback(pag, program, st, scratch, site, loc, invoked); + } +} + /// Wire the arguments a modelled callee forwards at `cs` into the formals of /// `callback`'s definitions, as [`wire_params`] does for an indirect call's /// target, in each way the callback can take them ([`invoke_alignments`]). @@ -3216,15 +3712,28 @@ fn wire_callback( program: &Program, st: &mut SolverState, scratch: &mut Scratch, - cs: &trace_ir::CallSite, - callback: FnId, + site: &InvocationSite<'_>, + callable: LocId, invoked: &Invoked, ) { + let cs = site.arguments(); + let Some(callback) = fn_for_loc(pag, callable) else { + return; + }; let args = invoked.args; - for (target, alignments) in invoke_targets(program, cs, callback, invoked) { + let bound = (pag.locations[callable.0 as usize].kind == LocKind::Bound) + .then(|| pag.bound_callables[&callable].clone()); + if args.is_empty() && bound.is_none() { + return; + } + for (target, alignments) in invoke_targets(program, cs, callback, bound.as_ref(), invoked) { for &skip in alignments.as_slice() { let actual_of = |formal: u32| invoke_site_index(cs, args.actual_for(formal.checked_sub(skip)?)?); + if let Some(binding) = &bound { + wire_bound_callable(pag, program, st, scratch, site, target, binding, actual_of); + continue; + } wire_actuals( pag, program, @@ -3233,7 +3742,9 @@ fn wire_callback( st, scratch, actual_of, - |st, formal, arg| record_forwarded(st, cs.id, target, (formal, arg)), + |pag, st, formal, arg| { + record_model_forwarded(program, pag, st, site, target, formal, arg); + }, ); } } @@ -3253,6 +3764,8 @@ fn callback_edges<'m>( st: &SolverState, invoked: &FxHashMap>, call_edges: &[CallGraphEdge], + resolved_indirect: &IndirectTargets, + bound_model_sites: &BoundModelSites<'_>, ) -> (Vec, Vec>) { let mut edges = Vec::new(); let mut invocations = Vec::new(); @@ -3273,52 +3786,72 @@ fn callback_edges<'m>( let Some(cs) = program.symbols.call_site_by_id(edge.call_site) else { continue; }; - for effect in params { - if !invocation_applies(program, cs, effect) { - continue; - } - let Invoked { - param, - context, - model, - .. - } = *effect; - let Some(index) = invoke_site_index(cs, param) else { - continue; - }; - // A modelled API forwarding its own callback parameter to - // another modelled API (`SubmitTask(task, name)` calling - // `SubmitTask(task, attr)`) would rebroadcast the parameter's - // whole points-to set — every callback handed to the API - // anywhere — as an edge from the API body. The outer submission - // site already resolves the concrete callback; skipping the - // forward keeps the graph from carrying that union once per - // forwarding overload. Only a context-less inner effect is - // skipped: one that starts a context keeps its edge and context, - // so no execution context is lost. - if context.is_none() && forwards_own_callback(program, cs, index, invoked) { - continue; - } - let start = ContextStart { - call_site: cs.id, - api: edge.callee, - param, - receiver: cs.receiver, - }; - let named = args_at(cs.fn_args(), index); - let pointed = args_at(&cs.var_args, index).flat_map(|var| held_functions(pag, st, var)); - for callee in named.chain(pointed) { - for (target, _) in invoke_targets(program, cs, callee, effect) { - if let Some(context) = context { - invocations.push((start, target, context, model)); - } - if seen.insert((cs.id, target)) { - edges.push(CallGraphEdge { - call_site: cs.id, - caller: cs.caller, - callee: target, - resolution: ResolutionKind::Indirect, - }); + let composed = bound_model_sites.get(&(edge.call_site, edge.callee)); + let ordinary = composed.is_none() + || resolved_indirect + .get(&edge.call_site) + .is_some_and(|targets| targets.contains(&(edge.callee, true))); + let source = InvocationSite::source(cs); + for site in ordinary + .then_some(&source) + .into_iter() + .chain(composed.into_iter().flatten()) + { + let cs = site.arguments(); + for effect in params { + if !invocation_applies(program, cs, effect) { + continue; + } + let Invoked { + param, + context, + model, + .. + } = *effect; + let Some(index) = invoke_site_index(cs, param) else { + continue; + }; + // A modelled API forwarding its own callback parameter to + // another modelled API (`SubmitTask(task, name)` calling + // `SubmitTask(task, attr)`) would rebroadcast the parameter's + // whole points-to set — every callback handed to the API + // anywhere — as an edge from the API body. The outer submission + // site already resolves the concrete callback; skipping the + // forward keeps the graph from carrying that union once per + // forwarding overload. Only a context-less inner effect is + // skipped: one that starts a context keeps its edge and context, + // so no execution context is lost. + if context.is_none() && forwards_own_callback(program, cs, index, invoked) { + continue; + } + let start = ContextStart { + call_site: cs.id, + api: edge.callee, + param, + receiver: cs.receiver, + }; + let named = + args_at(cs.fn_args(), index).filter_map(|f| pag.fn_locations.get(&f).copied()); + let pointed = + args_at(&cs.var_args, index).flat_map(|var| held_callables(pag, st, var)); + for loc in named.chain(pointed) { + let location = &pag.locations[loc.0 as usize]; + let Some(callback) = location.fn_id else { + continue; + }; + let bound = pag.bound_callables.get(&loc); + for (target, _) in invoke_targets(program, cs, callback, bound, effect) { + if let Some(context) = context { + invocations.push((start, target, context, model)); + } + if seen.insert((cs.id, target)) { + edges.push(CallGraphEdge { + call_site: cs.id, + caller: cs.caller, + callee: target, + resolution: ResolutionKind::Indirect, + }); + } } } } @@ -3446,15 +3979,54 @@ fn member_pointer_targets( targets } +/// The function a location names as a value: an ordinary function's own +/// location, or the one a bound callable wraps (docs/IR.md, "Bound +/// callables"), which every rule that moves a function value treats the +/// same. Its bound receiver and arguments are in [`Pag::bound_callables`]. fn fn_for_loc(pag: &Pag, loc: LocId) -> Option { let abstract_loc = &pag.locations[loc.0 as usize]; - if abstract_loc.kind == LocKind::Function { + if matches!(abstract_loc.kind, LocKind::Function | LocKind::Bound) { abstract_loc.fn_id } else { None } } +fn append_argument_rows( + pag: &Pag, + cs: &CallSite, + recorded: u32, + arg_index: u32, + formal: VarId, + arg_flow_edges: &mut Vec, +) { + if let Some(actual) = pag.argument_var(cs, recorded) { + arg_flow_edges.push(ArgFlowEdge { + call_site: cs.id, + arg_index, + actual_var: Some(actual), + actual_address: cs + .addr_of_args() + .contains(&recorded) + .then(|| args_at(&cs.var_args, recorded).next()) + .flatten(), + actual_fn: None, + formal, + }); + } else { + for &(_, fn_id) in cs.fn_args().iter().filter(|(j, _)| *j == recorded) { + arg_flow_edges.push(ArgFlowEdge { + call_site: cs.id, + arg_index, + actual_var: None, + actual_address: None, + actual_fn: Some(fn_id), + formal, + }); + } + } +} + fn extract_arg_flow( program: &Program, pag: &Pag, @@ -3476,27 +4048,8 @@ fn extract_arg_flow( .filter(|c| c.id == edge.call_site) .expect("call site for edge"); let callee = program.symbols.function(edge.callee); - // One row per variable or function passed at `arg_index`. let mut push_rows = |arg_index: u32, formal: VarId| { - if let Some(actual) = pag.argument_var(cs, arg_index) { - arg_flow_edges.push(ArgFlowEdge { - call_site: edge.call_site, - arg_index, - actual_var: Some(actual), - actual_fn: None, - formal, - }); - } else { - for &(_, fn_id) in cs.fn_args().iter().filter(|(j, _)| *j == arg_index) { - arg_flow_edges.push(ArgFlowEdge { - call_site: edge.call_site, - arg_index, - actual_var: None, - actual_fn: Some(fn_id), - formal, - }); - } - } + append_argument_rows(pag, cs, arg_index, arg_index, formal, arg_flow_edges); }; for (i, formal) in callee.params.iter().enumerate() { let idx = i as u32; diff --git a/crates/trace-analysis/src/summaries.rs b/crates/trace-analysis/src/summaries.rs index 7a872bae..9a791595 100644 --- a/crates/trace-analysis/src/summaries.rs +++ b/crates/trace-analysis/src/summaries.rs @@ -44,7 +44,7 @@ pub enum Effect { /// The callee may invoke the callback in `param[param]`, passing it /// `args`, in an execution context of kind `context`, or in none when /// `context` is `None`: a model that only wraps the callback - /// (`std::bind`) keeps the call edge and the argument wiring but starts + /// keeps the call edge and the argument wiring but starts /// nothing. Parameter indexes count explicit arguments, excluding a /// member's `this`. Not restricted to a bodyless callee, unlike the /// effects above that introduce a value. @@ -383,10 +383,8 @@ impl FnModelSet { }) .collect(), ); - // Wrappers that keep a callable reachable without running it where - // they are built: the edge is the wrapping site's, since no value - // carries the callable on (`docs/MODELS.md`, "Callable wrappers"). - reg("std::bind", wraps(0, InvokeArgs::Rest(1))); + // Retain the legacy reachability edge for a packaged task's + // unbound callable. Bind expressions produce separate callable values. reg( "std::packaged_task::packaged_task", wraps(0, InvokeArgs::Rest(1)), @@ -1226,13 +1224,11 @@ effects = [ { kind = "dlsym", param = 1 } ] #[test] fn builtin_wrappers_start_no_context() { let m = FnModelSet::builtin(); - for name in ["std::bind", "std::packaged_task::packaged_task"] { - assert_eq!( - m.get(name).unwrap().effects, - wraps(0, InvokeArgs::Rest(1)), - "{name} keeps its callable reachable and starts nothing" - ); - } + assert!(m.get("std::bind").is_none()); + assert_eq!( + m.get("std::packaged_task::packaged_task").unwrap().effects, + wraps(0, InvokeArgs::Rest(1)), + ); } #[test] @@ -1552,11 +1548,6 @@ effects = [{ kind = "invoke", param = 0, rest = 1 }] when: None, }] ); - assert_eq!( - effects("std::bind"), - wraps(0, InvokeArgs::Rest(1)), - "the callable and the arguments bound after it" - ); assert_eq!( effects("std::packaged_task::packaged_task"), wraps(0, InvokeArgs::Rest(1)), diff --git a/crates/trace-capi/include/trace.h b/crates/trace-capi/include/trace.h index c412a1bd..b42f3944 100644 --- a/crates/trace-capi/include/trace.h +++ b/crates/trace-capi/include/trace.h @@ -99,6 +99,7 @@ typedef enum trace_loc_kind { TRACE_LOC_ARRAY_SUMMARY = 7, /**< Array summary location for unknown index access. */ TRACE_LOC_FUNCTION = 8, /**< Function entry point location. */ TRACE_LOC_STRING_LIT = 9, /**< String literal constant interned abstract location. */ + TRACE_LOC_BOUND = 10, /**< Callable built by `std::bind`: names the function it wraps. */ TRACE_LOC_UNKNOWN = -1, /**< Not a loc node or unrecognized location kind. */ } trace_loc_kind; diff --git a/crates/trace-capi/src/inspect.rs b/crates/trace-capi/src/inspect.rs index 5656db51..f5853dc6 100644 --- a/crates/trace-capi/src/inspect.rs +++ b/crates/trace-capi/src/inspect.rs @@ -461,6 +461,7 @@ fn node_loc_kind(k: Option) -> TraceLocKind { Some(L::ArraySummary) => TraceLocKind::TraceLocArraySummary, Some(L::Function) => TraceLocKind::TraceLocFunction, Some(L::StringLit) => TraceLocKind::TraceLocStringLit, + Some(L::Bound) => TraceLocKind::TraceLocBound, } } diff --git a/crates/trace-capi/src/types.rs b/crates/trace-capi/src/types.rs index 623f5618..ca09b95d 100644 --- a/crates/trace-capi/src/types.rs +++ b/crates/trace-capi/src/types.rs @@ -48,6 +48,7 @@ pub enum TraceLocKind { TraceLocArraySummary = 7, TraceLocFunction = 8, TraceLocStringLit = 9, + TraceLocBound = 10, TraceLocUnknown = -1, } diff --git a/crates/trace-cli/tests/it/callable_wrappers.rs b/crates/trace-cli/tests/it/callable_wrappers.rs index 8c021b52..24d67ae7 100644 --- a/crates/trace-cli/tests/it/callable_wrappers.rs +++ b/crates/trace-cli/tests/it/callable_wrappers.rs @@ -1,6 +1,4 @@ -//! Callables wrapped by `std::bind` and `std::packaged_task` keep the call -//! edge from the code that wraps them (docs/MODELS.md, "Callable -//! wrappers"). +//! Legacy packaged-task reachability and context-less callable models. use crate::common; @@ -14,57 +12,31 @@ fn indirect(program: &Program, analysis: &AnalysisResult, caller: &str, callee: has_edge(program, analysis, caller, callee, ResolutionKind::Indirect) } -/// Whether `Worker::Step`'s `this` receives the variable `actual` of `caller`. -fn receives(program: &Program, analysis: &AnalysisResult, caller: &str, actual: &str) -> bool { - let this = local_variable(program, "Worker::Step", "this"); - let actual = local_variable(program, caller, actual); - analysis - .arg_flow_edges - .iter() - .any(|row| row.formal == this && row.actual_var == Some(actual)) -} - -#[test] -fn submit_reaches_the_callable_it_binds() { - let (p, a) = cpp_bind_packaged_task(); - assert!( - indirect(p, a, "Submit", "Work"), - "`Work` is only named inside `std::bind(std::forward(f), ...)`" - ); -} - -/// A parameter pack is followed (docs/POINTERS.md, "Variadic parameter -/// packs"): `Hit` goes into `Submit`'s `Args&&... args`, out through -/// `std::forward(args)...` into the bind, and so to `Work`'s `cb`. -#[test] -fn a_parameter_pack_carries_a_bound_argument_to_the_callable() { - let (p, a) = cpp_bind_packaged_task(); - assert!(indirect(p, a, "Submit", "Work")); - assert!( - must_not_have_edge(p, a, "Submit", "Hit"), - "`Hit` is only an argument; `Submit` never calls it" - ); - assert!( - indirect(p, a, "Work", "Hit"), - "`Hit` is passed to `Submit` through `Args&&... args` and bound to `Work`'s `cb`" - ); -} - -#[test] -fn a_pool_forwards_a_named_bound_argument_to_the_callable() { - let (p, a) = cpp_bind_packaged_task(); - assert!(indirect(p, a, "SubmitFixed", "FixedWork")); - assert!( - indirect(p, a, "FixedWork", "FixedHit"), - "`FixedHit` is the bound argument that reaches `FixedWork`'s `cb`" - ); -} - #[test] -fn a_plain_bind_reaches_the_callable_and_forwards_its_arguments() { +fn a_bind_without_an_invocation_creates_no_callback_edge() { let (p, a) = cpp_bind_packaged_task(); - assert!(indirect(p, a, "Bind", "BoundWork")); - assert!(indirect(p, a, "BoundWork", "BoundHit")); + for (caller, target) in [ + ("Submit", "Work"), + ("SubmitFixed", "FixedWork"), + ("Bind", "BoundWork"), + ("Worker::Start", "Worker::Step"), + ("StartOn", "Worker::Step"), + ] { + assert!( + must_not_have_edge(p, a, caller, target), + "{caller} -> {target}" + ); + } + for (caller, target) in [ + ("Work", "Hit"), + ("FixedWork", "FixedHit"), + ("BoundWork", "BoundHit"), + ] { + assert!( + must_not_have_edge(p, a, caller, target), + "{caller} -> {target}" + ); + } } #[test] @@ -82,26 +54,6 @@ fn a_packaged_task_built_from_a_callable_with_parameters_reaches_it() { ); } -#[test] -fn a_bind_of_a_member_function_reaches_it_from_the_binding_member() { - let (p, a) = cpp_bind_packaged_task(); - assert!(indirect(p, a, "Worker::Start", "Worker::Step")); - assert!( - receives(p, a, "Worker::Start", "this"), - "the bound `this` reaches `Worker::Step`'s `this`" - ); -} - -#[test] -fn a_bind_of_a_member_function_on_a_named_receiver_reaches_it() { - let (p, a) = cpp_bind_packaged_task(); - assert!(indirect(p, a, "StartOn", "Worker::Step")); - assert!( - receives(p, a, "StartOn", "worker"), - "the bound `&worker` reaches `Worker::Step`'s `this`" - ); -} - #[test] fn a_std_function_needs_no_model() { let (p, a) = cpp_bind_packaged_task(); diff --git a/crates/trace-cli/tests/it/fn_model_cases.rs b/crates/trace-cli/tests/it/fn_model_cases.rs index 1e6686ee..5f25f4dc 100644 --- a/crates/trace-cli/tests/it/fn_model_cases.rs +++ b/crates/trace-cli/tests/it/fn_model_cases.rs @@ -313,7 +313,7 @@ void std_clear(void) { std::memset(&g_std_cleared, 0, sizeof(op_t)); } let cleared_in: Vec = analysis .terminator_events .iter() - .map(|(cs, _)| { + .map(|(cs, _, _)| { let site = program .symbols .call_sites diff --git a/crates/trace-cli/tests/it/main.rs b/crates/trace-cli/tests/it/main.rs index 4a1b51ee..1557aa0f 100644 --- a/crates/trace-cli/tests/it/main.rs +++ b/crates/trace-cli/tests/it/main.rs @@ -55,3 +55,4 @@ mod cpp_review_257_invocations; mod cpp_review_257_opaque; mod cpp_review_257_postfix; mod cpp_review_257_templates; +mod std_bind; diff --git a/crates/trace-cli/tests/it/std_bind.rs b/crates/trace-cli/tests/it/std_bind.rs new file mode 100644 index 00000000..31d350da --- /dev/null +++ b/crates/trace-cli/tests/it/std_bind.rs @@ -0,0 +1,641 @@ +use crate::common; +use common::*; +use trace_analysis::{AnalysisResult, ContextKind, ResolutionKind}; +use trace_ir::{CallSiteId, Program}; + +analyzed_fixture!(std_bind); + +fn indirect_at(p: &Program, a: &AnalysisResult, caller: &str, spelling: &str) -> Vec { + a.call_edges + .iter() + .filter(|edge| { + edge.resolution == ResolutionKind::Indirect + && p.symbols.function(edge.caller).name == caller + && p.symbols + .call_site_by_id(edge.call_site) + .unwrap() + .callee_name + .as_str() + == spelling + }) + .map(|edge| p.symbols.function(edge.callee).name.clone()) + .collect() +} + +fn site(p: &Program, caller: &str, spelling: &str) -> CallSiteId { + p.symbols + .call_sites + .iter() + .find(|c| p.symbols.function(c.caller).name == caller && c.callee_name.as_str() == spelling) + .unwrap_or_else(|| panic!("missing {caller} -> {spelling}")) + .id +} + +fn check_args( + p: &Program, + a: &AnalysisResult, + caller: &str, + spelling: &str, + target: &str, + expected: &[(&str, &str, u32)], +) { + let site = site(p, caller, spelling); + let mut actual: Vec<_> = a + .arg_flow_edges + .iter() + .filter(|row| row.call_site == site) + .filter_map(|row| { + let formal = p.symbols.variable(row.formal); + if p.symbols.function(formal.fn_id?).name != target { + return None; + } + let actual = if let Some(var) = row.actual_var { + &p.symbols.variable(var).name + } else { + &p.symbols.function(row.actual_fn?).name + }; + Some((formal.name.as_str(), actual.as_str(), row.arg_index)) + }) + .collect(); + actual.sort_unstable(); + assert_eq!(actual, expected, "{caller} -> {target}"); +} + +#[test] +fn exact_targets_and_receivers_at_invocation() { + let (p, a) = std_bind(); + for (caller, target) in [ + ("control", "alpha"), + ("bound", "alpha"), + ("member", "Worker::run"), + ("member_placeholder", "Worker::run"), + ] { + assert_eq!(indirect_at(p, a, caller, "f"), [target]); + } + assert!(has_edge( + p, + a, + "bound", + "std::bind", + ResolutionKind::External + )); + assert_eq!(indirect_at(p, a, "via_directive", "copy"), ["alpha"]); + assert!(has_edge( + p, + a, + "immediate", + "alpha", + ResolutionKind::Indirect + )); + assert!(indirect_at(p, a, "immediate", "std::bind").is_empty()); + assert!(indirect_at(p, a, "bound", "std::bind").is_empty()); + assert!(indirect_at(p, a, "dropped", "std::bind").is_empty()); + assert!(a + .execution_contexts + .iter() + .all(|ctx| ctx.start.is_none_or(|start| { + let call = p.symbols.call_site_by_id(start.call_site).unwrap(); + !call.callee_name.as_str().contains("bind") + }))); + check_args(p, a, "member", "f", "Worker::run", &[("this", "w", 0)]); + check_args( + p, + a, + "member_placeholder", + "f", + "Worker::run", + &[("this", "later", 0)], + ); +} + +#[test] +fn named_captures_and_reordered_repeated_placeholders() { + let (p, a) = std_bind(); + assert_eq!(indirect_at(p, a, "order", "f"), ["Reorder"]); + check_args( + p, + a, + "order", + "f", + "Reorder", + &[ + ("first", "Right", 1), + ("second", "Left", 0), + ("stored", "Captured", 3), + ("third", "Right", 1), + ], + ); + for (arg, target) in [ + ("first", "Right"), + ("second", "Left"), + ("third", "Right"), + ("stored", "Captured"), + ] { + assert_eq!(indirect_at(p, a, "Reorder", arg), [target]); + } +} + +#[test] +fn return_copy_parameter_and_field_flow_cross_translation_units() { + let (p, a) = std_bind(); + assert_eq!(indirect_at(p, a, "returned", "f"), ["Echo"]); + assert_eq!(indirect_at(p, a, "returned", "result"), ["Captured"]); + assert_eq!(indirect_at(p, a, "Queue::Fire", "this->task"), ["Dispatch"]); + check_args( + p, + a, + "Queue::Fire", + "this->task", + "Dispatch", + &[("callback", "captured", 0)], + ); + assert_eq!(indirect_at(p, a, "Dispatch", "callback"), ["CrossTarget"]); +} + +#[test] +fn two_bindings_of_the_same_function_both_wire_at_one_invocation() { + let (p, a) = std_bind(); + assert_eq!(indirect_at(p, a, "alternatives", "f"), ["Dispatch"]); + check_args( + p, + a, + "alternatives", + "f", + "Dispatch", + &[("callback", "first", 0), ("callback", "second", 0)], + ); +} + +#[test] +fn bare_bind_requires_a_standard_candidate_or_explicit_import() { + let (p, a) = std_bind(); + assert!(indirect_at(p, a, "foreign_bind", "f").is_empty()); + assert!(has_edge( + p, + a, + "via_adl", + "custom::Job::operator()", + ResolutionKind::Direct, + )); + assert!(must_not_have_edge(p, a, "via_adl", "AdlTarget")); + assert!(must_not_have_edge( + p, + a, + "missing_bind_declaration", + "MissingBindTarget" + )); + assert_eq!( + indirect_at(p, a, "explicit_bind_import", "job"), + ["ExplicitBindTarget"] + ); +} + +#[test] +fn runtime_targets_resolve_from_points_to_only_at_invocation() { + let (p, a) = std_bind(); + assert_eq!(indirect_at(p, a, "runtime_target", "f"), ["unrelated"]); + let mut targets = indirect_at(p, a, "either_target", "f"); + targets.sort_unstable(); + assert_eq!(targets, ["alpha", "unrelated"]); + assert!(indirect_at(p, a, "runtime_target", "std::bind").is_empty()); + assert!(indirect_at(p, a, "no_known_target", "f").is_empty()); +} + +#[test] +fn lambda_and_forwarded_pack_targets_survive_binding() { + let (p, a) = std_bind(); + assert_eq!( + indirect_at(p, a, "invoke_packed_task", "f"), + ["PackedTarget"] + ); + // The trailing pack is summarized, so both elements may reach either formal. + for arg in ["first", "second"] { + let mut targets = indirect_at(p, a, "PackedTarget", arg); + targets.sort_unstable(); + assert_eq!(targets, ["Captured", "PackedHit"]); + } + assert!(indirect_at(p, a, "make_packed_task", "std::bind").is_empty()); + let lambda = lambda_in(p, "invoke_bound_lambda").name.as_str(); + assert_eq!(indirect_at(p, a, "invoke_bound_lambda", "f"), [lambda]); + assert_eq!(indirect_at(p, a, lambda, "cb"), ["LambdaHit"]); + assert!(indirect_at(p, a, "invoke_bound_lambda", "std::bind").is_empty()); +} + +#[test] +fn modeled_thread_and_timer_invoke_bindings_at_the_submission_site() { + let (p, _) = std_bind(); + let a = analyze_with_models( + p, + r#" +[[model]] +name = "AddTimerEvent" +effects = [{ kind = "invoke", param = 0, context = "serial_task" }] +"#, + ); + let thread = site(p, "Launch", "std::thread"); + let timer = site(p, "Plugin::DelayProcessEvent", "AddTimerEvent"); + for (start_site, entry, kind) in [ + (thread, "StartWorker", ContextKind::Thread), + (timer, "Plugin::OnEventProxy", ContextKind::SerialTask), + ( + site(p, "ScheduleLate", "AddTimerEvent"), + "LateTarget", + ContextKind::SerialTask, + ), + ] { + assert!( + a.execution_contexts.iter().any(|ctx| { + ctx.start.is_some_and(|start| start.call_site == start_site) + && p.symbols.function(ctx.entry).name == entry + && ctx.kind == kind + }), + "{entry}: {:?}", + a.execution_contexts + ); + } + check_args( + p, + &a, + "Launch", + "std::thread", + "StartWorker", + &[("left", "right", 2), ("right", "left", 1)], + ); + check_args( + p, + &a, + "Plugin::DelayProcessEvent", + "AddTimerEvent", + "Plugin::OnEventProxy", + &[("event", "event", 1), ("this", "this", 0)], + ); + assert_eq!( + indirect_at(p, &a, "Plugin::OnEventProxy", "event"), + ["Captured"] + ); + assert_eq!(indirect_at(p, &a, "StartWorker", "left"), ["Right"]); + assert_eq!(indirect_at(p, &a, "StartWorker", "right"), ["Left"]); + assert_eq!(indirect_at(p, &a, "LateTarget", "cb"), ["LateHit"]); +} + +#[test] +fn callable_casts_keep_the_selected_overload_and_leave_runtime_targets_opaque() { + let (p, a) = std_bind(); + assert_eq!(indirect_at(p, a, "member_cast", "f"), ["CastWorker::run"]); + check_args( + p, + a, + "member_cast", + "f", + "CastWorker::run", + &[("cb", "ReviewHit", 1), ("this", "worker", 0)], + ); + assert!(indirect_at(p, a, "member_variable_cast", "f").is_empty()); + assert_eq!(indirect_at(p, a, "free_cast", "f"), ["FreeCast"]); + check_args( + p, + a, + "free_cast", + "f", + "FreeCast", + &[("cb", "ReviewHit", 0)], + ); +} + +#[test] +fn a_braced_callable_slot_keeps_the_bind_result() { + let (p, a) = std_bind(); + assert_eq!(indirect_at(p, a, "brace_bind", "f"), ["BraceTarget"]); + assert!(indirect_at(p, a, "brace_bind", "std::bind").is_empty()); + assert!(must_not_have_edge( + p, + a, + "invoke_global_brace", + "GlobalBraceTarget" + )); +} + +#[test] +fn global_placeholders_work_without_a_standard_declaration() { + let (p, a) = std_bind(); + check_args( + p, + a, + "global_placeholder", + "f", + "ReviewTarget", + &[("cb", "ReviewHit", 0)], + ); + assert_eq!(indirect_at(p, a, "ReviewTarget", "cb"), ["ReviewHit"]); +} + +#[test] +fn a_model_on_the_bound_target_reads_composed_arguments() { + let (p, _) = std_bind(); + let a = analyze_with_models( + p, + r#" +[[model]] +name = "ModeledLaunch" +effects = [{ kind = "invoke", param = 0, args = [1], context = "thread" }] +"#, + ); + for (caller, position) in [("mode_with_capture", 1), ("mode_with_placeholders", 0)] { + let mut targets = indirect_at(p, &a, caller, "job"); + targets.sort_unstable(); + assert_eq!(targets, ["ModelActual", "ModeledLaunch"]); + check_args( + p, + &a, + caller, + "job", + "ModelActual", + &[("next", "ReviewHit", position)], + ); + let start = site(p, caller, "job"); + let contexts: Vec<_> = a + .execution_contexts + .iter() + .filter(|ctx| ctx.start.is_some_and(|loc| loc.call_site == start)) + .map(|ctx| (p.symbols.function(ctx.entry).name.as_str(), ctx.kind)) + .collect(); + assert_eq!(contexts, [("ModelActual", ContextKind::Thread)]); + } + assert_eq!(indirect_at(p, &a, "ModelActual", "next"), ["ReviewHit"]); +} + +#[test] +fn jthread_reserves_the_first_placeholder_for_its_stop_token() { + let (p, a) = std_bind(); + assert_eq!( + indirect_at(p, a, "with_stop_token", "std::jthread"), + ["StopWork"] + ); + check_args( + p, + a, + "with_stop_token", + "std::jthread", + "StopWork", + &[("cb", "ReviewHit", 1)], + ); + assert_eq!(indirect_at(p, a, "StopWork", "cb"), ["ReviewHit"]); + + let root = fixture("std_bind"); + let mut program = trace_parse::build_program(&root, &default_opts(&root)).expect("build"); + let token = local_variable(&program, "StopWork", "token"); + program.symbols.variable_mut(token).type_id = program.types.unknown(); + let (_, analysis) = trace_analysis::analyze(&program); + check_args( + &program, + &analysis, + "with_stop_token", + "std::jthread", + "StopWork", + &[("cb", "ReviewHit", 1), ("token", "ReviewHit", 1)], + ); +} + +#[test] +fn equal_captured_and_placeholder_values_export_once() { + let (p, a) = std_bind(); + check_args( + p, + a, + "duplicate_flow", + "f", + "ReviewTarget", + &[("cb", "x", 0)], + ); + let db = cli_analyze(&fixture("std_bind"), &[]); + let rows: i64 = trace_db::open_db(&db) + .unwrap() + .query_row( + "SELECT COUNT(*) FROM flow_calls f JOIN call_sites s ON s.id = f.call_site_id + JOIN functions c ON c.id = s.caller_fn_id + WHERE c.name = 'duplicate_flow' AND s.callee_text = 'f'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(rows, 1); +} + +#[test] +fn dereferenced_captures_supply_the_loaded_callback() { + let (p, a) = std_bind(); + for (caller, target) in [ + ("bind_dereferenced_callback", "ReadBoundCallback"), + ( + "bind_member_with_dereferenced_callback", + "BindArgumentWorker::run", + ), + ("bind_dereferenced_target_and_callback", "ReadBoundCallback"), + ] { + assert_eq!(indirect_at(p, a, caller, "job"), [target], "{caller}"); + assert_eq!(indirect_at(p, a, target, "callback"), ["DerefHit"]); + let call_site = site(p, caller, "job"); + assert!( + a.arg_flow_edges.iter().any(|row| { + row.call_site == call_site + && p.symbols.variable(row.formal).name == "callback" + && row + .actual_var + .is_some_and(|var| p.symbols.variable(var).name != "slot") + }), + "{caller}" + ); + } + assert_eq!( + indirect_at(p, a, "bind_dereferenced_reference", "job"), + ["ReadBoundReference"] + ); + check_args( + p, + a, + "bind_dereferenced_reference", + "job", + "ReadBoundReference", + &[("callback", "slot", 0)], + ); +} + +#[test] +fn stored_addresses_preserve_source_variables_and_model_arguments() { + let (p, _) = std_bind(); + let a = analyze_with_models( + p, + r#" +[[model]] +name = "ForwardBoundAddress" +effects = [{ kind = "invoke", param = 0, args = [1] }] +"#, + ); + for (caller, formal, actual, index) in [ + ( + "bind_member_with_dereferenced_callback", + "this", + "worker", + 0, + ), + ("bind_forwarded_address", "address", "payload", 1), + ] { + let call_site = site(p, caller, "job"); + assert!( + a.arg_flow_edges.iter().any(|row| { + row.call_site == call_site + && row.arg_index == index + && p.symbols.variable(row.formal).name == formal + && row + .actual_var + .is_some_and(|var| p.symbols.variable(var).name == actual) + && row + .actual_address + .is_some_and(|address| Some(address) != row.actual_var) + }), + "{caller}" + ); + } + let clear = site(p, "bind_clear", "job"); + assert!( + a.terminator_events.iter().any(|&(call, param, var)| { + call == clear && param == 0 && p.symbols.variable(var).name == "payload" + }), + "{:?}", + a.terminator_events + ); +} + +#[test] +fn stored_member_addresses_preserve_the_alias_fallback_guard() { + let (p, _) = std_bind(); + let models = trace_analysis::FnModelSet::from_toml_str( + "version = 1\n[[model]]\nname = \"BindAlias\"\neffects = [{kind = \"alias\", dst = 0, src = 1}]\n", + ).unwrap(); + let (pag, analysis) = trace_analysis::analyze_with_options( + p, + trace_analysis::AnalyzeOptions { + retain_points_to: true, + models: std::sync::Arc::new(models), + ..Default::default() + }, + ); + let payload = p + .symbols + .variables + .iter() + .find(|v| v.name == "bind_alias_payload") + .unwrap(); + let payload_loc = pag.var_location[&payload.id]; + for (caller, precise) in [ + ("bind_precise_member_address", true), + ("bind_fallback_member_address", false), + ] { + let call_site = site(p, caller, "std::bind"); + let arg = p.symbols.call_site_by_id(call_site).unwrap(); + assert_eq!(arg.addr_of_member_args().is_empty(), precise); + let dst = arg + .var_args + .iter() + .find(|(index, _)| *index == 1) + .unwrap() + .1; + let reaches_payload = analysis + .points_to + .get(&pag.var_node[&dst]) + .is_some_and(|pts| pts.contains(&payload_loc)); + assert_eq!(reaches_payload, precise, "{caller}"); + } +} + +#[test] +fn public_bound_lambda_is_an_anonymous_callable() { + let db = cli_analyze(&fixture("std_bind"), &["--full-export"]); + let conn = trace_db::open_db(&db).unwrap(); + let flow_node: (String, Option) = conn + .query_row( + "SELECT n.label, n.fn_id + FROM raw_flow_nodes r JOIN flow_nodes n ON n.id=r.id + WHERE r.detail='bound' AND r.label GLOB 'bind:invoke_bound_lambda::$lambda*' + AND r.fn_id IS NOT NULL", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(flow_node, ("anonymous callable".into(), None)); + let location: String = conn + .query_row( + "SELECT n.desc FROM raw_locations r JOIN locations n ON n.id=r.id + WHERE r.kind='Bound' AND r.desc GLOB 'invoke_bound_lambda::$lambda*'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(location, "anonymous callable"); +} + +#[test] +fn explored_and_runtime_bindings_keep_provenance_for_each_target() { + let dir = scratch(&[ + ("BUILD.gn", "defines = [ \"CHOOSE_FIRST\" ]\n"), + ( + "main.cpp", + r#" +void First() {} +void Second() {} +#ifdef CHOOSE_FIRST +#define CALLBACK First +#else +#define CALLBACK Second +#endif +void run() { + auto f = std::bind(CALLBACK); + f(); +} +void RuntimeFirst() {} +void RuntimeSecond() {} +void run_runtime(void (*callback)()) { + auto f = std::bind(callback); + f(); +} +void supply_callbacks() { + run_runtime(RuntimeFirst); + run_runtime(RuntimeSecond); +} +"#, + ), + ]); + let db = cli_analyze(dir.path(), &["--explore"]); + let conn = trace_db::open_db(&db).unwrap(); + let mut query = conn + .prepare( + "SELECT n.label, o.dst_node, o.line FROM flow_origins o + JOIN flow_nodes n ON n.id = o.src_node + WHERE o.kind = 'addr_of' AND n.detail = 'bound' + ORDER BY n.label", + ) + .unwrap(); + let rows: Vec<(String, i64, i64)> = query + .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?))) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!( + rows.iter() + .map(|(label, _, _)| label.as_str()) + .collect::>(), + [ + "bind:First", + "bind:RuntimeFirst", + "bind:RuntimeSecond", + "bind:Second" + ] + ); + for (first, second) in [(0, 3), (1, 2)] { + assert_eq!( + (rows[first].1, rows[first].2), + (rows[second].1, rows[second].2) + ); + } + assert_ne!(rows[0].1, rows[1].1); +} diff --git a/crates/trace-db/src/dataflow.rs b/crates/trace-db/src/dataflow.rs index 9307deab..9a2e907c 100644 --- a/crates/trace-db/src/dataflow.rs +++ b/crates/trace-db/src/dataflow.rs @@ -549,7 +549,7 @@ pub fn dataflow_view( let name: Option = r.get(6)?; let storage: Option = r.get(7)?; let synthetic: Option = r.get(8)?; - let function_entity = kind == "loc" && detail == "function"; + let function_entity = kind == "loc" && matches!(detail.as_str(), "function" | "bound"); let path = r .get::<_, Option>(if function_entity { 13 } else { 9 })? .unwrap_or_default(); @@ -587,7 +587,7 @@ pub fn dataflow_view( id: PagNodeId(id as u32), var_id: vid.map(|id| VarId(id as u32)), fn_id: owner.map(|id| FnId(id as u32)), - name: if detail == "function" { + name: if function_entity { fn_name.clone().unwrap_or(label) } else if detail == "field" { format!("field {label}") @@ -606,7 +606,7 @@ pub fn dataflow_view( "null_pointer" } else if detail == "string_lit" { "constant" - } else if detail == "function" { + } else if function_entity { "function" } else { kind.as_str() @@ -3271,9 +3271,9 @@ mod tests { INSERT INTO functions(id,name,file_id,line_start,line_end,linkage,signature,is_defined,target_id) VALUES(1,'f',0,20,30,'internal','f()',1,1); INSERT INTO variables(id,name,kind,fn_id,type_id,file_id,line,col) VALUES(8,'other','param',1,0,0,20,1); INSERT INTO call_sites(id,caller_fn_id,file_id,line,col,callee_text,is_direct) VALUES(0,0,0,10,3,'clear',1); - INSERT INTO flow_nodes(id,kind,label,detail,fn_id,call_site_id) VALUES(8,'terminator','clear clears arg0','',0,0),(9,'loc','allocation','heap',0,NULL),(10,'loc','constant','string_lit',NULL,NULL),(11,'loc','f','function',1,NULL); + INSERT INTO flow_nodes(id,kind,label,detail,fn_id,call_site_id) VALUES(8,'terminator','clear clears arg0','',0,0),(9,'loc','allocation','heap',0,NULL),(10,'loc','constant','string_lit',NULL,NULL),(11,'loc','f','function',1,NULL),(14,'loc','bind:f','bound',1,NULL); INSERT INTO flow_nodes(id,kind,label,var_id,fn_id) VALUES(12,'var','other',8,1); - INSERT INTO flow_edges VALUES(20,0,8,'terminates'),(21,9,0,'addr_of'),(22,10,0,'addr_of'),(23,11,0,'addr_of'),(24,0,12,'copy');").unwrap(); + INSERT INTO flow_edges VALUES(20,0,8,'terminates'),(21,9,0,'addr_of'),(22,10,0,'addr_of'),(23,11,0,'addr_of'),(24,0,12,'copy'),(26,14,0,'addr_of');").unwrap(); let down = dataflow_view(&conn, &[symbol(&conn, "a")], Direction::Down, 3).unwrap(); assert_eq!(down.scopes["fn:0"].target_id, Some(TargetId(0))); assert_eq!(down.scopes["fn:1"].target_id, Some(TargetId(1))); @@ -3300,7 +3300,12 @@ mod tests { assert_eq!(resolved.nodes[&PagNodeId(id)].targets[0].name, "f"); } let up = dataflow_view(&conn, &[symbol(&conn, "a")], Direction::Up, 3).unwrap(); - for (id, kind) in [(9, "allocation"), (10, "constant"), (11, "function")] { + for (id, kind) in [ + (9, "allocation"), + (10, "constant"), + (11, "function"), + (14, "function"), + ] { assert_eq!(up.nodes[&PagNodeId(id)].kind, kind); if kind == "function" { let entity = &up.nodes[&PagNodeId(id)]; @@ -3326,7 +3331,7 @@ mod tests { .iter() .any(|node| node["kind"] == "function" && node["location"]["line"] == 20)); let dot = render_dataflow(&up, RenderFormat::Graphviz, &meta); - assert!(dot.lines().any(|line| line.contains("n11 [") + assert!(dot.lines().any(|line| line.contains(&format!("n{id} [")) && line.contains("path=\"/src/main.c\", line=20, col=0"))); } } diff --git a/crates/trace-db/src/export.rs b/crates/trace-db/src/export.rs index b057a642..af678300 100644 --- a/crates/trace-db/src/export.rs +++ b/crates/trace-db/src/export.rs @@ -399,6 +399,7 @@ fn export_flow_graph( let kind_str = crate::inspect::loc_kind_schema_str(loc.kind); let label = match (loc.kind, loc.var) { (LocKind::Function, _) => format!("fn:{}", loc.desc), + (LocKind::Bound, _) => format!("bind:{}", loc.desc), (LocKind::StringLit, _) => format!("string:{}", loc.desc), (_, Some(v)) => match program.symbols.variable_by_id(v) { Some(var) => format!("{} of {}", loc.desc, var.name), @@ -504,12 +505,7 @@ fn export_flow_graph( // value the formal receives is the call site's actual, the // temporary holding `&x`, which the graph reaches from `x`'s // location through `addr_of`. - let passed = program - .symbols - .call_site_by_id(e.call_site) - .filter(|cs| cs.addr_of_args().contains(&e.arg_index)) - .and_then(|cs| cs.var_args.iter().find(|(i, _)| *i == e.arg_index)) - .map_or(actual, |(_, temp)| *temp); + let passed = e.actual_address.unwrap_or(actual); let Some(actual_node) = pag.var_node.get(&passed) else { continue; }; @@ -544,17 +540,14 @@ fn export_flow_graph( // per (call site, parameter) with an edge from the cleared actual, so // dataflow walks show where value chains are zeroed. let mut next_node_id = pag.nodes.len() as u64; - let mut seen_terms: FxHashSet<(trace_ir::CallSiteId, u32)> = FxHashSet::default(); - for &(cs_id, param) in &analysis.terminator_events { - if !seen_terms.insert((cs_id, param)) { + let mut seen_terms = FxHashSet::default(); + for &(cs_id, param, actual) in &analysis.terminator_events { + if !seen_terms.insert((cs_id, param, actual)) { continue; } let Some(site) = program.symbols.call_site_by_id(cs_id) else { continue; }; - let Some(actual) = pag.argument_var(site, param) else { - continue; - }; let Some(&actual_node) = pag.var_node.get(&actual) else { continue; }; @@ -695,12 +688,10 @@ fn export_flow_provenance( } } } - // The heap object a `new` allocates into `dst`: the source of the - // `addr_of` the PAG built for its `NewHeap` fact, which the fact itself - // does not name. - let new_heap = |dst: &PagNodeId| -> Option<&PagNodeId> { + // Find the location created by the PAG for a producer fact. + let new_heap = |dst: &PagNodeId| -> Option { pag.indices.addr_of_dst.get(dst)?.iter().find_map(|&i| { - let src = &pag.constraints[i].src; + let src = pag.constraints[i].src; match pag.nodes[src.0 as usize].kind { PagNodeKind::Loc(loc) if pag.locations[loc.0 as usize].kind == LocKind::Heap => { Some(src) @@ -718,49 +709,60 @@ fn export_flow_provenance( let Some(d) = pag.var_node.get(&dst) else { continue; }; + let mut binding_sources = &[][..]; let (src, kind) = match flow { - F::Copy { src, .. } => (pag.var_node.get(src), "copy"), - F::Store { src, .. } => (pag.var_node.get(src), "store"), - F::Load { src, .. } => (pag.var_node.get(src), "load"), - F::GepField { base, .. } => (pag.var_node.get(base), "gep"), - F::UnwrapPointer { src, .. } => (pag.var_node.get(src), "unwrap"), + F::Copy { src, .. } => (pag.var_node.get(src).copied(), "copy"), + F::Store { src, .. } => (pag.var_node.get(src).copied(), "store"), + F::Load { src, .. } => (pag.var_node.get(src).copied(), "load"), + F::GepField { base, .. } => (pag.var_node.get(base).copied(), "gep"), + F::UnwrapPointer { src, .. } => (pag.var_node.get(src).copied(), "unwrap"), F::AddrOfVar { src, .. } => ( - pag.var_location.get(src).and_then(|l| pag.loc_node.get(l)), + pag.var_location + .get(src) + .and_then(|l| pag.loc_node.get(l)) + .copied(), "addr_of", ), F::AddrOfFn { callee, .. } | F::ArrayFnMember { callee, .. } => ( pag.fn_locations .get(callee) - .and_then(|l| pag.loc_node.get(l)), + .and_then(|l| pag.loc_node.get(l)) + .copied(), "addr_of", ), - F::NullPointer { .. } => (pag.null_node.as_ref(), "copy"), + F::NullPointer { .. } => (pag.null_node, "copy"), F::NewHeap { .. } => (new_heap(d), "addr_of"), + F::BindCallable { .. } => { + binding_sources = pag.bound_locations(flow); + (None, "addr_of") + } F::StringConst { value, .. } => ( - pag.string_locs.get(value).and_then(|l| pag.loc_node.get(l)), + pag.string_locs + .get(value) + .and_then(|l| pag.loc_node.get(l)) + .copied(), "addr_of", ), _ => continue, }; - let Some(s) = src else { - continue; - }; let operation = if kind == "store" && field_destinations.contains(&dst) { "write field" } else { kind }; - for (span, expression) in sites { - origins.execute(params![ - s.0, - d.0, - strings.intern(kind)?, - span.file.0, - span.line, - span.col, - strings.intern(expression.as_ref())?, - strings.intern(operation)? - ])?; + for s in src.into_iter().chain(binding_sources.iter().copied()) { + for (span, expression) in sites { + origins.execute(params![ + s.0, + d.0, + strings.intern(kind)?, + span.file.0, + span.line, + span.col, + strings.intern(expression.as_ref())?, + strings.intern(operation)? + ])?; + } } } let mut return_destinations: FxHashSet<_> = unique_flows diff --git a/crates/trace-db/src/inspect.rs b/crates/trace-db/src/inspect.rs index 849e9183..9370d08f 100644 --- a/crates/trace-db/src/inspect.rs +++ b/crates/trace-db/src/inspect.rs @@ -218,6 +218,7 @@ pub fn loc_kind_schema_str(kind: LocKind) -> &'static str { LocKind::ArraySummary => "array_summary", LocKind::Function => "function", LocKind::StringLit => "string_lit", + LocKind::Bound => "bound", } } @@ -235,6 +236,7 @@ pub fn loc_kind_from_schema_str(s: &str) -> Option { "array_summary" => Some(LocKind::ArraySummary), "function" => Some(LocKind::Function), "string_lit" => Some(LocKind::StringLit), + "bound" => Some(LocKind::Bound), _ => None, } } diff --git a/crates/trace-db/src/inspect/slice.rs b/crates/trace-db/src/inspect/slice.rs index 1663d38a..48f7bfd8 100644 --- a/crates/trace-db/src/inspect/slice.rs +++ b/crates/trace-db/src/inspect/slice.rs @@ -331,7 +331,10 @@ impl NodeRow { _ if self.static_var() => Sharing::Shared, _ if self.constant => Sharing::Constant, Some(FlowNodeKind::Loc) - if matches!(self.loc_kind, Some(LocKind::Function | LocKind::StringLit)) => + if matches!( + self.loc_kind, + Some(LocKind::Function | LocKind::Bound | LocKind::StringLit) + ) => { Sharing::Constant } @@ -377,7 +380,7 @@ impl NodeRow { fn origin(&self) -> &'static str { match self.loc_kind { Some(LocKind::Heap) => "allocation", - Some(LocKind::Function) => "function", + Some(LocKind::Function | LocKind::Bound) => "function", Some(LocKind::StringLit) => "string", _ => "address", } diff --git a/crates/trace-db/src/projection.rs b/crates/trace-db/src/projection.rs index 0fcd2454..87dd2ee1 100644 --- a/crates/trace-db/src/projection.rs +++ b/crates/trace-db/src/projection.rs @@ -702,9 +702,9 @@ DROP TABLE projected_call_provenance; UPDATE variables_data SET kind='local' WHERE kind='param' AND fn_id IN (SELECT lambda_fn_id FROM lambda_owners); UPDATE variables_data SET fn_id=(SELECT owner_fn_id FROM lambda_owners WHERE lambda_fn_id=fn_id) WHERE fn_id IN (SELECT lambda_fn_id FROM lambda_owners); --- A function location is a callable value, not an ownership fact. Preserve +-- A function or bound location represents a callable value. Preserve -- its node and flow without claiming that it points to the lexical parent. --- Scope the relabeling and unlinking to actual fn: location nodes; other nodes +-- Scope the relabeling and unlinking to callable location nodes. Other nodes -- in the lambda (variables, call_target nodes) are remapped to the owner. INSERT INTO strings(id, text) SELECT (SELECT coalesce(max(id), 0) + 1 FROM strings), '{ANONYMOUS_CALLABLE}' @@ -713,17 +713,17 @@ WHERE NOT EXISTS (SELECT 1 FROM strings WHERE text = '{ANONYMOUS_CALLABLE}') SELECT 1 FROM flow_nodes_data n WHERE n.fn_id IN (SELECT lambda_fn_id FROM lambda_owners) AND n.kind_id = (SELECT id FROM strings WHERE text = 'loc') - AND n.label_id IN (SELECT id FROM strings WHERE text LIKE 'fn:%') + AND n.label_id IN (SELECT id FROM strings WHERE text LIKE 'fn:%' OR text LIKE 'bind:%') ); UPDATE flow_nodes_data SET label_id = (SELECT max(id) FROM strings WHERE text = '{ANONYMOUS_CALLABLE}'), fn_id = NULL WHERE fn_id IN (SELECT lambda_fn_id FROM lambda_owners) AND kind_id = (SELECT id FROM strings WHERE text = 'loc') - AND label_id IN (SELECT id FROM strings WHERE text LIKE 'fn:%'); + AND label_id IN (SELECT id FROM strings WHERE text LIKE 'fn:%' OR text LIKE 'bind:%'); -- Only a name ending at the generated segment is the lambda itself. UPDATE locations SET desc = '{ANONYMOUS_CALLABLE}' -WHERE kind = 'Function' AND desc GLOB '{LAMBDA_NAME}' +WHERE kind IN ('Function', 'Bound') AND desc GLOB '{LAMBDA_NAME}' AND rtrim(desc, '0123456789:') GLOB '*::$lambda'; UPDATE flow_nodes_data diff --git a/crates/trace-ir/src/flow.rs b/crates/trace-ir/src/flow.rs index cf51e550..4de6e202 100644 --- a/crates/trace-ir/src/flow.rs +++ b/crates/trace-ir/src/flow.rs @@ -24,6 +24,36 @@ pub enum ReturnFlow { LvalueAddress(Box), } +/// A callable supplied to `std::bind`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum BindTarget { + Function(FnId), + Value(VarId), +} + +/// One argument a `std::bind` holds for the callable it wraps +/// ([`FlowConstraint::BindCallable`]; docs/IR.md, "Bound callables"). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum BoundArg { + /// A value the binder keeps, passed to the callable as it was written. + Stored(VarId), + /// A temporary holding an explicit address such as `&x`. + AddressOf(VarId), + /// A member address represented by its base variable when lowering + /// cannot construct a precise field or element address. + MemberAddress(VarId), + /// A trailing expansion supplying any number of arguments. + Pack(VarId), + /// A named function passed as a stored argument. + Function(FnId), + /// `std::placeholders::_n`, which the invocation's argument `n` fills + /// (`n` is 1-based, as it is spelled). + Placeholder(u32), + /// An argument the site records no value for (a literal): it holds its + /// position in the callable's parameters but supplies no value. + Opaque, +} + /// Storage identity for a container with index-insensitive element flow. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ContainerOwner { @@ -121,6 +151,16 @@ pub enum FlowConstraint { /// raw pointer, whose pointee type filters the admitted locations. See /// `docs/IR.md`, "Smart-pointer unwrap". UnwrapPointer { dst: VarId, src: VarId }, + /// `dst` holds the callable `std::bind` built, with `args` bound in order. + /// The solver reads the receiver from the first argument when the + /// resolved function needs one. The bind + /// itself runs nothing; the callable runs where `dst` is invoked. See + /// `docs/IR.md`, "Bound callables". + BindCallable { + dst: VarId, + target: BindTarget, + args: Vec, + }, } impl FlowConstraint { @@ -137,6 +177,13 @@ impl FlowConstraint { (dst, container_owner_var(owner)) } FlowConstraint::CallReturnIndirect { dst, callee_var } => (dst, Some(callee_var)), + FlowConstraint::BindCallable { dst, target, .. } => ( + dst, + match target { + BindTarget::Function(_) => None, + BindTarget::Value(var) => Some(var), + }, + ), FlowConstraint::ArrayFnMember { array, .. } => (array, None), FlowConstraint::AddrOfFn { dst, .. } | FlowConstraint::CallReturn { dst, .. } @@ -154,6 +201,24 @@ impl FlowConstraint { std::iter::once(first) .chain(second) .chain(arguments.iter().map(|(_, var)| *var)) + .chain(self.held_vars()) + } + + /// The variables this constraint holds besides its operands: a bound + /// callable's stored arguments (including any receiver), which are values of the + /// function the bind is written in. Empty for every other kind. + pub fn held_vars(&self) -> impl Iterator + '_ { + let args: &[BoundArg] = match self { + FlowConstraint::BindCallable { args, .. } => args, + _ => &[], + }; + args.iter().copied().filter_map(|arg| match arg { + BoundArg::Stored(var) + | BoundArg::AddressOf(var) + | BoundArg::MemberAddress(var) + | BoundArg::Pack(var) => Some(var), + BoundArg::Function(_) | BoundArg::Placeholder(_) | BoundArg::Opaque => None, + }) } } diff --git a/crates/trace-ir/src/symbol.rs b/crates/trace-ir/src/symbol.rs index 73fe34b6..62c51bea 100644 --- a/crates/trace-ir/src/symbol.rs +++ b/crates/trace-ir/src/symbol.rs @@ -3812,6 +3812,17 @@ impl SymbolTable { .is_some_and(|&p| self.variable_by_id(p).map(|v| v.name.as_str()) == Some("this")) } + /// An in-class prototype can omit parameters in the symbol table even + /// when its definition has an implicit receiver. + pub fn is_member_function(&self, fid: FnId) -> bool { + let f = self.function(fid); + if f.params.is_empty() { + f.is_cpp && f.declared_in_class + } else { + self.has_this_param(fid) + } + } + pub fn variable_by_id(&self, id: VarId) -> Option<&Variable> { self.variables.get(id.0 as usize).filter(|v| v.id == id) } diff --git a/crates/trace-parse/src/lower.rs b/crates/trace-parse/src/lower.rs index 35ede1bf..fa32ff96 100644 --- a/crates/trace-parse/src/lower.rs +++ b/crates/trace-parse/src/lower.rs @@ -32,9 +32,9 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Condvar, Mutex}; use std::time::Instant; use trace_ir::{ - is_anonymous_tag, CallOccurrence, CallSite, CallSiteDetails, ContainerModels, Diagnostic, - DiagnosticSeverity, FieldId, FlowConstraint, FnId, Function, Linkage, Program, ReturnFlow, - ScalarKind, Span, StorageClass, TempKind, TypeDesc, VarId, Variable, + is_anonymous_tag, BoundArg, CallOccurrence, CallSite, CallSiteDetails, ContainerModels, + Diagnostic, DiagnosticSeverity, FieldId, FlowConstraint, FnId, Function, Linkage, Program, + ReturnFlow, ScalarKind, Span, StorageClass, TempKind, TypeDesc, VarId, Variable, }; use trace_ir::{is_template_literal, split_pointer_suffix, strip_trailing_cv}; use trace_preproc::{Language, PreprocessOptions}; @@ -9181,6 +9181,12 @@ fn call_result_shape( } let raw = normalize_spacing(node_text(source, &func)); let name = strip_template_args(&raw); + if ctx.is_cpp && std_bind_result(program, ctx, source, value, func, &name) { + return Some(CallResult::Decided(Some(TypeDesc::FnPtr { + ret: Box::new(TypeDesc::Unknown), + params: vec![TypeDesc::Unknown], + }))); + } if let Some(&SmartPtrFactory { wrapper, .. }) = smart_ptr_factory(program, ctx, value, &name) { return Some(CallResult::Decided(smart_ptr_type( program, @@ -10308,6 +10314,249 @@ fn bare_names_std( is_std } +/// Whether the call `node` spells the standard `std::bind`, by the shared +/// lookup: written `std::bind` or `::std::bind`, or bare and brought into +/// scope by `using std::bind;` or `using namespace std;` +/// ([`bare_names_std`]). A `bind` of the user's own, or of another +/// namespace, is not it (docs/IR.md, "Bound callables"). +fn is_std_bind(program: &Program, ctx: &LowerContext, node: Node, name: &str) -> bool { + match name { + "::std::bind" => true, + "std::bind" => resolve_function_named(program, ctx, name) + .is_none_or(|id| program.symbols.function(id).name == "std::bind"), + "bind" => bare_names_std(program, ctx, node, name, "std::bind"), + _ => false, + } +} + +fn bind_candidates_are_standard( + program: &Program, + ctx: &LowerContext, + name: &str, + candidates: &[FnId], +) -> bool { + if candidates.is_empty() { + return name != "bind" + || ctx.using_name_imports.iter().any(|import| { + import.base == name && import.candidates.iter().any(|name| name == "std::bind") + }); + } + candidates + .iter() + .all(|&id| program.symbols.function(id).name == "std::bind") +} + +/// Before overload resolution, a bind result can be treated as callable +/// when ordinary lookup admits the standard name and ADL offers no other +/// candidates. The indexed call uses its ranked candidates instead. +fn std_bind_result( + program: &Program, + ctx: &LowerContext, + source: &str, + call: Node, + func: Node, + name: &str, +) -> bool { + if !is_std_bind(program, ctx, call, name) + || lookup_var_node(program, ctx, source, func).is_some() + { + return false; + } + if name != "bind" { + return true; + } + let types: Vec<_> = call_arg_nodes(call) + .into_iter() + .map(|arg| known_arg_type(program, ctx, source, arg)) + .collect(); + bind_candidates_are_standard( + program, + ctx, + name, + &resolve_cpp_name_candidates(program, ctx, name, &types), + ) +} + +/// Record the bound value independently of any sites that invoke it. +fn lower_std_bind( + program: &mut Program, + ctx: &mut LowerContext, + source: &str, + node: Node, + args: &CallArgs, + dst: VarId, +) { + use trace_ir::BindTarget; + + let Some(list) = node.cached_field("arguments") else { + return; + }; + let mut cursor = list.walk(); + let mut arguments = list + .named_children(&mut cursor) + .filter(|arg| !arg.is_extra()); + let Some(target) = arguments.next().and_then(|operand| { + if operand.cached_kind() == "parameter_pack_expansion" { + return None; + } + let mut named = args.fn_args.iter().filter(|(at, _)| *at == 0); + if let Some(&(_, callee)) = named.next() { + named + .all(|&(_, other)| other == callee) + .then_some(BindTarget::Function(callee)) + } else { + static_bind_cast_target(program, ctx, source, operand) + .map(BindTarget::Function) + .or_else(|| { + args.var_args + .iter() + .find(|(at, _)| *at == 0) + .map(|&(_, var)| { + let value = args + .deref_args + .iter() + .find(|arg| arg.index == 0) + .map_or(var, |arg| arg.passed(program, var, Some(false))); + BindTarget::Value(value) + }) + }) + } + }) else { + return; + }; + let explicit = match target { + BindTarget::Function(callee) => { + let member = program.symbols.is_member_function(callee) + && !program.symbols.function(callee).is_static_member; + Some((callee, usize::from(member))) + } + BindTarget::Value(_) => None, + }; + let mut bindings = Vec::new(); + let mut arguments = arguments.enumerate().peekable(); + while let Some((index, arg)) = arguments.next() { + let position = index as u32 + 1; + let mut stored = args.var_args.iter().filter(|(at, _)| *at == position); + if arg.cached_kind() == "parameter_pack_expansion" { + if let (None, Some(&(_, var)), None) = (arguments.peek(), stored.next(), stored.next()) + { + bindings.push(BoundArg::Pack(var)); + break; + } + return; + } + let spelled = node_text(source, &peel_casts(source, arg)); + let binding = if let Some(n) = bind_placeholder(program, ctx, spelled) { + BoundArg::Placeholder(n) + } else if let Some(&(_, var)) = stored.next() { + let var = args + .deref_args + .iter() + .find(|arg| arg.index == position) + .map_or(var, |arg| { + let reference = explicit.and_then(|(callee, receiver)| { + index + .checked_sub(receiver) + .and_then(|param| parameter_reference(program, callee, param)) + }); + arg.passed(program, var, reference) + }); + if args.addr_of_args.contains(&position) { + BoundArg::AddressOf(var) + } else if args.addr_of_member_args.contains(&position) { + BoundArg::MemberAddress(var) + } else { + BoundArg::Stored(var) + } + } else { + let mut named = args.fn_args.iter().filter(|(at, _)| *at == position); + match (named.next(), named.next()) { + (Some(&(_, function)), None) => BoundArg::Function(function), + _ => BoundArg::Opaque, + } + }; + bindings.push(binding); + } + // One producer per expression, including separate assignments to the + // same variable and branches that share an expression destination. + let value = alloc_ret_temp(program, ctx, node); + program.flow.push(FlowConstraint::BindCallable { + dst: value, + target, + args: bindings, + }); + program.flow.push(FlowConstraint::Copy { dst, src: value }); +} + +/// A callable cast is collected as a variable argument. Recover a static +/// binding only when the cast actually names a single matching function. +fn static_bind_cast_target( + program: &mut Program, + ctx: &mut LowerContext, + source: &str, + operand: Node, +) -> Option { + let signature = callable_cast_type(program, ctx, source, operand)?; + let callee = resolve_call_fn_arg(program, ctx, source, operand)?; + let function = program.symbols.function(callee); + let candidates = if is_member_function(program, callee) || function.is_static_member { + function_value_candidates(program, ctx, source, operand, callee, None) + } else { + program + .symbols + .resolve_function_candidates(&function.name, Some(ctx.current_file)) + .into_iter() + .filter(|candidate| { + program.symbols.function_pointer_signature_admits( + *candidate, + &signature, + &program.types, + ctx.reference_returns.contains(candidate), + ) + }) + .collect() + }; + match candidates.as_slice() { + [callee] => Some(*callee), + _ => None, + } +} + +fn bind_placeholder(program: &Program, ctx: &LowerContext, spelled: &str) -> Option { + let spelled = normalize_qualified(spelled.trim()); + let (scope, leaf) = spelled.rsplit_once("::").unwrap_or(("", &spelled)); + let number = leaf.strip_prefix('_')?; + if !number.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let n: u32 = number.parse().ok()?; + let placeholder_ns = |ns: &str| { + matches!( + ns, + "std::placeholders" | "std::__1::placeholders" | "std::__cxx11::placeholders" + ) + }; + let name_is_placeholder = |name: &str| { + name.rsplit_once("::") + .is_some_and(|(ns, _)| placeholder_ns(ns)) + }; + let admitted = if let Some(resolved) = lookup_var_unless_hidden(ctx, program, &spelled) { + resolved.is_some_and(|v| name_is_placeholder(program.symbols.variable(v).lookup_name())) + } else if !spelled.contains("::") { + ctx.using_name_imports.iter().any(|import| { + import.base == leaf + && import + .candidates + .iter() + .any(|name| name_is_placeholder(name)) + }) || ctx.directive_namespaces().any(placeholder_ns) + } else { + placeholder_ns(global_lookup_name(scope)) + || scope == "placeholders" && ctx.directive_namespaces().any(|ns| ns == "std") + }; + (admitted && n > 0).then_some(n) +} + /// Weak pointers, by their last name segment, and the method that yields the /// matching strong pointer. const WEAK_PTR_UPGRADES: &[(&str, &str, &str)] = &[ @@ -15210,6 +15459,34 @@ fn lower_var_initializer( { return; } + // `std::function` is represented as a callable slot. A single braced + // bind initializer supplies its value directly, like copy initialization. + if ctx.is_cpp + && ctx.current_fn.is_some() + && init.cached_kind() == "initializer_list" + && matches!( + program.types.get(type_id).desc.as_ref(), + TypeDesc::FnPtr { .. } + ) + { + let mut cursor = init.walk(); + let mut values = init + .named_children(&mut cursor) + .filter(|node| !node.is_extra()); + if let (Some(value), None) = (values.next(), values.next()) { + let value = peel_expression(value); + if value.cached_kind() == "call_expression" + && value.cached_field("function").is_some_and(|func| { + resolve_direct_call_name_from_func(source, func).is_some_and(|name| { + std_bind_result(program, ctx, source, value, func, &name) + }) + }) + { + extract_flow_from_expr(program, ctx, source, value, Some(var_id)); + return; + } + } + } // This is the common boundary for file-scope value, address, array and // aggregate initializers. No function body walk follows these operands. lower_file_expression_effects(program, ctx, source, init); @@ -17085,6 +17362,16 @@ fn collect_call_at_node_inner( Vec::new() }; + if let Some(dst) = return_dst.filter(|_| { + ctx.is_cpp + && callee_var.is_none() + && !is_field_or_element_call + && is_std_bind(program, ctx, node, &callee_name) + && bind_candidates_are_standard(program, ctx, &callee_name, &chosen) + }) { + lower_std_bind(program, ctx, source, node, &args, dst); + } + if chosen.is_empty() { let args = args.for_callee(program, ctx, None, false); let call_id = program.symbols.alloc_call_id(); @@ -17297,18 +17584,8 @@ impl CallArgs { args_bound_past_this: bool, ) -> Self { for deref in &self.deref_args { - // A position past the declared list takes the variadic tail's. - let reference = callee.and_then(|callee| { - let declared = program.symbols.function(callee); - let references = &declared.reference_params; - if declared.pack_positions.first().is_some_and(|&pack| { - pack as usize + 1 < references.len() && deref.param >= pack as usize - }) { - return None; - } - let tail = references.last().filter(|_| declared.variadic); - references.get(deref.param).or(tail).copied() - }); + let reference = + callee.and_then(|callee| parameter_reference(program, callee, deref.param)); if let Some(arg) = self.var_args.iter_mut().find(|(i, _)| *i == deref.index) { arg.1 = deref.passed(program, arg.1, reference); } @@ -17428,6 +17705,21 @@ impl CallArgs { } } +/// A position past the declared list uses the variadic tail's reference mode. +fn parameter_reference(program: &Program, callee: FnId, param: usize) -> Option { + let declared = program.symbols.function(callee); + let references = &declared.reference_params; + if declared + .pack_positions + .first() + .is_some_and(|&pack| pack as usize + 1 < references.len() && param >= pack as usize) + { + return None; + } + let tail = references.last().filter(|_| declared.variadic); + references.get(param).or(tail).copied() +} + /// A C++ `*x` argument, collected with `x`'s value and bound per site /// ([`CallArgs::for_callee`]). #[derive(Clone)] @@ -17513,16 +17805,8 @@ fn has_this_param(program: &Program, fid: FnId) -> bool { program.symbols.has_this_param(fid) } -/// Whether `fid` is a member function. An in-class prototype carries no -/// parameters, yet merges into a definition whose parameter 0 is `this`, so -/// a parameterless entry is a member when it was declared in its class. fn is_member_function(program: &Program, fid: FnId) -> bool { - let f = program.symbols.function(fid); - if f.params.is_empty() { - f.is_cpp && f.declared_in_class - } else { - has_this_param(program, fid) - } + program.symbols.is_member_function(fid) } /// Collect call arguments once; shared by the member-call, overload and @@ -28004,7 +28288,17 @@ fn return_flow_from_expr( } ResolvedCallReturn::PromotedReceiver(src) => Some(ReturnFlow::Copy { src }), ResolvedCallReturn::Direct(callee_name) => { - if call_may_return_reference(program, ctx, source, node) { + if ctx.is_cpp + && node.cached_field("function").is_some_and(|func| { + std_bind_result(program, ctx, source, node, func, &callee_name) + }) + { + // The returned value belongs to this bind expression. + // Its function body does not supply the binding. + let src = alloc_ret_temp(program, ctx, node); + ctx.call_return_dst.borrow_mut().insert(node.id(), src); + Some(ReturnFlow::Copy { src }) + } else if call_may_return_reference(program, ctx, source, node) { // Read the original cell supplied by this selected // call, rather than re-resolving the overload by name. let ReturnFlow::Copy { src } = @@ -30631,6 +30925,16 @@ fn resolve_callee_with_loads( return result; } let node = peel_value_derefs(program, ctx, source, node); + if ctx.is_cpp + && node.cached_kind() == "call_expression" + && node.cached_field("function").is_some_and(|func| { + resolve_direct_call_name_from_func(source, func) + .is_some_and(|name| std_bind_result(program, ctx, source, node, func, &name)) + }) + { + let var = lower_nested_call_arg(program, ctx, source, node); + return (node_text(source, &node).to_string(), false, var); + } if materialized_expression(program, ctx, source, node) { let var = expression_value(program, ctx, source, node); return (node_text(source, &node).to_string(), false, var); diff --git a/crates/trace-parse/src/merge.rs b/crates/trace-parse/src/merge.rs index b448b6eb..24791acf 100644 --- a/crates/trace-parse/src/merge.rs +++ b/crates/trace-parse/src/merge.rs @@ -1691,18 +1691,31 @@ fn merges_body(program: &Program, mode: MergeMode, function: &Function) -> bool || (function.linkage == trace_ir::Linkage::Internal && function.is_cpp)) } -fn flow_fns(flow: &FlowConstraint) -> impl Iterator { - match flow { +fn flow_fns(flow: &FlowConstraint) -> impl Iterator + '_ { + let args = match flow { + FlowConstraint::BindCallable { args, .. } => args.as_slice(), + _ => &[][..], + }; + let callee = match flow { FlowConstraint::AddrOfFn { callee, .. } | FlowConstraint::ArrayFnMember { callee, .. } | FlowConstraint::CallReturnResolved { callee, .. } - | FlowConstraint::CallReferenceReturnDeclared { callee, .. } => Some(*callee), + | FlowConstraint::CallReferenceReturnDeclared { callee, .. } + | FlowConstraint::BindCallable { + target: trace_ir::BindTarget::Function(callee), + .. + } => Some(*callee), // A call follows the function it is written in: dropped with it in // `valid_flow`, replayed with it in `MergeMode::SymbolsOnly`. FlowConstraint::CallReturn { caller, .. } => *caller, _ => None, - } - .into_iter() + }; + callee + .into_iter() + .chain(args.iter().copied().filter_map(|arg| match arg { + trace_ir::BoundArg::Function(function) => Some(function), + _ => None, + })) } fn return_flow_fns(flow: &ReturnFlow) -> impl Iterator { @@ -2061,6 +2074,30 @@ fn remap_flow( dst: rv(*dst), src: rv(*src), }, + FlowConstraint::BindCallable { dst, target, args } => { + let remap_arg = |arg| match arg { + trace_ir::BoundArg::Stored(var) => trace_ir::BoundArg::Stored(rv(var)), + trace_ir::BoundArg::AddressOf(var) => trace_ir::BoundArg::AddressOf(rv(var)), + trace_ir::BoundArg::MemberAddress(var) => { + trace_ir::BoundArg::MemberAddress(rv(var)) + } + trace_ir::BoundArg::Pack(var) => trace_ir::BoundArg::Pack(rv(var)), + trace_ir::BoundArg::Function(function) => { + trace_ir::BoundArg::Function(rf(function)) + } + trace_ir::BoundArg::Placeholder(_) | trace_ir::BoundArg::Opaque => arg, + }; + FlowConstraint::BindCallable { + dst: rv(*dst), + target: match target { + trace_ir::BindTarget::Function(callee) => { + trace_ir::BindTarget::Function(rf(*callee)) + } + trace_ir::BindTarget::Value(var) => trace_ir::BindTarget::Value(rv(*var)), + }, + args: args.iter().copied().map(remap_arg).collect(), + } + } } } diff --git a/docs/CPP_ROADMAP.md b/docs/CPP_ROADMAP.md index 24dfbfe4..61d00d0a 100644 --- a/docs/CPP_ROADMAP.md +++ b/docs/CPP_ROADMAP.md @@ -127,10 +127,10 @@ Eval **H7**. Three stacked gaps; fixing only intern-as-`FnPtr` is not enough. ## C4 — Deferred callables (`std::bind`, `packaged_task`, `ffrt::submit`) -Hiview’s second dispatch axis: **do this later on a work loop / ffrt -queue**. Lambdas exist as `$lambda` but creators have **0 incoming -edges**; `std::bind` reaches its callable at the bind site (#250), but the -later call through the stored task is not tied back to it. +The analyzer carries [bound callables](IR.md#bound-callables) through +ordinary callable storage to visible indirect calls and modeled task +submissions. Framework and SDK entry points still need visible dispatch +or a corresponding invocation model. | Site | Pattern | |------|---------| @@ -142,42 +142,12 @@ later call through the stored task is not tied back to it. | `uc_telemetry_callback.cpp:187` | `[callback = shared_from_this()] { callback->RunTraceOnTimeTask(); }` | | `platform_monitor.cpp:451` | `std::bind(&PlatformMonitor::CollectPerfProfiler, this)` | -**Design sketch:** - -- `std::bind(&Cls::m, recv, args…)` → `AddrOfFn(Cls::m)` into the - destination callable (ignore bound args for v1; may over-approx). -- `ffrt::submit(F)` / `std::thread(F)` summaries: if `F` is a `$lambda` - or `FnPtr` slot, emit a **direct/indirect** edge from the submit site - to that function (async, same as a call). -- Lambda **captures**: `[this]`, `[callback = shared_from_this()]` copy - the receiver into the lambda’s implicit `this` / first synthetic - field so body member calls type. -- `std::packaged_task` intern as `FnPtr` like `std::function`. - -**Done so far:** thread entry points (`std::thread`, `pthread_create`, -#187) and the OpenHarmony task primitives (#203, `ffrt::submit` among them) -are `invoke` models; the list and its imprecision are in -`docs/MODELS.md`, "Built-in models" and "Documented imprecision". A -submitted lambda (`FaultLogDatabase::SaveFaultLogInfo`, the -`PassthroughMonitor` handlers) now has an edge **from the submitter** -([EVAL_REPORT.md](EVAL_REPORT.md#task-and-thread-primitives-203--2026-10-09)). -Lambda captures bind the enclosing scope (`docs/CXX.md`, "C++ support -(first step)"), and `[callback = shared_from_this()]` captures the object -itself, typed as its `shared_ptr` (`docs/IR.md`, "`shared_from_this`"), -so `uc_telemetry_callback.cpp:187` reaches `RunTraceOnTimeTask`. -`std::bind` and `std::packaged_task` (#250) keep the wrapped callable's edge -from the wrapping site (`base/plugin.cpp:93`, `base/event_loop.cpp:191`), as -`docs/MODELS.md`, "Callable wrappers", states; calling the stored task -(`event.packagedTask->operator()()`) is not tied back to it. Arguments -through a variadic parameter pack are followed since #282 -(`docs/POINTERS.md`, "Variadic parameter packs"). - -**Eval when done:** `Plugin::DelayProcessEvent` reaches `OnEventProxy` (met by -#250); `EventLoop::ProcessEvent` packaged path reaches -`EventHandler::OnEventProxy` (`EventLoop::AddEventForResult`, which builds the -task, reaches it; the call in `ProcessEvent` is not tied to the task). - ---- +The timer fixture in `tests/fixtures/std_bind` covers registration with +an explicit invocation model, including the stored event and receiver. +HiView's `EventLoop` path through `handler.get()` and +`std::packaged_task` also needs storage and invocation of the +wrapper, as described under [Callable wrappers](MODELS.md#callable-wrappers). +External Camera registration requires an appropriate SDK invocation model. ## C5 — Named plugin lookup (`pluginMap_["XPower"]`) @@ -618,7 +588,7 @@ plugins without `dlsym` is C3 (static `REGISTER` ctors). | C1 | `auto p = wp.lock(); p->OnEventProxy();` + `auto l = p->GetWorkLoop(); l->AddEvent(...)` — done, see `tests/fixtures/cpp_auto_return` | | C2 | `Event::DownCastTo(e); sys->SetEventValue(...)` | | C3 | `REGISTER`-like static `PluginRegistInfo(MakeFoo)` + `info->getPluginObject()` | -| C4 | `std::bind(&Plugin::OnEventProxy, this, e)` stored and invoked; `ffrt::submit` summary done, see `tests/fixtures/task_primitives`; `std::bind` / `packaged_task` edge from the wrapping site done (#250, `tests/fixtures/cpp_bind_packaged_task`), the call through the stored task not | +| C4 | Concrete `std::bind` values flow to their invocation. See `tests/fixtures/std_bind`. Packaged-task dispatch remains pending. | | C5 | `map>` + `find("Foo")->second->OnEventProxy()` | | C6 | Proxy field filled by factory, then `proxy->OnEvent()` | | C7 | `map` + `parser(msg)` | diff --git a/docs/CXX.md b/docs/CXX.md index 50b8c787..99d4c832 100644 --- a/docs/CXX.md +++ b/docs/CXX.md @@ -989,8 +989,9 @@ Known C++ imprecision (in addition to the [general list](FAQ.md#known-imprecisio - An out-of-line member definition under `using namespace N;` at global scope registers under the bare class name, apart from `N::`'s in-class prototypes; a call reaching the prototype stays external. -- `std::bind` / generic functors without a visible `operator()` stay - unresolved-indirect unless a function address flows into them. +- [Bound callables](IR.md#bound-callables) carry their target and bindings + through ordinary callable slots. Generic functors need a visible + `operator()` or a function value that flows into the slot. - Default construction without parens (`Cls o;`) emits no ctor site. - **No call site resolves to a conversion operator**: `Cls::operator T` is indexed, but neither the compiler-inserted call of an implicit conversion diff --git a/docs/EVAL_REPORT.md b/docs/EVAL_REPORT.md index 8fc0a14e..5647b59c 100644 --- a/docs/EVAL_REPORT.md +++ b/docs/EVAL_REPORT.md @@ -1,5 +1,49 @@ # Evaluation Report +## Deferred std::bind callables + +On the pinned OpenHarmony revisions, moving bound callbacks from +construction to invocation changed the raw indirect graph as follows. +Both profiles used the embedded models. The canonical checks used +MSYS2 MinGW GCC 15.2.0. + +| Corpus | Default indirect edges | Canonical indirect edges | Indirect edges removed / added | +|---|---:|---:|---| +| HDF | 5,226 ? 5,212 | 5,226 ? 5,212 | 14 / 0 in both profiles | +| HiView | 266 ? 264 | 349 ? 347 | 16 / 14 in both profiles | +| Camera | 475 ? 463 | 500 ? 487 | 16 / 4 default, 17 / 4 canonical | +| Ability Runtime | 2,533 ? 2,537 | 2,536 ? 2,540 | 1 / 5 in both profiles | + +- HDF loses the 14 construction-site edges in the HDI method registries. + The registry invocation remains unresolved. +- HiView gains 11 targets at `EventLoop::ProcessEvent`'s `event.task()`, + including `Plugin::OnEventProxy` with the receiver and event from + `Plugin::DelayProcessEvent`. The filename parser's stored callback reaches + both implementations. The `ffrt::submit` in `InitAndRunTasks` starts + `InitAndRunTask`. The `handler.get()` receiver in the separate + `EventLoop::AddEventForResult` example still reaches a packaged-task + constructor. Dispatch through that wrapper needs storage and invocation + modeling. +- Camera gains the death, common-event and control-center callbacks at + their stored-value calls. The `std::thread` in `MuxerFilter::OnBufferFilled` + starts `EventCompleteStopAsync`. The rotate plugin's external + `openCameraDeviceFunc` needs SDK dispatch or a matching invoke model. + The pool's seven forwarded lambdas now appear as bound values at + `UnifiedPipelineThreadpool::Submit` in both profiles. Their deferred calls + still require packaged-task storage and dispatch. The canonical profile + also preserves the map-selected `CameraRoateParamManager::HandleParamUpdate` + as a bound value in `SubscriberEvent`. +- Ability Runtime gains four `SubmitTask` submission edges and one + `task()` edge in its lambda, all to + `AppMgrServiceInner::AttachedToStatusBar`. The canonical total moves from + 420,591 to 420,595 call edges and from 457,970 to 458,002 argument-flow + rows. + +The default profile passed 199 checks and the canonical profile passed 91, +including the Camera pool probe. Canonical debug HiView and Camera passed +51 checks. The one-job and eight-job exports matched across the analysis +tables after excluding build and run metadata. + ## Nested container cells - 2026-11-26 Containers whose element type is itself a modeled container now get the outer diff --git a/docs/IR.md b/docs/IR.md index 7f4bae94..04ed1554 100644 --- a/docs/IR.md +++ b/docs/IR.md @@ -132,6 +132,7 @@ Lowered from C during parse. Mapped to PAG in `Pag::build_flow_constraints`. | `StringConst { dst, value }` | `dst` points at a string literal | `p = "target"`; `dlsym(h, "target")` | | `NullPointer { dst }` | explicit null pointer value with no points-to target | C++ `nullptr`, including a call argument | | `UnwrapPointer { dst, src }` | cross a smart-pointer wrapper into its pointee (see [Smart-pointer unwrap](#smart-pointer-unwrap)) | C++ `sp->field`, `(*sp).field`, `sp.get()` | +| `BindCallable { dst, target, args }` | `dst` holds the callable `std::bind` built from a named function or callable value, with its arguments including any receiver (see [Bound callables](#bound-callables)) | C++ `f = std::bind(&C::m, this, _1, x)` | `NullPointer` copies from an interned immutable PAG value node into `dst`. That source is not an abstract location and always has an empty points-to set: @@ -969,6 +970,59 @@ The call site itself is recorded as before, so the call edge to the external `sh This is a may-alias relation. It does not check that a `shared_ptr` owns the object: on an unowned object `shared_from_this()` throws `std::bad_weak_ptr` (C++17 and later) and `weak_from_this()` returns an empty `weak_ptr`, and neither outcome is modeled; the result still aliases the object. Expiry, ownership counts, the held class's constness and the C++17 availability of `weak_from_this` are not modeled. +### Bound callables + +A standard `std::bind(f, args...)` in a function body produces a deferred +callable. Lowering records a `BindCallable` with a named function or a +variable holding the target. Name lookup and overload resolution identify +the standard function. A bare name without a declaration requires an +explicit `using std::bind` import. Explicit callable casts can select a +named overload. A single braced bind initializer supplies the +callable slot the same way as a copy initializer. The receiver of a +nonstatic member occupies the first binding slot. Each slot holds a +stored variable, a named function value, a one-based +`std::placeholders::_n` index, an expanded trailing pack, or an opaque value. +Stored dereferences use the [ordinary argument rules](#dereferenced-operands) +for the bound target's formal when known. Stored address expressions carry +their ordinary argument metadata through invocation, including the +member-address fallback used by alias models. + +The PAG gives each binding its own `Bound` points-to location per target. +For a variable target, the solver creates these locations as ordinary +function locations reach the variable. Copies, field stores and loads, +returns, and parameter passing preserve that location. Indirect calls and +modeled invocations resolve targets such as forwarded functions and lambdas +through the ordinary link-image-aware function lookup. Each binding +wires its arguments independently, even if other bindings at the same +invocation reach the same function. Persistent argument copies propagate +the stored values and the invocation values selected by placeholders. +At an indirect call, argument and callback models on the bound target +read these same composed actuals. A value supplied by a model, such as +a stop token, occupies an invocation slot +even when it contributes no points-to information. +Repeated placeholders can feed several formals. Extra invocation +arguments are ignored. An argument supplied by the invocation is +reported at its position in that call, while a stored argument is +reported at the invoking site with its destination formal's position. +Identical argument-flow rows from multiple bindings are exported once. +The invocation also receives ordinary indirect return flow. An execution +context comes from the model that invokes the callable, when applicable. + +The model tracks ordinary variable, pointer, and named function +arguments using the analysis's existing flow-insensitive value model. +An opaque slot or a missing placeholder argument contributes no value. +A trailing expanded pack supplies its index-insensitive value to each +remaining formal. Ambiguous overloads, target variables with no reachable +ordinary function, other binding pack layouts, and targets with variadic +template parameters stay opaque. +File-scope bind initializers remain opaque. The receiver mapping supports +object pointers, including explicit address expressions and placeholders. +Nested bind arguments, custom placeholders, reference wrappers, by-value +receiver object identity, and virtual member dispatch remain outside this +model. The wrapping site retains its ordinary call to `std::bind` and +starts no callable execution. See [Callable wrappers](MODELS.md#callable-wrappers) +for packaged tasks and task APIs. + ### `dlsym` / `GetProcAddress` Built-in models treat `dlsym` / `dlvsym` / `GetProcAddress` as **symbol lookup**: the return destination of a call (the `CallSite.return_dst` of `f = dlsym(...)`, including `return dlsym(...)` via a temp) may point to every **in-tree** function whose exact name matches a string constant in the name argument (parameter 1). Out-of-tree names add no pointees (true external). The handle / DSO path is ignored. Lookup searches the caller’s link target and its incorporated dependencies when link metadata exists, otherwise the whole program. Dynamically loaded targets absent from that dependency closure are not modeled. Non-literal names that never receive a string constant stay unresolved — they do **not** fan out to every exported function. diff --git a/docs/MODELS.md b/docs/MODELS.md index ea58596a..d1054f43 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -248,61 +248,29 @@ image as an indirect call's targets are. and no `async_start` boundary. Only an `invoke` may say it (an `entry` is where a context starts), and the context graph then treats the wrapping site's edge as an ordinary call. -- **Not modeled.** No ordering or scheduling (the callback is simply - reachable from the starting site), no return value, and no bound state: - a `std::bind` result, a `std::packaged_task` and a `std::function` object - are not looked into. What the first two do keep reachable is - [Callable wrappers](#callable-wrappers). +- **Bound callables.** An invocation of a [bound callable](IR.md#bound-callables) + composes the arguments forwarded by the model with the stored arguments + and receiver. A supplied value occupies the first invocation slot + when the callback accepts it, shifting which arguments later + placeholders receive. The model attributes the callback and its + execution context to the submission site. Callback scheduling and + callback returns to the submitting API are outside this mapping. #### Callable wrappers -`std::bind(f, args...)` and `std::packaged_task(f)` only wrap a -callable that something runs later, usually a thread pool's worker. No value in the analysis carries a -callable on, so the later call, `task()` or `(*task)()`, cannot be tied back -to `f`. Both are therefore `invoke` models that start no context, `context = -"none"` ([Built-in models](#built-in-models)): `std::bind` with `param = 0, -rest = 1` and `std::packaged_task::packaged_task` with `param = 0, rest = 1`: the -constructor forwards no argument, and `rest` (not an empty `args`) lets the -stored callable take any number of parameters, as the task's signature, not the -constructor, says what it is called with. This is what keeps a -`Submit`-style pool's `Submit -> f` edge, from `std::bind(std::forward(f), -...)` inside `Submit`, where `f` is the callable the pool's caller passed. - -- **The edge is the wrapping site's.** It runs from the function that builds - the bind or the task, at that site, not from the caller of `operator()`. - It is an over-approximation: it exists whether or not the task ever runs, - and a bind that is built and then dropped has it too. -- **Bound arguments.** `rest = 1` wires the arguments after the callable into - the callable's formals as for `std::thread`, so a named bound argument - reaches the callable's formal. The model does not read `std::placeholders`: - nothing supplies the later caller's arguments. -- **A parameter pack is followed.** An argument passed through a - variadic template's `Args&&... args` reaches the callable's formal: - `Submit(f, a)` carries `a` through the pack and out through - `std::forward(args)...` into `f`'s formals, as a named parameter - would ([Variadic parameter packs](POINTERS.md#variadic-parameter-packs), including - what it over-approximates). -- **No execution context.** Both models state `context = "none"`: nothing - starts at a bind or at a task's construction, so a match exports no - `execution_contexts` row and, in call sequencing, no `async_start` - boundary; the wrapping site is an ordinary call. Where the callable runs - is for whatever later calls the task, which the analysis does not follow. - A `--models` entry for another wrapper (a task-making helper, an - `emplace`-style forwarder) states `context = "none"` the same way. -- **Built through a factory.** `std::make_shared>(f)` - and `std::make_unique<...>(f)` take the constructor model too, from a named - function or a lambda: the factory's constructor site - ([Factory construction](CXX.md#factory-construction)) is the one the model - matches, with `f` as its first argument, so the edge runs from the function - holding the factory call. Pinned by `tests/fixtures/cpp_bind_packaged_task`. - A task whose signature names an enclosing template's parameter - (`std::packaged_task` in `template `) is the same class, - so it reaches its callable too, as `new std::packaged_task(f)` does. - `Submit`'s `std::packaged_task` records the site as well, but - its argument is a bind result, not a function, so the site adds an external - edge and the edge to the callable still comes from the `std::bind`. -- **`std::function`.** No model: a callable stored in one flows through the - ordinary copy and points-to handling, and calling it is an indirect call. +[Bound callables](IR.md#bound-callables) describes the modeled subset of +`std::bind`, which builds a value without invoking anything. A +`std::function` slot carries the value through ordinary points-to flow and +invokes it through an indirect call. + +The `std::packaged_task` constructor retains its legacy context-less +reachability edge for ordinary function values. Its `param = 0, rest = 1` +model permits the stored function's arity to differ from the constructor's +arity. Smart-pointer factories emit the same constructor site +([Factory construction](CXX.md#factory-construction)). The constructor +starts no execution context. Propagating a bound value from this +constructor to `task()` or `(*task)()` still requires a model of the +packaged task's storage and invocation. ### Execution contexts @@ -442,8 +410,7 @@ entries: | `std::thread::thread` | `invoke param=0 rest=1 context=thread` (callable and everything after it); covers a temporary recorded as `std::thread` | | `std::jthread::jthread` | `invoke param=0 rest=1 supplies=std::stop_token context=thread` (as `std::thread`, with the thread's stop token first to a callable that takes one); covers a temporary recorded as `std::jthread` | | `std::async` | `invoke param=0 rest=1 unless_arg={param=0, type=std::launch} context=thread` and `invoke param=1 rest=2 if_arg={param=0, type=std::launch} context=thread` (the callable first, or after a launch policy) | -| `std::bind` | `invoke param=0 rest=1 context=none` (the callable and the arguments bound after it; [Callable wrappers](#callable-wrappers)) | -| `std::packaged_task::packaged_task` | `invoke param=0 rest=1 context=none` (the callable the task stores, of any arity; the constructor forwards no argument; a bind result is not a function, so the bind site makes the edge) | +| `std::packaged_task::packaged_task` | `invoke param=0 rest=1 context=none` (legacy reachability for ordinary function values of any arity). A bound value contributes its edge when invoked, and following it through packaged-task storage requires the wrapper support described under [Callable wrappers](#callable-wrappers). | | `OHOS::Thread::Run` | `entry context=thread` (c_utils runs it on the thread `Start` creates) | | `OHOS::AppExecFwk::EventHandler::ProcessEvent` | `entry context=serial_task` (the handler's event runner calls it) | | `OHOS::IRemoteObject::DeathRecipient::OnRemoteDied` | `entry context=ipc_handler` (an IPC thread calls it when the remote dies) | @@ -816,8 +783,8 @@ effects = [ { kind = "invoke", param = 0, rest = 1, supplies = "Token", context **Wrappers that start nothing** -`std::bind` and `std::packaged_task` keep a callable reachable without running -it. `context = "none"` keeps the call edge and forwarded arguments but starts no +A model can keep a callable reachable from a wrapper such as a +`std::packaged_task` constructor. `context = "none"` keeps the call edge and forwarded arguments but starts no execution context and no `async_start` boundary: ```toml diff --git a/docs/POINTERS.md b/docs/POINTERS.md index 108c4026..56b415f7 100644 --- a/docs/POINTERS.md +++ b/docs/POINTERS.md @@ -572,8 +572,8 @@ is added: the wiring is the ordinary actual-to-formal copy of position too, as a pack variable: it may reach any formal from there on. - **Arity.** An expansion may be empty. At an `invoke` site ([Callback invocation](MODELS.md#callback-invocation-invoke)) only the positions before - it count as passed, so a callable that takes nothing is still the one a - `std::bind(f, args...)` runs when `args` is empty. + it count as passed, so a model can invoke a zero-argument callback when + its forwarded pack may be empty. - **Arg-flow rows.** A row is the position the actual is recorded at and the formal it reached, so a pack formal has one row per later position that passes a variable or a function (a literal records none), and a formal diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 6e719075..7a7cc66e 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -165,7 +165,7 @@ Further index-time wins: smarter header/preprocess skipping, incremental TU cach | C++ first-step | `cpp_basic/`, `cpp_more/`, `cpp_flow/`, `cpp_implicit_this/`, `cpp_callable/`, `cpp_dispatch/`, `cpp_extern_c_driver/` | | C++ member-initializer construction (#207) | `cpp_implicit_member_initializers/`, `cpp_nested_member_initializers/`, `cpp_member_initializer_review/`, `cpp_unknown_member_copy/`, `cpp_constructor_subobjects/` and `constructor_review.rs` cover own/inherited overload lookup with cv/ref distinctions, C++20 aggregates, constant and unknown array bounds, inherited construction with scoped default initializers, implicit copy/move subobjects, unknown class/union copies and cached/grouped reference bindings — [rules](CXX.md#c-support-first-step) | | C++ `auto` from declared returns (C1) | `cpp_auto_return/` | -| C++ next (planned) | [CPP_ROADMAP.md](CPP_ROADMAP.md) — `DownCastTo`, `REGISTER`+map, `std::bind` called through its stored task (the wrapping-site edge, #250, and `ffrt::submit` and the other task primitives, #203, are modelled) | +| C++ next (planned) | [CPP_ROADMAP.md](CPP_ROADMAP.md) — `DownCastTo`, `REGISTER`+map, `std::packaged_task` storage and invocation (concrete `std::bind` values and `ffrt::submit` are modeled) | | Weak symbols / link targets | `weak_symbol_override/`, `weak_annotations/` | | Adversarial / limitations | `tests/fixtures/adversarial_*`, `macro_*` | diff --git a/docs/SQLITE_SCHEMA.md b/docs/SQLITE_SCHEMA.md index 632c84b1..f15e219c 100644 --- a/docs/SQLITE_SCHEMA.md +++ b/docs/SQLITE_SCHEMA.md @@ -271,8 +271,9 @@ these rows treats them as follows: Generated `::$lambda:` name segments are removed from public dictionary text and from `locations.desc`; raw strings retain the original text under the same IDs, and `raw_locations` keeps the original descriptions. A -lambda's `Function` location reads `anonymous callable`, as its `flow_nodes` -label does, because the name left after stripping would be its parent's. A +lambda's `Function` or `Bound` location reads `anonymous callable`. The +corresponding `flow_nodes` label uses the same text and its function ID is +null because the callable has no public function entry. A `StringLit` location and its `string:` flow-node label keep their text, which is the program's own. Source-level lambda expressions are not removed from source expressions. @@ -624,7 +625,7 @@ contract. |--------|------|-------------| | `id` | INTEGER PK | Edge id | | `call_site_id` | INTEGER FK → `call_sites` | Call site | -| `arg_index` | INTEGER | 0-based parameter position the argument binds to; for a C++ member function or constructor 0 is the implicit `this`, so explicit arguments start at 1 | +| `arg_index` | INTEGER | 0-based argument position at the call site. A member or constructor can record its receiver at position 0. A stored bind argument uses the position of its destination formal | | `actual_var_id` | INTEGER FK → `variables` | Actual variable (`NULL` if actual is a function) | | `actual_fn_id` | INTEGER FK → `functions` | Actual function for fn-ptr args (`NULL` if actual is a variable) | | `formal_var_id` | INTEGER FK → `variables` | Callee parameter var | @@ -642,7 +643,7 @@ v7 export written before it existed has no `execution_contexts` table, so a reader checks for the table (and the columns it reads) instead of the schema version; in an ordinary analysis an empty table means no context was found. A callable only wrapped (`std::bind`, `std::packaged_task`) starts nothing and -has no row: a model states that with `context = "none"`, which is no `kind`. +has no row. A packaged-task wrapper model uses `context = "none"`. | Column | Type | Description | |--------|------|-------------| @@ -902,7 +903,7 @@ PAG abstract locations (`--full-export` or `--debug-points-to`). | Column | Type | Description | |--------|------|-------------| | `id` | INTEGER PK | Location id | -| `kind` | TEXT | `Global`, `FileStatic`, `FnStatic`, `Local`, `Heap`, `Field`, `FieldSummary`, `ArraySummary`, `Function`, `StringLit` | +| `kind` | TEXT | `Global`, `FileStatic`, `FnStatic`, `Local`, `Heap`, `Field`, `FieldSummary`, `ArraySummary`, `Function`, `StringLit`, `Bound` | | `desc` | TEXT | Description | | `type_id` | INTEGER FK → `types` | Optional | diff --git a/scripts/eval_expected.json b/scripts/eval_expected.json index e284309d..ecd49041 100644 --- a/scripts/eval_expected.json +++ b/scripts/eval_expected.json @@ -1,5 +1,5 @@ { - "note": "PR #257 expectation centers were recaptured relative to parent aa6f846, including HDF functions_total 12198 -> 12172, indirect edges 5153 -> 5226 and arg_flow_edges 72400 -> 72585; HiView and Camera centers were also recaptured. The 2026-11-13 owner-dependency/reference-alias/receiver-qualification follow-up remeasured every HDF, HiView and Camera global with release analyzer 3980106-dirty including all production changes in this amend, at jobs 1 and 8, matching the preceding 3980106 review snapshot. Existing tolerances were retained. Source/binary identities, strict compiler cases, parent differential residuals and the Camera metadata audit are in docs/EVAL_REPORT.md, Dependent owners, reference aliases and receiver qualification. Ability Runtime was recaptured from local master bb64b1e on 2026-11-19 with unchanged tolerances. See docs/EVAL_REPORT.md for the rebase comparison. The 2026-11-20 binder Host/interface-overload change recaptured only the affected exact IPC centers: Camera 808 -> 702 and ability_runtime 1762 -> 1641, with HDF and HiView unchanged. Ability_runtime's SendTransactCmd-only probes moved to 661 edges and 233 sender functions. The 2026-11-23 AAFwk TaskHandlerWrap::SubmitTask/SubmitTaskJust invoke models recaptured ability_runtime edges_indirect 2043 -> 2533 and public_edges_total 376130 -> 377471; the new probe pins AmsMgrScheduler::StartSpecifiedAbility reaching AppMgrServiceInner::StartSpecifiedAbility through its submitted lambda. The 2026-11-23 binder-wrapper member-resolution change recaptured ability_runtime public_functions_total 77351 -> 76978 and public_edges_total 377471 -> 379668, and one evaluated DataObsOption default constructor (75 -> 76); IPC and indirect centers are unchanged and the TaskHandler probe still passes.", + "note": "PR #257 expectation centers were recaptured relative to parent aa6f846, including HDF functions_total 12198 -> 12172, indirect edges 5153 -> 5226 and arg_flow_edges 72400 -> 72585; HiView and Camera centers were also recaptured. The 2026-11-13 owner-dependency/reference-alias/receiver-qualification follow-up remeasured every HDF, HiView and Camera global with release analyzer 3980106-dirty including all production changes in this amend, at jobs 1 and 8, matching the preceding 3980106 review snapshot. Existing tolerances were retained. Source/binary identities, strict compiler cases, parent differential residuals and the Camera metadata audit are in docs/EVAL_REPORT.md, Dependent owners, reference aliases and receiver qualification. Ability Runtime was recaptured from local master bb64b1e on 2026-11-19 with unchanged tolerances. See docs/EVAL_REPORT.md for the rebase comparison. The 2026-11-20 binder Host/interface-overload change recaptured only the affected exact IPC centers: Camera 808 -> 702 and ability_runtime 1762 -> 1641, with HDF and HiView unchanged. Ability_runtime's SendTransactCmd-only probes moved to 661 edges and 233 sender functions. The 2026-11-23 AAFwk TaskHandlerWrap::SubmitTask/SubmitTaskJust invoke models recaptured ability_runtime edges_indirect 2043 -> 2533 and public_edges_total 376130 -> 377471; the new probe pins AmsMgrScheduler::StartSpecifiedAbility reaching AppMgrServiceInner::StartSpecifiedAbility through its submitted lambda. The 2026-11-23 binder-wrapper member-resolution change recaptured ability_runtime public_functions_total 77351 -> 76978 and public_edges_total 377471 -> 379668, and one evaluated DataObsOption default constructor (75 -> 76); IPC and indirect centers are unchanged and the TaskHandler probe still passes. The bind update moves callback edges to invocation sites. See docs/EVAL_REPORT.md, Deferred std::bind callables.", "budget_pops": 800000, "jobs": 8, "corpora": { @@ -15,7 +15,7 @@ "functions_external": {"cmp": "band", "value": 1866, "tol": 40}, "edges_total": {"cmp": "band", "value": 78974, "tol": 240}, "edges_direct": {"cmp": "band", "value": 49816, "tol": 240}, - "edges_indirect": {"cmp": "exact", "value": 5226}, + "edges_indirect": {"cmp": "exact", "value": 5212}, "edges_external": {"cmp": "band", "value": 23874, "tol": 200}, "edges_ipc": {"cmp": "exact", "value": 58}, "arg_flow_edges": {"cmp": "band", "value": 72585, "tol": 150}, @@ -40,6 +40,7 @@ {"case": "WorkEntry (linux workqueue)", "caller": "%WorkEntry", "caller_file": "%linux/osal/src/osal_workqueue.c%", "line": 0, "resolution": "indirect", "expected": 20} ], "probes": [ + {"name": "std::bind construction emits no indirect callback edge", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id WHERE e.resolution='indirect' AND s.callee_text IN ('std::bind','::std::bind')", "cmp": "exact", "value": 0}, {"name": "reinterpreted void worker retains its int-returning HDF thread-entry call (#257)", "sql": "SELECT COUNT(*) FROM call_edges e JOIN functions c ON c.id=e.caller_fn_id JOIN functions t ON t.id=e.callee_fn_id WHERE e.resolution='indirect' AND c.name='OsalThreadFn' AND t.name='HdfThreadMain'", "cmp": "exact", "value": 1}, {"name": "a wrapped callable starts no execution context (#283)", "sql": "SELECT COUNT(*) FROM execution_contexts WHERE model IN ('std::bind','std::packaged_task::packaged_task')", "cmp": "exact", "value": 0}, {"name": "first-member cast arguments retain six HdfRemoteService field projections (#244)", "sql": "SELECT COUNT(*) FROM arg_flow_edges a JOIN call_sites s ON s.id=a.call_site_id JOIN files p ON p.id=s.file_id JOIN variables f ON f.id=a.formal_var_id JOIN variables v ON v.id=a.actual_var_id JOIN files vp ON vp.id=v.file_id WHERE p.path LIKE '%/framework/core/manager/test/unittest/common/hdf_remote_adapter_test.cpp' AND s.line IN(50,52,91,96,98,103) AND a.arg_index=0 AND f.name='service' AND EXISTS (SELECT 1 FROM flow_nodes n JOIN flow_edges e ON e.dst_node=n.id WHERE n.var_id=v.id AND e.kind='gep')", "cmp": "exact", "value": 6}, @@ -88,7 +89,7 @@ "functions_external": {"cmp": "band", "value": 1770, "tol": 120}, "edges_total": {"cmp": "band", "value": 39500, "tol": 160}, "edges_direct": {"cmp": "band", "value": 24105, "tol": 160}, - "edges_indirect": {"cmp": "exact", "value": 266}, + "edges_indirect": {"cmp": "exact", "value": 264}, "edges_external": {"cmp": "band", "value": 15085, "tol": 160}, "edges_ipc": {"cmp": "exact", "value": 44}, "arg_flow_edges": {"cmp": "band", "value": 33789, "tol": 120}, @@ -107,6 +108,9 @@ {"case": "PluginProxy::GetHandlerInfo", "caller": "%PluginProxy::GetHandlerInfo", "line": 62, "resolution": "all", "expected": 2} ], "probes": [ + {"name": "std::bind construction emits no indirect callback edge", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id WHERE e.resolution='indirect' AND s.callee_text IN ('std::bind','::std::bind')", "cmp": "exact", "value": 0}, + {"name": "Timer dispatch forwards the binding receiver and event to Plugin::OnEventProxy", "sql": "SELECT COUNT(*) FROM arg_flow_edges a JOIN call_sites s ON s.id=a.call_site_id JOIN functions c ON c.id=s.caller_fn_id JOIN variables actual ON actual.id=a.actual_var_id JOIN functions owner ON owner.id=actual.fn_id JOIN variables formal ON formal.id=a.formal_var_id JOIN functions t ON t.id=formal.fn_id WHERE c.name='OHOS::HiviewDFX::EventLoop::ProcessEvent' AND s.callee_text='event.task' AND t.name='OHOS::HiviewDFX::Plugin::OnEventProxy' AND owner.name='OHOS::HiviewDFX::Plugin::DelayProcessEvent' AND (formal.name,actual.name) IN (('this','this'),('event','event'))", "cmp": "exact", "value": 2}, + {"name": "ffrt::submit starts the bound InitAndRunTask in a pool task", "sql": "SELECT EXISTS(SELECT 1 FROM execution_contexts x JOIN call_sites s ON s.id=x.call_site_id JOIN functions t ON t.id=x.entry_fn_id WHERE s.callee_text='ffrt::submit' AND t.name='OHOS::HiviewDFX::EventExportEngine::InitAndRunTask' AND x.kind='pool_task')", "cmp": "exact", "value": 1}, {"name": "a wrapped callable starts no execution context (#283)", "sql": "SELECT COUNT(*) FROM execution_contexts WHERE model IN ('std::bind','std::packaged_task::packaged_task')", "cmp": "exact", "value": 0}, {"name": "const-reference string defaults bind eight SettingObserverManager temporaries (#244)", "sql": "SELECT COUNT(*) FROM arg_flow_edges a JOIN call_sites s ON s.id=a.call_site_id JOIN files p ON p.id=s.file_id JOIN variables f ON f.id=a.formal_var_id JOIN variables v ON v.id=a.actual_var_id JOIN files vp ON vp.id=v.file_id WHERE f.name='defaultVal' AND a.arg_index=2 AND vp.path LIKE '%/base/utility/include/setting_observer_manager.h' AND v.line=49 AND EXISTS (SELECT 1 FROM flow_nodes n JOIN flow_edges e ON e.dst_node=n.id WHERE n.var_id=v.id AND e.kind='addr_of')", "cmp": "exact", "value": 8}, {"name": "retained HiView default calls preserve all 19 named caller identities (#244)", "sql": "WITH expected(caller,file,line,col,target,resolution) AS (VALUES ('OHOS::HiviewDFX::AdapterUtilityOhosTest_TimeUtilOhosTest002_Test::TestBody','base/utility/include/time_util.h',57,45,'std::time','external'),('OHOS::HiviewDFX::DBHelper::SelectEventFromDB','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::DBHelper::SelectRecords','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::DBHelper::SelectRecordsByPidUid','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::FaultLogDatabase::GetAppFreezeExtInfoFromFileName','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::FaultLogDatabase::GetFaultInfoList','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::FaultLogDatabase::IsFaultExist','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::FoldAppUsageEventFactory::Create','base/utility/include/time_util.h',57,45,'std::time','external'),('OHOS::HiviewDFX::FoldAppUsageTest::SetUp','base/utility/include/time_util.h',57,45,'std::time','external'),('OHOS::HiviewDFX::FoldEventCacher::CountLifeCycleDuration','base/utility/include/time_util.h',57,45,'std::time','external'),('OHOS::HiviewDFX::HisysEventUtil::IsEventProcessed','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::SysEventDaoTest_TestEventDaoQuery_002_Test::TestBody','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::SysEventDaoTest_TestEventDaoQuery_003_Test::TestBody','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::SysEventDaoTest_TestEventDaoQuery_004_Test::TestBody','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::SysEventDaoTest_TestEventDaoQuery_005_Test::TestBody','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::SysEventDaoTest_TestEventDaoQuery_011_Test::TestBody','base/event_store/include/sys_event_query.h',299,39,'std::make_pair','external'),('OHOS::HiviewDFX::UsageEventReport::Init','base/utility/include/time_util.h',57,45,'std::time','external'),('OHOS::HiviewDFX::UsageEventReport::InnerReportDailyEvent','base/utility/include/time_util.h',57,45,'std::time','external'),('OHOS::HiviewDFX::UsageEventReport::ReportDailyEvent','base/utility/include/time_util.h',57,45,'std::time','external')) SELECT COUNT(*) FROM expected x WHERE EXISTS (SELECT 1 FROM call_sites s JOIN functions c ON c.id=s.caller_fn_id JOIN files p ON p.id=s.file_id JOIN call_edges e ON e.call_site_id=s.id JOIN functions t ON t.id=e.callee_fn_id WHERE c.name=x.caller AND p.path LIKE '%/'||x.file AND s.line=x.line AND s.col=x.col AND t.name=x.target AND e.resolution=x.resolution)", "cmp": "exact", "value": 19}, @@ -148,7 +152,7 @@ "functions_external": {"cmp": "band", "value": 3733, "tol": 120}, "edges_total": {"cmp": "band", "value": 117298, "tol": 420}, "edges_direct": {"cmp": "band", "value": 70073, "tol": 420}, - "edges_indirect": {"cmp": "exact", "value": 475}, + "edges_indirect": {"cmp": "exact", "value": 463}, "edges_external": {"cmp": "band", "value": 45942, "tol": 420}, "edges_ipc": {"cmp": "exact", "value": 702}, "arg_flow_edges": {"cmp": "band", "value": 60961, "tol": 250}, @@ -165,6 +169,10 @@ {"case": "CaptureSession::AddOutput CanAddOutput", "caller": "%CaptureSession::AddOutput", "line": 1272, "resolution": "all", "expected": 19} ], "probes": [ + {"name": "std::bind construction emits no indirect callback edge", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id WHERE e.resolution='indirect' AND s.callee_text IN ('std::bind','::std::bind')", "cmp": "exact", "value": 0}, + {"name": "Stored Camera bindings reach the common event, death and control-center callbacks", "sql": "SELECT COUNT(DISTINCT t.name) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id JOIN functions t ON t.id=e.callee_fn_id WHERE e.resolution='indirect' AND (s.callee_text,t.name) IN (('this->eventReceiver_','OHOS::CameraStandard::HCameraService::OnReceiveEvent'),('this->diedCb_','OHOS::CameraStandard::DeferredVideoProcSession::CameraServerDied'),('this->updateControlCenterCallback_','OHOS::CameraStandard::HCameraService::UpdateControlCenterStatus'))", "cmp": "exact", "value": 3}, + {"name": "Camera pool preserves seven forwarded lambdas as bound values", "sql": "SELECT COUNT(DISTINCT n.fn_id) FROM flow_origins o JOIN flow_nodes n ON n.id=o.src_node JOIN functions t ON t.id=n.fn_id JOIN files p ON p.id=o.file_id WHERE p.path LIKE '%unified_pipeline_threadpool.h' AND o.line=72 AND n.detail='bound' AND t.name LIKE '%::$lambda%'", "cmp": "exact", "value": 7}, + {"name": "The std::thread submission starts bound EventCompleteStopAsync", "sql": "SELECT EXISTS(SELECT 1 FROM execution_contexts x JOIN call_sites s ON s.id=x.call_site_id JOIN functions t ON t.id=x.entry_fn_id WHERE s.callee_text='std::thread::thread' AND t.name='OHOS::CameraStandard::MuxerFilter::EventCompleteStopAsync' AND x.kind='thread')", "cmp": "exact", "value": 1}, {"name": "a wrapped callable starts no execution context (#283)", "sql": "SELECT COUNT(*) FROM execution_contexts WHERE model IN ('std::bind','std::packaged_task::packaged_task')", "cmp": "exact", "value": 0}, {"name": "pack formals receive their arguments: CameraNapiObjectTypes::Hold takes 52 (#282)", "sql": "SELECT COUNT(*) FROM arg_flow_edges a JOIN variables f ON f.id=a.formal_var_id JOIN functions c ON c.id=f.fn_id WHERE c.name='OHOS::CameraStandard::CameraNapiObjectTypes::Hold' AND f.name='args'", "cmp": "exact", "value": 52}, {"name": "const-reference moviePath defaults bind all 136 retained VideoInfo arguments (#244)", "sql": "SELECT COUNT(*) FROM arg_flow_edges a JOIN call_sites s ON s.id=a.call_site_id JOIN files p ON p.id=s.file_id JOIN variables f ON f.id=a.formal_var_id JOIN variables v ON v.id=a.actual_var_id JOIN files vp ON vp.id=v.file_id WHERE f.name='moviePath' AND a.arg_index=4 AND vp.path LIKE '%/services/deferred_processing_service/include/base/video_info.h' AND v.line IN(30,32) AND EXISTS (SELECT 1 FROM flow_nodes n JOIN flow_edges e ON e.dst_node=n.id WHERE n.var_id=v.id AND e.kind='addr_of')", "cmp": "exact", "value": 136}, @@ -197,7 +205,6 @@ {"name": "an FFI entry point is indexed under its own name and defined (#46: the definition hid behind the glued spelling, so this function was absent from the index under its own name)", "sql": "SELECT COUNT(*) FROM functions WHERE name='OHOS::CameraStandard::FfiCameraZoomGetZoomRatioRange' AND is_defined=1", "cmp": "exact", "value": 1}, {"name": "a `[[deprecated]]`-annotated member is indexed under its own name (#46 review: all 26 of `CameraInput`'s annotated members collapsed into a single `CameraInput::deprecated`; scoped to the name rather than the file so a moved path cannot make this pass vacuously)", "sql": "SELECT COUNT(*) FROM functions WHERE name='OHOS::CameraStandard::CameraInput::LockForControl'", "cmp": "exact", "value": 1}, {"name": "`sptr::MakeSptr(...)` constructs its class (#192: moving_photo_proxy.cpp:263 had only the external `sptr::MakeSptr` edge, 0 on the baseline)", "sql": "SELECT COUNT(*) FROM call_edges e JOIN functions c ON c.id = e.caller_fn_id JOIN functions t ON t.id = e.callee_fn_id WHERE c.name='OHOS::CameraStandard::MovingPhotoManagerProxy::CreateMovingPhotoManagerProxy' AND t.name='OHOS::CameraStandard::MovingPhotoManagerProxy::MovingPhotoManagerProxy'", "cmp": "exact", "value": 1}, - {"name": "UnifiedPipelineThreadpool::Submit reaches the 7 lambdas it binds through std::bind (#250)", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id JOIN functions f ON f.id=e.caller_fn_id WHERE e.resolution='indirect' AND s.callee_text='std::bind' AND f.name='OHOS::CameraStandard::UnifiedPipelineThreadpool::Submit'", "cmp": "exact", "value": 7}, {"name": "grouped member-pointer casts parse in both Camera callback emitters (#246 grouping)", "sql": "SELECT COUNT(*) FROM diagnostics d LEFT JOIN files f ON f.id=d.file_id WHERE d.stage='parse' AND (f.path LIKE '%/camera_napi_event_emitter.h' OR d.message LIKE '%/camera_napi_event_emitter.h' OR d.message LIKE '%/camera_napi_event_emitter.h:%' OR f.path LIKE '%/camera_event_emitter_taihe.h' OR d.message LIKE '%/camera_event_emitter_taihe.h' OR d.message LIKE '%/camera_event_emitter_taihe.h:%')", "cmp": "exact", "value": 0} ] }, @@ -209,11 +216,13 @@ "analyze_args": ["--ignore-logging", "--timeout-secs", "600"], "globals": { "edges_ipc": {"cmp": "exact", "value": 1641}, - "edges_indirect": {"cmp": "exact", "value": 2533}, + "edges_indirect": {"cmp": "exact", "value": 2537}, "public_functions_total": {"cmp": "band", "value": 76978, "tol": 400}, "public_edges_total": {"cmp": "band", "value": 379668, "tol": 1300} }, "probes": [ + {"name": "std::bind construction emits no indirect callback edge", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id WHERE e.resolution='indirect' AND s.callee_text IN ('std::bind','::std::bind')", "cmp": "exact", "value": 0}, + {"name": "The TaskHandlerWrap::SubmitTask lambda invokes the bound AttachedToStatusBar", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id JOIN functions c ON c.id=e.caller_fn_id JOIN functions t ON t.id=e.callee_fn_id WHERE e.resolution='indirect' AND s.callee_text='task' AND c.name GLOB 'OHOS::AAFwk::TaskHandlerWrap::SubmitTask::$lambda*' AND t.name='OHOS::AppExecFwk::AppMgrServiceInner::AttachedToStatusBar'", "cmp": "exact", "value": 1}, {"name": "a wrapped callable starts no execution context (#283)", "sql": "SELECT COUNT(*) FROM execution_contexts WHERE model IN ('std::bind','std::packaged_task::packaged_task')", "cmp": "exact", "value": 0}, {"name": "an AAFwk task handler's submitted task reaches its callback from the submission site (AmsMgrScheduler::StartSpecifiedAbility -> AppMgrServiceInner::StartSpecifiedAbility)", "sql": "SELECT COUNT(DISTINCT t.id) FROM call_edges e JOIN functions c ON c.id=e.caller_fn_id JOIN functions t ON t.id=e.callee_fn_id WHERE e.resolution='indirect' AND c.name='OHOS::AppExecFwk::AmsMgrScheduler::StartSpecifiedAbility' AND t.name='OHOS::AppExecFwk::AppMgrServiceInner::StartSpecifiedAbility'", "relations": "public", "cmp": "exact", "value": 1}, {"name": "the solver converges within the check's budget (a partial fixpoint silently drops indirect edges, as 800000 pops did for #271)", "sql": "SELECT COUNT(*) FROM diagnostics WHERE stage='analyze' AND message LIKE 'solver stopped early%'", "cmp": "exact", "value": 0}, diff --git a/scripts/eval_expected_canonical.json b/scripts/eval_expected_canonical.json index 8f6f74a4..4d3b5251 100644 --- a/scripts/eval_expected_canonical.json +++ b/scripts/eval_expected_canonical.json @@ -1,5 +1,5 @@ { - "note": "Pinned corpora in canonical system-header mode with the embedded models. Recaptured after rebasing onto local master bb64b1e on Windows 11 x64 with MSYS2 MinGW GCC 15.2.0. Header-dependent totals use that toolchain as the reference. Counts include the 2026-11-20 vector specialization audit. The 2026-11-20 binder Host/interface-overload change recaptured the canonical IPC centers: Camera 808 -> 702 and ability_runtime 1762 -> 1641; ability_runtime edges_total 418036 -> 417915 and diagnostics 11944 -> 11945; HDF and HiView IPC counts are unchanged. The 2026-11-23 AAFwk TaskHandlerWrap::SubmitTask/SubmitTaskJust invoke models recaptured ability_runtime edges_total 417915 -> 418405, edges_indirect 2043 -> 2533 and public_edges_total 409148 -> 410574, with the same run reporting diagnostics 11944; the new probe pins AmsMgrScheduler::StartSpecifiedAbility reaching AppMgrServiceInner::StartSpecifiedAbility through its submitted lambda. The 2026-11-23 binder-wrapper member-resolution change recaptured ability_runtime functions_total 89063 -> 88690, functions_external 20414 -> 20041, edges_total 418405 -> 420602, edges_direct 255993 -> 257078, edges_external 158238 -> 159350, arg_flow_edges 455892 -> 457968, public_functions_total 85660 -> 85287 and public_edges_total 410574 -> 412771; diagnostics, IPC and indirect centers are unchanged. `budget_pops` is null so canonical runs use the analyzer's derived pop budget, which scales with the PAG constraint count and reaches a fixpoint instead of truncating at a flat cap (docs/POINTERS.md, Work budget). The range-for container read recaptured the modeled element counts (HDF 3 -> 4, HiView 33 -> 35, Camera 7 -> 8, Ability Runtime 38 -> 39) and ability_runtime edges_total 420602 -> 420605, edges_indirect 2533 -> 2536 and arg_flow_edges 457968 -> 457970, where ConnectServerManager's range-for callback dispatch now reaches its registered callbacks. The range-for pointee-const change recaptured ability_runtime edges_total 420605 -> 420591 and edges_direct 257078 -> 257064: const receivers no longer reach the non-const overload of ExtractInsightIntentGenericInfo::get(). The nested-container change then added the outer and nested cells for containers whose elements are themselves modeled containers: HiView modeled element cells 35 -> 39 and Camera 8 -> 10, with every other global and probe unchanged. See docs/EVAL_REPORT.md.", + "note": "Pinned corpora in canonical system-header mode with the embedded models. Recaptured after rebasing onto local master bb64b1e on Windows 11 x64 with MSYS2 MinGW GCC 15.2.0. Header-dependent totals use that toolchain as the reference. Counts include the 2026-11-20 vector specialization audit. The 2026-11-20 binder Host/interface-overload change recaptured the canonical IPC centers: Camera 808 -> 702 and ability_runtime 1762 -> 1641; ability_runtime edges_total 418036 -> 417915 and diagnostics 11944 -> 11945; HDF and HiView IPC counts are unchanged. The 2026-11-23 AAFwk TaskHandlerWrap::SubmitTask/SubmitTaskJust invoke models recaptured ability_runtime edges_total 417915 -> 418405, edges_indirect 2043 -> 2533 and public_edges_total 409148 -> 410574, with the same run reporting diagnostics 11944; the new probe pins AmsMgrScheduler::StartSpecifiedAbility reaching AppMgrServiceInner::StartSpecifiedAbility through its submitted lambda. The 2026-11-23 binder-wrapper member-resolution change recaptured ability_runtime functions_total 89063 -> 88690, functions_external 20414 -> 20041, edges_total 418405 -> 420602, edges_direct 255993 -> 257078, edges_external 158238 -> 159350, arg_flow_edges 455892 -> 457968, public_functions_total 85660 -> 85287 and public_edges_total 410574 -> 412771; diagnostics, IPC and indirect centers are unchanged. `budget_pops` is null so canonical runs use the analyzer's derived pop budget, which scales with the PAG constraint count and reaches a fixpoint instead of truncating at a flat cap (docs/POINTERS.md, Work budget). The range-for container read recaptured the modeled element counts (HDF 3 -> 4, HiView 33 -> 35, Camera 7 -> 8, Ability Runtime 38 -> 39) and ability_runtime edges_total 420602 -> 420605, edges_indirect 2533 -> 2536 and arg_flow_edges 457968 -> 457970, where ConnectServerManager's range-for callback dispatch now reaches its registered callbacks. The range-for pointee-const change recaptured ability_runtime edges_total 420605 -> 420591 and edges_direct 257078 -> 257064: const receivers no longer reach the non-const overload of ExtractInsightIntentGenericInfo::get(). The nested-container change then added the outer and nested cells for containers whose elements are themselves modeled containers: HiView modeled element cells 35 -> 39 and Camera 8 -> 10, with every other global and probe unchanged. See docs/EVAL_REPORT.md. The bind update moves callback edges to invocation sites. See docs/EVAL_REPORT.md, Deferred std::bind callables.", "analyze_args": [ "--canonical-system-headers", "--compiler", @@ -20,7 +20,7 @@ "functions_external": {"cmp": "band", "value": 15834, "tol": 40}, "edges_total": {"cmp": "band", "value": 79874, "tol": 240}, "edges_direct": {"cmp": "band", "value": 49816, "tol": 240}, - "edges_indirect": {"cmp": "exact", "value": 5226}, + "edges_indirect": {"cmp": "exact", "value": 5212}, "edges_external": {"cmp": "band", "value": 24774, "tol": 200}, "edges_ipc": {"cmp": "exact", "value": 58}, "arg_flow_edges": {"cmp": "band", "value": 76129, "tol": 150}, @@ -34,6 +34,7 @@ {"case": "HdfDeviceLaunchNode", "caller": "%HdfDeviceLaunchNode", "line": 0, "resolution": "indirect", "expected": 127} ], "probes": [ + {"name": "std::bind construction emits no indirect callback edge", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id WHERE e.resolution='indirect' AND s.callee_text IN ('std::bind','::std::bind')", "cmp": "exact", "value": 0}, {"name": "Modeled container element cells", "sql": "SELECT COUNT(*) FROM flow_nodes WHERE detail = 'array_summary' AND label LIKE 'elements:%'", "cmp": "exact", "value": 4} ] }, @@ -49,7 +50,7 @@ "functions_external": {"cmp": "band", "value": 10851, "tol": 120}, "edges_total": {"cmp": "band", "value": 45681, "tol": 160}, "edges_direct": {"cmp": "band", "value": 24106, "tol": 160}, - "edges_indirect": {"cmp": "exact", "value": 349}, + "edges_indirect": {"cmp": "exact", "value": 347}, "edges_external": {"cmp": "band", "value": 21182, "tol": 160}, "edges_ipc": {"cmp": "exact", "value": 44}, "arg_flow_edges": {"cmp": "band", "value": 44856, "tol": 120}, @@ -65,6 +66,9 @@ {"case": "Raw data builder array dispatch", "caller": "%::InitArrayValueParams", "caller_file": "%raw_data_builder.cpp", "line": 425, "resolution": "indirect", "expected": 4} ], "probes": [ + {"name": "std::bind construction emits no indirect callback edge", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id WHERE e.resolution='indirect' AND s.callee_text IN ('std::bind','::std::bind')", "cmp": "exact", "value": 0}, + {"name": "Timer dispatch forwards the binding receiver and event to Plugin::OnEventProxy", "sql": "SELECT COUNT(*) FROM arg_flow_edges a JOIN call_sites s ON s.id=a.call_site_id JOIN functions c ON c.id=s.caller_fn_id JOIN variables actual ON actual.id=a.actual_var_id JOIN functions owner ON owner.id=actual.fn_id JOIN variables formal ON formal.id=a.formal_var_id JOIN functions t ON t.id=formal.fn_id WHERE c.name='OHOS::HiviewDFX::EventLoop::ProcessEvent' AND s.callee_text='event.task' AND t.name='OHOS::HiviewDFX::Plugin::OnEventProxy' AND owner.name='OHOS::HiviewDFX::Plugin::DelayProcessEvent' AND (formal.name,actual.name) IN (('this','this'),('event','event'))", "cmp": "exact", "value": 2}, + {"name": "ffrt::submit starts the bound InitAndRunTask in a pool task", "sql": "SELECT EXISTS(SELECT 1 FROM execution_contexts x JOIN call_sites s ON s.id=x.call_site_id JOIN functions t ON t.id=x.entry_fn_id WHERE s.callee_text='ffrt::submit' AND t.name='OHOS::HiviewDFX::EventExportEngine::InitAndRunTask' AND x.kind='pool_task')", "cmp": "exact", "value": 1}, {"name": "Modeled container element cells", "sql": "SELECT COUNT(*) FROM flow_nodes WHERE detail = 'array_summary' AND label LIKE 'elements:%'", "cmp": "exact", "value": 39}, {"name": "DecodedEvent array lookup reaches only its four local lambdas", "sql": "SELECT COUNT(*) = 4 AND SUM(t.name GLOB c.name || '::$lambda*') = 4 FROM call_edges e JOIN call_sites s ON s.id = e.call_site_id JOIN functions c ON c.id = e.caller_fn_id JOIN functions t ON t.id = e.callee_fn_id JOIN files p ON p.id = s.file_id WHERE p.path LIKE '%decoded_event.cpp' AND s.line = 162 AND c.name LIKE '%::AppendCustomizedArrayParam' AND e.resolution = 'indirect'", "cmp": "exact", "value": 1}, {"name": "DecodedEvent scalar lookup reaches only its four local lambdas", "sql": "SELECT COUNT(*) = 4 AND SUM(t.name GLOB c.name || '::$lambda*') = 4 FROM call_edges e JOIN call_sites s ON s.id = e.call_site_id JOIN functions c ON c.id = e.caller_fn_id JOIN functions t ON t.id = e.callee_fn_id JOIN files p ON p.id = s.file_id WHERE p.path LIKE '%decoded_event.cpp' AND s.line = 201 AND c.name LIKE '%::AppendCustomizedParam' AND e.resolution = 'indirect'", "cmp": "exact", "value": 1}, @@ -83,7 +87,7 @@ "functions_external": {"cmp": "band", "value": 11315, "tol": 120}, "edges_total": {"cmp": "band", "value": 129949, "tol": 420}, "edges_direct": {"cmp": "band", "value": 70060, "tol": 420}, - "edges_indirect": {"cmp": "exact", "value": 500}, + "edges_indirect": {"cmp": "exact", "value": 487}, "edges_external": {"cmp": "band", "value": 58581, "tol": 420}, "edges_ipc": {"cmp": "exact", "value": 702}, "arg_flow_edges": {"cmp": "band", "value": 81527, "tol": 250}, @@ -99,6 +103,10 @@ {"case": "System NAPI session factory subscript", "caller": "%::createSessionInstanceForSys", "caller_file": "%camera_session_for_sys_napi.cpp", "line": 2419, "resolution": "indirect", "expected": 19} ], "probes": [ + {"name": "std::bind construction emits no indirect callback edge", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id WHERE e.resolution='indirect' AND s.callee_text IN ('std::bind','::std::bind')", "cmp": "exact", "value": 0}, + {"name": "Stored Camera bindings reach the common event, death and control-center callbacks", "sql": "SELECT COUNT(DISTINCT t.name) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id JOIN functions t ON t.id=e.callee_fn_id WHERE e.resolution='indirect' AND (s.callee_text,t.name) IN (('this->eventReceiver_','OHOS::CameraStandard::HCameraService::OnReceiveEvent'),('this->diedCb_','OHOS::CameraStandard::DeferredVideoProcSession::CameraServerDied'),('this->updateControlCenterCallback_','OHOS::CameraStandard::HCameraService::UpdateControlCenterStatus'))", "cmp": "exact", "value": 3}, + {"name": "Camera pool preserves seven forwarded lambdas as bound values", "sql": "SELECT COUNT(DISTINCT n.fn_id) FROM flow_origins o JOIN flow_nodes n ON n.id=o.src_node JOIN functions t ON t.id=n.fn_id JOIN files p ON p.id=o.file_id WHERE p.path LIKE '%unified_pipeline_threadpool.h' AND o.line=72 AND n.detail='bound' AND t.name LIKE '%::$lambda%'", "cmp": "exact", "value": 7}, + {"name": "The std::thread submission starts bound EventCompleteStopAsync", "sql": "SELECT EXISTS(SELECT 1 FROM execution_contexts x JOIN call_sites s ON s.id=x.call_site_id JOIN functions t ON t.id=x.entry_fn_id WHERE s.callee_text='std::thread::thread' AND t.name='OHOS::CameraStandard::MuxerFilter::EventCompleteStopAsync' AND x.kind='thread')", "cmp": "exact", "value": 1}, {"name": "Modeled container element cells", "sql": "SELECT COUNT(*) FROM flow_nodes WHERE detail = 'array_summary' AND label LIKE 'elements:%'", "cmp": "exact", "value": 10}, {"name": "Device protection map values reach the disconnect callback field", "sql": "SELECT COUNT(*) = 2 AND SUM(t.name IN ('OHOS::CameraStandard::HCameraDevice::DeviceEjectCallBack', 'OHOS::CameraStandard::HCameraDevice::DeviceFaultCallBack')) = 2 FROM call_edges e JOIN call_sites s ON s.id = e.call_site_id JOIN functions t ON t.id = e.callee_fn_id JOIN files p ON p.id = s.file_id WHERE p.path LIKE '%device_protection_ability_connection.cpp' AND s.line = 41 AND e.resolution = 'indirect'", "cmp": "exact", "value": 1} ] @@ -118,18 +126,20 @@ "functions_total": {"cmp": "exact", "value": 88690}, "functions_defined": {"cmp": "exact", "value": 68649}, "functions_external": {"cmp": "exact", "value": 20041}, - "edges_total": {"cmp": "exact", "value": 420591}, + "edges_total": {"cmp": "exact", "value": 420595}, "edges_direct": {"cmp": "exact", "value": 257064}, - "edges_indirect": {"cmp": "exact", "value": 2536}, + "edges_indirect": {"cmp": "exact", "value": 2540}, "edges_external": {"cmp": "exact", "value": 159350}, "edges_ipc": {"cmp": "exact", "value": 1641}, - "arg_flow_edges": {"cmp": "exact", "value": 457970}, + "arg_flow_edges": {"cmp": "exact", "value": 458002}, "diagnostics": {"cmp": "exact", "value": 11944}, "dlsym_edges": {"cmp": "exact", "value": 107}, "public_functions_total": {"cmp": "band", "value": 85287, "tol": 400}, "public_edges_total": {"cmp": "band", "value": 412771, "tol": 1300} }, "probes": [ + {"name": "std::bind construction emits no indirect callback edge", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id WHERE e.resolution='indirect' AND s.callee_text IN ('std::bind','::std::bind')", "cmp": "exact", "value": 0}, + {"name": "The TaskHandlerWrap::SubmitTask lambda invokes the bound AttachedToStatusBar", "sql": "SELECT COUNT(*) FROM call_edges e JOIN call_sites s ON s.id=e.call_site_id JOIN functions c ON c.id=e.caller_fn_id JOIN functions t ON t.id=e.callee_fn_id WHERE e.resolution='indirect' AND s.callee_text='task' AND c.name GLOB 'OHOS::AAFwk::TaskHandlerWrap::SubmitTask::$lambda*' AND t.name='OHOS::AppExecFwk::AppMgrServiceInner::AttachedToStatusBar'", "cmp": "exact", "value": 1}, {"name": "the solver converges within the check's budget (a partial fixpoint silently drops indirect edges, as 800000 pops did for #271)", "sql": "SELECT COUNT(*) FROM diagnostics WHERE stage='analyze' AND message LIKE 'solver stopped early%'", "cmp": "exact", "value": 0}, {"name": "Modeled container element cells", "sql": "SELECT COUNT(*) FROM flow_nodes WHERE detail = 'array_summary' AND label LIKE 'elements:%'", "cmp": "exact", "value": 39}, {"name": "App death callback map lookup reaches the registered lambda through both dispatches", "sql": "SELECT COUNT(DISTINCT s.line) FROM call_edges e JOIN call_sites s ON s.id = e.call_site_id JOIN functions t ON t.id = e.callee_fn_id JOIN files p ON p.id = s.file_id WHERE p.path LIKE '%app_recovery_mgr.cpp' AND s.line IN (103, 108) AND t.name GLOB 'OHOS::AAFwk::AbilityManagerService::SetAppDeathRecipient::$lambda*' AND e.resolution = 'indirect'", "cmp": "exact", "value": 2}, diff --git a/tests/fixtures/cpp_bind_packaged_task/main.cpp b/tests/fixtures/cpp_bind_packaged_task/main.cpp index f447f4ad..30a2e966 100644 --- a/tests/fixtures/cpp_bind_packaged_task/main.cpp +++ b/tests/fixtures/cpp_bind_packaged_task/main.cpp @@ -1,7 +1,6 @@ -// Callables wrapped by `std::bind` and `std::packaged_task` keep their call -// edge from the code that wraps them. As in the corpora, the standard headers -// are not in the tree: `std::bind`, `std::packaged_task`, `std::function` and -// `std::make_shared` are names the unit never sees declared. +// As in the corpora, standard callable wrappers are used without +// indexing their declarations. The packaged-task constructor retains +// ordinary function reachability. Bind construction runs no callback. #include #include #include @@ -11,7 +10,7 @@ typedef void (*Callback)(); // A minimal `Submit`-style thread pool: the task is a `packaged_task` over a // `std::bind` of the submitted callable and its arguments, run later through -// a queued lambda. The callable is only ever named inside `std::bind`. +// a queued lambda. void Hit() {} int Work(Callback cb, int n) { cb(); @@ -29,9 +28,8 @@ auto Submit(F &&f, Args &&...args) { } void Enqueue() { Submit(Work, Hit, 1); } -// The same pool with the bound argument declared by name rather than in a -// parameter pack, which the analysis does not follow: the argument reaches -// the callable's formal. +// The same pool with a named forwarded argument. The packaged task's +// later invocation is outside the constructor model. void FixedHit() {} int FixedWork(Callback cb, int n) { cb(); @@ -45,10 +43,7 @@ auto SubmitFixed(F &&f, A &&a) { } void EnqueueFixed() { SubmitFixed(FixedWork, FixedHit); } -// A parameter pack is not a formal, so `Hit` does not reach `Work`'s `cb` -// through `Submit`'s `args`; the edge from `Submit` to `Work` is still there. - -// `std::bind` on its own: the callable and its bound arguments. +// Construct and discard the binding. void BoundHit() {} void BoundWork(Callback cb, int n) { cb(); } void Bind() { auto bound = std::bind(BoundWork, BoundHit, 3); } diff --git a/tests/fixtures/std_bind/adl.cpp b/tests/fixtures/std_bind/adl.cpp new file mode 100644 index 00000000..d6cdf04e --- /dev/null +++ b/tests/fixtures/std_bind/adl.cpp @@ -0,0 +1,31 @@ +namespace std {} + +namespace custom { +struct Tag {}; +struct Job { + void operator()() const {} +}; +Job bind(void (*callback)(), Tag tag); +} + +void AdlTarget() {} +void via_adl() { + using namespace std; + custom::Tag tag; + auto job = bind(AdlTarget, tag); + job(); +} + +void MissingBindTarget() {} +void missing_bind_declaration() { + using namespace std; + auto job = bind(MissingBindTarget); + job(); +} + +void ExplicitBindTarget() {} +void explicit_bind_import() { + using std::bind; + auto job = bind(ExplicitBindTarget); + job(); +} diff --git a/tests/fixtures/std_bind/bind_arguments.cpp b/tests/fixtures/std_bind/bind_arguments.cpp new file mode 100644 index 00000000..d53fbfe1 --- /dev/null +++ b/tests/fixtures/std_bind/bind_arguments.cpp @@ -0,0 +1,69 @@ +#include "callbacks.h" + +void DerefHit() {} +void ReadBoundCallback(Callback callback) { callback(); } +void ReadBoundReference(Callback& callback) { callback(); } +struct BindArgumentWorker { + void run(Callback callback) { callback(); } +}; + +void bind_dereferenced_callback(Callback* slot) { + auto job = std::bind(ReadBoundCallback, *slot); + job(); +} +void bind_dereferenced_reference(Callback* slot) { + auto job = std::bind(ReadBoundReference, *slot); + job(); +} +void bind_member_with_dereferenced_callback(Callback* slot) { + BindArgumentWorker worker; + auto job = std::bind(&BindArgumentWorker::run, &worker, *slot); + job(); +} +using BoundReader = void (*)(Callback); +void bind_dereferenced_target_and_callback(BoundReader* target, Callback* slot) { + auto job = std::bind(*target, *slot); + job(); +} +void pass_slots() { + Callback callback = DerefHit; + BoundReader target = ReadBoundCallback; + bind_dereferenced_callback(&callback); + bind_dereferenced_reference(&callback); + bind_member_with_dereferenced_callback(&callback); + bind_dereferenced_target_and_callback(&target, &callback); +} + +extern "C" void* memset(void*, int, decltype(sizeof(0))); +void bind_clear() { + int payload; + auto job = std::bind(memset, &payload, 0, sizeof(payload)); + job(); +} + +void ForwardBoundAddress(void (*callback)(void*), void* address); +void ReceiveBoundAddress(void* address) {} +void bind_forwarded_address() { + int payload; + auto job = std::bind(ForwardBoundAddress, ReceiveBoundAddress, &payload); + job(); +} + +struct BindFieldSource { void* member; }; +struct BindFieldDestination { void* member; }; +int bind_alias_payload; +void BindAlias(void* dst, void* src); +void bind_precise_member_address() { + BindFieldSource source; + BindFieldDestination destination; + source.member = &bind_alias_payload; + auto job = std::bind(BindAlias, &destination.member, &source.member); + job(); +} +void bind_fallback_member_address() { + BindFieldSource source; + void* slots[2]; + source.member = &bind_alias_payload; + auto job = std::bind(BindAlias, &slots[1], &source.member); + job(); +} diff --git a/tests/fixtures/std_bind/bind_review.cpp b/tests/fixtures/std_bind/bind_review.cpp new file mode 100644 index 00000000..bd431e86 --- /dev/null +++ b/tests/fixtures/std_bind/bind_review.cpp @@ -0,0 +1,71 @@ +// Keep standard declarations out of this TU to exercise placeholder lookup +// when the standard header is unavailable. +using Callback = void (*)(); +void ReviewHit() {} +void ReviewWrong() {} + +void BraceTarget() {} +void brace_bind() { + std::function f{std::bind(BraceTarget)}; + f(); +} + +void GlobalBraceTarget() {} +std::function global_brace{std::bind(GlobalBraceTarget)}; +void invoke_global_brace() { global_brace(); } + +struct CastWorker { + void run(Callback cb) { cb(); } + void run(int) {} +}; +using Method = void (CastWorker::*)(Callback); +void member_cast(CastWorker* worker) { + auto f = std::bind(static_cast(&CastWorker::run), worker, ReviewHit); + f(); +} +void member_variable_cast(CastWorker* worker, Method target) { + auto f = std::bind(static_cast(target), worker, ReviewWrong); + f(); +} + +void FreeCast(Callback cb) { cb(); } +void FreeCast(int) {} +using Function = void (*)(Callback); +void free_cast() { + auto f = std::bind(static_cast(&FreeCast), ReviewHit); + f(); +} + +void ReviewTarget(Callback cb) { cb(); } +void global_placeholder() { + auto f = std::bind(ReviewTarget, ::std::placeholders::_1); + f(ReviewHit); +} +void duplicate_flow(Callback x, bool choose) { + std::function f = std::bind(ReviewTarget, x); + if (choose) { + f = std::bind(ReviewTarget, ::std::placeholders::_1); + } + f(x); +} + +void ModeledLaunch(void (*entry)(Callback), Callback payload); +void ModelActual(Callback next) { next(); } +void ModelIgnored(Callback) {} +void mode_with_capture() { + auto entry = ModelActual; + auto job = std::bind(ModeledLaunch, entry, ReviewHit); + job(ModelIgnored, ReviewWrong); +} +void mode_with_placeholders() { + auto job = std::bind(ModeledLaunch, ::std::placeholders::_2, ::std::placeholders::_1); + job(ReviewHit, ModelActual); +} + +void StopWork(std::stop_token token, Callback cb) { cb(); } +void with_stop_token() { + auto worker = std::jthread( + std::bind(StopWork, ::std::placeholders::_1, ::std::placeholders::_2), + ReviewHit); + worker.join(); +} diff --git a/tests/fixtures/std_bind/callbacks.h b/tests/fixtures/std_bind/callbacks.h new file mode 100644 index 00000000..c2c75f0a --- /dev/null +++ b/tests/fixtures/std_bind/callbacks.h @@ -0,0 +1,24 @@ +#pragma once + +namespace std { +template class function; +template class function { +public: + template function(F); + R operator()(A...); +}; +template function bind(F, A...); +namespace placeholders { extern int _1; extern int _2; } +} + +using Callback = void (*)(); +using Task = std::function; + +void Dispatch(Callback callback); +Task MakeTask(Callback captured); + +struct Queue { + Task task; + void Store(Task work); + void Fire(); +}; diff --git a/tests/fixtures/std_bind/dispatch.cpp b/tests/fixtures/std_bind/dispatch.cpp new file mode 100644 index 00000000..d1b733ba --- /dev/null +++ b/tests/fixtures/std_bind/dispatch.cpp @@ -0,0 +1,13 @@ +#include "callbacks.h" + +void Dispatch(Callback callback) { callback(); } +void Queue::Store(Task work) { task = work; } +void Queue::Fire() { task(); } + +void CrossTarget() {} +void Cross(Queue* queue) { + Task a = MakeTask(CrossTarget); + Task copy = a; + queue->Store(copy); + queue->Fire(); +} diff --git a/tests/fixtures/std_bind/main.cpp b/tests/fixtures/std_bind/main.cpp new file mode 100644 index 00000000..887d110d --- /dev/null +++ b/tests/fixtures/std_bind/main.cpp @@ -0,0 +1,131 @@ +#include "callbacks.h" + +void alpha() {} +void unrelated() {} + +void control() { std::function f = alpha; f(); } +void bound() { std::function f = std::bind(alpha); f(); } +void dropped() { auto unused = std::bind(alpha); } +void immediate() { std::bind(alpha)(); } +void via_directive() { + using namespace std; + auto f = bind(alpha); + auto copy = f; + copy(); +} + +struct Worker { void run() {} }; +void member(Worker* w) { + std::function f = std::bind(&Worker::run, w); + f(); +} +void member_placeholder(Worker* later) { + std::function f = std::bind(&Worker::run, std::placeholders::_1); + f(later); +} + +void Reorder(Callback first, Callback second, Callback third, Callback stored) { + first(); + second(); + third(); + stored(); +} +void Left() {} +void Right() {} +void Captured() {} +void order() { + using std::bind; + using std::placeholders::_2; + using namespace std::placeholders; + std::function f = bind(Reorder, _2, _1, _2, Captured); + f(Left, Right, unrelated); +} + +Callback Echo(Callback cb) { return cb; } +void returned() { + std::function f = ::std::bind(Echo, Captured); + Callback result = f(); + result(); +} + +Task MakeTask(Callback captured) { return std::bind(Dispatch, captured); } + +void alternatives(bool choose, Callback first, Callback second) { + Task f = std::bind(Dispatch, first); + if (choose) { + f = std::bind(Dispatch, second); + } + f(); +} + +namespace custom { Task bind(Callback); } +void foreign_bind() { + using custom::bind; + using namespace std; + Task f = bind(unrelated); + f(); +} +void runtime_target(Callback callback) { + Task f = std::bind(callback); + f(); +} +void either_target(Callback callback, bool choose) { + Task f = std::bind(alpha); + if (choose) { + f = std::bind(callback); + } + f(); +} +void SupplyRuntimeTarget(bool choose) { + runtime_target(unrelated); + either_target(unrelated, choose); +} + +void no_known_target(Callback callback) { + Task f = std::bind(callback); + f(); +} + +namespace std { +template T&& forward(T&); +} + +template +Task make_packed_task(F&& f, Args&&... args) { + return std::bind(std::forward(f), std::forward(args)...); +} + +void PackedHit() {} +void PackedTarget(Callback first, Callback second) { first(); second(); } +void invoke_packed_task() { + Task f = make_packed_task(PackedTarget, PackedHit, Captured); + f(); +} + +void LambdaHit() {} +void invoke_bound_lambda() { + auto f = std::bind([](Callback cb) { cb(); }, LambdaHit); + f(); +} + +int* AddTimerEvent(Task task); +void LateHit() {} +void LateTarget(Callback cb) { cb(); } +Task MakeLateTask(void (*entry)(Callback), Callback cb) { return std::bind(entry, cb); } +void ScheduleLate() { AddTimerEvent(MakeLateTask(LateTarget, LateHit)); } + +struct Plugin { + void OnEventProxy(Callback event) { event(); } + void DelayProcessEvent(Callback event) { + AddTimerEvent(std::bind(&Plugin::OnEventProxy, this, event)); + } +}; +void Schedule(Plugin* plugin) { plugin->DelayProcessEvent(Captured); } + +void StartWorker(Callback left, Callback right) { left(); right(); } +void Launch(Callback left, Callback right) { + auto worker = std::thread(std::bind(StartWorker, std::placeholders::_2, std::placeholders::_1), + left, right); + worker.join(); +} +void LaunchBoth() { Launch(Left, Right); }