Skip to content

cppia: adoptInstances moves instances that code then calls or reads with the wrong layout #464

Open

Description

@dimensionscape

adoptInstances (#265, #442) checks fields and storage layout but not methods, or the classes that fields refer to. So it moves instances that code then calls or reads with the wrong layout, which crashes or reads garbage. docs/CppiaModuleRelease.md says methods "can differ in any way". Found in the architecture pass for 6.0.0 (#154).

Old code calling a moved instance

A call's vtable slot is fixed when the code links (Cppia.cpp:3603-3611), and slots are assigned in declaration order (CppiaClasses.cpp:1339-1349). The check in CppiaModule.cpp:1299-1342 compares only field names, storage types and offsets. So old code still running, which the docs say "finishes normally", calls a moved instance with its old slot numbers on the new vtable.

Old module:

class Foo {
	public var v:Int = 7;
	public function new() {}
	public function a():String return "old a " + v;
	public function b():String return "old b " + v;
}

New module, the same fields with a method added first:

class Foo {
	public var v:Int = 7;
	public function new() {}
	public function x():Int return 12345;
	public function a():String return "new a " + v;
	public function b():String return "new b " + v;
}

After adoptInstances, old code calling foo.b() gets new a 7. Calling foo.a() reaches x(), and its Int is read as a String:

  • the interpreter segfaults (139);
  • the JIT returns a String of length 12345 full of garbage.

New code reading a field that holds an old instance

A moved Parent can have a field holding a Child that didn't move, because Child's layout changed. New code then reads that old Child with the new Child's layout. In the repro it read c.n as -3 from past the end of the object, and c.s as a garbage String. A write there would corrupt the heap.

Retyped fields

The docs say a class that "retypes" a field keeps its instances. But retyping within one storage type, such as Array<Int> to Array<Float>, passes the check. I found that by reading the code, not with a repro.

Fix

  • Require the same member function names, in the same slots, and the same script interface slots.
  • Compare field types by name, not just storage type.
  • Move a class only when every script class its fields refer to also moves or is unchanged, iterating to a fixed point.

Or, failing that, narrow the docs to what the check actually covers.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions