Search code examples
assemblymasm

TYPEDEF PTR - size doesn't matter?


I noticed using TYPEDEF to define PTR's with various data types doesn't seem to make any difference. For example, these three types seem to behave exactly the same when used to store and mov 32-bit addresses:

PTYPE TYPEDEF PTR 
PBYTE TYPEDEF PTR BYTE
PWORD TYPEDEF PTR WORD

.data 

arrayByte BYTE 10h,20h,30h

ptr_1 PTYPE arrayByte
ptr_2 PBYTE arrayByte
ptr_3 PWORD arrayByte

.code
main PROC

mov eax, ptr_1 
mov eax, ptr_2 
mov eax, ptr_3 

exit    
main ENDP

Is there any practical reason to specify a size other than it's more self-documenting?


Solution

  • Declaring and using pointer types has little use in MASM. Types in MASM basically are just sizes and are only to used determine sizes of objects and operands and their compatibility size-wise. If you generate a listing file while assembling your example code (after adding .MODEL FLAT and END directives so it assembles), you'll see that the type of ptr1, ptr2 and ptr3 are all DWORD:

    Types:
    
                    N a m e                  Size     Attr
    
    PBYTE  . . . . . . . . . . . . .         00000004     Near32 PTR Byte
    PTYPE  . . . . . . . . . . . . .         00000004     Near32 PTR
    PWORD  . . . . . . . . . . . . .         00000004     Near32 PTR Word
    
    ...
    
    Symbols:
    
                    N a m e                 Type     Value    Attr
    
    ...
    ptr_1  . . . . . . . . . . . . .        DWord    00000003 _DATA
    ptr_2  . . . . . . . . . . . . .        DWord    00000007 _DATA
    ptr_3  . . . . . . . . . . . . .        DWord    0000000B _DATA
    

    The only thing I can see the about pointer types that might make them useful is the fact that they'll automatically change in size according to the memory model in force. So you if you assemble your example with .MODEL SMALL instead of .MODEL FLAT the types of ptr1, ptr2 and ptr3 become WORD instead of DWORD. Similarly if you delete the model directive and assemble it with the x64 version of MASM the types of those symbols becomes QWORD. However doing either of these things reveals that it's not as useful as it sounds, because the MOV EAX, ... instructions in your example code will then generate errors because of the operand size mismatch. In practice a lot of other code would still need to be rewritten to adjust to the change in pointer size.

    Another possibility is that the pointer types would somehow be used in macros to do something useful, but I can't really see what that would be. Even as documentation, using the pointer types is dubious, as other readers aren't going to know what PBYTE or PTYPE mean without searching through the code for their definition. I wouldn't recommend using them.