Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VM over-captures variables in closures #50462

Closed
lrhn opened this issue Nov 14, 2022 · 1 comment
Closed

VM over-captures variables in closures #50462

lrhn opened this issue Nov 14, 2022 · 1 comment
Labels
area-vm Use area-vm for VM related issues, including code coverage, and the AOT and JIT backends.

Comments

@lrhn
Copy link
Member

lrhn commented Nov 14, 2022

This problem has been significantly improved, but still hits some very likely code patterns.
Example:

import "dart:isolate";
void main() {
  var r = RawReceivePort();
  r.handler = (v) {
    print(v);
    r.close();
  };
  var p = r.sendPort;
  Isolate.run(() => p.send(42));
}

The closure only references p, a variable containing a SendPort, which should be sendable to any other isolate.

When running, you get the errror:

Invalid argument(s): Illegal argument in isolate message: (object is a ReceivePort)
#0      Isolate._spawnFunction (dart:isolate-patch/isolate_patch.dart:399:25)
...

which shows that the closure remembers the r variable, for no apparent reason. There is no reference to r in the function expression, or any time later. I'm assuming the earlier handler closure is what triggers the problem.
If I remove the r.close from the handler, the error goes away (but I also don't get to close the port).

This is a very likely problem, my first attempt to write an example of using Isolate.run to send multiple results was code precisely like this, and I had to introduce a helper function to work around it:

Future<void> runRemote(SendPort port) => Isolate.run(() { ... p.send ...});

which moves the closure out of the scope of the RawReceivePort declaration.

@lrhn lrhn added the area-vm Use area-vm for VM related issues, including code coverage, and the AOT and JIT backends. label Nov 14, 2022
@mraleph
Copy link
Member

mraleph commented Nov 14, 2022

Duplicate of #36983

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-vm Use area-vm for VM related issues, including code coverage, and the AOT and JIT backends.
Projects
None yet
Development

No branches or pull requests

2 participants