Jump to content
Tuts 4 You

How to execute same code part more times?


LCF-AT

Recommended Posts

Hi guys,

I have a new question and nee some help again.

Problem I have is that I wrote a code part which I wanna execute more times.First I thought again to create a new thread for this but problem is the thraed will run so long till I finish it so I mean the thread 1 runs some minutes (lets think so now) and now I wanna execute the code part again (only other paramters) but the problem is the thread will access the code part again (same address of my routine thread) so what then?Maybe I do think wrong anyhow.

I try to explain it better.Lets say I have a code part I do execute as thread and the code does download any file what needs one minute.Now imagine I execute same thread again what does also download a other file.Now the new thread will also access my code part to do this so it means the code get executed 2 times with other paramters (download other file) but the question whether they also work separated?I am not sure now and think they maybe overlap anyhow or?

Next question I have is how to send thread XY a message?Lets say thread 1 works and dosen't stop and now I wanna stop this code in this thread XY only but how is the question again.In my thread code is a own loop of me what does check for a value 1 in a variable "CHECK" for example so this variable holds value 0 but now I wanna stop this loop and have to send value 1 into variable "CHECK" into this one thread XY so how can I do this now without to send value 1 into variable "CHECK" to all threads you know what I mean right?

Maybe you can tell me something about it or show me a tiny example how to handle this.

Thank you

Link to comment

Have you read up on these? That should help answer your first question...

https://msdn.microsoft.com/en-us/library/windows/desktop/ms684254%28v=vs.85%29.aspx

https://msdn.microsoft.com/en-us/library/windows/desktop/ms687069%28v=vs.85%29.aspx

As for the second... when I want a particular thread to end I pass the thread handle to a global variable, the thread would be listening for their own thread handle being sent to the global variable in their thread loop. The thread handle is the one returned by CreateThread. Passing true or false values will simply be confusing when you are running many threads and you want a specific thread to end. I find this method much more graceful...

Ted.

  • Like 1
Link to comment

Hello Ted,

thanks for your answer so far but I am still confused.Still don't know how to handle it.I made a very tiny example with 2 buttons to start a thread per each click and to send value 1 into check variable but in this case it will exit all thread.Right after the loop what checks for value 1 comes a messagebox so this I also wanna get if I close / terminate the thread but if I terminate the thread by this API then the rest of the code into my thread will not executed anymore so thats also a problem.Maybe you can have a quick look into the example code (added all files) and maybe you can show me how to do it right so that would be nice if course.

My thread looks so...

THREAD_CHECK proc

TESTER:
cmp CHECK, 1h
je OVER
invoke Sleep,300
jmp TESTER
OVER:
invoke MessageBox,NULL,chr$("Thread will exit now!"),chr$("Info!"),MB_ICONINFORMATION
mov CHECK, 0h
ret

THREAD_CHECK endp

...as you can see it loops endless so long till I set value 1 in variable CHECK.So if I wanna terminate the thread etc then the code after the loop (messagebox) must also be executed but isn't working if I just terminate the thread with the thread ID I got before you know.

Thanks

ThreadTest.rar

Link to comment

Hi,

sorry I did checked this tutorial 15 before already but isn't this what I am looking for.

I try to explain it again.I wrote one code part which I so run with some paramters from my main code similar like an API.My code part does run in a loop and checking a variable CHECK for value 1 and if this is inside then the loop will end and the thread will also exit.The problem is how to send value 1 into variable check of only a specific thread without to send value 1 in CHECK of all threads.So I think it seems to be not possible to use one static variable location for more than one thread.So what can I do now to stop the loop in the specific thread xy only + that the code after the loop also gets executed?I got no ideas anymore how to handle this.

greetz

Link to comment

What you are doing is fine for one thread using a global variable but when using multiple threads, you need to use thread id's

I don't know the code for ASM but I would suggest reading up on threading in general which will give you hints and examples on doing this

a very basic example would be to use one global variable which stores a thread id for a thread you want to end. The thread would check this variable against its own id to see if it should end or not. Although this will achieve what you want you have to be careful of race conditions and code changing this 1 variable before the last thread id used it

Link to comment

OK... first of all, u need to form a strategy of how your threads will be handled... I guess you already know that.

So, what I understood from your comment is that you want to create many threads using the same function, simply use more than one variable to control more than one thread :)

Look at the modified source code, once you click on the button, the first thread will get out. If you wanna stop the second thread add "mov [Check2], 2"... all of that achieved by passing arguments to the threads.

ThreadTest_mod1.rar

Link to comment

Hi again,

thanks so far but isn't that what I am looking for so my situation is more complex.Just imagine I use a Listview with entrys on same line which get filled with infos from thread xy and there I do also store infos on each xy entrys and for each entry it must be created a thread and I need to control all threads from my main code to send new infos / updates into any desired thread.

So it means I have to log all infos I do need each time before I create a new thread,also I need to use a own struct where I put paramters into + some details where I have stored this thread in the log place.

Its not so easy to handle that but in the last two days I build something what does work so far but I think there should be also some better solutions out there I don't know yet.

Example: Listview with 10 entrys (DL infos) = starting 10 threads (lets say I do start all at same time now) now all 10 threads start to download.Listview entrys (DL infos & DL Time & DL Size) gets updated during download for each line = 10 x 3 datas to update which happens into my thread code (paramter I did send into struct like handle / LV position etc).Now all would work fine for itself now but I also want to control each DL so that I can also stop any DL if I want so for this I need to send the infos for this into the struct I did send with thread xy.For this I need to build before a log location so that I now can read the log from top and do compare the Listview position and DL status etc.All in all its a little ornate to manage this but at the moment I am happy that I got it working so far also if I am not so happy with the much code I did wrote for this.I am still looking for any more simple way.Also I need to add a check to disable my drag & drop from Listview if something is downloaded at the moment.

Another small question about the threads.So how to exit / terminate a thread if I don't need it anymore?Each time if threads are created then they keep to see in the Thread Map in Olly also if I terminate them etc so they don't disappear from the Thread map.So how to handle this correctly?Lets say I just do start a dummy code thread (only ret command) so what to do now to finish this thread?

greetz

Link to comment

Well, this seems like the common, "check x elements with y threads" if i understood it properly. 

If thats the case, id use a global stack with the elements to check and pop them once needed and execute all threads in loops untill the stack is empty. 

Link to comment

Hhmm,so the threads needs to run for itself and the time how long any thread does run is X = unknown you know.All in all I used now also a global variable what gets checked at all thread tops so if value 0 inside = thread can start if 1 = sleep loop a while.The first thread part does read datas from internet so this take a short time and I don't what that all threads do access internet at the same time (I think this will make trouble).At the moment all is working so far but anywhere I get a problem after a while (30 or 40+ minutes) and the app does crash.So to find the possible problem I try to install SEHs now with a context error log to a textfile & messagebox (now I need to wait again till it crashs / if it crashs again).

So now I just had a tiny question about my installed SEHs.So I don't wanna handle the possible exception only wanna log the datas to file (all working so far) to see where the problem is I got before etc.Now I see that I also have to install a SEH on each thread I do run..

    ASSUME fs:NOTHING    
    mov esi, offset HANDLER_SEH
    push esi
    push FS:[0]
    mov fs:[0], esp  

...and wanna just ask whether this could be bring a problem later etc or something?So I don't remove the SEH at the end of the threads and just let exit the thread by itself.Is that ok or have I to do something more / or safe etc?Just wanna prevent possible another problems with that etc thats why I am asking about it.

greetz

Link to comment

Handling threads and exceptions ! That's gonna be tiresome in Assembly. I highly encourage you to use C++... faster to test many stuff (codes) and easier to spot the problem (inside the IDE debugger, such as VS).

A good place to start with C++: http://www.tutorialspoint.com/cplusplus/index.htm

Imagine that you can create a thread in C++ like this:

#include <iostream>
#include <thread>

  //This function will be called from a thread
void call_from_thread() {
     std::cout << "Hello, World" << std::endl;
}

int main() {
  //Launch a thread
  std::thread t1(call_from_thread);
  //Join the thread with the main thread
  t1.join();

  return 0;
}

====

Quote

Its not so easy to handle that but in the last two days I build something what does work so far but I think there should be also some better solutions out there I don't know yet

The solution is up there: use C++ :)

Quote

Another small question about the threads.So how to exit / terminate a thread if I don't need it anymore

It's likely to be a normal behavior (if the thread returns with no problem in your case). I checked Olly and it's as you said, but x64dbg shows things better.

Quote

 log the datas to file

Without writing the log into a file, you can check things (stack before unwinding and the error cause) in the debugger.

Quote

Is that ok or have I to do something more / or safe etc?

I don't know.

Link to comment

Hi,

good ok but its not my goal to switch the language now also if C++ should be a lot easier than to code in assembly language.Anyway,so I think I have to handle this now with ASM.I made a another check today with my app and it keeps running now for 60+ minutes (then I did quit) without any problem so that I think that some changes I made was enough.Anyway,if a problem does come again then exception & context infos get logged.

greetz

Link to comment

Hi again,

I have now another problem.After running my app an hour I get a stackoverflow exception from a thread which calls a dll API inside & inside this dll API I get the overflow.How to handle that now?I added a SEH what did log the register of exception address etc and let show a messagebox too which I got and so long I do keep the MSG then the other threads are still running / main app too etc.So if I can't find the problem or fix it etc would it then be possible to close the problem thread from my SEH (but what to set then now into context etc?) and to keep the app running?Some kind of aha thread X failed but keep app running and start a new thread for the failed one etc something like this?So I don't know now how to force a stackoverflow exception (maybe you know) then I could check this problem in Olly.Or maybe you have any another ideas to prevent possible stackoverflows with any checks or else etc would be nice of course.

PS: So I don't have a good hand to handle the C language so its more harder to get this method in my head.Also these bracket signs "} {" are not my thing etc. :) 

greetz

Link to comment

Not sure if you already discovered it (your text is really long to read), but CreateThread has an lpParameter. This will be put as the parameter for the lpStartAddress function.

Usually what you would do is allocate a struct on the heap using GlobalAlloc (or malloc), fill it with the info you need and then use the lpParameter in the THREAD_CHECK proc. Also make sure to free the buffer after you're finished :)

If you want to stop your threads, store the pointer to the thread struct in your program somewhere (in a list or something), make the thread check THREADSTRUCT.mustStop and set the THREADSTRUCT.mustStop in the main program.

Not familiar with the assembler so here is some C (not too complicated, just look at the WinAPI used) :D

struct ThreadInfo
{
  char file[256];
  int someValue;
}

DWORD WINAPI ThreadProc(void* parameter)
{
  ThreadInfo* info = (ThreadInfo*)parameter;
  //do something with info->file or info->someValue
  return 0;
}

int main()
{
  //start first thread
  HANDLE threads[2];
  ThreadInfo* info1 = (ThreadInfo*)GlobalAlloc(GMEM_FIXED, sizeof(ThreadInfo));
  strcpy(info1.file, "C:\\test.exe");
  threads[0] = CreateThread(0, 0, ThreadProc, info1, 0, 0);
  
  //start second thread
  ThreadInfo* info2 = (ThreadInfo*)GlobalAlloc(GMEM_FIXED, sizeof(ThreadInfo));
  strcpy(info2.file, "C:\\test2.exe");
  threads[1] = CreateThread(0, 0, ThreadProc, info2, 0, 0);
  
  //wait for threads to terminate
  WaitForMultipleObjects(2, threads, TRUE, INFINITE);
  return 0;
}

 

  • Like 1
Link to comment

As a sidenote to what Mr.eXoDia posted, keep in mind that if you pass the same info to both threads, you have to implement a method of thread-safety for that data. You can use things such as:

 - Mutex
 - Critical Sections
 - Or any other thread-safe locking mechanism. 

  • Like 1
Link to comment

Hi again,

ok listen.So have alloc 1000 bytes via VirtualAlloc and inside this I do fill the struct datas right before I start the thread.As I said all is working so far good but not endless as it should be and then I get this StackOverlow problem and the app crashs (just exits) or my SEH does info me if it happens.Strange thing is the one day the app just exits without to show me message about exception so it seems my SEH didn't work in that case but should work so I create a SEH at the top on each thread + one SEH from my maincode.Normaly if something goes wrong inside of my maincode or my threadcode then SEH should work but this one time not.No idea why I get this stackOverflow problem.

So is there any chance to find it out or is there any app what can catch the problems + log them etc?

PS: Another this about my thread code.So if I stop at the top of the thread then I see that the used stack now had only 1000 bytes but my thread routine does sub already -1300 bytes from ESP and ESP does point now into a space which not belongs to the stack anymore.I think this should be the problem.So why only 1000 bytes of stack are given and not more?Is there a way to say CreateThread to use more stack bytes like 3000 etc or is this limited?Uhhmm!So in my thread routine I also use many local variables & sizes [256] / [1024] etc which I need and wanna use in this thread code to prevent more manually space allocing & Pointers etc you know.The question now is can I use more stacksizes (if yes - how to tell them that) or have I to re-code this part to prevent long size holder in the stack itself etc?

greetz

Link to comment
45 minutes ago, LCF-AT said:

So is there any chance to find it out or is there any app what can catch the problems + log them etc?

Yes, it's called a debugger. You might have heard of them.. :)

45 minutes ago, LCF-AT said:

The question now is can I use more stacksizes (if yes - how to tell them that)

Either set fields in PE header (SizeOfStackReserve, SizeOfStackCommit), or pass required stack size to CreateThread call (2nd param).

  • Like 1
Link to comment

Hey Kao so you make me really K.O.Ahhhhhh :) Hmmmm a debugger......never heard about that. :) (Remebers me on old part of "Married with Children" where Peggy works as seller in a shop watches (watches all around) and a men comes in and asked "Do you have watches?" and Peggy answers "No". :) Just funny,almost same case now about stacksize so I really didn't notice the 2. paramter on CreateThread API also if I have seen it tons of times.Anyway,so this solution of you was really really simple Kao so thanks again for this hint.Now I try it again with more stacksizes and I will see whether I get the StackOverflow problem again or not (I hope so).

Thank Shoe :)

Link to comment

Hi,

short info.I found the problem now why my app did crash after a while.Problem was I did use some APIs of any extern module where I need to restore some stack bytes after API call (add esp,xy) and thats all. :) 

greetz

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...