0

Often while disassembling ARM files, I see some code snippet with the following pattern:

loc_BB30:
.text:C0 FE 5F 88 LDAXR           WZR, W0, [X22]
.text:00 04 00 51 SUB             W0, W0, #1
.text:C0 FE 01 88 STLXR           W1, W0, [X22]
.text:A1 FF FF 35 CBNZ            W1, loc_BB30

Which is translated to the following decompile code:

  do
  {
    v2 = __ldaxr((unsigned int *)v1);
    v1 = (unsigned int)(v1 - 1);
  }
  while ( __stlxr(v1, v3) );

What is the meaning of this code? What kind of c code actually produces this kind of snippet?

4

This general pattern of exclusive-access instructions is usually seen when atomic variables are modified.

C++ Example (C++11 or later)

  #include <atomic>

  void release( std::atomic<int>& refcount ) {
      refcount--;
  }

You can see here on godbolt that GCC's ARM64 compilation of the above produces your assembly code.

C Example (C11)

#include <stdatomic.h>

void release( _Atomic int* refcount ) {
    (*refcount)--;
}

Godbolt version here

C Example (prior to C11, using GCC built-ins)

void release( int* refcount ) {
    __atomic_sub_fetch( refcount, 1, __ATOMIC_ACQ_REL );
}

Godbolt version here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.