Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Here is some sample code (from ~10 years ago) that I created. This demonstrates using some inline assembly code concerning CMPXCHG, within the Pelles C.
- I’ve included the 8-bit, 16-bit, & 32-bit flavors for CMPXCHG:
- // Sorry, yet the text formatting may look lousy on a // smartphone .
- typedef unsigned int ui;
- // reference : http://faydoc.tripod.com/cpu/cmpxchg.htm
- //
- // This atomic functtion returns the ZF, (ZF = result of comparison).
- // -------- How it works :: --------
- // "expected" is stored into AL, (=8 bits)
- // then compare AL with "mem".
- // If equal then { ZF=1, and "expected" is stored in mem }
- // else { ZF=0, and AL=MEM (only temporarily) }
- //
- __declspec(naked) __declspec(dllexport) bool cmpxchg_1(volatile ui *mem, ui expected, ui new)
- {
- __asm {
- push ebp
- mov ebp,esp
- push ebx
- push ecx
- mov ebx,[ebp+8] ;; EBX points to mem
- mov eax,[ebp+12] ;; EAX = expected; Only AL shall be used.
- mov ecx,[ebp+16] ;; ECX = new; Only CL shall be used
- lock cmpxchg [ebx],cl
- setz cl ;; store the zero flag result into CL
- xor eax,eax
- add al,cl ;; store CL into EAX, and return EAX
- pop ecx
- pop ebx
- pop ebp
- ret 12
- }
- }
- // reference : http://faydoc.tripod.com/cpu/cmpxchg.htm
- //
- // This atomic function returns the ZF, (ZF = result of comparison).
- // -------- How it works :: --------
- // "expected" is stored into AX, (=16 bits)
- // then compare AX with "mem".
- // If equal then { ZF=1, and "expected" is stored in mem }
- // else { ZF=0, and AX=MEM (only temporarily) }
- //
- __declspec(naked) __declspec(dllexport) bool cmpxchg_2(volatile ui *mem, ui expected, ui new)
- {
- __asm {
- push ebp
- mov ebp,esp
- push ebx
- push ecx
- mov ebx,[ebp+8] ;; EBX points to mem
- mov eax,[ebp+12] ;; EAX = expected; Only AX shall be used.
- mov ecx,[ebp+16] ;; ECX = new; Only CX shall be used
- lock cmpxchg [ebx],cx
- setz cl ;; store the zero flag result into CL
- xor eax,eax
- add al,cl ;; store CL into EAX, and return EAX
- pop ecx
- pop ebx
- pop ebp
- ret 12
- }
- }
- // reference : http://faydoc.tripod.com/cpu/cmpxchg.htm
- //
- // This atomic functtion returns the ZF, (ZF = result of comparison).
- // -------- How it works :: --------
- // "expected" is stored into EAX, (=32 bits)
- // then compare EAX with "mem".
- // If equal then { ZF=1, and "expected" is stored in mem }
- // else { ZF=0, and EAX=MEM (only temporarily) }
- //
- __declspec(naked) __declspec(dllexport) bool cmpxchg_4(volatile ui *mem, ui expected, ui new)
- {
- __asm {
- push ebp
- mov ebp,esp
- push ebx
- push ecx
- mov ebx,[ebp+8] ;; EBX points to mem
- mov eax,[ebp+12] ;; EAX = expected;
- mov ecx,[ebp+16] ;; ECX = new;
- lock cmpxchg [ebx],ecx
- setz cl ;; store the zero flag result into CL
- xor eax,eax
- add al,cl ;; store CL into EAX, and return EAX
- pop ecx
- pop ebx
- pop ebp
- ret 12
- }
- }
Add Comment
Please, Sign In to add comment