; Name: calcstructsum.asm;; Build: g++ -m32 -c main.cpp -o main.o; nasm -f elf32 -o calcstructsum.o calcstructsum.asm; g++ -m32 -o calcstructsum calcstructsum.o main.o;; Source: Modern x86 Assembly Language Programming p.68global CalcStructSum
; the structure in nasmstruc TEST_STRUC
.Val8:resb1 .Pad8:resb1 .Val16:resw1 .Val32:resd1 .Val64:resq1 .size:endstruc; assuming that ts is represented in esi%define ts.Val8 byte[esi+TEST_STRUC.Val8]%define ts.Val16 word[esi+TEST_STRUC.Val16]%define ts.Val32 dword[esi+TEST_STRUC.Val32]%define ts.Val64.low dword[esi+TEST_STRUC.Val64]%define ts.Val64.high dword[esi+TEST_STRUC.Val64+4]section .text
; extern "C" int64_t CalcStructSum(const TestStruct* ts);;; Description: This function sums the members of a TestStruc.;; Returns: Sum of 'ts' members as a 64-bit integer.%define ts [ebp+8]CalcStructSum:pushebpmovebp,esppushebxpushesi; Compute ts->Val8 + ts->Val16, note sign extension to 32-bitsmovesi,ts
movsxeax,ts.Val8
movsxecx,ts.Val16
addeax,ecx; Sign extend previous sum to 64 bits, save result to ebx:ecxcdqmovebx,eaxmovecx,edx; Add ts->Val32 to summoveax,ts.Val32
cdqaddeax,ebxadcedx,ecx; Add ts->Val64 to sumaddeax,ts.Val64.low
adcedx,ts.Val64.high
popesipopebxpopebpret