<div dir="ltr">Hi Bert,<div class="gmail_extra"><br><div class="gmail_quote">On Mon, Nov 24, 2014 at 2:49 PM, Bert Freudenberg <span dir="ltr">&lt;<a href="mailto:bert@freudenbergs.de" target="_blank">bert@freudenbergs.de</a>&gt;</span> wrote:<br><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex"> <br>How do they actually work? I want to know what information the thunk needs, and what happens when it is activated. I think SqueakJS would benefit from callback support.<br></blockquote><div><br></div><div>I&#39;ll try and write this up properly in a blog post tomorrow.  But...</div><div><br></div><div>Callback is a wrapper round a piece of executable code, a block, and a &quot;signature&quot; (see below).  The executable code is wrapped by an FFICallbackThunk, an Alien, which is just a pointer to this code.  Th code is allocated from a special pool of memory marked as executable.  The address of the code is unique and is hence used as a key to identify the Callback and hence locate the block from the thunk.  The FFI marshalling code should pass the address of the thunk when passing the Callback.  Right now that has to be done explicitly.  The thunk, when called, invokes thunkEntry, which is defined in e.g. platforms/Cross/plugins/IA32ABI/ia32abicc.c (it needs a different definition for each API).  On x86 thinkEntry needs only to be invoked with the think and the stack pointer, since on x86 all arguments are accessible from the stack.  On other platforms thunkEntry will need to be invoked with the register arguments.</div><div><br></div><div>thunkEntry&#39;s job is to store the state necessary to return from the callback in an instance of either VMCallbackContext32 or VMCallbackContext64.  These are aliens for the following structure:</div><div><br></div><div><div>typedef struct {</div><div>    void *thunkp;</div><div>    char *stackptr;</div><div>    long *intRegArgs;</div><div>    double *floatRegArgs;</div><div>    void *savedCStackPointer;</div><div>    void *savedCFramePointer;</div><div>    union {</div><div>                            long vallong;</div><div>                            struct { int low, high; } valleint64;</div><div>                            struct { int high, low; } valbeint64;</div><div>                            double valflt64;</div><div>                            struct { void *addr; long size; } valstruct;</div><div>                        }   rvs;</div><div>    jmp_buf trampoline;</div><div> } VMCallbackContext;</div></div><div><br></div><div>The structure lives in the stack frame of thunkEntry, hence one per callback.</div><div><br></div><div>It does three things:</div><div><br></div><div>1. it identifies all the input arguments.  These are accessible, depending on platform, through stackptr, intRegArgs and floatRegArgs.</div><div>2. it maintains the jmp_buf which can be used to longjmp back to the callback to return from it.</div><div>3. it has slots to hold the result to be returned from the callback (the union rvs).  The argument to the longjmp (the value returned from the setjmp in thinkEntry) tells thunkEntry how to return the result, i.e. as a 32-bit value, a 64-bit value, a double or a struct.</div><div><br></div><div>Once thinkEntry has packed up the state in its local VMCallbackContext, it uses</div><div><br></div><div><div>    if ((flags = interpreterProxy-&gt;ownVM(0)) &lt; 0) {</div><div>        fprintf(stderr,&quot;Warning; callback failed to own the VM\n&quot;);</div><div>        return -1;</div><div>    }</div></div><div><br></div><div>to &quot;own&quot; the VM.  If the VM is single-threaded then this can check that the callback is being made on the same thread as the VM, and fail otherwise.  If the VM is multi-threaded ownVM can block until the thread can enter the VM.</div><div><br></div><div>It then calls-back into the VM using</div><div><br></div><div>        interpreterProxy-&gt;sendInvokeCallbackContext(&amp;vmcc);<br></div><div><br></div><div>which sends the message (found in the specialObjectsArray) #invokeCallbackContext: which is understood by Alien (see Alien class&gt;&gt;#invokeCallbackContext:).  This method wraps up the input argument (the raw address of thunkEntry&#39;s VMCallbackContext) in the relevant Alien and invokes Callback&#39;s entry point:</div><div><br></div><div><div>invokeCallbackContext: vmCallbackContextAddress &quot;&lt;Integer&gt;&quot; &quot;^&lt;FFICallbackReturnValue&gt;&quot;</div><div><span class="" style="white-space:pre">        </span>&quot;The low-level entry-point for callbacks sent from the VM/IA32ABI plugin.</div><div><span class="" style="white-space:pre">        </span> Return via primReturnFromContext:through:.  thisContext&#39;s sender is the</div><div><span class="" style="white-space:pre">        </span> call-out context.&quot;</div><div><span class="" style="white-space:pre">        </span>| callbackAlien type |</div><div><span class="" style="white-space:pre">        </span>callbackAlien := (Smalltalk wordSize = 4</div><div><span class="" style="white-space:pre">                                                </span>ifTrue: [VMCallbackContext32]</div><div><span class="" style="white-space:pre">                                                </span>ifFalse: [VMCallbackContext64])</div><div><span class="" style="white-space:pre">                                                        </span>atAddress: vmCallbackContextAddress.</div><div><span class="" style="white-space:pre">        </span>[type := Callback evaluateCallbackForContext: callbackAlien]</div><div><span class="" style="white-space:pre">                </span>ifCurtailed: [self error: &#39;attempt to non-local return across a callback&#39;].</div><div><span class="" style="white-space:pre">        </span>type ifNil:</div><div><span class="" style="white-space:pre">                </span>[type := 1. callbackAlien wordResult: -1].</div><div><span class="" style="white-space:pre">        </span>callbackAlien primReturnAs: type fromContext: thisContext</div></div><div><br></div><div>The sendInvokeCallbackContext machinery just constructs an activation of invokeCallbackContext: on top of the current process&#39;s stack, which is usually the process that called out through the FFI.  Bit it doesn&#39;t have to be.  threaded callbacks are too detailed for this brief message.</div><div><br></div><div>Callback then locates the relevant marshalling method for the callback&#39;s signature (actually it does this when the Callback is created, but the effect is the same).  Callback uses methods that identify themselves via pragmas to choose the relevant marshaller.  e.g. for a qsort sort function callback the marshaller on x86 is</div><div><br></div><div>Callback methods for signatures</div><div><div>voidstarvoidstarRetint: callbackContext sp: spAlien</div><div><span class="" style="white-space:pre">        </span>&lt;signature: #(int (*)(const void *, const void *)) abi: &#39;IA32&#39;&gt;</div><div><span class="" style="white-space:pre">        </span>^callbackContext wordResult:</div><div><span class="" style="white-space:pre">                </span>(block</div><div><span class="" style="white-space:pre">                        </span>value: (Alien forPointer: (spAlien unsignedLongAt: 1))</div><div><span class="" style="white-space:pre">                        </span>value: (Alien forPointer: (spAlien unsignedLongAt: 5)))</div></div><div><br></div><div><br></div><div>So it fetches the arguments from the stack using Alien accessors, evaluates the block with them and then assigns the result via wordResult, and answers the type code back to invokeCallbackContext:, e.g.</div><div><br></div><div>VMCallbackContext32 methods for accessing</div><div><div>wordResult: anInteger</div><div><span class="" style="white-space:pre">        </span>&quot;Accept any value in the -2^31 to 2^32-1 range.&quot;</div><div><span class="" style="white-space:pre">        </span>anInteger &gt;= 0</div><div><span class="" style="white-space:pre">                </span>ifTrue: [self unsignedLongAt: 25 put: anInteger]</div><div><span class="" style="white-space:pre">                </span>ifFalse: [self signedLongAt: 25 put: anInteger].</div><div><span class="" style="white-space:pre">        </span>^1</div></div><div><br></div><div>Then invokeCallbackContext: invokes the primitive to longjmp back to thunkEntry, supplying the return code that will allow thunkEntry to return the reslt correctly:</div><div><br></div><div>VMCallbackContext32 methods for primitives<br></div><div><div>primReturnAs: typeCode &quot;&lt;SmallInteger&gt;&quot; fromContext: context &quot;&lt;MethodContext&gt;&quot;</div><div><span class="" style="white-space:pre">        </span>&lt;primitive: &#39;primReturnAsFromContextThrough&#39; module: &#39;IA32ABI&#39; error: ec&gt;</div><div><span class="" style="white-space:pre">        </span>^self primitiveFailed</div></div><div><br></div><div><br></div><div>Then thunkEntry switches on the return code and returns to the caller.</div><div><br></div><div><br></div><div>Note that sendInvokeCallbackContext and primReturnAsFromContextThrough conspire to save, set and restore the VM&#39;s notion of what the C stack is in the VMCallbackContext&#39;s savedCStackPointer &amp; savedCFramePointer, growing the stack on callback, and cutting it back on return.  There&#39;s a variable in the VM, previousCallbackContext, that primReturnAsFromContextThrough uses to make sure returns are LIFO.</div><div><br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">I imagine that somehow the VM&#39;s state needs to be saved, then the context that defined the block is activated, and then the VM would run the block until it returns (or until the return prim is called?), then the VM&#39;s state would need to be restored to what it was, and the result is passed back by the thunk returning.<br></blockquote><div><br></div><div>That&#39;s right.</div><div><br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">Am I close? Since the callback can happen at any time, and it could do anything, saving the whole VM state seems daunting.<br><br></blockquote><div>Provided that the callback occurs from the context of a callout there are no problems.  Threaded callbacks take some more doing.  Basically the VM needs to b sharable between threads.  This is the threaded VM prototype.  If you absolutely need threaded callbacks we should have a serious talk.  This is not trivial to productise.</div></div><br><br clear="all"><div>HTH</div>-- <br><div class="gmail_signature">best,<div>Eliot</div></div>
</div></div>