boost::asio::async_resolve Problem - sockets

I'm in the process of constructing a Socket class that uses boost::asio. To start with, I made a connect method that took a host and a port and resolved it to an IP address. This worked well, so I decided to look in to async_resolve. However, my callback always gets an error code of 995 (using the same destination host/port as when it worked synchronously).
code:
Function that starts the resolution:
// resolve a host asynchronously
template<typename ResolveHandler>
void resolveHost(const String& _host, Port _port, ResolveHandler _handler) const
{
boost::asio::ip::tcp::endpoint ret;
boost::asio::ip::tcp::resolver::query query(_host, boost::lexical_cast<std::string>(_port));
boost::asio::ip::tcp::resolver r(m_IOService);
r.async_resolve(query, _handler);
}; // eo resolveHost
Code that calls this function:
void Socket::connect(const String& _host, Port _port)
{
// Anon function for resolution of the host-name and asynchronous calling of the above
auto anonResolve = [this](const boost::system::error_code& _errorCode,
boost::asio::ip::tcp::resolver_iterator _epIt)
{
// raise event
onResolve.raise(SocketResolveEventArgs(*this, !_errorCode ? (*_epIt).host_name() : String(""), _errorCode));
// perform connect, calling back to anonymous function
if(!_errorCode)
connect(*_epIt);
};
// Resolve the host calling back to anonymous function
Root::instance().resolveHost(_host, _port, anonResolve);
}; // eo connect
The message() function of the error_code is:
The I/O operation has been aborted because of either a thread exit or an application request
And my main.cpp looks like this:
int _tmain(int argc, _TCHAR* argv[])
{
morse::Root root;
TextSocket s;
s.connect("somehost.com", 1234);
while(true)
{
root.performIO(); // calls io_service::run_one()
}
return 0;
}
Thanks in advance!

Your resolver object is going out of scope, move it to a member of the Socket class and make resolveHost a method rather than free function.
This happens because boost::asio::ip::tcp::resolver is a typedef of a basic_resolver, which inherits from basic_io_object. When the resolver goes out of scope, ~basic_io_object() destroys the underlying resolver service before your handler can be posted.
Regardless of whether the asynchronous
operation completes immediately or
not, the handler will not be invoked
from within this function. Invocation
of the handler will be performed in a
manner equivalent to using
boost::asio::io_service::post().

Related

va_arg prevents me from calling a managed delegate in a native callback

In a C++/CLI assembly, I'm trying to call a managed delegate from a native callback. I followed Doc Brown's answer here, and my implementation so far looks like this:
The native callback - ignore the commented out parts for now:
static ssize_t idaapi idb_callback(void* user_data, int notification_code, va_list va)
{
switch (notification_code)
{
case idb_event::byte_patched:
{
//ea_t address = va_arg(va, ea_t);
//uint32 old_value = va_arg(va, uint32);
return IdaEvents::BytePatched(0, 0);
}
break;
}
return 0;
}
As you can see above, I call this managed delegate instantiated in a static class:
public delegate int DatabaseBytePatchedHandler(int address, int originalValue);
private ref class IdaEvents
{
static IdaEvents()
{
BytePatched = gcnew DatabaseBytePatchedHandler(&OnDatabaseBytePatched);
}
public: static DatabaseBytePatchedHandler^ BytePatched;
private: static int OnDatabaseBytePatched(int address, int originalValue)
{
return 0;
}
};
This compiles fine. But the code is incomplete - remember the commented out part in the native callback above? I actually have to retrieve the values from the va_list passed to the callback, and pass those on to my managed delegate:
ea_t address = va_arg(va, ea_t);
uint32 old_value = va_arg(va, uint32);
return IdaEvents::BytePatched(address, old_value);
But as soon as I uncomment one of the lines using va_arg, I cannot compile the project anymore and retrieve the following errors marking the line where I call the managed delegate:
C3821 'IdaEvents': managed type or function cannot be used in an unmanaged function
C3821 'IdaEvents::BytePatched': managed type or function cannot be used in an unmanaged function
C3821 'BytePatched': managed type or function cannot be used in an unmanaged function
C3821 'DatabaseBytePatchedHandler::Invoke': managed type or function cannot be used in an unmanaged function
C3642 'int DatabaseBytePatchedHandler::Invoke(int,int)': cannot call a function with __clrcall calling convention from native code
C3175 'DatabaseBytePatchedHandler::Invoke': cannot call a method of a managed type from unmanaged function 'idb_callback'
This really confuses me. Why is the compiler suddenly acting up as soon as I try to use va_arg? Even a single line without any assignment causes this error to pop up.
Am I thinking too naive here? I'm obviously missing a piece of the puzzle, and any help supporting me in finding it is greatly appreciated.

Does MongoCollection.forEach need to be thread safe?

When using the MongoDB Async Java Driver:
Does the following callback need to use a AtomicInteger counter or would a normal int do the job?
Block<Document> theBlock = new Block<Document>() {
AtomicInteger counter = new AtomicInteger();
#Override
public void apply(final Document document) {
counter.incrementAndGet();
}
};
SingleResultCallback<Void> callbackWhenFinished = ...
collection.find().forEach(theBlock, callbackWhenFinished);
The only real difference between the MongoDB Java API and its async counterpart is that the methods of the latter are non-blocking and take callbacks as arguments. This means that what you receive in your callback is equivalent to what the method returns in the non-async API.
Here, you use the find method. It returns a "normal" iterable, so calling forEach on it will not result in multiple threads.
In other words, you don't need an AtomicInteger: your apply method is called sequentially, by the same thread.
If you still have doubts or need a "proof", you can do one of the following:
add a System.out.println(Thread.currentThread().getName()); inside your block. You will see it is always performed by the same thread;
add a breakpoint inside your block, configured to stop only the thread. Once again, the breakpoint will block the whole code.

Register function that will be called before system call

How can we register function such that it will be called before executing system call.
For example, pthread_atfork() registers functions that will be called before and after fork().
Below is the example on Linux system.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_atfork.html
void prepare_function() {
printf("%d : In Prepare Function\n", getpid());
}
void parent_fuction() {
printf("%d : In Parent Function\n", getpid());
}
void child_function() {
printf("%d : In Child Function\n", getpid());
}
int main() {
pthread_atfork(prepare_function, parent_fuction, child_function);
if (fork() == 0) {
//sleep(1);
printf("%d : In Child\n", getpid());
return 0;
}
//sleep(1);
printf("%d : In Parent\n", getpid());
return 0;
}
I'm curious about how this can be implemented.
What is the actual goal here?
Fork has hooks because the state of the child with presence of threads in undefined. So by hooking yourself up you can ensure whatever mechanisms you want to use remain operational (for instance, if the fork happened after one of your threads takes a lock, the lock will remain taken within the child - what now?).
In general there is no mechanism which provides hooks for all syscalls.
For the most part syscalls are wrapped in glibc so there are few entry points which actually call the kernel. Someone bored enough could hack this up by e.g. inserting a jump in generated code to which would land the execution in their routine. But such a routine would have to have its own way of calling syscalls or a hack.
But wait, any piece of code is free to call a syscall without the use of such wrappers and such code could be dynamically generated, so you can't binary patch it prior to execution.
You can trace syscall entry/exit with ptrace, but you need a separate process for that.

Call function in main program from a library in Arduino

I've just started making libraries in Arduino. I've made a library named inSerialCmd. I want to call a function named delegate() that is defined in the main program file, stackedcontrol.ino, after the inSerialCmd library is included.
When I try to compile, one error is thrown:
...\Arduino\libraries\inSerialCmd\inSerialCmd.cpp: In member function
'void inSerialCmd::serialListen()':
...\Arduino\libraries\inSerialCmd\inSerialCmd.cpp:32: error:
'delegate' has not been declared
After doing a bit of searching, it seemed that adding the scope resolution operator might do the trick. So I added the "::" before delegate(), now "::delegate()", but the same error is thrown.
Now I'm stumped.
You cannot and should not directly call a function in a program from a library. Keep in mind a key aspect that makes a library into a library:
A library does not depend on the specific application. A library can be fully compiled and packaged into the .a file without the existence of a program.
So there is a one way dependency, a program depends on a library. This at first glance may seem to prevent you from achieving what you want. You can achieve the functionality you are asking about through what is sometimes referred to as a callback. The main program would provide to the library at runtime a pointer to the function to execute.
// in program somwehere
int myDelegate(int a, int b);
// you set this to the library
setDelegate( myDelegate );
You see this in the arduino if you look at how interrupt handlers are installed. This same concept exists in many environments - event listeners, action adapters - all with the same goal of allowing a program to define the specific action that a library cannot know.
The library would store and call the function via the function pointer. Here is a rough sketch of what this looks like:
// in the main program
int someAction(int t1, int t2) {
return 1;
}
/* in library
this is the delegate function pointer
a function that takes two int's and returns an int */
int (*fpAction)(int, int) = 0;
/* in library
this is how an application registers its action */
void setDelegate( int (*fp)(int,int) ) {
fpAction = fp;
}
/* in libary
this is how the library can safely execute the action */
int doAction(int t1, int t2) {
int r;
if( 0 != fpAction ) {
r = (*fpAction)(t1,t2);
}
else {
// some error or default action here
r = 0;
}
return r;
}
/* in program
The main program installs its delegate, likely in setup() */
void setup () {
...
setDelegate(someAction);
...

PowerRegisterSuspendResumeNotification - provided callback function doesn't work as expected

I register my application to receive notification when the system is suspended or resumed.
MSDN documentation
Function I'd like to be executed after application receives notification (I tried both void and void CALLBACK and both work same way):
void isConnectedStandby()
{
printf( "ConnectedStandby Request");
}
1st case - I provide pointer to the isConnectedStandby function, but system treats as a double pointer to the function - it calls an address which is under this callback pointer.
HPOWERNOTIFY RegistrationHandle;
PowerRegisterSuspendResumeNotification(
DEVICE_NOTIFY_CALLBACK,
&isConnectedStandby,
&RegistrationHandle
);
2nd case - here I provide as follows (this way my function code is executed):
typedef void (*StatusFunction_t)();
StatusFunction_t StatusFunction = isConnectedStandby;
HPOWERNOTIFY RegistrationHandle;
PowerRegisterSuspendResumeNotification(
DEVICE_NOTIFY_CALLBACK,
&isConnectedStandby,
&RegistrationHandle
);
System calls not only mine function, but all addresses after the first one (if I provide an array of functions, it executes one after another to crash when there is no valid code available)
What is the correct way to use this function?
Function declaration (must be static ULONG with 3 parameters as you can see below):
static ULONG isConnectedStandby(PVOID Context, ULONG Type, PVOID Setting);
ULONG isConnectedStandby(PVOID Context, ULONG Type, PVOID Setting)
{
printf( "ConnectedStandby Request");
return 0;
}
Istead of providing callback function directly to PowerRegisterSuspendResumeNotification we have to provide struct _DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS filled with our functions address :
static _DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS testCallback = {
isConnectedStandby,
nullptr
};
HPOWERNOTIFY RegistrationHandle;
PowerRegisterSuspendResumeNotification(
DEVICE_NOTIFY_CALLBACK,
&testCallback,
&RegistrationHandle
);
MSDN documentation did not mention any of those information.