flat assembler
Message board for the users of flat assembler.

Index > Macroinstructions > Extended macro packet for FASM. FASM almost like in C

Author
Thread Post new topic Reply to topic
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 05 Jul 2023, 19:28
The macropackage is intended for significant simplification of application development on FASM under the Windows platform - Win32 and Win64. Under Dos the package isn't realized yet, nevertheless implementation plans were as well under Windows 16 bit.

In special cases with the help the package was succeeded to achieve almost cross-platform development for Win32 and Win64 for a set of teams x86.


Example of the code with this package such:

Code:

format PE GUI 3.1
entry start

   include 'Win32M.inc'
  _class TCHAR 'FASMWIN32',0
  _title TCHAR 'Win32 program template',0
  _error TCHAR 'Startup failed.',0

  wc WNDCLASS 0,WindowProc,0,0,NULL,NULL,NULL,COLOR_BTNFACE+1,NULL,_class

  msg MSG

  start:

  movv  [wc.hInstance],GetModuleHandleA,0
  movv  [wc.hIcon],LoadIconA,0,IDI_APPLICATION
  movv  [wc.hCursor],LoadCursorA,0,IDC_ARROW
  
 _IF RegisterClassA(wc) ==0 
 
     capi       MessageBoxA,NULL,_error,NULL,MB_ICONERROR+MB_OK
     
 _END

_IF capi CreateWindowExA,0,_class,_title,WS_VISIBLE+WS_DLGFRAME+WS_SYSMENU,128,128,256,192,NULL,NULL,[wc.hInstance],NULL == 0
    
     capi       MessageBoxA,NULL,_error,NULL,MB_ICONERROR+MB_OK
      
_ENDIF
 
  _WHILE GetMessageA,msg,NULL,0,0 != 0

        capi    TranslateMessage,msg
        capi    DispatchMessageA,msg
      
  _ENDW

  end_loop:
        capi    ExitProcess,[msg.wParam]

proc WindowProc hwnd,wmsg,wparam,lparam

  _IF [wmsg]==WM_DESTROY
  
      capi      PostQuitMessage,0
      return FALSE;
      
  _ELSE
  
     capi       DefWindowProcA,[hwnd],[wmsg],[wparam],[lparam];

  _ENDIF
ret
endp

  IMPORTTABLE

    


The sample folder contains examples of the use of this macro package.


Description: FASM and my macros packet. All configurate.
Download
Filename: fasmw17330 with extended macro packet.zip
Filesize: 1.11 MB
Downloaded: 170 Time(s)


_________________
Best regards, Dmitry


Last edited by Dima1205 on 06 Jul 2023, 22:32; edited 1 time in total
Post 05 Jul 2023, 19:28
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 05 Jul 2023, 19:36
Dima1205 wrote:

Example of the code with this package such to Win32 and Win64 platform auto convert
Code:
; Template for program using standard Win32 headers

;Win 32 header:
;format PE GUI 3.1

   ;include 'Win32M.inc'
   
;Win64 header:
   format PE64 GUI 5.0
   include 'Win64M.inc'
   
  _class TCHAR 'FASMWIN32',0
  _title TCHAR 'Win32 program template',0
  _error TCHAR 'Startup failed.',0

  wc WNDCLASS 0,WindowProc,0,0,NULL,NULL,NULL,COLOR_BTNFACE+1,NULL,_class

  msg MSG

  EntryMain start

  movv  [wc.hInstance],GetModuleHandleA,0
  movv  [wc.hIcon],LoadIconA,0,IDI_APPLICATION
  movv  [wc.hCursor],LoadCursorA,0,IDC_ARROW
  
 _IF RegisterClassA(wc) ==0 
 
     capi       MessageBoxA,NULL,_error,NULL,MB_ICONERROR+MB_OK
     
 _END

_IF capi CreateWindowExA,0,_class,_title,WS_VISIBLE+WS_DLGFRAME+WS_SYSMENU,128,128,256,192,NULL,NULL,[wc.hInstance],NULL == 0
    
     capi       MessageBoxA,NULL,_error,NULL,MB_ICONERROR+MB_OK
      
_ENDIF
 
  _WHILE GetMessageA,msg,NULL,0,0 != 0

        capi    TranslateMessage,msg
        capi    DispatchMessageA,msg
      
  _ENDW

  end_loop:
        capi    ExitProcess,[msg.wParam]

proc WindowProc hwnd,wmsg,wparam,lparam

    correct 0,hwnd,wmsg,wparam,lparam
  _IF [wmsg]==WM_DESTROY
  
      capi      PostQuitMessage,0
      return FALSE;
      
  _ELSE
  
     capi       DefWindowProcA,[hwnd],[wmsg],[wparam],[lparam];

  _ENDIF
ret
endp

  IMPORTTABLE


    


_________________
Best regards, Dmitry
Post 05 Jul 2023, 19:36
View user's profile Send private message Reply with quote
luboput



Joined: 09 Mar 2023
Posts: 8
luboput 06 Jul 2023, 22:18
IF fix .if
..
ENDIF fix .endif

и не надо макроса
Post 06 Jul 2023, 22:18
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 06 Jul 2023, 22:28
It`s don`t work:
Code:
 .if invoke RegisterClassA,wc ==0
 
     capi       MessageBoxA,NULL,_error,NULL,MB_ICONERROR+MB_OK
     
 .endif
    


It`s correct work:
Code:
_IF  RegisterClassA(wc) ==0
 
     capi       MessageBoxA,NULL,_error,NULL,MB_ICONERROR+MB_OK
     
 _END
    


So that in the condition you can write the invoke call, I write these macros.

_________________
Best regards, Dmitry
Post 06 Jul 2023, 22:28
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 06 Jul 2023, 22:41
Update macros, include FOREACH maco
Post 06 Jul 2023, 22:41
View user's profile Send private message Reply with quote
luboput



Joined: 09 Mar 2023
Posts: 8
luboput 07 Jul 2023, 01:11
понял
;-------------------
у меня DIALOG.asm example not work - Error illegal instruction (_IF msg==WM_INITDIALOG)


Description:
Filesize: 51.02 KB
Viewed: 4461 Time(s)

sc1.jpg


Post 07 Jul 2023, 01:11
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 07 Jul 2023, 13:52
Okey, I fixed error:
Code:
;DialogBox example
format PE GUI 3.1
include 'Win32M.inc'
;format PE64 GUI 5.0 
;include 'Win64M.inc'
ID_CAPTION         = 101
ID_MESSAGE         = 102
ID_ICONERROR       = 201
ID_ICONINFORMATION = 202
ID_ICONQUESTION    = 203
ID_ICONWARNING     = 204
ID_TOPMOST         = 301

section '.text' code readable executable

  EntryMain start

        capi    GetModuleHandleA,0
        
  _IF -1 == capi        DialogBoxParamA,eax,37,HWND_DESKTOP,DialogProc,0

        capi    MessageBoxA,HWND_DESKTOP,message,caption,[flags]  
    
  _END
        capi    ExitProcess,0

proc DialogProc hwnddlg,msg,wparam,lparam
         ;push  ebx esi edi
   correct 0,hwnddlg,msg,wparam,lparam
  _IF [msg]== WM_INITDIALOG
  
     capi       CheckRadioButton,[hwnddlg],ID_ICONERROR,ID_ICONWARNING,ID_ICONINFORMATION
     return TRUE;
     
  _ELSE_IF  [msg]==WM_COMMAND
  
      _IF [wparam]==BN_CLICKED shl 16 + IDCANCEL
           jmp close_dlg
           
      _ELSE_IF [wparam]==BN_CLICKED shl 16 + IDOK
      
            capi        GetDlgItemTextA,[hwnddlg],ID_CAPTION,caption,40h
          capi  GetDlgItemTextA,[hwnddlg],ID_MESSAGE,message,100h
          mov   [flags],MB_OK
      
      _ENDIF
      return TRUE;
  _ELSE_IF  [msg]==WM_CLOSE
  
      close_dlg:
      capi      EndDialog,[hwnddlg],0
  _ELSE

      return FALSE;
  
  _ENDIF
        
        ;pop    edi esi ebx
        ret
endp

section '.bss' readable writeable

  flags dd ?
  caption rb 40h
  message rb 100h

  IMPORTTABLE

section '.rsrc' resource data readable

  directory RT_DIALOG,dialogs

  resource dialogs,\
           37,LANG_ENGLISH+SUBLANG_DEFAULT,demonstration

  dialog demonstration,'Create message box',70,70,190,175,WS_CAPTION+WS_POPUP+WS_SYSMENU+DS_MODALFRAME
    dialogitem 'STATIC','&Caption:',-1,10,10,70,8,WS_VISIBLE
    dialogitem 'EDIT','',ID_CAPTION,10,20,170,13,WS_VISIBLE+WS_BORDER+WS_TABSTOP
    dialogitem 'STATIC','&Message:',-1,10,40,70,8,WS_VISIBLE
    dialogitem 'EDIT','',ID_MESSAGE,10,50,170,13,WS_VISIBLE+WS_BORDER+WS_TABSTOP+ES_AUTOHSCROLL
    dialogitem 'BUTTON','&Icon',-1,10,70,80,70,WS_VISIBLE+BS_GROUPBOX
    dialogitem 'BUTTON','&Error',ID_ICONERROR,20,82,60,13,WS_VISIBLE+BS_AUTORADIOBUTTON+WS_TABSTOP+WS_GROUP
    dialogitem 'BUTTON','I&nformation',ID_ICONINFORMATION,20,95,60,13,WS_VISIBLE+BS_AUTORADIOBUTTON
    dialogitem 'BUTTON','&Question',ID_ICONQUESTION,20,108,60,13,WS_VISIBLE+BS_AUTORADIOBUTTON
    dialogitem 'BUTTON','&Warning',ID_ICONWARNING,20,121,60,13,WS_VISIBLE+BS_AUTORADIOBUTTON
    dialogitem 'BUTTON','&Style',-1,100,70,80,70,WS_VISIBLE+BS_GROUPBOX
    dialogitem 'BUTTON','&Top most',ID_TOPMOST,110,82,60,13,WS_VISIBLE+WS_TABSTOP+BS_AUTOCHECKBOX
    dialogitem 'BUTTON','OK',IDOK,85,150,45,15,WS_VISIBLE+WS_TABSTOP+BS_DEFPUSHBUTTON
    dialogitem 'BUTTON','C&ancel',IDCANCEL,135,150,45,15,WS_VISIBLE+WS_TABSTOP+BS_PUSHBUTTON
  enddialog
    


It's work to Win32/Win64

_________________
Best regards, Dmitry
Post 07 Jul 2023, 13:52
View user's profile Send private message Reply with quote
luboput



Joined: 09 Mar 2023
Posts: 8
luboput 07 Jul 2023, 20:03
?: why not IF-ELSE--END
fasm allows
Post 07 Jul 2023, 20:03
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 07 Jul 2023, 21:31
I write _END macro simulate to _ENDIF.
Post 07 Jul 2023, 21:31
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 07 Jul 2023, 21:42
IF-ELSE--END AND UNLESS-ELSE_END can use this structure.
Post 07 Jul 2023, 21:42
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 08 Jul 2023, 11:55
I wrote analog api macro for my package interface capi.
Source:
Code:
macro API_N [name]
{
   common
  ;Генерируем список параметров: 
  TConstList test123
  argv_test_data_argument equ  
  rept  argument_count item
  \{             
     testequ argv_test_data_argument,arg,item 
     test123.Append argv_test_data_argument 
     purge argv_test_data_argument     
  \}
  forward
  match any,test123
  \{        
    ;Отменяем предыдущее определение, если еще один макрос найден с таким же именем:
    PURGE name    
    macro name any
    \\{   
         match any,UNICODE_CONST_FASM_LABEL  \\\{  name#W any    \\\}
         match ,UNICODE_CONST_FASM_LABEL     \\\{  name#A any    \\\}           
    \\}      
  \}
    
  macro F.#name args 
  \{  
      match any,UNICODE_CONST_FASM_LABEL  \\{  F.#name#W <args>  \\}
      match ,UNICODE_CONST_FASM_LABEL     \\{  F.#name#A <args>  \\}          
  \}
  
  macro CF.#name args 
  \{  
      match any,UNICODE_CONST_FASM_LABEL  \\{  CF.#name#W <args>  \\}
      match ,UNICODE_CONST_FASM_LABEL     \\{  CF.#name#A <args>  \\}          
  \}
}
    

It's can to use MessageBox how MessageBoxA and MessageBoxW. UNICODE_CONST_FASM_LABEL determinate in header files.

_________________
Best regards, Dmitry
Post 08 Jul 2023, 11:55
View user's profile Send private message Reply with quote
luboput



Joined: 09 Mar 2023
Posts: 8
luboput 08 Jul 2023, 18:58
bug


Description:
Filesize: 37.98 KB
Viewed: 4310 Time(s)

er2.jpg


Post 08 Jul 2023, 18:58
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 08 Jul 2023, 22:07
Поправил код.
Code:
;format PE GUI 3.1
;include 'Win32M.inc'
format PE64 GUI 5.0 
include 'Win64M.inc'
        
     lpFindFileData WIN32_FIND_DATA
      ;i dd NULL
      HANDLE i;
      x dd NULL

      test1 db "C:\WINDOWS\*.exe",0
         
EntryMain WinMain
                       
        i=capi FindFirstFileA,test1,lpFindFileData;
                             
       _FOR [x]= 2 TO 5 
              
          capi FindNextFileA,i,lpFindFileData
          capi MessageBoxA,NULL,lpFindFileData.cFileName,'',MB_OK ; <<< фигню пишет
        
       _ENDF 
                   
        capi FindClose,i
        capi ExitProcess,NULL

IMPORTTABLE
    

Макросы и примеры ещё накопятся потом пакет перезалью.

_________________
Best regards, Dmitry
Post 08 Jul 2023, 22:07
View user's profile Send private message Reply with quote
luboput



Joined: 09 Mar 2023
Posts: 8
luboput 08 Jul 2023, 22:44
efficient macro to use (ru=эффективный по использованию макрос)
macro _cmp Var,Val,jto{cmp Var,Val
jto };
;===================================
_cmp [uMsg],WM_XXX, je fun_XXX
---->
cmp [uMsg],WM_XXX
je fun_XXX
Post 08 Jul 2023, 22:44
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 08 Jul 2023, 23:54
ru=Он хорош, но бывают ситуации, когда требуется изменить условие на противоположное (например слева стоит число, а справа регистр или ячейка памяти), поэтому я писал свой обработчик. Думаю, когда будет время на FASMG перенесу.

It is good, but there are situations when you need to change the condition to the opposite (for example, a number is on the left, and a register or memory cell is on the right), so I wrote my own handler. I think when I have time for FASMG I will transfer it.
Post 08 Jul 2023, 23:54
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 08 Jul 2023, 23:57
ru=Тем не менее, его включить в пакет стоит. Чем больше макросов для упрощения жизни, тем лучше. Я думаю, что имеет смысл ещё посмотреть как из MASM и NASM недостающую часть конструкций перенести. Можно и TASM поискать - там DOS макросы должны быть нормальными.

However, it is worth including it in the package. The more macros to make life easier, the better. I think that it makes sense to look at how to transfer the missing part of the structures from MASM and NASM. You can also look for TASM - there DOS macros should be normal.
Post 08 Jul 2023, 23:57
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 10 Jul 2023, 16:46
Macros for create dll on Windows.
Code:
;
;
;  Макросы для упрощённого создания Dll библиотек
;
;
;
;объявляем системный список - константу, которая будет использоваться для генерирования секции:
TConstList ExportList ;системный список для export

;
;
;
;  Точка входа в библиотеку
;
;
macro entrylib {
proc DllEntryPoint hinstDLL,fdwReason,lpvReserved ;функция инициализации DLL
xor ACC,ACC
add ACC,1
;mov    ACC,1 ; перемещаем в регистр eax значение True т.е Истина. Если сюда поставить False (ложь), то DLL не ;запустится
ret ;выходим из этой функции
endp
}


;
;
; интерфейсные макроссы к секции экспорта
;
;
macro EXPORTTABLE
{
  data export
    match any,ExportList
    \{
      export any
    \}
  end data
}
macro expproc [name1,name]
{
  ExportList.Append <name1,name>
}
;простой макросс для работы с секцией экспорта
macro eproc [name]
{
  ExportList.Append <name,`name>
}
macro explib name
{
   ExportList.ReverseAppend `name#'.dll'
}


    


Example for uses:
ru=Пример использования:
Code:
format PE DLL
include 'Win32M.inc'
module advapi32
explib api
entrylib
; Определяем константы
TOKEN_ADJUST_PRIVILEGES = 20h
TOKEN_QUERY             = 8h
SE_PRIVILEGE_ENABLED    = 2h

;здесь разместятся переменные библиотеки
         pid dd 0
        count dd 0 
        hProcess dd 0
        Pidcount dd 0
;Определяем необходимые структуры для работы с привелегиями процесса
struct LUID
  lowPart  dd ?
  HighPart dd ?
ends
 
struct LUID_AND_ATTRIBUTES
  pLuid       LUID
  Attributes  dd ?
ends
 
struct _TOKEN_PRIVILEGES
  PrivilegeCount   dd ?
  Privileges       LUID_AND_ATTRIBUTES
ends

udtLUID  LUID
tkp     _TOKEN_PRIVILEGES
;объявляем структуры для работы с процессами в windows9x
 struct PROCESSENTRY32
dwSize dd ?
cntUsage dd ?
th32ProcessID dd ?
th32DefaultHeapID dd ?
th32ModuleID dd ?
cntThreads dd ?
th32ParentProcessID dd ?
pcPriClassBase dd ?
dwFlags dd ?
szExeFile db 260 dup(?)
ends

;------------------------------------------------------------------
; Функция повышения привелегий процесса
; Параметры вызова:
; type - тип привелегии,которую необходимо получить
;------------------------------------------------------------------
proc GetProcessPrivelege,type:dword
    capi    GetCurrentProcess
    capi    OpenProcessToken,eax,TOKEN_ADJUST_PRIVILEGES+TOKEN_QUERY,TTokenHd
    capi    LookupPrivilegeValue, NULL,[type], udtLUID
    mov     [tkp.PrivilegeCount],1
    mov     [tkp.Privileges.Attributes],SE_PRIVILEGE_ENABLED
    movv [udtLUID.lowPart],[tkp.Privileges.pLuid.lowPart]
    movv [udtLUID.HighPart],[tkp.Privileges.pLuid.HighPart]
    capi    AdjustTokenPrivileges,[TTokenHd],0,tkp,0,0,0
    ret
    TTokenHd dd ?
endp
eproc GetProcessPrivelege
;------------------------------------------------------------------
; Функция обрезки строки
; Параметры вызова:
; string - строка,которую надо обрезать
; kolvo - количество символов, которые надо убрать
; key - ключ обрезки.
; если key=1, то орбрезка происходит с начала,
; если key=0, то обрезка происходит с конца
;------------------------------------------------------------------
proc strcut,string:dword,kolvo:dword,key:dword
capi lstrlen,[string]
cmp [key],1
jne @f
mov edi,[string]
mov esi,edi
add esi,[kolvo]
mov ecx,eax
repe movsb
jmp exit1
@@:
sub eax,[kolvo]
add eax,[string]
mov byte [eax],0
exit1:
ret
endp
eproc strcut
;------------------------------------------------------------------
; Функция убийства процесса
; Параметры вызова:
; id - pid процесса, который надо завершить
;------------------------------------------------------------------
proc KillProcess,id:dword
capi OpenProcess,PROCESS_TERMINATE,0,[id]
capi TerminateProcess,eax,0
ret
endp
eproc KillProcess
;------------------------------------------------------------------
; Функция получения id процесса через ToolHelp32
; Параметры вызова:
; name - имя процесса, id которого надо получить
;callback - процедура обработки значения(т.к. процесс может быть не 1, а несколько).
;Системные требования к функции:
; Windows 9x
; Windows 2000 и выше
;------------------------------------------------------------------
proc GetProcessID9x,name:dword,callback:dword
mov [prcs.dwSize],sizeof.PROCESSENTRY32
capi CreateToolhelp32Snapshot,2,0
mov [hSnapshot], eax
capi Process32First,[hSnapshot],prcs
call_back_label_return_ifromation_process:
mov edi,[name]
capi strstr,prcs.szExeFile,edi
cmp eax,0
je _NextProc_i
stdcall [callback],[prcs.th32ProcessID]
_NextProc_i:
capi Process32Next,[hSnapshot],prcs
cmp eax,0
jne call_back_label_return_ifromation_process
ret
prcs PROCESSENTRY32
hSnapshot dd ?
endp

eproc GetProcessID9x

IMPORTTABLE
EXPORTTABLE

    

_________________
Best regards, Dmitry
Post 10 Jul 2023, 16:46
View user's profile Send private message Reply with quote
Dima1205



Joined: 02 Jul 2023
Posts: 24
Location: Russian, Moscow
Dima1205 14 Jul 2023, 22:11
Post 14 Jul 2023, 22:11
View user's profile Send private message Reply with quote
Display posts from previous:
Post new topic Reply to topic

Jump to:  


< Last Thread | Next Thread >
Forum Rules:
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Copyright © 1999-2024, Tomasz Grysztar. Also on GitHub, YouTube.

Website powered by rwasa.