[fpc-devel] Optimisation and thread safety

J. Gareth Moreton gareth at moreton-family.com
Sat Nov 13 00:55:42 CET 2021


Hi everyone,

I have a question when it comes to optimising memory reads and writes.  
What are the rules for FPC when it comes to writing to memory and then 
reading from it later within a single subroutine? For example, say I had 
this pair of commands:

     movq    %rdx,-584(%rbp)
     movl    -584(%rbp),%eax

That could easily be converted to "movl %edx,%eax", especially as %rbp 
is likely pointing to the top of the stack.  But if the reference uses 
different registers, would it still be safe to make this optimisation 
given that the scheduler could suspend the thread in between the two 
instructions and then another thread writes to the same memory block 
before control is returned?

I am aware of other examples that require caution.  For example:

     movslq    -608(%rbp),%rdx
     subl    %eax,-84(%rbp,%rdx,4)
     movslq    -608(%rbp),%rdx

Here it might be tempting to remove the second "movslq" instruction, but 
the value of %rdx could happen to be equal to -131, which would allow 
the subl instruction to modify -608(%rbp), and in this situation, it's 
quite likely if a malicious input is given to the program to manipulate 
the value stored at -608(%rbp) and invoke a buffer overrun.

So in conclusion, theoretically, where is it perfectly safe to assume 
the value in memory hasn't changed, where would it be permissible only 
under -O4 and where must it not be optimised at all?

Gareth aka. Kit

P.S. Assembly examples were taken from the System unit.


-- 
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus



More information about the fpc-devel mailing list