In src/mongo/db/exec/expression/evaluate_javascript.cpp, $function serializes arguments into a stack-local BSONObjBuilder and passes bob.done() (unowned BSONObj) to MozJS. Unlike $where (which calls scope->advanceGeneration() before each invocation), $function never invalidates old unowned BSON wrappers between documents. A JS function can retain an argument in a global variable across invocations, then access freed stack memory on the next call.
Impact: A user with read privileges can crash mongod or leak heap contents via a crafted aggregation pipeline.
Suggested Fix: Invoke scope->advanceGeneration() before building arguments in the $function evaluate path, matching the existing $where pattern in js_function.cpp