Cheat Engine Forum Index Cheat Engine
The Official Site of Cheat Engine
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 


Safe memory management with threads

 
Post new topic   Reply to topic    Cheat Engine Forum Index -> Cheat Engine Tutorials -> Auto Assembler tutorials
View previous topic :: View next topic  
Author Message
ParkourPenguin
I post too much
Reputation: 138

Joined: 06 Jul 2014
Posts: 4275

PostPosted: Tue Feb 15, 2022 4:16 pm    Post subject: Safe memory management with threads This post has 2 review(s) Reply with quote

Creating a thread can let you run code in the target process that wouldn't otherwise be run by the game. In an Auto Assembler script, this can be done using `createthread`.
Code:
createthread(address_to_call)
This should be placed near the end of the script, and the function called should return 0. The script will likely work even if these two rules are not followed.

This is a more complete example, but it doesn't manage memory well:
Code:
// Bad example
alloc(foo,4096)

foo:
  sub rsp,28
  mov ecx,#1000
  call kernel32.sleep
  add rsp,28
  xor eax,eax
  ret

createthread(foo)
This example sleeps for 1 second and returns. See MSDN documentation for information regarding 64-bit calling conventions:
https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention

Every time this AA script gets executed, it will allocate a page of memory (4096 bytes) that will never be deallocated. This is a bad thing to do.

The easiest way to resolve this is to use `globalalloc`:
Code:
globalalloc(foo,4096)

foo:
  ...

createthread(foo)
Memory allocated with `globalalloc` will only ever be allocated once and cannot be deallocated. When the script is executed again, the memory will be reused.
It also has the side effect of registering the symbol (i.e. "foo") so that it can be used outside the script.

`globalalloc` can also be used in scripts that are toggled on or off:
Code:
[ENABLE]
globalalloc(foo,4096)

foo:
  ...

createthread(foo)

[DISABLE]
This is still correct and safe usage of createthread.

Problems can occur when memory should be deallocated in the disable section.
Code:
// Bad example
[ENABLE]
alloc(foo,4096)

foo:
  sub rsp,28
  mov ecx,#1000
  call kernel32.sleep
  add rsp,28
  xor eax,eax
  ret

createthread(foo)

[DISABLE]
dealloc(foo)
This naive approach will only work when the script is disabled at least 1 second after it was enabled.
When the script is disabled, the memory gets deallocated. If the thread tries to execute deallocated memory, it will crash the process. Therefore, the thread must finish executing before the script can be disabled.

Use `createthreadandwait` (create thread and wait) to avoid this problem:
Code:
[ENABLE]
alloc(foo,4096)

foo:
  sub rsp,28
  mov ecx,#1000
  call kernel32.sleep
  add rsp,28
  xor eax,eax
  ret

createthreadandwait(foo)

[DISABLE]
dealloc(foo)
A script using `createthreadandwait` will wait until the thread has finished before it is considered enabled. This way, the script cannot be disabled and memory will not be deallocated while the thread is running.

`createthreadandwait` can also take a timeout parameter:
Code:
[ENABLE]
alloc(foo,4096)

foo:
  sub rsp,28
  mov ecx,#1000
  call kernel32.sleep
  add rsp,28
  xor eax,eax
  ret

createthreadandwait(foo,10000)  // 10 seconds

[DISABLE]
dealloc(foo)
The timeout parameter specifies a number of milliseconds CE will wait before it gives up. If the thread hasn't finished in this amount of time, enabling the script will fail. Any allocated memory will not be deallocated, and the created thread will still continue running.

If the timeout parameter is not provided, CE will wait forever for the thread to finish. This can deadlock CE and might result in loss of work. With this in mind, it's a good idea to set the timeout parameter to something large enough that the thread should finish before then but not too large in case something goes wrong and CE must wait for the timeout to expire.

When using `createthreadandwait`, it might be useful to execute the script asynchronously to avoid freezing the GUI while CE is waiting for the thread to finish. This can be done by right clicking the memory record in the address list and selecting "Execute asynchronous". Be aware that this has other side effects: e.g. {$lua} blocks will be executed in another thread and should not carelessly access the GUI.


For long running threads that shouldn't be waited on to finish, another alternative is to allow the thread to manage its own memory deallocation:
Code:
[ENABLE]
alloc(foo,4096)

foo:
  sub rsp,28
  mov ecx,#1000
  call kernel32.sleep
  add rsp,28

  mov rcx,foo
  xor rdx,rdx
  mov r8d,8000
  jmp kernel32.VirtualFree

createthread(foo)
[DISABLE]
The final 4 instructions are a tail call to VirtualFree. When the thread is finished running whatever code it is running, it will deallocate its own memory and return to the procedure that created the thread in the first place. This gracefully cleans up the thread immediately after deallocating memory.
Note the absence of `dealloc` in the disable section: the thread is now responsible for deallocating memory. CE doesn't have to do anything.

Edit 1: 2 additions + minor changes
`createthread` / `createthreadandwait` should be placed after most other lines in the script. I've infrequently had problems if they were placed near the beginning- probably some race condition regarding how AA scripts get executed.
The function called by `createthread` should return 0. If it doesn't return anything, Microsoft documentation says there's a small chance the process will crash.

_________________
I don't know where I'm going, but I'll figure it out when I get there.


Last edited by ParkourPenguin on Fri Sep 22, 2023 12:22 pm; edited 1 time in total
Back to top
View user's profile Send private message
++METHOS
I post too much
Reputation: 92

Joined: 29 Oct 2010
Posts: 4197

PostPosted: Wed Feb 16, 2022 7:49 am    Post subject: Reply with quote

We need more tutorials like this. Thank you, ParkourPenguin.
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Cheat Engine Forum Index -> Cheat Engine Tutorials -> Auto Assembler tutorials All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Powered by phpBB © 2001, 2005 phpBB Group

CE Wiki   IRC (#CEF)   Twitter
Third party websites