News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

Create buffer divisible by 4

Started by Gunner, April 27, 2011, 12:22:56 AM

Previous topic - Next topic

dedndave


dedndave

align2 proc len:dword,multiple_of_2:dword
;to do: need check if multiple of 2 is so high to fit in this dword

        mov     edx,multiple_of_2
        mov     eax,len
        add     eax,edx
        dec     eax
        neg     edx
        and     eax,edx
        ret

align2 endp

mineiro

Fatality, Sr Dedndave wins, flawers victory hehehe.  :thumbu

drizz

or
mov eax,Value
mov edx,Alignment
dec eax
dec edx
or eax,edx
inc eax


and aligned memory alloc

if @WordSize ne 8
rax equ <eax>
rdx equ <edx>
size_t typedef dword
else
size_t typedef qword
endif

_alloc:
mov rax,_ALLOC_BYTES
add rax,_MEMORY_ALIGN
invoke HeapAlloc,_HHEAP,HEAP_GENERATE_EXCEPTIONS+HEAP_ZERO_MEMORY,rax
mov rdx,rax
add rax,_MEMORY_ALIGN
and rax,-_MEMORY_ALIGN
mov [rax-size_t],rdx
ret

_free:
mov rax,[rax-size_t]
invoke HeapFree,_HHEAP,HEAP_GENERATE_EXCEPTIONS+HEAP_ZERO_MEMORY,rax
ret


The truth cannot be learned ... it can only be recognized.

dedndave

sorry, drizz, i don't speak "rax"   :lol

hutch--

Rob,

To address your original question, there is no overriding reason to make a buffer divisible by 4. As Erol mentioned allocated memory is already 8 byte aligned and the solution is to simply make your buffer large enough to fit the data you want to put into it. Memory is rarely ever allocated in very small amounts at an OS level so there is no reason why you should have to trim its size down to an arbitrary byte count. Now this means that if you need 15k there is no loss at allocating 16k.

If you need to have memory aligned by greater than 8 bytes, add the extra onto the buffer length then align a location near the beginning of the start address and pass back a pointer to that location. When you deallocate the memory later make sure you deallocate the original memory pointer, not the aligned location. This matters if you want to use later SSE opcodes where they require 16 byte alignment.
Download site for MASM32      New MASM Forum
https://masm32.com          https://masm32.com/board/index.php

cmpxchg


  dec   eax              ; make sure # is either aligned to lower value or not aligned
  and   eax, -2          ; align down, has no effect if aligned to lower
  add   eax, 2           ; += 2


  number 0, 2byte aligned will result in 0
  number 1, 2byte aligned will result in 2
  number 2, 2byte aligned will result in 2
  number 3, 2byte aligned will result in 4
  number 4 2byte aligned will result in 4
                                                   

dedndave

why not...
        inc     eax
        and     eax,-2

INC/DEC only works for 2-alignment
larger than that, and you are back to...
        add     eax,M-1
        and     eax,-M