2
votes
Init: int x = y = 0;

thr1       thr2
----       ----
y = 1;     x = 1;    WRITE to global variables
a = x;     b = y;    READ from global variables
print(a);  print(b);

In the above code snippet running under the TSO memory model, it is well known that both threads can print 0 at the same time because a CPU can re-order instructions to execute a read instruction (i.e., the second line of a thread) before a write instruction.

Then, what will happen we insert breakpoints on the read instructions, and do nothing but keep executing when breakpoints are hit? Still can both threads print 0 at the same time, or do breakpoints prevent reordering?

I assume the x86-64 architecture and the x86-TSO memory model. It though will be appreciated if any difference between architectures (or memory models) is given. Also I guess hardware breakpoint and software breakpoint will not make a difference in result (since they both trigger an exception, and the x86 architecture handles them similarly). Is this guessing correct?

1

1 Answers

2
votes

I assume this is pseudo-code for assembly (not C where lots of compile-time optimization could happen), for the same case as https://preshing.com/20120515/memory-reordering-caught-in-the-act/ where StoreLoad reordering will be visible.

A breakpoint with a breakpoint-handler that returns right away is just a really expensive alternative to a serializing instruction (like CPUID or IRET) which ensures that all previous instructions have been executed, and all previous stores are committed to coherent cache (i.e. drain the store buffer).

The reason for this is that returning from the breakpoint will probably involve IRET, which is a serializing instruction. (Like MFENCE but also serializing out-of-order exec).

So yes, a breakpoint is a full barrier for memory reordering as observed by other threads.

This applies for hardware breakpoints or for software breakpoints where the debugger has to restore the original instruction's first byte to let it execute normally, instead of the 0xcc int3 software breakpoint.