win32 threads in Qt - winapi

Is there a way to create a thread in Qt without using subclassing (ie. making a QThread class)? It's getting difficult sending data into the thread. Is is possible to use win32 threads in Qt if so can someone give me an example on how to?
Thanks.

You shouldn't necessarily subclass QThread - See discussion here http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/

Or if you have many simple tasks and want to have them processed in threaded fashion. QRunnable and QThreadPool provide a quick and easy approach without dealing with threads themselves.

If you just want to run a function in another thread you should check the QT Concurrent Namespace.
The following example will run the function 'aFunction()' in separate thread and will not block on the line where calling the function. Of course there are mechanisms to understand when a function ends, to get a result, to wait for it.
void aFunction(int arg1, double arg2, const QString &string);
int integer = ...;
double floatingPoint = ...;
QString string = ...;
QtConcurrent::run(aFunction, integer, floatingPoint, string);

Related

Why does QSerialPort::writeData start writes with a single-shot timer?

I'm trying to understand Qt's serial port module and I'm not too familiar with how Qt handles asynchronous I/O. On Windows, the QSerialPort::writeData method places the data to be written in a ring buffer and then starts a single-shot QTimer to actually perform the write when its timeout signal fires:
qint64 QSerialPortPrivate::writeData(const char *data, qint64 maxSize)
{
Q_Q(QSerialPort);
writeBuffer.append(data, maxSize);
if (!writeBuffer.isEmpty() && !writeStarted) {
if (!startAsyncWriteTimer) {
startAsyncWriteTimer = new QTimer(q);
QObjectPrivate::connect(startAsyncWriteTimer, &QTimer::timeout, this, &QSerialPortPrivate::_q_startAsyncWrite);
startAsyncWriteTimer->setSingleShot(true);
}
if (!startAsyncWriteTimer->isActive())
startAsyncWriteTimer->start();
}
return maxSize;
}
The readData method doesn't use a timer in this way, instead calling ReadFileEx directly.
What does the single-shot timer accomplish versus just calling WriteFileEx?
There is a special case for a QTimer with an interval of 0: this timer will fire once control returns to the event loop. The implementation on Unix/Linux does something similar, but not using a QTimer, instead having a subclass of QSocketNotifier that will get called when the port is able to be written to. Both of these implementations mean that you will buffer the data and write it out once you get back to the main event loop.
There are two reasons that I can think of for doing this:
There is something different between the POSIX and Win32 serial APIs that require the code to be structured this way. As far as I am aware, this is not the case
What #Mike said in a comment: this will allow for data to be buffered before it is written
The buffering seems like the most likely reason for this, as doing a syscall for each piece of data that you want to write would be a rather expensive operation.

Identify and intercept function call

I'm developing a launcher for a game.
Want to intercept game's call for a function that prints text.
I don't know whether the code that contains this function is dynamically linked or statically. So I dont even know the function name.
I did intercepted some windows-api calls of this game through microsoft Detours, Ninject and some others.
But this one is not in import table either.
What should I do to catch this function call? What profiler should be used? IDA? How this could be done?
EDIT:
Finally found function address. Thanks, Skino!
Tried to hook it with Detours, injected dll. Injected DllMain:
typedef int (WINAPI *PrintTextType)(char *, int, float , int);
static PrintTextType PrintText_Origin = NULL;
int WINAPI PrintText_Hooked(char * a, int b, float c, int d)
{
return PrintText_Origin(a, b, c , d);
}
HMODULE game_dll_base;
/* game_dll_base initialization goes here */
BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if(fdwReason==DLL_PROCESS_ATTACH)
{
DisableThreadLibraryCalls(hinstDLL);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
PrintText_Origin = (PrintTextType)((DWORD)game_dll_base + 0x6049B0);
DetourAttach((PVOID *)&PrintText_Origin , PrintText_Hooked);
DetourTransactionCommit();
}
}
It hooks as expected. Parameter a has text that should be displayed. But when calling original function return PrintText_Origin (a, b, c , d); application crashes(http://i46.tinypic.com/ohabm.png, http://i46.tinypic.com/dfeh4.png)
Original function disassembly:
http://pastebin.com/1Ydg7NED
After Detours:
http://pastebin.com/eM3L8EJh
EDIT2:
After Detours:
http://pastebin.com/GuJXtyad
PrintText_Hooked disassembly http://pastebin.com/FPRMK5qt w3_loader.dll is the injected dll
Im bad at ASM, please tell what can be wrong ?
Want to intercept game's call for a function that prints text.
You can use a debugger for the investigative phase. Either IDA, or even Visual Studio (in combination with e.g. HxD), should do. It should be relatively easy to identify the function using the steps below:
Identify a particular fragment of text whose printing you want to trace (e.g. Hello World!)
Break the game execution at any point before the game normally prints the fragment you identified above
Search for that fragment of text† (look for either Unicode or ANSI) in the game's memory. IDA will allow you to do that IIRC, as will the free HxD (Extras > Open RAM...)
Once the address of the fragment has been identified, set a break-on-access/read data breakpoint so the debugger will give you control the moment the game attempts to read said fragment (while or immediately prior to displaying it)
Resume execution, wait for the data breakpoint to trigger
Inspect the stack trace and look for a suitable candidate for hooking
Step through from the moment the fragment is read from memory until it is printed if you want to explore additional potential hook points
†provided text is not kept compressed (or, for whatever reason, encrypted) until the very last moment
Once you are done with the investigative phase and you have identified where you'd like to inject your hook, you have two options when writing your launcher:
If, based on the above exercise, you were able to identify an export/import after all, then use any API hooking techniques
EDIT Use Microsoft Detours, making sure that you first correctly identify the calling convention (cdecl, fastcall, stdcall) of the function you are trying to detour, and use that calling convention for both the prototype of the original as well as for the implementation of the dummy. See examples.
If not, you will have to
use the Debugging API to programatically load the game
compute the hook address based on your investigative phase (either as a hard-coded offset from the module base, or by looking for the instruction bytes around the hook site‡)
set a breakpoint
resume the process
wait for the breakpoint to trigger, do whatever you have to do
resume execution, wait for the next trigger etc. again, all done programatically by your launcher via the Debugging API.
‡to be able to continue to work with eventual patch releases of the game
At this stage it sounds like you don't have a notion of what library function you're trying to hook, and you've stated it's not (obviously at least) an imported external function in the import table which probably means that the function responsible for generating the text is likely located inside the .text of the application you are disassembling directly or loaded dynamically, the text generation (especially in a game) is likely a part of the application.
In my experience, this simplest way to find code that is difficult to trace such as this is by stopping the application shortly during or before/after text is displayed and using IDA's fabulous call-graph functionality to establish what is responsible for writing it out (use watches and breakpoints liberally!)
Look carefully to calls to CreateRemoteThread or any other commonly used dynamic loading mechanism if you have reason to believe this functionality might be provided by an exported function that isn't showing up in the import table.
I strongly advice against it but for the sake of completeness, you could also hook NtSetInformationThread in the system service dispatch table. here's a good dump of the table for different Windows versions here. If you want to get the index in the table yourself you can just disassemble the NtSetInformationThread export from ntdll.dll.

Dialog box to abort a while-loop in C++/CLI

I have a while loop executed in a function. While the loop is executed, I would like to have a dialog box with an "Abort" button to show up on the screen on Windows. If I press the Abort button, the program would terminate the while loop. It's like a dialog which pops up when a file is copied. Could anybody suggest a simple way to do this with C++/CLI or something similar?
Since I don't have a lot of experience with C++/CLI, I would appreciate if you could provide me with code snippets or sample codes.
Using a separate thread is the modern way to do this, but there is another approach.
You can take the guts of your while loop and put them in an event handler. Arrange to have the message loop call this event handler again and again until the job it done (e.g., with a timer or idle processing). In the mean time, you can display a non-modal pop-up dialog. This is how printing used to work in the pre-emptive multitasking era. See SetAbortProc.
I'd recommend that second thread approach listed by others. I just wanted to point out that it's not the only way.
The construction of the while loop is the easy part. What makes it hard is you'll have to put the abort dialog in a different thread and then coordinate a flag in the while condition with the dialog. This is usually handled with semaphores which are known to be difficult to code without subtle side-effects.
The while loop, at a minimum, will need to have a mechanism that allows the event queue to get processed AND periodically checks for a change in the status of the abort semaphore.
//psuedo-code below
bool f_abort = false;
while (!f_abort)
{
do_partial_work();
f_abort = checkForAbort();
sleep(0); // don't want to lock the CPU
}
I'm not an expert in threads so I'll have to point you to other resources for what to do in checkForAbort().
Windows Forms Threading and Events - ListBox updates promptly but progressbar experiences huge delay
Win32 synchronization
Is putting thread on hold optimal?
Thread for Windows form
One simple (but poor) example could be this one:
#include "stdafx.h"
#include "windows.h"
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
using namespace System::Threading;
DialogResult *res=new DialogResult(DialogResult::No);
void waitForUserAction()
{
while(*res==DialogResult::No)
{
*res=System::Windows::Forms::MessageBox::Show("Exit the loop ? YES/NO","TEST",
MessageBoxButtons::YesNo,MessageBoxIcon::Question);
if(*res==DialogResult::Yes)
Console::WriteLine(L"Exit by user");
}
}
int main()
{
ThreadStart ^start=gcnew ThreadStart(waitForUserAction);
Thread ^pThread=gcnew Thread(start);
int a=0;
pThread->Start();
while(*res!=DialogResult::Yes)
{
a=a+1;
Console::WriteLine(L"Loop processing here...{0}",a);
}
//pThread->Abort();
return 0;
}
You can check this article for more info on the topic...

How can you implement a condition variable using semaphores?

A while back I was thinking about how to implement various synchronization primitives in terms of one another. For example, in pthreads you get mutexes and condition variables, and from these can build semaphores.
In the Windows API (or at least, older versions of the Windows API) there are mutexes and semaphores, but no condition variables. I think that it should be possible to build condition variables out of mutexes and semaphores, but for the life of me I just can't think of a way to do so.
Does anyone know of a good construction for doing this?
Here's a paper from Microsoft Research [pdf] which deals with exactly that.
One way of implementing X given semaphores is to add a server process to the system, use semaphores to communicate with it, and have the process do all the hard work of implementing X. As an academic exercise, this might be cheating, but it does get the job done, and it can be more robust to misbehaviour by the client processes, or to their sudden death.
I may be missing something here, but there seem to be a simpler way to implement a Condition from a Semaphore and Lock than the way described in the paper.
class Condition {
sem_t m_sem;
int m_waiters;
int m_signals;
pthread_mutex_t *m_mutex;
public:
Condition(pthread_mutex_t *_mutex){
sem_init(&this->m_sem,0,0);
this->m_waiters = 0;
this->m_signals = 0;
this->m_mutex = _mutex;
}
~Condition(){}
void wait();
void signal();
void broadcast();
};
void Condition::wait() {
this->m_waiters++;
pthread_mutex_unlock(this->m_mutex);
sem_wait(&this->m_sem);
pthread_mutex_lock(this->m_mutex);
this->m_waiters--;
this->m_signals--;
}
void Condition::signal() {
pthread_mutex_lock(this->m_mutex);
if (this->m_waiters && (this->m_waiters > this->m_signals)) {
sem_post(&this->m_sem);
this->m_signals++;
}
pthread_mutex_unlock(this->m_mutex);
}

C/C++: duplicate main() loop in many threads

I have this "interesting" problem. I have this legacy code that looks like
int main()
{
while(true) {
doSomething();
}
}
I would like to duplicate that doSomething() in many threads, so that now main() would look like
int main() {
runManyThreads(threadEntry)
}
void threadEntry() {
while(true) {
doSomething();
}
}
The problem is that doSomething() access many global and static variables, and I cannot alter its code. Is there a trick to duplicate those static variables, so each thread has its own set ? (somekind of thread local storage, but without affecting doSomething())..
I use VisualC++
To make a long story short, no, at least not (what I'd call) reasonably.
Under the circumstance of not wanting to change doSomething(), your best bet is probably to run a number of copies of the existing process instead of attempting to use multi-threading. If each thread is going to use a separate copy of global variables and such anyway, the difference between multithreading and multiple processes will be fairly minor in any case.
Untested, but I think you can do something like:
#define threadlocal __declspec(thread)
And then put threadlocal before all the variables that should be local to the thread. Might not work though, it's generally not a good idea to just throw functions into threads when they weren't written to be multi-threaded.
Your best bet is thread local storage.

Resources