Call native code when a JS value is garbage collected - cobalt

In my application I'm creating some JS objects, and also on C++ side some objects for running some handling.
I would like to delete C++ objects when they are not needed anymore: the corresponding JS object is Garbage Collected.
I'm trying to find that in Cobalt source code/documentation but I cannot find that. I do see ScriptValue::Reference but this seems to be the opposite:
Prevent a JS object from being garbage collected by declaring a relation between a JS value and C++ object.
Could someone give some hints how this can be achieved? (getting some callback called in C++ when an object is garbage collected).

Any C++ class exposed to JavaScript must inherit (directly or indirectly) script::Wrappable which has a virtual destructor. This destructor will be called when a corresponding JavaScript object is destroyed, either as a result of garbage collection or JS VM teardown.
Usual caveats apply: GC order and timing are non-deterministic. If you need to free critical resources as soon as possible, expose explicit cleanup methods to JavaScript.
See cobalt::dom::Node::~Node() for example of a cleanup performed upon destruction.

Related

C++ std::unique_ptr with STL container

I got a piece of code which uses a std::set to keep a bunch of pointer.
I used this to be sure of that each pointer will present only once in my container.
Then, I heard about std::unique_ptr that ensure the pointer will exists only once in my entire code, and that's exactly what I need.
So my question is quite simple, should I change my container type to std::vector ? Or It won't changes anything leaving a std::set ?
I think the job your set is doing is probably different to unique_ptr.
Your set is likely recording some events, and ensuring that only 1 event is recorded for each object that triggers, using these terms very loosely.
An example might be tracing through a mesh and recording all the nodes that are passed through.
The objects themselves already exist and are owned elsewhere.
The purpose of unique_ptr is to ensure that there is only one owner for a dynamically allocated object, and ensure automatic destruction of the object. Your objects already have owners, they don't need new ones!

Xamarin garbage collector and circular references

While reading Xamarin docs under section "Performance", I've noticed the following chapter:
The following diagram illustrates a problem that can occur with strong references:
Object A has a strong reference to object B, and object B has a strong reference to object A. Such objects are known as immortal objects due to the presence of the circular strong references. This parent-child relationship is not unusual, and as a result, neither object can be reclaimed by the garbage collector, even if the objects are no longer in use by the application.
That's the first time I've heard of "immortal objects" in C#/.NET/Mono context.
The page then continues with a suggestion to use a WeakReference in one of the objects, which will remove the strong circular reference and fix this "issue".
At the same time, Xamarin docs on garbage collection claim that:
Xamarin.Android uses Mono's Simple Generational garbage collector. This is a mark-and-sweep garbage collector [...]
Aren't mark and sweep GCs unaffected by circular references?
The memory leaks due to circular references apply only for Xamarin.iOS, wich use reference counting for native objects.
The page about immortal objects also says:
Boehm – This is a conservative, non-generational garbage collector. It
is the default garbage collector used for Xamarin.iOS applications
that use the Classic API.
The second quote specifically talks about Xamarin.Android.

What is the design rationale behind HandleScope?

V8 requires a HandleScope to be declared in order to clean up any Local handles that were created within scope. I understand that HandleScope will dereference these handles for garbage collection, but I'm interested in why each Local class doesn't do the dereferencing themselves like most internal ref_ptr type helpers.
My thought is that HandleScope can do it more efficiently by dumping a large number of handles all at once rather than one by one as they would in a ref_ptr type scoped class.
Here is how I understand the documentation and the handles-inl.h source code. I, too, might be completely wrong since I'm not a V8 developer and documentation is scarce.
The garbage collector will, at times, move stuff from one memory location to another and, during one such sweep, also check which objects are still reachable and which are not. In contrast to reference-counting types like std::shared_ptr, this is able to detect and collect cyclic data structures. For all of this to work, V8 has to have a good idea about what objects are reachable.
On the other hand, objects are created and deleted quite a lot during the internals of some computation. You don't want too much overhead for each such operation. The way to achieve this is by creating a stack of handles. Each object listed in that stack is available from some handle in some C++ computation. In addition to this, there are persistent handles, which presumably take more work to set up and which can survive beyond C++ computations.
Having a stack of references requires that you use this in a stack-like way. There is no “invalid” mark in that stack. All the objects from bottom to top of the stack are valid object references. The way to ensure this is the LocalScope. It keeps things hierarchical. With reference counted pointers you can do something like this:
shared_ptr<Object>* f() {
shared_ptr<Object> a(new Object(1));
shared_ptr<Object>* b = new shared_ptr<Object>(new Object(2));
return b;
}
void g() {
shared_ptr<Object> c = *f();
}
Here the object 1 is created first, then the object 2 is created, then the function returns and object 1 is destroyed, then object 2 is destroyed. The key point here is that there is a point in time when object 1 is invalid but object 2 is still valid. That's what LocalScope aims to avoid.
Some other GC implementations examine the C stack and look for pointers they find there. This has a good chance of false positives, since stuff which is in fact data could be misinterpreted as a pointer. For reachability this might seem rather harmless, but when rewriting pointers since you're moving objects, this can be fatal. It has a number of other drawbacks, and relies a lot on how the low level implementation of the language actually works. V8 avoids that by keeping the handle stack separate from the function call stack, while at the same time ensuring that they are sufficiently aligned to guarantee the mentioned hierarchy requirements.
To offer yet another comparison: an object references by just one shared_ptr becomes collectible (and actually will be collected) once its C++ block scope ends. An object referenced by a v8::Handle will become collectible when leaving the nearest enclosing scope which did contain a HandleScope object. So programmers have more control over the granularity of stack operations. In a tight loop where performance is important, it might be useful to maintain just a single HandleScope for the whole computation, so that you won't have to access the handle stack data structure so often. On the other hand, doing so will keep all the objects around for the whole duration of the computation, which would be very bad indeed if this were a loop iterating over many values, since all of them would be kept around till the end. But the programmer has full control, and can arrange things in the most appropriate way.
Personally, I'd make sure to construct a HandleScope
At the beginning of every function which might be called from outside your code. This ensures that your code will clean up after itself.
In the body of every loop which might see more than three or so iterations, so that you only keep variables from the current iteration.
Around every block of code which is followed by some callback invocation, since this ensures that your stuff can get cleaned if the callback requires more memory.
Whenever I feel that something might produce considerable amounts of intermediate data which should get cleaned (or at least become collectible) as soon as possible.
In general I'd not create a HandleScope for every internal function if I can be sure that every other function calling this will already have set up a HandleScope. But that's probably a matter of taste.
Disclaimer: This may not be an official answer, more of a conjuncture on my part; but the v8 documentation is hardly
useful on this topic. So I may be proven wrong.
From my understanding, in developing various v8 based backed application. Its a means of handling the difference between the C++ and javaScript environment.
Imagine the following sequence, which a self dereferencing pointer can break the system.
JavaScript calls up a C++ wrapped v8 function : lets say helloWorld()
C++ function creates a v8::handle of value "hello world =x"
C++ returns the value to the v8 virtual machine
C++ function does its usual cleaning up of resources, including dereferencing of handles
Another C++ function / process, overwrites the freed memory space
V8 reads the handle : and the data is no longer the same "hell!#(#..."
And that's just the surface of the complicated inconsistency between the two; Hence to tackle the various issues of connecting the JavaScript VM (Virtual Machine) to the C++ interfacing code, i believe the development team, decided to simplify the issue via the following...
All variable handles, are to be stored in "buckets" aka HandleScopes, to be built / compiled / run / destroyed by their
respective C++ code, when needed.
Additionally all function handles, are to only refer to C++ static functions (i know this is irritating), which ensures the "existence"
of the function call regardless of constructors / destructor.
Think of it from a development point of view, in which it marks a very strong distinction between the JavaScript VM development team, and the C++ integration team (Chrome dev team?). Allowing both sides to work without interfering one another.
Lastly it could also be the sake of simplicity, to emulate multiple VM : as v8 was originally meant for google chrome. Hence a simple HandleScope creation and destruction whenever we open / close a tab, makes for much easier GC managment, especially in cases where you have many VM running (each tab in chrome).

Check Value of .NET Handle ^

Here's my situation:
I have .NET wrapper-objects in a C++/CLI layer that hold pointers to unmanaged C++ objects. I've implemented the finalizer so that it deletes the unmanaged memory pointed to by the wrapper-object on garbage-collection and sets the pointer to null.
Here's the problem:
I'm watching the finalizer for the .NET wrapper-object and it gets called twice and tries to delete the same memory twice, indicating that I have somehow created 2 .NET wrapper objects that go out-of-scope, and are garbage collected while I'm still expecting the wrapper object to be in scope (these wrapper objects are getting passed to a VB.NET application).
Here's my question:
Is there anyway for me to check the handle value so that I can confirm where the wrapper objects are getting created (copied or whatever)? Currently I'm looking at the handle values (EG - 0x0014fe80), but I see 3 different values for when the object is created, added to a collection, and deleted. So I'm not sure if the GC is just moving stuff around and this is the same object, or if I'm actually seeing 3 different objects that reference the same unmanaged memory. I would like to resolve the duplicate object copies if possible, but I understand that I will probably want to implement some sort of smart pointer so that this doesn't happen.
Thanks,
Ian
Take a look at this question
Here is an implementation of a scoped_ptr that is noncopyable and has an auto-release mechanism for unmanaged objects, by #Ben Voigt
Yeah, I ended up modifying an auto_ptr class to be a shared pointer to ensure that the unmanaged memory is only deleted once through the smart pointer finalizer. I'm assuming I did something similar to all the other implementations; I created a static dictionary in the auto_ptr template class, using the native pointer value as the key, that is checked every time the finalizer is called to update the count of each item, or delete the memory.

Windows Form Closed but not destroyed

In my Windows Form application when I close a form (which is derived from a base form), its FormClosing and FormClosed Events fire but destructor never fires off. It still keeps the memory occupied.
Any ideas on how to destroy the form completely when it is closed?
If it's not destroyed that means the Garbage Collector doesn't think it should be destroyed.
This basically means that you're either:
Holding a reference to the object somewhere
Have the object listening to an event (That's also a kind of reference to the object)
The garbage collector won't free the Form until there are no references to it.
If you have important resources you want to dispose of, make it IDisposable, and use the Dispose method.
Destructors (or more correctly, finalizers - there are no destructors in .NET) are not guaranteed to be executed in .NET - objects may be cleaned up at the whim of the runtime or even never. You cannot rely on your finalizer method ever being called.
If you need to do something when your form is closed, handle the Closed event.
If you need to release an unmanaged resource (e.g. close an open file), add this logic to the Dispose() method.
If you are worried about memory use, do not worry about memory use. The runtime manages memory automatically based on its own logic.
Reference: Garbage Collection (MSDN)

Resources