Can a JS Object's constructor be written in C++ with SpiderMonkey? - spidermonkey

I would like to implement a constructor for a Javascript Object in C++, using SpiderMonkey 38's API. But a constructor needs access to this (the JS Object being constructed) and the docs for JS::CallArgs say you mustn't call thisv() from a constructor, without suggesting any alternative. Does that mean it isn't actually possible to write a useful constructor in C++?

In C++ you just have to create the object that should be returned from the constructor yourself. (Nothing creates an initial object that would be accessible from this for your) Depending on what you need you should look into creating a new JSClass for that object.
bool
MyConstructor(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, JS_NewObject(cx, MyJSClass));
if (!obj)
return false;
args.rval().setObject(*obj);
return true;
}

Related

Example of "copy_from_user" in Linux Kernel (just copying a pointer to an int)

I know there are a lot of posts on this, but most are very complex and I'm hoping someone can help me with my simple example.
I'm writing a system call and the function I'm writing has the form:
SYS_CALLDEFINE4(calc, int, param1, int, param2, char, operation, int*, result)
{
//Do system call stuff here
}
I know that the pointer to the int will be a problem, because the userspace application could have passed a pointer to vital system space (and we don't want to mess with that). So I need to use the copy_from_user function.
Can someone possibly give an example of how to correctly use those two functions in the context of making sure you can access that pointer correctly?
Replacement for
*result = <value>;
would be
int local_value = <value>;
if (copy_to_user(&local_value, result, sizeof(*result)))
{
// 'result' points to inaccessible memory.
}
// assigning 'result' has been successful.
Alternatively, because the size of the result is small (int in your case), you may use put_user, which is simpler and more effective:
if (put_user(<value>, result) < 0)
{
// 'result' points to inaccessible memory.
}
// assigning 'result' has been successful.

Passing pointers to async as arguments generates compiler error

I'm trying to get my head around async but have not yet found a way to pass pointers. The aim is to pass a pointer to a pointer so that the thread readTable initialises the pointer to a PostgreSQL connection as shown below.
PGconn *conn = NULL;
future<int> resultFuture;
void init
{
resultFuture = async(launch::async, readTable(&conn));
}
However the compiler complains with:
error: no matching function for call to ‘async(std::launch, int)'
Is passing pointers like this not allowed with async?
Thanks for any help.
I guess
void init
{
resultFuture = async(launch::async, readTable,&conn);
}
the second parameters is a Callable (which is a function to pointer, or an object with overloaded operator() or a lambda function). all the rest are the argument to pass into the callable.
please read std::async documentation here:
http://en.cppreference.com/w/cpp/thread/async
and about perfect forwarding here :
Advantages of using forward

Correct use of HandleScope in Asynchronous Addon

I'm writing a asynchronous Node Addon, but I have been struggling to figure out if I need to use a HandleScope in the "After" function that calls the client JavaScript callback. I've seen examples showing with and without new scopes, but never any explanation why. Here is an example:
void asyncWorkAfter(uv_work_t* req) {
HandleScope scope; // <-- Do you need a new scope?
const int argc = 1;
Local<Value> foo = String::New("foo");
Local<Value> argv[] = { foo };
// assume I got my callback function out of req
callback->Call(Context::GetCurrent()->Global(), argc, argv);
callback.Dispose();
// if i use a new HandleScope, what happens to argv when we go out of scope?
// Do i need to do something like a scope.Close() to copy argv to the parent scope?
}
Do you need/want a HandleScope when you call the callback?
What happens to argv in the example if you do use a new HandleScope?
String::New("foo") will allocate something on heap and return a handle, so you need to free the memory referenced by this handle some how. If you attach them to a HandleScope v8 will do that for you once all references are counted to zero.
Local handles are held on a stack and are deleted when the appropriate
destructor is called. These handles' lifetime is determined by a
handle scope, which is often created at the beginning of a function
call. When the handle scope is deleted, the garbage collector is free
to deallocate those objects previously referenced by handles in the
handle scope, provided they are no longer accessible from JavaScript
or other handles.
https://developers.google.com/v8/embed

Is making a GWT asynccallback in a constructor safe?

Assuming the constructor runs in the client part of the code (the one that gets translated to javascript).
The callback method onSuccess does modify the instance variables of the class.
The callback is implemented as an anonymous class so the instance of the outer class can be accessed by using OuterClass.this.
Normally in plain Java we should not do something like this because by doing so, 'this' reference can escape before the object construction is finished.
But does it also hold for the case when Java code is translated to Javascript? I assume that javascript code is executed by a single thread in a web browser so this should not be an issue (single thread => no visibility problems)?
On the one hand, you're right - the problem cannot be triggered by a separate thread, because JavaScript is single threaded.
Callback events will definitely be handled by an event handler that starts after the current event handler (the one which constructs the current object) has finished. So they will only ever see the fully constructed object.
On the other hand, you generally don't need threads to exploit the basic problem. Here's a simple example:
final A a = new A();
final B b = new B(a);
public class A {
private B b;
public void setB(final B b) {
this.b = b;
}
public void letBSaySomething() {
b.saySomething();
}
}
public class B {
private A a;
private final int some;
public B(final A a) {
this.a = a;
a.setB(this);
a.letBSaySomething();
some = 55;
a.letBSaySomething();
}
public void saySomething() {
RootPanel.get().add(new Label("Hello " + some));
}
}
This results in the output
Hello 0
Hello 55
(although 'some' is final). This happens both in GWT (compiled/uncompiled) and plain Java programs.
AsyncCallback, by itself, is just a class. When you send an RPC request in production mode, you are guaranteed that the result will come in asynchronously through XmlHttpRequest; in compiled javascript it is 100% impossible to leak the reference before construction is finished, as the callback will get called in a separate javascript execution stack.
In gwt-dev mode, however, things that should be asynchronous aren't always so. Personally, I abandoned gwt-dev over super-dev-mode, and only use gwt-dev when I really need java debugger, so I can't tell you for sure if it will be immune to construction problems or not (test it and find out!).
If you are not sending any requests in the constructor, you will be 100% safe. Just creating the async callback will only lead to problems if you are subsequently accessing OuterClass.this in unsafe ways, regardless of the classes involved.

Is there any advantage/disadvantage to using function delegates over lambdas in a collection?

I am at that really boring part in the development of my library, where I want to construct a class based on a windows message identifier and the WPARAM and LPARAM arguments. The prototype for such functions is trivial:
boost::shared_ptr<EventArgs>(const UINT& _id, const WPARAM& _w, const LPARAM& _l);
For each windows message, I will have a function of this nature.
Now, what I am currently doing is using the FastDelegate library to do my delegates. These are stored in a map thusly:
typedef fastdelegate::FastDelegate3<const UINT&, const WPARAM&, const LPARAM&, boost::shared_ptr<EventArgs> > delegate_type;
typedef std::map<int, delegate_type> CreatorMap;
And when a windows message needs to have an EventArg-derived class created, it's a simple case of looking up the appropriate delegate, invoking it and returning the newly-created instance nicely contained in a shared_ptr.
boost::shared_ptr<EventArgs> make(const UINT& _id, const WPARAM& _w, const LPARAM& _l) const
{
MsgMap::const_iterator cit(m_Map.find(_id));
assert(cit != m_Map.end());
boost::shared_ptr<EventArgs> ret(cit->second(_w, _l));
return ret;
}; // eo make
All is working fine. But then I was thinking, rather than having all these delegates around, why not take advantage of lambdas in C++0x? So, I quickly prototyped the following:
typedef std::map<int, std::function<boost::shared_ptr<EventArgs>(const WPARAM&, const LPARAM&)> > MapType;
typedef MapType::iterator mit;
MapType map;
map[WM_WHATEVER] = [](const WPARAM& _w, const LPARAM& _l) { /* create appropriate eventargs class given parameters */ };
map[WM_ANOTHER] = ....;
// and so on
Once again, it's simple to look up and invoke:
mit m = map.find(WM_PAINT);
boost::shared_ptr<EventArgs> e(m->second(_wParam, _lParam));
// dispatch e
Is there an advantage to using lambdas in this way? I know the overhead of looking up the right delegate/lambda will be the same (as both types of map are keyed with an int), but I am aiming to dispatch my messages from the wndProc in my nice C++ friendly-way as efficiently as possible. My gut-feeling is that lambdas will be faster, but unfortunately i lack the experience in understanding compiler-optimizations to make a judgement call on this, hence my question here :) Oh, and in keeping with the topic of the question, are there any gotchas/something I haven't thought about?
I see two real differences here:
The first is how you store the callback: Either the fast-delegate or std::function. The latter is based on boost::function, and fast delegates were specifically designed to outperform those. However, std::function is standard conforming, while fast delegates are not.
The other difference is the way you setup your code, and I see a clear advantage for lambdas here. You can write the actual code exactly where it matters, you don't need to define a separate function that only serves a niche-purpose.
If you want raw speed - fast-delegates probably win (but you should benchmark, if that is an argument), but if you want readability and standard conformity, go with std::function and lambdas.

Resources