Author Topic: Interprocess communication  (Read 4691 times)

Mikl__

  • Member
  • *****
  • Posts: 1345
Interprocess communication
« on: August 18, 2022, 11:29:24 AM »
Interprocess communication (IPC)
The Windows operating system provides mechanisms for facilitating communications and data sharing between applications. Collectively, the activities enabled by these mechanisms are called interprocess communications (IPC). Some forms of IPC facilitate the division of labor among several specialized processes. Other forms of IPC facilitate the division of labor among computers on a network.

Typically, applications can use IPC categorized as clients or servers. A client is an application or a process that requests a service from some other application or process. A server is an application or a process that responds to a client request. Many applications act as both a client and a server, depending on the situation.

The following IPC mechanisms are supported by Windows:There are show several ways to transfer data between two applications in this thread. Text string, 128x128 pictures and media data are sent.
The pictures and the wav file are in an attachment in the Images folder.
Place the sender-application with the index "s" and the reciever-application with the index "r" side by side.
  • Write or edit the text in the sender-application and press the "Send Text" button.
  • Press the "Send ICO" button several times.
  • Press the "Send WAV" button.
There are total IPC mechanisms: 19/are written: 12 now.
01. WM_COPYDATA
The following example demonstrates how to send information between two applications using the WM_COPYDATA message.
The sending application displays a dialog box to the user which requests certain information. The application packages the information into a private data structure, includes a pointer to the structure in the COPYDATASTRUCT structure, and sends the information to the receiving application using the WM_COPYDATA message.

01s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc

ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_DIALOG equ 200
IDC_ICON1 equ 500
IDC_IMG1 equ 104

.code
WinMain proc ;dummy:qword
enter 30h,0
mov r9d,256
mov [rbp-10h],r9
and     qword ptr [rbp-8],LR_DEFAULTCOLOR
invoke LoadImageA,IMAGE_BASE,IDC_ICON1,IMAGE_ICON;,0,0,LR_DEFAULTCOLOR
mov r9d,offset DialogProc
mov [rbp-10h],rax
invoke DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local buffer:qword
local cdata:COPYDATASTRUCT
local FSize:dword
local hFile:dword
local p:qword
local szReadWrite:qword ;number of bytes actually read or write
local hResource:qword
local pResource:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_INITDIALOG
        jne wmBYE
wmINITDIALOG:invoke GetDlgItem,,IDC_IMG1
invoke SendMessageA,eax,STM_SETIMAGE,IMAGE_ICON,lParam
jmp wmBYE
wmSEND_TXT:invoke GlobalAlloc,GPTR,256
mov buffer,rax
        mov cdata.lpData,rax
invoke  GetDlgItemTextA,hWnddlg,ID_TXT,eax,256
        or      eax,eax
        jz      wmBYE
        ; fill structure COPYDATASTRUCT
        mov     cdata.dwData,CF_TEXT
        inc     eax
        mov     cdata.cbData,eax
jmp @f
wmSEND_ICO:mov     cdata.dwData,CF_BITMAP
mov edx,p1
invoke FindResource,0,,RT_ICON; find the resource
mov hResource,rax
invoke  SizeofResource,0,eax ; get its size
mov     cdata.cbData,eax
mov FSize,eax
invoke LoadResource,0,hResource ; load the resource
invoke LockResource,eax;pResource
mov cdata.lpData,rax
mov p,rax
;-------------------------------------------------
        mov ecx,256
and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov [rsp+20h],rcx
mov [rsp+28h],rcx
mov edx,FSize
invoke  CreateIconFromResourceEx,p,,TRUE,30000h;270376,TRUE,30000h
mov [rsp+20h],rax
invoke  SendDlgItemMessageA,hWnddlg,IDC_IMG1,STM_SETIMAGE,IMAGE_ICON
xor p1,11b
;--------------------------------------------------
jmp @f
wmSEND_WAV:mov ecx,offset wav_file
invoke CreateFile,,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,\
        FILE_ATTRIBUTE_ARCHIVE,0
        mov hFile,eax
        invoke GetFileSize,eax,0
mov FSize,eax
        mov     cdata.dwData,CF_WAVE
        mov     cdata.cbData,eax
invoke GlobalAlloc,GPTR,eax
        mov cdata.lpData,rax
lea r9d,szReadWrite
and qword ptr[rsp+20h],0
        invoke ReadFile,hFile,eax,FSize
        invoke CloseHandle,hFile
@@:mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jz      wmBYE
lea r9d,cdata
mov qword ptr[rsp+20h],SMTO_ABORTIFHUNG
mov qword ptr[rsp+28h],500
and qword ptr[rsp+30h],0
invoke  SendMessageTimeoutA,eax,WM_COPYDATA,hWnddlg
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_ICO
        je      wmSEND_ICO
cmp r8d,BN_CLICKED shl 16 + ID_SEND_WAV
        je      wmSEND_WAV
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
;---------------------------------------
.data
szWin db 'WM_COPYDATA Reciever',0
wav_file db '..\Images\03.wav',0
p1 dd 1
end

01s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "WM_COPYDATA Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}

01r.asm (Client)
Code: [Select]
; GUI #
include win64a.inc

IDC_DIALOG equ 200
ID_TXT equ 100
ID_ICON equ 102
IDC_ICON1 equ 500

.code
WinMain proc dummy:qword

        invoke  DialogBoxParam,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP,qword ptr(offset DialogProc),0
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword
local p:qword
local FSize:dword
local lpwiocb:WAVEHDR
local hWaveOut:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COPYDATA ; Пришло сообщение WM_COPYDATA?
je wmCOPYDATA
cmp edx,WM_COMMAND
je wmCOMMAND
        cmp edx,WM_INITDIALOG
jne wmBYE

wmINITDIALOG:;mov rcx,hWnd
; Найти окно получателя
        invoke  FindWindow,NULL,&szWin
        or      eax,eax
        jnz wmBYE
invoke MessageBox,hWnddlg,&Error1,&szAppName,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      wmBYE     
invoke WinExec,&szService,SW_SHOW
jmp wmBYE
wmCOPYDATA:; Получить строку от первого приложения
; В lParam приходит указатель на структуру COPYDATASTRUCT
        mov eax,[r9+COPYDATASTRUCT.cbData]
or eax,eax; Размер данных нулевой?
        je      wmBYE; Да, пропускаем
mov FSize,eax
        mov rax,[r9+COPYDATASTRUCT.lpData]
mov p,rax
mov rax,[r9+COPYDATASTRUCT.dwData]
        cmp     eax,CF_TEXT; Это нужный тип данных?
        je COPYDATA_TEXT; Нет, пропускаем
cmp     eax,CF_WAVE; Это нужный тип данных?
        je COPYDATA_MUSIC; Нет, пропускаем
cmp     eax,CF_BITMAP; Это нужный тип данных?
        jne wmBYE
COPYDATA_ICON:; Создать HICON напрямую из памяти
invoke  CreateIconFromResourceEx,p,FSize,TRUE,30000h,256,256,LR_DEFAULTCOLOR
invoke  SendDlgItemMessage,hWnddlg,ID_ICON,STM_SETIMAGE,IMAGE_ICON,eax
jmp wmBYE
COPYDATA_MUSIC:mov r8,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data) = 14h
        add r8d,14h
        invoke waveOutOpen,&hWaveOut,WAVE_MAPPER,,0,0,WAVE_ALLOWSYNC
; Подготавливаем заголовок для вывода
lea edi,lpwiocb
mov edx,edi
xor eax,eax
mov ecx,(sizeof WAVEHDR)/8
rep stosq

mov rax,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data)+\
;(Type of format)+(Number of Channels)+(Sample Rate)+(Sample Rate*BitsPerSample*Channels/8)+\
;(BitsPerSample*Channels/8)+(Bits per sample)+(“data” chunk header)+(Size of the data section)=2Ch
add rax,2Ch
mov [rdx].WAVEHDR.lpData,rax ;адрес блока данных
mov eax,FSize
sub eax,2Ch
mov [rdx].WAVEHDR.dwBufferLength,eax ;размер блока данных
invoke waveOutPrepareHeader,hWaveOut,,sizeof WAVEHDR
; Запускаем проигрывание блока
invoke waveOutWrite,hWaveOut,&lpwiocb,sizeof WAVEHDR
@@: test lpwiocb.dwFlags,WHDR_DONE
jz @b
invoke waveOutUnprepareHeader,hWaveOut,&lpwiocb,sizeof WAVEHDR
invoke waveOutClose,hWaveOut
jmp wmBYE
COPYDATA_TEXT:invoke SetDlgItemText,,ID_TXT,p
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
.data
szWin   db "Clipboard Sender",0
Error1   db "The server is not running.",10,"Run?",0
szAppName db "Clipboard Reciever",0
szService db "01s",0
end
01r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "WM_COPYDATA Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
}
« Last Edit: October 02, 2022, 07:47:51 PM by Mikl__ »

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #1 on: August 18, 2022, 11:51:58 AM »
02. ClipBoard
The clipboard is a set of functions and messages that enable applications to transfer data. Because all applications have access to the clipboard, data can be easily transferred between applications or within an application.
02r.asm (Client)
Code: [Select]
; GUI #
include win64a.inc
IDC_DIALOG equ 200
ID_TXT equ 100
ID_ICON equ 102
IDC_ICON1 equ 500

.code
WinMain proc  dummy:qword

        invoke  DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP,qword ptr(offset DialogProc),0
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword
local hGin:qword
local p:qword
local FSize:dword
local lpwiocb:WAVEHDR
local hWaveOut:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_CLIPBOARDUPDATE
je wmCLIPBOARDUPDATE
cmp edx,WM_COMMAND
je wmCOMMAND
        cmp edx,WM_INITDIALOG
jne wmBYE
wmINITDIALOG:invoke  FindWindowA,NULL,&szWin
        or      eax,eax
        jnz wmBYE
invoke MessageBoxA,hWnddlg,&Error1,&szAppName,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      wmBYE     
invoke WinExec,&szService,SW_SHOW
jmp wmBYE
wmCLIPBOARDUPDATE:; В lParam приходит длина и тип данных
invoke OpenClipboard ;открываем буфер обмена
mov ecx,dword ptr lParam
invoke GetClipboardData;извлекаем текст из буфера обмена
mov hGin,rax
invoke GlobalLock,eax  ;блокируем память
mov p,rax
mov rax,lParam
shr rax,32
mov FSize,eax
cmp     dword ptr lParam,CF_WAVE; Это нужный тип данных?
        jz WAVE
cmp     dword ptr lParam,CF_DIB; Это нужный тип данных?
        jz DIB
cmp dword ptr lParam,CF_TEXT
jnz wmBYE
;---------------------------------------------------
; Получить строку от первого приложения
TXT: invoke  SetDlgItemTextA,hWnddlg,ID_TXT,p
jmp @0
DIB: mov edx,FSize
invoke  CreateIconFromResourceEx,p,,TRUE,30000h,256,256,LR_DEFAULTCOLOR
invoke  SendDlgItemMessageA,hWnddlg,ID_ICON,STM_SETIMAGE,IMAGE_ICON,eax
jmp @0
WAVE: mov r8,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data) = 14h
        add r8d,14h
        invoke waveOutOpen,&hWaveOut,WAVE_MAPPER,,0,0,WAVE_ALLOWSYNC
; Подготавливаем заголовок для вывода
lea edi,lpwiocb
mov edx,edi
xor eax,eax
mov ecx,(sizeof WAVEHDR)/8
rep stosq
mov rax,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data)+\
;(Type of format)+(Number of Channels)+(Sample Rate)+(Sample Rate*BitsPerSample*Channels/8)+\
;(BitsPerSample*Channels/8)+(Bits per sample)+(“data” chunk header)+(Size of the data section)=2Ch
add rax,2Ch
mov [rdx].WAVEHDR.lpData,rax ;адрес блока данных
mov eax,FSize
sub eax,2Ch
mov [rdx].WAVEHDR.dwBufferLength,eax ;размер блока данных
invoke waveOutPrepareHeader,hWaveOut,,sizeof WAVEHDR
; Запускаем проигрывание блока
invoke waveOutWrite,hWaveOut,&lpwiocb,sizeof WAVEHDR
@@: test lpwiocb.dwFlags,WHDR_DONE
jz @b
invoke waveOutUnprepareHeader,hWaveOut,&lpwiocb,sizeof WAVEHDR
invoke waveOutClose,hWaveOut
@0: invoke GlobalLock,hGin
invoke CloseClipboard
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
.data
szWin db "Clipboard Sender",0
Error1 db "The server is not running.",10,"Run?",0
szAppName db "Clipboard Reciever",0
szService db "02s",0
end
02r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Clipboard Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
}
02s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc
ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_DIALOG equ 200
IDC_ICON1 equ 500
IDC_IMG1 equ 104
WM_CLIPBOARDUPDATE  equ 31Dh

.code
WinMain proc dummy:qword

invoke LoadImageA,IMAGE_BASE,IDC_ICON1,IMAGE_ICON,256,256,LR_DEFAULTCOLOR
mov r9d,offset DialogProc
invoke DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP,,eax
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
size_of_buffer equ 96
local hGout:qword
local p:qword
local FSize:dword
local hFile:dword
local szReadWrite:qword ;number of bytes actually read or write
local hResource:qword
local pResource:qword
local type0:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_INITDIALOG
        jne wmBYE
wmINITDIALOG:invoke GetDlgItem,,IDC_IMG1
invoke SendMessageA,eax,STM_SETIMAGE,IMAGE_ICON,lParam
jmp wmBYE
wmSEND_TXT:invoke GlobalAlloc,GPTR,size_of_buffer;GHND or GMEM_DDESHARE
mov hGout,rax
invoke GlobalLock,eax
mov p,rax
invoke  GetDlgItemTextA,hWnddlg,ID_TXT,eax,size_of_buffer;255
        or      eax,eax
        jz      wmBYE
mov FSize,eax
add rax,p
and byte ptr[rax],0
mov rdx,CF_TEXT
jmp @f
;--------------------------------------------------
wmSEND_ICO:; Отправить изображение второму приложению
mov edx,p1
invoke FindResource,0,,RT_ICON; find the resource
mov hResource,rax
invoke  SizeofResource,0,eax ; get its size
mov FSize,eax
invoke GlobalAlloc,GPTR,eax; or GMEM_DDESHARE,eax
mov hGout,rax
invoke GlobalLock,eax
mov p,rax
mov edi,eax
invoke LoadResource,0,hResource ; load the resource
invoke LockResource,eax;pResource
mov esi,eax
mov ecx,FSize
rep movsb
;------------------------------------------------
mov edx,FSize
invoke  CreateIconFromResourceEx,p,,TRUE,30000h,256,256,LR_DEFAULTCOLOR
invoke  SendDlgItemMessageA,hWnddlg,IDC_IMG1,STM_SETIMAGE,IMAGE_ICON,eax
xor p1,11b
mov rdx,CF_DIB
jmp @f
;--------------------------------------------------
wmSEND_WAV:invoke CreateFile,&wav_file,GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_ARCHIVE,0
        mov hFile,eax
        invoke GetFileSize,eax,0
mov FSize,eax
invoke GlobalAlloc,GPTR,eax
mov hGout,rax
invoke GlobalLock,eax
mov p,rax
        invoke ReadFile,hFile,eax,FSize,&szReadWrite,0
        invoke CloseHandle,hFile
mov rdx,CF_WAVE
;--------------------------------------------------------
@@: mov eax,FSize
shl rax,32
or rax,rdx
mov type0,rax
invoke GlobalUnlock,hGout
invoke OpenClipboard,hWnddlg
or eax,eax
jz wmBYE
invoke EmptyClipboard
invoke SetClipboardData,type0,hGout
invoke CloseClipboard
; Найти окно получателя
        invoke  FindWindowA,NULL,&szWin
        or      eax,eax
        jz      wmBYE
; Отправить данные получателю
invoke  PostMessageA,eax,WM_CLIPBOARDUPDATE,hWnddlg,type0
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_ICO
        je      wmSEND_ICO
cmp r8d,BN_CLICKED shl 16 + ID_SEND_WAV
        je      wmSEND_WAV
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
;---------------------------------------
.data
szWin db 'Clipboard Reciever',0
wav_file db '..\Images\03.wav',0
p1 dd 1
end
02s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Clipboard Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}
« Last Edit: August 18, 2022, 06:13:37 PM by Mikl__ »

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #2 on: August 18, 2022, 12:02:37 PM »
03. Memory Mapped File
Memory-mapped files can be shared across multiple processes. Processes can map to the same memory-mapped file by using a common name that is assigned by the process that created the file.
To work with a memory-mapped file, you must create a view of the entire memory-mapped file or a part of it. You can also create multiple views to the same part of the memory-mapped file, thereby creating concurrent memory. For two views to remain concurrent, they have to be created from the same memory-mapped file.
03r.asm (Client)
Code: [Select]
; GUI #
include win64a.inc
IDC_DIALOG equ 200
ID_TXT equ 100
ID_ICON equ 102
IDC_ICON1 equ 500

.code
WinMain proc dummy:qword

        invoke  DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP,qword ptr(offset DialogProc),0
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword
local pMapping:qword
local hMapping:qword
local FSize:dword
local lpwiocb:WAVEHDR
local hWaveOut:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_USER+1
je wmUSER_1
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_INITDIALOG
        jne wmBYE
wmINITDIALOG:; Найти окно получателя
        invoke  FindWindowA,NULL,&szWin
        or      eax,eax
        jnz wmBYE
invoke MessageBoxA,hWnddlg,&Error1,&szAppName,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      wmBYE     
invoke WinExec,&szService,SW_SHOW
jmp wmBYE
wmUSER_1:; Получить строку от первого приложения
invoke OpenFileMapping,FILE_MAP_READ,FALSE,&lpszName
mov hMapping,rax
invoke MapViewOfFile,eax,FILE_MAP_READ,0,0,0
mov pMapping,rax
;-------------------------------------------
mov rax,lParam
shr rax,8
mov FSize,eax
cmp byte ptr lParam,CF_DIB
je DIB
cmp byte ptr lParam,CF_WAVE
je WAVE
cmp byte ptr lParam,CF_TEXT
jne wmBYE
TEXT: invoke  SetDlgItemTextA,hWnddlg,ID_TXT,pMapping
        jmp @0
DIB: mov edx,FSize
invoke  CreateIconFromResourceEx,pMapping,,TRUE,30000h,256,256,LR_DEFAULTCOLOR
invoke  SendDlgItemMessageA,hWnddlg,ID_ICON,STM_SETIMAGE,IMAGE_ICON,eax
        jmp @0
WAVE: mov r8,pMapping
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data) = 14h
        add r8d,14h
        invoke waveOutOpen,&hWaveOut,WAVE_MAPPER,,0,0,WAVE_ALLOWSYNC
; Подготавливаем заголовок для вывода
lea edx,lpwiocb
mov edi,edx
xor eax,eax
        mov ecx,(sizeof WAVEHDR)/8
rep stosq
mov rax,pMapping
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data)+\
;(Type of format)+(Number of Channels)+(Sample Rate)+(Sample Rate*BitsPerSample*Channels/8)+\
;(BitsPerSample*Channels/8)+(Bits per sample)+(“data” chunk header)+(Size of the data section)=2Ch
add rax,2Ch
mov [rdx].WAVEHDR.lpData,rax ;адрес блока данных
mov eax,FSize
sub eax,2Ch
mov [rdx].WAVEHDR.dwBufferLength,eax ;размер блока данных
invoke waveOutPrepareHeader,hWaveOut,,sizeof WAVEHDR
; Запускаем проигрывание блока
invoke waveOutWrite,hWaveOut,&lpwiocb,sizeof WAVEHDR
@@: cmp lpwiocb.dwFlags,WHDR_DONE or WHDR_PREPARED
jnz @b
invoke waveOutUnprepareHeader,hWaveOut,&lpwiocb,sizeof WAVEHDR
invoke waveOutClose,hWaveOut
@0: invoke UnmapViewOfFile,pMapping
        invoke CloseHandle,hMapping
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
;--------------------------------------------------------
.data
szWin   db "Memory-Mapped File Sender",0
Error1   db "The server is not running.",10,"Run?",0
szAppName db "Memory-Mapped File Reciever",0
szService db "03s",0
align 10h
lpszName db "Song_of_the_South",0
end
03r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Memory-Mapped File Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
}
03s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc
ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_DIALOG equ 200
IDC_ICON1 equ 500
IDC_IMG1 equ 104

.code
WinMain proc dummy:qword

invoke LoadImageA,IMAGE_BASE,IDC_ICON1,IMAGE_ICON,256,256,LR_DEFAULTCOLOR
invoke DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP,qword ptr(offset DialogProc),eax
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
size_of_buffer equ 96
local FSize:dword
local hResource:qword
local pResource:qword
local szReadWrite:qword
local type0:qword
local p:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_INITDIALOG
        jne wmBYE
wmINITDIALOG:invoke GetDlgItem,,IDC_IMG1
invoke SendMessageA,eax,STM_SETIMAGE,IMAGE_ICON,lParam
jmp wmBYE
wmSEND_TXT:invoke GlobalAlloc,GPTR,size_of_buffer
        invoke GlobalLock,eax
mov p,rax
invoke  GetDlgItemTextA,hWnddlg,ID_TXT,eax,size_of_buffer;255
        or      eax,eax
        jz      wmBYE
        inc     eax
mov FSize,eax
;созддание файла
invoke CreateFile,&szMapName0,GENERIC_READ or GENERIC_WRITE,0,0,OPEN_ALWAYS,0,0
mov hFile,rax
invoke WriteFile,eax,p,FSize,&szReadWrite,0
invoke Func,hFile,0
mov edx,CF_TEXT
jmp @0
wmSEND_ICO:mov edx,p1
invoke FindResource,0,,RT_ICON; find the resource
mov hResource,rax
invoke  SizeofResource,0,eax ; get its size
mov     FSize,eax
; shl eax,8
; mov edx,CF_DIB
;        mov type0,rax
invoke LoadResource,0,hResource ; load the resource
invoke LockResource,eax
mov esi,eax
;созддание в памяти объекта "проекция файла" и
;отображение проекции файла на адресное пространство процесса
invoke Func,INVALID_HANDLE_VALUE,FSize
;-----------------------------------------------------------------
mov ecx,FSize
mov edi,eax;rdi,pMapping
rep movsb
;--------------------------------------------------
mov edx,FSize
invoke  CreateIconFromResourceEx,pMapping,,TRUE,30000h,256,256,LR_DEFAULTCOLOR
invoke  SendDlgItemMessageA,hWnddlg,IDC_IMG1,STM_SETIMAGE,IMAGE_ICON,eax
xor p1,11b
mov edx,CF_DIB
jmp @0
;-------------------------------------------------------
wmSEND_WAV:invoke CreateFile,&wav_file,GENERIC_READ or GENERIC_WRITE,FILE_SHARE_READ \
or FILE_SHARE_WRITE,0,OPEN_EXISTING,FILE_ATTRIBUTE_ARCHIVE,0
        mov hFile,rax
        invoke GetFileSize,eax,0
mov FSize,eax
invoke Func,hFile,0
mov edx,CF_WAVE
;-------------------------------------------------------
@0: mov eax,FSize
shl eax,8
or eax,edx
mov type0,rax
; Найти окно получателя
mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jz      wmBYE
; Отправить данные получателю
        invoke  SendMessageTimeoutA,eax,WM_USER+1,hWnddlg,type0,SMTO_ABORTIFHUNG,5000,0
invoke UnmapViewOfFile,pMapping
invoke CloseHandle,hMapping
invoke CloseHandle,hFile
cmp byte ptr type0,CF_TEXT
jnz     wmBYE
mov ecx,offset szMapName0
invoke DeleteFile
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_ICO
        je      wmSEND_ICO
cmp r8d,BN_CLICKED shl 16 + ID_SEND_WAV
        je      wmSEND_WAV
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
;----------------------------------------
Func proc hFile:qword,FSize:qword
mov FSize,rdx
;созддание в памяти объекта "проекция файла"
movr qword ptr[rsp+28h],szMapName
mov [rsp+20h],rdx
        invoke CreateFileMapping,,0,PAGE_READWRITE,0
mov hMapping,rax
;отображение проекции файла на адресное пространство процесса
mov rax,FSize
mov [rsp+20h],rax
invoke MapViewOfFile,hMapping,FILE_MAP_ALL_ACCESS,0,0
mov pMapping,rax
leave
ret
Func endp
;---------------------------------------
szWin      db 'Memory-Mapped File Reciever',0
wav_file   db '..\Images\03.wav',0
szMapName  db "Song_of_the_South",0
szMapName0 db "15.txt",0
p1 dd 1
hMapping dq ?
pMapping dq ?
hFile dq ?
end
03s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Memory-Mapped File Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}
« Last Edit: August 18, 2022, 06:21:16 PM by Mikl__ »

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #3 on: August 18, 2022, 12:09:14 PM »
04. Paging File

Memory Mapped File and Paging File: fast communication mechanisms between processes, provide an efficient way to use the contents of a file in virtual memory or by accessing shared memory. In these IPCs, the file data is treated as part of the process's address space, so that the process can easily access the address of the content. Any other process that has access to shared memory must implement synchronization to reduce the risk of data corruption. File mapping is performed on the same system/machine and is not available to network processes.
04r.asm (Client)
Code: [Select]
; GUI #
include win64a.inc
IDC_DIALOG equ 200
IMAGE_BASE equ 400000h
ID_TXT equ 100
ID_ICON equ 102
IDC_ICON1 equ 500

.code
WinMain proc dummy:qword

invoke  DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP,qword ptr(offset DialogProc),0
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword
local pMapping:qword
local hMapping:qword
local FSize:dword
local lpwiocb:WAVEHDR
local hWaveOut:qword
local type0:byte

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_USER+1
je wmUSER_1
cmp edx,WM_COMMAND
je wmCOMMAND
        cmp edx,WM_INITDIALOG
        jne wmBYE
wmINITDIALOG:; Найти окно отправителя
        invoke  FindWindowA,NULL,&szWin
        or      eax,eax
        jnz wmBYE
invoke MessageBoxA,hWnddlg,&Error1,&szAppName,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      wmBYE     
invoke WinExec,&szService,SW_SHOW
jmp wmBYE
wmUSER_1:mov rcx,lParam
mov type0,cl
shr ecx,8
mov FSize,ecx
@@: mov r8d,offset lpszName
invoke OpenFileMapping,FILE_MAP_ALL_ACCESS,FALSE
mov hMapping,rax
mov ecx,eax
mov eax,FSize;lParam
mov [rsp+20h],rax
invoke MapViewOfFile,,FILE_MAP_ALL_ACCESS,0,0
mov pMapping,rax
cmp type0,CF_TEXT
je TXT
cmp type0,CF_DIB
je DIB
WAVE: mov r8,pMapping
        add r8d,14h
        invoke waveOutOpen,&hWaveOut,WAVE_MAPPER,,0,0,WAVE_ALLOWSYNC
; Подготавливаем заголовок для вывода
lea edx,lpwiocb
mov edi,edx
xor eax,eax
mov ecx,(sizeof WAVEHDR)/8
rep stosq

mov rax,pMapping
add rax,2Ch

mov [rdx].WAVEHDR.lpData,rax ;адрес блока данных
mov eax,FSize;[rcx+4]
sub eax,2Ch
mov [rdx].WAVEHDR.dwBufferLength,eax ;размер блока данных
invoke waveOutPrepareHeader,hWaveOut,,sizeof WAVEHDR
; Запускаем проигрывание блока
invoke waveOutWrite,hWaveOut,&lpwiocb,sizeof WAVEHDR
@@: cmp lpwiocb.dwFlags,WHDR_DONE or WHDR_PREPARED
jnz @b
invoke waveOutUnprepareHeader,hWaveOut,&lpwiocb,sizeof WAVEHDR
invoke waveOutClose,hWaveOut
jmp @f
TXT: invoke  SetDlgItemTextA,hWnddlg,ID_TXT,pMapping
jmp @f
DIB: and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
mov edx,FSize
invoke  CreateIconFromResourceEx,pMapping,,TRUE,30000h
invoke  SendDlgItemMessageA,hWnddlg,ID_ICON,STM_SETIMAGE,IMAGE_ICON,eax
@@: invoke UnmapViewOfFile,pMapping
        invoke CloseHandle,hMapping
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
.data
lpszName  db "Song_of_the_South",0
Error1   db "The server is not running.",10,"Run?",0
szService db "04s",0
szWin   db "Paging File Sender",0
szAppName db "Paging File Reciever",0
end
04r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Paging File Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
}
04s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc
ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_DIALOG equ 200
IDC_ICON1 equ 500
IDC_IMG1 equ 104

.code
WinMain proc dummy:qword

invoke LoadImageA,IMAGE_BASE,IDC_ICON1,IMAGE_ICON,256,256,LR_DEFAULTCOLOR

mov r9d,offset DialogProc
invoke DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP,,eax
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
size_of_buffer equ 96
local buffer[size_of_buffer]:BYTE
local hFile:dword
local FSize:dword
local hMapping:qword
local pMapping:qword
local hResource:qword
local pResource:qword
local szReadWrite:qword
local type0:qword

        mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
        cmp edx,WM_INITDIALOG
        jne wmBYE
wmINITDIALOG:invoke GetDlgItem,,IDC_IMG1
invoke SendMessageA,eax,STM_SETIMAGE,IMAGE_ICON,lParam
jmp wmBYE
wmSEND_TXT:lea r8d,buffer
invoke  GetDlgItemTextA,,ID_TXT,,size_of_buffer;255
        or      eax,eax
        jz      wmBYE
        inc     eax
mov FSize,eax
;созддание в памяти объекта "проекция файла"
; sub esp,30h
movr qword ptr[rsp+28h],szMapName
mov eax,FSize
mov [rsp+20h],rax
or rcx,INVALID_HANDLE_VALUE
        invoke CreateFileMapping,,0,PAGE_READWRITE,0
mov hMapping,rax
;отображение проекции файла на адресное пространство процесса
mov ecx,eax
mov eax,FSize
mov [rsp+20h],rax
invoke MapViewOfFile,,FILE_MAP_ALL_ACCESS,0,0
mov pMapping,rax
mov ecx,FSize
mov edi,eax
lea esi,buffer
rep movsb
mov eax,FSize
shl rax,8
or rax,CF_TEXT
mov type0,rax
;--------------------------------------------------
jmp @f
wmSEND_ICO:;sub esp,30h
mov edx,p1
invoke FindResource,0,,RT_ICON; find the resource
mov hResource,rax
invoke  SizeofResource,0,eax ; get its size
mov     FSize,eax
invoke LoadResource,0,hResource ; load the resource
invoke LockResource,eax
mov esi,eax
;созддание в памяти объекта "проекция файла"
movr qword ptr[rsp+28h],szMapName
mov eax,FSize
mov [rsp+20h],rax
or rcx,INVALID_HANDLE_VALUE
        invoke CreateFileMapping,,0,PAGE_READWRITE,0
mov hMapping,rax
;отображение проекции файла на адресное пространство процесса
mov ecx,eax
mov eax,FSize
mov [rsp+20h],rax
invoke MapViewOfFile,,FILE_MAP_ALL_ACCESS,0,0
mov pMapping,rax
mov ecx,FSize
mov edi,eax;rdi,pMapping
rep movsb
;--------------------------------------------------
        mov ecx,256
and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov [rsp+20h],rcx
mov [rsp+28h],rcx
mov edx,FSize
invoke  CreateIconFromResourceEx,pMapping,,TRUE,30000h;270376,TRUE,30000h
mov [rsp+20h],rax
invoke  SendDlgItemMessageA,hWnddlg,IDC_IMG1,STM_SETIMAGE,IMAGE_ICON
xor p1,11b
        mov eax,FSize
shl rax,8
or rax,CF_DIB
mov type0,rax
;-------------------------------------------------------
jmp @f
wmSEND_WAV:;sub esp,40h
mov ecx,offset wav_file
xor r9d,r9d
mov qword ptr[rsp+30h],r9
mov qword ptr[rsp+28h],FILE_ATTRIBUTE_ARCHIVE
mov qword ptr[rsp+20h],OPEN_EXISTING
invoke CreateFile,,GENERIC_READ or GENERIC_WRITE,\
FILE_SHARE_READ or FILE_SHARE_WRITE
        mov hFile,eax
        invoke GetFileSize,eax,0
mov FSize,eax
;созддание в памяти объекта "проекция файла"
movr qword ptr[rsp+28h],szMapName
mov eax,FSize
mov [rsp+20h],rax
or rcx,INVALID_HANDLE_VALUE
        invoke CreateFileMapping,,0,PAGE_READWRITE,0
mov hMapping,rax
;отображение проекции файла на адресное пространство процесса
invoke MapViewOfFile,eax,FILE_MAP_ALL_ACCESS,0,0,FSize
mov pMapping,rax
;-------------------------------------------------
and qword ptr[rsp+20h],0
lea r9,szReadWrite
invoke ReadFile,hFile,pMapping,FSize
mov eax,FSize
shl rax,8
or rax,CF_WAVE
mov type0,rax
@@:; Найти окно получателя
        invoke  FindWindowA,NULL,&szWin
        or      eax,eax
        jz      wmBYE
; Отправить данные получателю
mov qword ptr[rsp+20h],SMTO_ABORTIFHUNG
mov qword ptr[rsp+28h],5000
and qword ptr[rsp+30h],0
        invoke  SendMessageTimeoutA,eax,WM_USER+1,hWnddlg,type0
invoke UnmapViewOfFile,pMapping
invoke CloseHandle,hMapping
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_ICO
        je      wmSEND_ICO
cmp r8d,BN_CLICKED shl 16 + ID_SEND_WAV
        je      wmSEND_WAV
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
;---------------------------------------
.data
szWin     db 'Paging File Reciever',0
wav_file  db '..\Images\03.wav',0
szMapName db "Song_of_the_South",0
p1   dd 1
end
04s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Paging File Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}
« Last Edit: August 18, 2022, 06:20:45 PM by Mikl__ »

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #4 on: August 18, 2022, 12:16:06 PM »
05. Mail Slots
A mailslot is a mechanism for one-way interprocess communications (IPC). Applications can store messages in a mailslot. The owner of the mailslot can retrieve messages that are stored there. These messages are typically sent over a network to either a specified computer or to all computers in a specified domain.
05r.asm (Client)
Code: [Select]
; GUI #
include win64a.inc
WM_CLIPBOARDUPDATE equ 31Dh
IDC_DIALOG equ 200
ID_TXT equ 100
ID_ICON equ 102
IDC_ICON1 equ 500
TXT equ 10
ICO equ 11
WAV equ 12
.code
WinMain proc dummy:qword

mov r9d,offset DialogProc
        invoke  DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP,,0
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword
local cbRead:DWORD;Количество байт данных, принятых через канал
local cbMessages:DWORD;Размер сообщения в байтах
local cbMsgNumber:DWORD;Количество сообщений в канале Mailslot
local p:QWORD
local lpwiocb:WAVEHDR
local hWaveOut:qword
local FSize:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_USER+1
je wmUSER_1
cmp edx,WM_COMMAND
je wmCOMMAND
        cmp edx,WM_INITDIALOG
jne wmBYE
wmINITDIALOG:; Найти окно отправителя
        invoke  FindWindowA,NULL,&szWin
        or      eax,eax
        jnz @f
invoke MessageBoxA,hWnddlg,&Error1,&szAppName,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      @f     
invoke WinExec,&szService,SW_SHOW
; Создаем канал Mailslot, имеющий имя lpszMailslotName
@@: mov ecx,offset lpszMailslotName
invoke CreateMailslot,,0,MAILSLOT_WAIT_FOREVER, NULL
mov hMailslot,rax
jmp wmBYE
wmUSER_1:mov rax,lParam
mov type0,al
shr rax,8
mov FSize,rax
; Определяем состояние канала Mailslot
lea r8d,cbMessages
lea r9d,cbMsgNumber
xor edx,edx
mov [rsp+20h],rdx
invoke GetMailslotInfo,hMailslot
; Выполняем задержку на  500 миллисекунд
invoke Sleep,500
; Если в канале есть Mailslot сообщения, читаем первое из них и выводим на экран
cmp cbMsgNumber,0
jz wmBYE
invoke GlobalAlloc,GMEM_FIXED,FSize
mov p,rax
invoke ReadFile,hMailslot,p,FSize,&cbRead,0
cmp type0,CF_TEXT
je TEXT
        cmp type0,CF_DIB
je DIB
WAVE: mov r8,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data) = 14h
        add r8d,14h
        invoke waveOutOpen,&hWaveOut,WAVE_MAPPER,,0,0,WAVE_ALLOWSYNC
; Подготавливаем заголовок для вывода
lea edx,lpwiocb
mov edi,edx
xor eax,eax
mov ecx,(sizeof WAVEHDR)/8
rep stosq

mov rax,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data)+\
;(Type of format)+(Number of Channels)+(Sample Rate)+(Sample Rate*BitsPerSample*Channels/8)+\
;(BitsPerSample*Channels/8)+(Bits per sample)+(“data” chunk header)+(Size of the data section)=2Ch
add rax,2Ch
mov [rdx].WAVEHDR.lpData,rax ;адрес блока данных
mov rax,FSize
sub eax,2Ch
mov [rdx].WAVEHDR.dwBufferLength,eax ;размер блока данных

invoke waveOutPrepareHeader,hWaveOut,,sizeof WAVEHDR
; Запускаем проигрывание блока
invoke waveOutWrite,hWaveOut,&lpwiocb,sizeof WAVEHDR
@@: test lpwiocb.dwFlags,WHDR_DONE
jz @b
invoke waveOutUnprepareHeader,hWaveOut,&lpwiocb,sizeof WAVEHDR
invoke waveOutClose,hWaveOut
jmp @0
TEXT: invoke  SetDlgItemTextA,hWnddlg,ID_TXT,p
jmp @0
DIB:    and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
invoke  CreateIconFromResourceEx,p,FSize,TRUE,30000h
invoke  SendDlgItemMessageA,hWnddlg,ID_ICON,STM_SETIMAGE,IMAGE_ICON,eax
@0: invoke GlobalFree,p
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:;Перед завершением приложения закрываем идентификатор канала Mailslot
invoke CloseHandle,hMailslot
invoke EndDialog,hWnddlg,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
.data
lpszMailslotName db "\\.\mailslot\brer_Rabbit",0;Имя создаваемого канала Mailslot
hMailslot dq ?;Идентификатор канала Mailslot
type0 db ?
szWin db "Mailslot Sender",0
Error1 db "The server is not running.",10,"Run?",0
szAppName db "Mailslot Reciever",0
szService db "05s",0
end
05r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Mailslot Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
}
05s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc
WM_CLIPBOARDUPDATE equ 31Dh
ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_DIALOG equ 200
IDC_ICON1 equ 500
IDC_IMG1 equ 104
.code
WinMain proc dummy:qword

mov r9d,256
mov [rsp+20h],r9
mov qword ptr [rsp+28],LR_DEFAULTCOLOR
invoke LoadImageA,IMAGE_BASE,IDC_ICON1,IMAGE_ICON;,256,256,LR_DEFAULTCOLOR

mov r9d,offset DialogProc
mov qword ptr[rsp+20h],rax
invoke DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local cbWritten:dword;Количество байт, переданных через канал
local FSize:dword;
local p:qword
local hMailslot:qword; Идентификатор канала Mailslot
local hResource:qword
local hFile:dword
local szReadWrite:qword ;number of bytes actually read or write
local lpwiocb:WAVEHDR
local hWaveOut:qword
local type0:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_INITDIALOG
        jne wmBYE
wmINITDIALOG:invoke GetDlgItem,,IDC_IMG1
invoke SendMessageA,eax,STM_SETIMAGE,IMAGE_ICON,lParam
jmp wmBYE
wmSEND_TXT:invoke GlobalAlloc,GPTR,256
        mov p,rax;Буфер для передачи данных через канал
invoke  GetDlgItemTextA,hWnddlg,ID_TXT,eax,256
        or      eax,eax
        jz      wmBYE
        inc     eax
mov FSize,eax
shl rax,8
or rax,CF_TEXT
mov type0,rax
jmp @f
wmSEND_ICO:mov edx,p1
invoke FindResource,0,,RT_ICON; find the resource
mov hResource,rax
invoke  SizeofResource,0,eax ; get its size
mov FSize,eax
shl rax,8
or rax,CF_DIB
mov type0,rax
invoke LoadResource,0,hResource ; load the resource
invoke LockResource,eax;pResource
  mov p,rax
;-------------------------------------------------
and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
mov edx,FSize
invoke  CreateIconFromResourceEx,p,,TRUE,30000h;270376,TRUE,30000h
invoke  SendDlgItemMessageA,hWnddlg,IDC_IMG1,STM_SETIMAGE,IMAGE_ICON,eax
xor p1,11b
jmp @f
wmSEND_WAV:;sub esp,40h
mov ecx,offset wav_file
xor r9d,r9d
mov qword ptr[rsp+30h],r9
mov qword ptr[rsp+28h],FILE_ATTRIBUTE_ARCHIVE
mov qword ptr[rsp+20h],OPEN_EXISTING
invoke CreateFile,,GENERIC_READ or GENERIC_WRITE,\
FILE_SHARE_READ or FILE_SHARE_WRITE
        mov hFile,eax
        invoke GetFileSize,eax,0
mov FSize,eax
invoke GlobalAlloc,GPTR,eax
        mov p,rax
mov eax,FSize
shl rax,8
or rax,CF_WAVE
mov type0,rax
lea r9d,cbWritten
and qword ptr[rsp+20h],0
        invoke ReadFile,hFile,p,FSize
        invoke CloseHandle,hFile
@@:; Создаем канал с процессом MSLOTS
mov ecx,offset szMailslotName
xor r9d,r9d
mov qword ptr[rsp+20h],OPEN_EXISTING
mov [rsp+28h],r9
mov [rsp+30h],r9
invoke CreateFile,,GENERIC_WRITE,FILE_SHARE_READ
mov hMailslot,rax

lea r9d,cbWritten
and qword ptr[rsp+20h],0
        invoke WriteFile,hMailslot,p,FSize
; Найти окно получателя
mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jz      wmBYE
; Отправить данные получателю
invoke PostMessageA,eax,WM_USER+1,hWnddlg,type0
;Закрываем идентификатор канала
invoke CloseHandle,hMailslot
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_ICO
        je      wmSEND_ICO
cmp r8d,BN_CLICKED shl 16 + ID_SEND_WAV
        je      wmSEND_WAV
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
;---------------------------------------
szWin db 'Mailslot Reciever',0
szMailslotName db "\\.\mailslot\brer_Rabbit",0; Имя создаваемого канала
wav_file db '..\Images\03.wav',0
p1 dd 1
end
05s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Mailslot Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}
« Last Edit: August 20, 2022, 02:12:13 PM by Mikl__ »

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #5 on: August 18, 2022, 12:24:05 PM »
06. Named Pipes
A pipe is a section of shared memory that processes use for communication. The process that creates a pipe is the pipe server. A process that connects to a pipe is a pipe client. One process writes information to the pipe, then the other process reads the information from the pipe.
06r.asm (Client)
Code: [Select]
; GUI #
include win64a.inc
WM_CLIPBOARDUPDATE equ 31Dh
IDC_DIALOG equ 200
ID_TXT equ 100
ID_ICON equ 102
IDC_ICON1 equ 500
.code
WinMain proc dummy:qword

mov r9d,offset DialogProc
and qword ptr[rsp+20h],0
        invoke  DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword
local cbRead:DWORD;Количество байт данных, принятых через канал
local p:qword;Буфер для передачи данных через канал
local lpwiocb:WAVEHDR
local hWaveOut:qword
local FSize:qword
local type0:byte

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_USER+1
je wmUSER_1
cmp edx,WM_COMMAND
je wmCOMMAND
        cmp edx,WM_INITDIALOG
jne wmBYE
wmINITDIALOG:; Найти окно получателя
        invoke  FindWindowA,NULL,&szWin
        or      eax,eax
        jnz wmBYE
invoke MessageBoxA,hWnddlg,&Error1,&szAppName,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      wmBYE     
invoke WinExec,&szService,SW_SHOW
        jmp wmBYE
wmUSER_1:; Получить строку от первого приложения
mov rax,lParam
mov type0,al
shr rax,8
mov FSize,rax
invoke GlobalAlloc,GMEM_FIXED,eax
mov p,rax
mov ecx,offset lpszPipeName
invoke CreateNamedPipe,,PIPE_ACCESS_INBOUND,PIPE_TYPE_BYTE,1,0,FSize,0,0
mov hNamedPipe,rax
invoke ConnectNamedPipe,eax,NULL
lea r9d,cbRead
and qword ptr[rsp+20h],0
invoke ReadFile,hNamedPipe,p,FSize
;----------------------------------------------------
cmp type0,CF_TEXT
je TEXT
cmp type0,CF_DIB
je DIB
WAVE: mov r8,p

        add r8d,14h
        lea ecx,hWaveOut
        xor r9,r9
mov [rsp+20h],r9
mov qword ptr[rsp+28h],WAVE_ALLOWSYNC
        or edx,WAVE_MAPPER
        invoke waveOutOpen
; Подготавливаем заголовок для вывода
lea edx,lpwiocb
mov edi,edx
xor eax,eax
mov ecx,(sizeof WAVEHDR)/8
rep stosq

mov rax,p
add rax,2Ch

mov [rdx].WAVEHDR.lpData,rax ;адрес блока данных
mov rax,FSize
sub eax,2Ch
mov [rdx].WAVEHDR.dwBufferLength,eax ;размер блока данных

invoke waveOutPrepareHeader,hWaveOut,,sizeof WAVEHDR
; Запускаем проигрывание блока
lea edx,lpwiocb
mov rcx,hWaveOut
mov r8d,sizeof WAVEHDR
invoke waveOutWrite
@@: test lpwiocb.dwFlags,WHDR_DONE
jz @b
lea edx,lpwiocb
invoke waveOutUnprepareHeader,hWaveOut,,sizeof WAVEHDR
invoke waveOutClose,hWaveOut
jmp @0
;------------------------------------------------------------
TEXT: invoke  SetDlgItemTextA,hWnddlg,ID_TXT,p
jmp @0
;----------------------------------------------------
DIB: and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
invoke  CreateIconFromResourceEx,p,FSize,TRUE,30000h
invoke  SendDlgItemMessageA,hWnddlg,ID_ICON,STM_SETIMAGE,IMAGE_ICON,eax
;-----------------------------------------------------------
@0:     invoke GlobalFree,p
invoke DisconnectNamedPipe,hNamedPipe
invoke CloseHandle,hNamedPipe
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
;--------------------------------------------------
.data
lpszPipeName db "\\.\pipe\Song_of_the_South",0;Имя создаваемого пайпа
hNamedPipe dq ?;Идентификатор пайпа
szWin db "Pipe Sender",0
Error1 db "The server is not running.",10,"Run?",0
szAppName db "Pipe Reciever",0
szService db "06s",0
end
06r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Pipe Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
}
06s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc
WM_CLIPBOARDUPDATE equ 31Dh
ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_DIALOG equ 200
IDC_ICON1 equ 500
IDC_IMG1 equ 104
.code
WinMain proc dummy:qword

mov r9d,256
mov [rsp+20h],r9
mov qword ptr [rsp+28],LR_DEFAULTCOLOR
invoke LoadImageA,IMAGE_BASE,IDC_ICON1,IMAGE_ICON
mov r9d,offset DialogProc
mov qword ptr[rsp+20h],rax
invoke DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
size_of_buffer equ 256
local cbWritten:dword;Количество байт, переданных через канал
local FSize:dword;
local hNamePipe:qword; Идентификатор канала Mailslot
local hFile:dword
local p:qword
local hResource:qword
local type0:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_INITDIALOG
        jne wmBYE
wmINITDIALOG:invoke GetDlgItem,,IDC_IMG1
invoke SendMessageA,eax,STM_SETIMAGE,IMAGE_ICON,lParam
jmp wmBYE
wmSEND_TXT:invoke GlobalAlloc,GPTR,size_of_buffer
        mov p,rax;Буфер для передачи данных через канал
invoke  GetDlgItemTextA,hWnddlg,ID_TXT,eax,size_of_buffer;255
        or      eax,eax
        jz      wmBYE
        inc     eax
mov FSize,eax
shl rax,8
or rax,CF_TEXT
mov type0,rax
jmp @f
wmSEND_ICO:mov edx,p1
invoke FindResource,0,,RT_ICON; find the resource
mov hResource,rax
invoke  SizeofResource,0,eax ; get its size
mov FSize,eax
shl rax,8
or rax,CF_DIB
mov type0,rax
invoke LoadResource,0,hResource ; load the resource
invoke LockResource,eax;pResource
  mov p,rax
;-------------------------------------------------
and qword ptr[rsp+30h],LR_DEFAULTCOLOR
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
mov edx,FSize
invoke  CreateIconFromResourceEx,p,,TRUE,30000h
invoke  SendDlgItemMessageA,hWnddlg,IDC_IMG1,STM_SETIMAGE,IMAGE_ICON,eax
xor p1,11b
jmp @f
wmSEND_WAV:mov ecx,offset wav_file
xor r9d,r9d
mov qword ptr[rsp+30h],r9
mov qword ptr[rsp+28h],FILE_ATTRIBUTE_ARCHIVE
mov qword ptr[rsp+20h],OPEN_EXISTING
invoke CreateFile,,GENERIC_READ or GENERIC_WRITE,\
FILE_SHARE_READ or FILE_SHARE_WRITE
        mov hFile,eax
        invoke GetFileSize,eax,0
mov FSize,eax
invoke GlobalAlloc,GPTR,eax
        mov p,rax
lea r9d,cbWritten
and qword ptr[rsp+20h],0
        invoke ReadFile,hFile,eax,FSize
        invoke CloseHandle,hFile
mov eax,FSize
shl rax,8
or rax,CF_WAVE
mov type0,rax
@@:; Найти окно получателя
mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jz      wmBYE
        ; Отправить данные получателю
mov qword ptr[rsp+20h],SMTO_ABORTIFHUNG
mov qword ptr[rsp+28h],250
and qword ptr[rsp+30h],0
        invoke  SendMessageTimeoutA,eax,WM_USER+1,hWnddlg,type0
; Создаем пайп
mov ecx,offset szPipeName
xor r9d,r9d
mov qword ptr[rsp+20h],OPEN_EXISTING
mov [rsp+28h],r9
mov [rsp+30h],r9
invoke CreateFile,,GENERIC_WRITE,FILE_SHARE_READ
mov hNamePipe,rax
mov rdx,p
lea r9d,cbWritten
and qword ptr[rsp+20h],0
        invoke WriteFile,eax,,FSize
;Закрываем идентификатор канала
invoke CloseHandle,hNamePipe
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_ICO
        je      wmSEND_ICO
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_WAV
        je      wmSEND_WAV
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: xor eax,eax
leave
retn
DialogProc endp
;---------------------------------------
.data
szWin db 'Pipe Reciever',0
szPipeName db "\\.\pipe\Song_of_the_South",0; Имя создаваемого пайпа
p1 dd 1
wav_file db '..\Images\03.wav',0
end
06s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Pipe Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}
« Last Edit: August 20, 2022, 02:13:28 PM by Mikl__ »

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #6 on: August 18, 2022, 12:31:04 PM »
07. Dynamic Data Exchange
The dynamic data exchange for applications used the Dynamic Data Exchange Management Library (DDEML)
Dynamic Data Exchange is a protocol that contains a set of guidelines and rules for sending data between processes. A process uses the SendMessage function with a WM_DDE_INITIATE or WM_DDE_ACK message sent in response to a WM_DDE_INITIATE message. Shared memory is used for data exchange.
07r.asm
Code: [Select]
; GUI #
include win64a.inc
IDC_DIALOG equ 200
ID_TXT equ 100
ID_ICON equ 102
IDC_ICON1 equ 500
WM_USER_INITIATE equ WM_USER + 1
.code
WinMain proc dummy:qword

mov r9d,offset DialogProc
and qword ptr[rsp+20h],0
        invoke  DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword
local p:qword
local lpwiocb:WAVEHDR
local hWaveOut:qword
local dwResult:dword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
        cmp edx,WM_USER+2
je wmUSER_2
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_USER_INITIATE
je wmUSER_INITIATE
        cmp edx,WM_INITDIALOG
jne wmBYE
wmINITDIALOG:; Выполняем инициализацию
xor esi,esi
mov ecx,offset idInst
mov edx,offset DDEServerCallback
invoke DdeInitializeA,,,APPCMD_CLIENTONLY or APPCLASS_STANDARD,0
or eax,eax
jnz Error
; После успешной инициализации получаем идентификаторы строк для сервиса, раздела и элемента данных
invoke SendMessageA,hWnddlg,WM_USER_INITIATE,0,0
mov eax,TRUE
jmp exit0
wmUSER_2:mov rdx,lParam
mov bFmt,dl;CF_BITMAP
shr edx,8
mov FSize,edx
invoke GlobalAlloc,GMEM_FIXED;,FSize;lParam
mov p,rax
; Запускаем транзакцию чтения данных
mov rax,hConv
mov esi,4
or eax,eax
jz Error
mov r8,rax
movzx eax,bFmt
mov [rsp+20h],rax
mov qword ptr[rsp+28h],XTYP_REQUEST
mov qword ptr[rsp+30h],TIMEOUT_ASYNC;5000
lea eax,dwResult
mov [rsp+38h],rax
invoke DdeClientTransaction,0,0,,hszItem
; Получаем строку от сервера
mov esi,5
or eax,eax;if(hData != NULL)
jz Error
mov r8d,FSize
invoke DdeGetData,eax,p,,0
mov esi,6
or eax,eax
jz Error
cmp bFmt,CF_BITMAP
jnz @f
mov edx,FSize
invoke  CreateIconFromResourceEx,p,,TRUE,30000h,256,256,LR_DEFAULTCOLOR
invoke  SendDlgItemMessageA,hWnddlg,ID_ICON,STM_SETIMAGE,IMAGE_ICON,eax
jmp @0
@@:     cmp bFmt,CF_TEXT
jnz @f
invoke  SetDlgItemTextA,hWnddlg,ID_TXT,p
jmp @0
;-----------------------------------------------------------
@@: mov r8,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data) = 14h
        add r8d,14h
        invoke waveOutOpen,&hWaveOut,WAVE_MAPPER,,0,0,WAVE_ALLOWSYNC
; Подготавливаем заголовок для вывода
lea edx,lpwiocb
mov edi,edx
xor eax,eax
mov ecx,(sizeof WAVEHDR)/8
rep stosq

mov rax,p
add rax,2Ch
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data)+\
;(Type of format)+(Number of Channels)+(Sample Rate)+(Sample Rate*BitsPerSample*Channels/8)+\
;(BitsPerSample*Channels/8)+(Bits per sample)+(“data” chunk header)+(Size of the data section)=2Ch
mov [rdx].WAVEHDR.lpData,rax ;адрес блока данных
mov eax,FSize
sub eax,2Ch
mov [rdx].WAVEHDR.dwBufferLength,eax ;размер блока данных
invoke waveOutPrepareHeader,hWaveOut,,sizeof WAVEHDR
; Запускаем проигрывание блока
invoke waveOutWrite,hWaveOut,&lpwiocb,sizeof WAVEHDR
@@: test lpwiocb.dwFlags,WHDR_DONE
jz @b
invoke waveOutUnprepareHeader,hWaveOut,&lpwiocb,sizeof WAVEHDR
invoke waveOutClose,hWaveOut
;------------------------------------------------------------
@0: invoke GlobalFree,p
jmp wmBYE
wmUSER_INITIATE:; Инициализация DDEML и создание канала связи
invoke DDEClientOpen
or eax,eax
jnz wmBYE
mov edx,offset Error1
mov r8d,offset szAppName
invoke MessageBoxA,hWnddlg,,,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      wmBYE     
mov ecx,offset szService
invoke WinExec,,SW_SHOW
cmp eax,32
mov esi,2
jb Error
; После удачного запуска повторяем попытку инициализации DDEML и создания канала связи
invoke DDEClientOpen
jmp wmBYE
Error:: mov r8d,offset szAppName
invoke MessageBoxA,hWnddlg,ErrorMsg[rsi*8],,MB_ICONEXCLAMATION
jmp aExit
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:; Завершаем работу с DDEML. Закрываем канал связи
cmp hConv,0
jz @f
invoke DdeDisconnect,hConv
@@:; Освобождаем идентификаторы строк
invoke DdeFreeStringHandle,idInst,hszService
invoke DdeFreeStringHandle,idInst,hszTopic
invoke DdeFreeStringHandle,idInst,hszItem
aExit: invoke EndDialog,hWnddlg,0
wmBYE: xor eax,eax
exit0: leave
retn
DialogProc endp

DDEServerCallback proc wType:qword,wFmt:qword,hConv:qword,hsz1:qword,hsz2:qword,hData:qword,dwData1:qword,dwData2:qword
xor eax,eax
wmBYE: leave
retn
DDEServerCallback endp
DDEClientOpen proc
local dummy:qword
; При успешной инициализации создаем идентификаторы строк для сервиса,
; раздела и элемента данных
mov edx,offset szService
invoke DdeCreateStringHandleA,idInst,,CP_WINANSI
mov hszService,rax
mov edx,offset szTopic
invoke DdeCreateStringHandleA,idInst,,CP_WINANSI
mov hszTopic,rax
mov edx,offset szItem
invoke DdeCreateStringHandleA,idInst,,CP_WINANSI
mov hszItem,rax
; Устанавливаем канал связи
invoke DdeConnect,idInst, hszService, hszTopic,0
mov hConv,rax
; Возвращаем идентификатор созданного канала связи
leave
ret
DDEClientOpen endp
;-----------------------------------
.data
szAppName db "DDEML Client",0
szService db "07s",0
szTopic db "Brer Rabbit",0
szItem db "DDEData",0
ErrorMsg dq Error0,Error1,Error2,Error3,Error4,Error5,Error6
Error0 db "Could not initialize client!",0
Error1 db "The server is not running.",10,"Run?",0
Error2 db "Unable to start the server",0
Error3 db "The server isn't responding",0
Error4 db "hConv = 0",0
Error5 db "hData = 0",0
Error6 db "lParam = 0",0
; Идентификатор приложения для DDEML
hConv dq 0
idInst dq 0
hszService dq ?
hszTopic dq ?
hszItem dq ?
bFmt db ?
FSize dd ?
end
07r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "DDE Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
}
07s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc
ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_DIALOG equ 200
IDC_ICON1 equ 500
IDC_IMG1 equ 104
WM_USER_INITIATE equ WM_USER + 1
.code
WinMain proc dummy:qword

invoke LoadImageA,IMAGE_BASE,IDC_ICON1,IMAGE_ICON,256,256,LR_DEFAULTCOLOR
mov r9d,offset DialogProc
invoke DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP,,eax
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local hFile:dword
local cbWritten:dword
local hResource:qword
local pResource:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_USER_INITIATE
je wmUSER_INITIATE
cmp edx,WM_INITDIALOG
        jne wmBYE
wmINITDIALOG:invoke GetDlgItem,,IDC_IMG1
invoke SendMessageA,eax,STM_SETIMAGE,IMAGE_ICON,lParam
; Выполняем инициализацию
mov ecx,offset idInst
mov edx,offset DDEServerCallback
invoke DdeInitializeA,,,APPCLASS_STANDARD,0
or eax,eax
jz @f
mov edx,offset Error0
mov edx,offset szAppName
invoke MessageBoxA,hWnddlg,,,MB_ICONEXCLAMATION or MB_OK
jmp wmCLOSE
; После успешной инициализации получаем идентификаторы строк для сервиса, раздела и элемента данных
@@:     invoke SendMessageA,hWnddlg,WM_USER_INITIATE,0,0
mov eax,TRUE
jmp exit0
wmUSER_INITIATE:
mov edx,offset szService
invoke DdeCreateStringHandleA,idInst,,CP_WINANSI
mov hszService,rax
mov edx,offset szTopic
invoke DdeCreateStringHandleA,idInst,,CP_WINANSI
mov hszTopic,rax
mov edx,offset szItem
invoke DdeCreateStringHandleA,idInst,,CP_WINANSI
mov hszItem,rax
; Регистрируем сервис
invoke DdeNameService,idInst,hszService,NULL,DNS_REGISTER
jmp wmBYE
wmSEND_ICO:mov edx,p1
invoke FindResource,0,,RT_ICON; find the resource
mov hResource,rax
invoke  SizeofResource,0,eax ; get its size
mov FSize,rax
shl rax,8
or rax,CF_BITMAP
mov type0,rax
invoke LoadResource,0,hResource ; load the resource
invoke LockResource,eax;pResource
mov p,rax
        mov ecx,eax
and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
invoke  CreateIconFromResourceEx,,FSize,TRUE,30000h;270376,TRUE,30000h
mov [rsp+20h],rax
invoke  SendDlgItemMessageA,hWnddlg,IDC_IMG1,STM_SETIMAGE,IMAGE_ICON
xor p1,11b
jmp @f
wmSEND_WAV:mov ecx,offset wav_file
xor r9d,r9d
mov qword ptr[rsp+30h],r9
mov qword ptr[rsp+28h],FILE_ATTRIBUTE_ARCHIVE
mov qword ptr[rsp+20h],OPEN_EXISTING
invoke CreateFile,,GENERIC_READ or GENERIC_WRITE,\
FILE_SHARE_READ or FILE_SHARE_WRITE
        mov hFile,eax
        invoke GetFileSize,eax,0
mov FSize,rax
invoke GlobalAlloc,GPTR,eax
        mov p,rax
lea r9d,cbWritten
and qword ptr[rsp+20h],0
        invoke ReadFile,hFile,eax,FSize
        invoke CloseHandle,hFile
mov rax,FSize
shl rax,8
or rax,CF_WAVE
mov type0,rax
jmp @f
wmSEND_TXT:invoke GlobalAlloc,GPTR,256
        mov p,rax
invoke GetDlgItemTextA,hWnddlg,ID_TXT,eax,256
inc eax
mov FSize,rax
shl rax,8
or rax,CF_TEXT
mov type0,rax
; Найти окно получателя
@@: mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jz      wmBYE
        ; Отправить данные получателю
        invoke  PostMessageA,eax,WM_USER+2,hWnddlg,type0
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_WAV
        je      wmSEND_WAV
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_ICO
        je      wmSEND_ICO
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE::;Завершение работы канала связи
cmp hConvApp,NULL
jnz @f
invoke DdeDisconnect,hConvApp
@@:; Сервис больше не доступен
invoke DdeNameService,idInst,hszService,NULL,DNS_UNREGISTER
; Освобождение идентификаторов строк
invoke DdeFreeStringHandle,idInst, hszService
invoke DdeFreeStringHandle,idInst, hszTopic
invoke DdeFreeStringHandle,idInst, hszItem
invoke EndDialog,hWnddlg,0
wmBYE: xor eax,eax
exit0: leave
retn
DialogProc endp

DDEServerCallback proc wType:qword,wFmt:qword,hConv:qword,hsz1:qword,hsz2:qword,hData:qword,dwData1:qword,dwData2:qword

mov hConv,r8
mov hsz1,r9

cmp ecx,XTYP_CONNECT
je      xtypCONNECT
cmp ecx,XTYP_REQUEST
je xtypREQUEST
cmp ecx,XTYP_EXECUTE
je xtypEXECUTE
cmp ecx,XTYP_ERROR
je xtypERROR
cmp ecx,XTYP_DISCONNECT
je xtypDISCONNECT
cmp ecx,XTYP_CONNECT_CONFIRM
je xtypCONNECT_CONFIRM
xor eax,eax
jmp wmBYE
xtypCONNECT:;Создание канала передачи данных
; Если сервис поддерживается, возвращаем признак успешного создания канала
mov rax,hsz2
cmp rax,hszService
jne xtypEXECUTE
mov eax,TRUE
jmp wmBYE
xtypDISCONNECT:; Завершение работы канала
and hConvApp,NULL
xtypERROR:; Ошибка
; Запрос на выполнение команды, отрабатывается вхолостую
xtypEXECUTE: xor eax,eax
jmp wmBYE
xtypREQUEST:; Создаем идентификатор данных
        cmp edx,CF_TEXT
jz @f
cmp edx,CF_BITMAP
jz @f
cmp edx,CF_WAVE
jnz wmBYE
@@: xor r9d,r9d
mov rax,hszItem
mov [rsp+20h],rax
mov [rsp+28h],rdx
mov [rsp+30h],r9
invoke DdeCreateDataHandle,idInst,p,FSize
; В случае успеха возвращаем созданный идентификатор или ноль
mov hData,rax
jmp wmBYE
;  Подтверждение создания канала
xtypCONNECT_CONFIRM:
mov hConvApp,r8
@@: xor eax,eax
wmBYE: leave
retn
DDEServerCallback endp
;---------------------------------------
szWin db 'DDE Reciever',0
wav_file db '..\Images\03.wav',0
Error0 db "Could not initialize server!",0
; Идентификатор приложения, полученный после регистрации в библиотеке DDEML
idInst dq 0
hszService dq 0
hszTopic dq 0
hszItem dq 0
; Идентификатор канала
hConvApp dq 0
; Буфер для приема данных
p dq ?
szService db "07s",0
szTopic db "Brer Rabbit",0
szItem db "DDEData",0
szAppName db "DDEML Server",0
FSize dq ?
type0 dq ?
p1 dd 1
end
07s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "DDE Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}
« Last Edit: August 18, 2022, 06:19:12 PM by Mikl__ »

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #7 on: August 18, 2022, 12:40:09 PM »
Interprocess Synchronization

Multiple processes can have handles to the same event, mutex, semaphore, or timer object, so these objects can be used to accomplish interprocess synchronization. The process that creates an object can use the handle returned by the creation function (CreateEvent, CreateMutex, CreateSemaphore, or CreateWaitableTimer). Other processes can open a handle to the object by using its name, or through inheritance or duplication.
08. Event Pipes

One of the tasks creates an event object by calling the CreateEvent function to do so. The event has a name that is available to all tasks in active processes. During creation or later, this task sets the event to its initial state (signaled or nonsignaled).
By calling the WaitForSingleObject or WaitForMultipleObjects functions, the task waits for the moment when the event goes into the signaled state.
Another task, owned by the same or a different process, obtains an event handle by its name using the OpenEvent function. Next, using the SetEvent, ResetEvent, or PulseEvent functions, the application changes the state of the event.
After a nonsignaled/unchecked event is raised, the first task goes into a waiting state until the second task prepares data for it. Once this happens, the second task flags and then resets the event, which causes the first task to complete its wait.
After displaying the prepared data, the first task again enters the waiting state until the second task prepares the data and flags the event. With the help of an event object, two tasks synchronize their work.
08r.asm (Client)
Code: [Select]
; GUI #
include win64a.inc
EVENT_DATA_COUNT = 16
EventPipeObjectStruct struct
hEventDataHigh1 dq EVENT_DATA_COUNT dup(?)
hEventDataLow1 dq EVENT_DATA_COUNT dup(?)
hEventDataHigh2 dq EVENT_DATA_COUNT dup(?)
hEventDataLow2 dq EVENT_DATA_COUNT dup(?)
hEventAck dq ?
EventPipeObjectStruct ends

IDC_DIALOG equ 200
ID_TXT equ 100
ID_ICON equ 102
ID_PROGRESS equ 106
ID_TXT1 equ 107
IDC_ICON1 equ 500
.code
WinMain proc
enter 30h,0
mov r9d,offset DialogProc
and qword ptr[rbp-10h],0
        invoke  DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword

mov hWnddlg,rcx
mov lParam,r9

        cmp edx,WM_INITDIALOG
jne wmBYE
wmINITDIALOG:mov hWnd,rcx
        mov edx,GWL_STYLE
invoke GetWindowLongPtrA
    or eax,WS_THICKFRAME OR WS_MINIMIZEBOX OR WS_MAXIMIZEBOX
mov edx,GWL_STYLE
invoke SetWindowLongPtrA,hWnddlg,,rax
mov r8d,offset WndProc
mov edx,GWL_WNDPROC
invoke SetWindowLongPtrA,hWnddlg
; Найти окно получателя
mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jnz @f;wmBYE
mov edx,offset Error1
mov r8d,offset szAppName
invoke MessageBoxA,hWnddlg,,,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      @f;wmBYE     
mov ecx,offset szService
invoke WinExec,,SW_SHOW
; create "high" data event handles
xor edi,edi;for(DWORD i = 0; i < ; i++)
; set current event name
@@: invoke sprintf,&szEventName,&Format1,edi
; open existing object
invoke OpenEvent,EVENT_ALL_ACCESS,0,&szEventName
mov EventPipeObject.hEventDataHigh1[rdi*8],rax
or eax,eax
jz wmBYE
invoke sprintf,&szEventName,&Format2,edi
; open existing object
invoke OpenEvent,EVENT_ALL_ACCESS,0,&szEventName
mov EventPipeObject.hEventDataLow1[rdi*8],rax
; check for errors
or eax,eax;if(EventPipeObject.hEventDataLow[i] == NULL)
jz wmBYE
invoke sprintf,&szEventName,&Format3,edi
; open existing object
invoke OpenEvent,EVENT_ALL_ACCESS,0,&szEventName
mov EventPipeObject.hEventDataHigh2[rdi*8],rax
or eax,eax
jz wmBYE
invoke sprintf,&szEventName,&Format4,edi
; open existing object
invoke OpenEvent,EVENT_ALL_ACCESS,0,&szEventName
mov EventPipeObject.hEventDataLow2[rdi*8],rax
; check for errors
or eax,eax;if(EventPipeObject.hEventDataLow[i] == NULL)
jz wmBYE
inc edi
cmp edi,EVENT_DATA_COUNT
jb @b
; create acknowledgement event
invoke OpenEvent,EVENT_ALL_ACCESS,0,&Format5
mov EventPipeObject.hEventAck,rax
;--------------------------------------------------
; Шрифт текста
pushaddr szFont
push FIXED_PITCH+FF_DONTCARE
push PROOF_QUALITY
push CLIP_DEFAULT_PRECIS
push OUT_RASTER_PRECIS
push ANSI_CHARSET
push FALSE
push FALSE
push FALSE
push FW_BOLD
sub esp,20h
        invoke  CreateFont,32,12,0,0               
        mov     hFont,rax

        invoke  GetDlgItem,hWnddlg,ID_PROGRESS
        mov     hProgress,rax
; Установить наш собственный обработчик
mov r8d,offset ProgressWindowProc
        invoke  SetWindowLongPtrA,hProgress,GWL_WNDPROC
        ; Сохранить хэндл предыдущего обработчика
        mov     OldProc,rax
wmBYE: xor eax,eax
leave
retn
DialogProc endp
WndProc proc hWnd:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local text:dword
local ps:PAINTSTRUCT               
local hDC:dword
local rcClient:RECT

mov hWnd,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_USER+1
je wmUSER_1
cmp edx,WM_USER+2
je wmUSER_2
cmp edx,WM_USER+3
je wmUSER_3
leave
jmp NtdllDialogWndProc_
;-----------------------------------------------------
wmUSER_1:mov rax,lParam
mov DataLength,rax
inc eax
invoke GlobalAlloc,GPTR,eax
mov p_Text,rax
invoke EventPipeRecieve,eax
and byte ptr[rdi],0
        invoke  SetDlgItemTextA,hWnd,ID_TXT,p_Text
invoke GlobalFree,p_Text
jmp wmBYE
wmUSER_2:and percent,0
        xor ecx,ecx   ;<-- lpThreadAttributes
mov [rsp+20h],rcx  ;<-- dwCreationFlags
movr qword ptr[rsp+28h],hThread2 ;<-- lpThreadId
mov r8d,offset TimerFuncProgress;<-- lpStartAddress
invoke CreateThread,,0,,16; <-- lpParameter
invoke CloseHandle,eax;hThread2
;------------------------------------------------------
mov rax,lParam
mov DataLength,rax
invoke GlobalAlloc,GPTR,eax
mov r8d,offset TimerFuncICO
jmp @f
wmUSER_3:and percent,0
        xor ecx,ecx
mov [rsp+20h],rcx
movr qword ptr[rsp+28h],hThread2;4
mov r8d,offset TimerFuncProgress
invoke CreateThread,,0,,101
invoke CloseHandle,eax;hThread4
;-----------------------------------------------
mov rax,lParam
mov DataLength,rax
invoke GlobalAlloc,GPTR,eax
mov r8d,offset TimerFuncWAV
@@: xor ecx,ecx
mov [rsp+20h],rcx
movr qword ptr[rsp+28h],hThread2;5
invoke CreateThread,,0,,eax
invoke CloseHandle,eax;hThread5
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:invoke EndDialog,,0
; Закрываем идентификаторы объектов-событий 
xor edi,edi
@@: invoke CloseHandle,EventPipeObject.hEventDataHigh1[rdi*8]
inc edi
cmp edi,4*EVENT_DATA_COUNT+1
jb @b
wmBYE:  mov eax,TRUE
exit0: leave
ret
WndProc endp

TimerFuncICO proc p:qword
mov p,rcx

invoke EventPipeRecieve
; Создать HICON напрямую из памяти
and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
invoke  CreateIconFromResourceEx,p,DataLength,TRUE,30000h
mov [rsp+20h],rax
invoke  SendDlgItemMessageA,hWnd,ID_ICON,STM_SETIMAGE,IMAGE_ICON
invoke GlobalFree,p
exit2: leave
ret
TimerFuncICO endp

TimerFuncWAV proc p:qword
local lpwiocb:WAVEHDR
local hWaveOut:qword
mov p,rcx

invoke EventPipeRecieve
WAVE: mov r8,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data) = 14h
        add r8d,14h
        lea ecx,hWaveOut
        xor r9,r9
mov [rsp+20h],r9
mov qword ptr[rsp+28h],WAVE_ALLOWSYNC
        or edx,WAVE_MAPPER
        invoke waveOutOpen
; Подготавливаем заголовок для вывода
lea edx,lpwiocb
mov edi,edx
xor eax,eax
mov ecx,(sizeof WAVEHDR)/8
rep stosq

mov rax,p
mov ecx,eax
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data)+\
;(Type of format)+(Number of Channels)+(Sample Rate)+(Sample Rate*BitsPerSample*Channels/8)+\
;(BitsPerSample*Channels/8)+(Bits per sample)+(“data” chunk header)+(Size of the data section)=2Ch
add eax,2Ch

mov [rdx].WAVEHDR.lpData,rax ;адрес блока данных
mov eax,[rcx+4];размер блока данных
sub eax,2Ch
mov [rdx].WAVEHDR.dwBufferLength,eax ;размер блока данных

invoke waveOutPrepareHeader,hWaveOut,,sizeof WAVEHDR
; Запускаем проигрывание блока
lea edx,lpwiocb
mov rcx,hWaveOut
mov r8d,sizeof WAVEHDR
invoke waveOutWrite
@@: test lpwiocb.dwFlags,WHDR_DONE
jz @b
lea edx,lpwiocb
invoke waveOutUnprepareHeader,hWaveOut,,sizeof WAVEHDR
invoke waveOutClose,hWaveOut
@1: invoke GlobalFree,p
exit2: leave
ret
TimerFuncWAV endp
TimerFuncProgress proc lParam:qword
mov lParam,rcx
; Сформировать строку для отрисовки
@@: mov r8d,percent
mov edx,offset szText
mov ecx,offset buff
        invoke  wsprintfA
; Назначить строку свойством ProgressBar
mov r8d,offset buff
mov edx,offset szProp
        invoke  SetPropA,hProgress
; Назначить значение процента свойством ProgressBar
mov r8d,percent
mov edx,offset szPerc
        invoke  SetPropA,hProgress
; Перерисовать содержимое окна
        invoke  InvalidateRect,hProgress,0,FALSE
        inc     percent
        cmp     percent,101
        je exit0
invoke Sleep,lParam
jmp @b
exit0: leave
ret
TimerFuncProgress endp
EventPipeRecieve proc p:qword
local dwEventDataLowValue:byte
local begin:dword
local buffer[20]:byte

mov edi,ecx
add rcx,DataLength
mov EndDataLength,ecx
invoke GetTickCount
mov begin,eax
lea r8d,buffer
and byte ptr[r8],0
invoke  SetDlgItemTextA,hWnd,ID_TXT1
@@: lea edx,EventPipeObject.hEventDataLow1
invoke WaitForMultipleObjects,EVENT_DATA_COUNT,,0,2
mov dwEventDataLowValue,al;eax
cmp eax,EVENT_DATA_COUNT;if(dwEventDataLowValue >= EVENT_DATA_COUNT)
jnb exit1
; wait for "high" data value
lea edx,EventPipeObject.hEventDataHigh1
invoke WaitForMultipleObjects,EVENT_DATA_COUNT,,0,0
; calculate byte value from high/low value
shl al,4;dwEventDataHighValue * 16
add al,dwEventDataLowValue
; store byte value
stosb
lea edx,EventPipeObject.hEventDataLow2
invoke WaitForMultipleObjects,EVENT_DATA_COUNT,,0,2
mov dwEventDataLowValue,al;eax
cmp eax,EVENT_DATA_COUNT;if(dwEventDataLowValue >= EVENT_DATA_COUNT)
jnb exit1
; wait for "high" data value
lea edx,EventPipeObject.hEventDataHigh2
invoke WaitForMultipleObjects,EVENT_DATA_COUNT,,0,0
; calculate byte value from high/low value
shl al,4;dwEventDataHighValue * 16
add al,dwEventDataLowValue
; store byte value
stosb
; set acknowledgement event
invoke SetEvent,EventPipeObject.hEventAck
;------------------------------------------------------------------
; increase ptr
exit1: cmp edi,EndDataLength
jb @b;for(DWORD i = 0; i < EndDataLength; i++)
invoke GetTickCount
sub eax,begin
mov r8d,eax
mov edx,offset fmt
lea ecx,buffer
        invoke  wsprintfA
lea r8d,buffer
invoke  SetDlgItemTextA,hWnd,ID_TXT1
leave
ret
EventPipeRecieve endp
ProgressWindowProc proc hEdit:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local text:dword
local ps:PAINTSTRUCT               
local hDC:dword
local rcClient:RECT

mov hEdit,rcx
mov uMsg,rdx
mov wParam,r8
mov lParam,r9

cmp edx,WM_PAINT
je wmPAINT
mov [rsp+20h],r9;lParam
mov r9,wParam
mov r8,uMsg
mov rdx,hEdit
        invoke  CallWindowProcA,OldProc
jmp wmBYE
wmPAINT:; Размеры окна
        lea     edx,rcClient
        invoke  GetClientRect,hEdit;,edi
        ; Получить текст из свойств
mov edx,offset szProp
        invoke  GetPropA,hEdit;hProgress
        mov     text,eax
; Начать рисование
        lea     edx,ps
        invoke  BeginPaint,hEdit;hProgress
        mov     hDC,eax
; Шрифт
        invoke  SelectObject,hDC,hFont
        invoke  SetBkMode,hDC,TRANSPARENT
; Отрисовать общий фон
        invoke  GetSysColorBrush,COLOR_WINDOW
        lea     edx,rcClient
        invoke  FillRect,hDC,,eax
; Текст для отрисовки есть?
        cmp     text,0
        je      @f
        invoke  GetSysColor,COLOR_WINDOWTEXT
        invoke  SetTextColor,hDC,eax
mov edx,offset buff
mov qword ptr[rsp+20h],DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER or DT_CENTER
        lea     r9d,rcClient
        invoke  DrawTextA,hDC,,-1               
@@:; Вычислить размеры области для заливки
mov edx,offset szPerc
        invoke  GetPropA,hEdit;hProgress
        mov     ecx,eax
        lea     r9d,rcClient
        mov     eax,[r9].RECT.right
        sub     eax,[r9].RECT.left
        mul     ecx
        xor     edx,edx
        mov     ecx,100
        div     ecx
; Позиция выполненного прогресса
        add     eax,[r9].RECT.left
; Наложить выполненный прогресс
mov ecx,[r9].RECT.left
mov edx,[r9].RECT.top
mov r9d,[r9].RECT.bottom
        invoke  CreateRectRgn,,,eax
        invoke  SelectClipRgn,hDC,eax
        invoke  GetSysColorBrush,COLOR_HIGHLIGHT
lea     edx,rcClient
        invoke  FillRect,hDC,,eax
; Текст для отрисовки есть?
        cmp     text,0
        je      @f
        invoke  GetSysColor,COLOR_HIGHLIGHTTEXT
        invoke  SetTextColor,hDC,eax
mov qword ptr[rsp+20h],DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER or DT_CENTER
mov edx,offset buff
        lea     r9d,rcClient
        invoke  DrawTextA,hDC,,-1
@@: lea     edx,ps
        invoke  EndPaint,hDC
xor eax,eax
wmBYE: leave
retn
ProgressWindowProc endp
;-----------------------------------------------------------------------
.data
hWnd dq ?
Format1 db "Song_of_the_South_H1%X",0
Format2 db "Song_of_the_South_L1%X",0
Format3 db "Song_of_the_South_H2%X",0
Format4 db "Song_of_the_South_L2%X",0
Format5 db "Song_of_the_South_A",0
p_Text dq ?
p_ICO dq ?
p_WAV dq ?
szWin db "EventPipe Sender",0
Error1 db "The server is not running.",10,"Run?",0
szAppName db "EventPipe Reciever",0
szService db "08s",0
hThread2 dq ?
szEventName db 32 dup(?)
buff db 100 dup(?)
szText  db '%u%% completed',0
fmt db 'Transmitting %u mSec',0
percent dd 0
hProgress dq ?
hFont dq ?
szProp db 'text',0
szPerc db 'percent',0
szFont db "Verdana",0
OldProc dq ?
align 16
EventPipeObject EventPipeObjectStruct <>
DataLength dq ?
EndDataLength dd ?
end
08r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "EventPipe Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "", ID_PROGRESS, STATIC, WS_CHILD | WS_VISIBLE | WS_DISABLED |
WS_BORDER, 2, 22, 146, 19
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "",ID_TXT1, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 155, 45, 50, 18
}
« Last Edit: August 18, 2022, 09:18:37 PM by Mikl__ »

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #8 on: August 18, 2022, 12:46:45 PM »
08s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc
ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_DIALOG equ 200
IDC_ICON1 equ 500
IDC_IMG1 equ 104
EVENT_DATA_COUNT = 16
size_of_buffer = 96
time_interval    = 10
EventPipeObjectStruct struct
hEventDataHigh1 dq EVENT_DATA_COUNT dup(?)
hEventDataLow1 dq EVENT_DATA_COUNT dup(?)
hEventDataHigh2 dq EVENT_DATA_COUNT dup(?)
hEventDataLow2 dq EVENT_DATA_COUNT dup(?)
hEventAck dq ?
EventPipeObjectStruct ends
.code
WinMain proc
enter 30h,0
mov r9d,256;cx
mov [rbp-10h],r9
mov qword ptr [rbp-8],LR_DEFAULTCOLOR
invoke LoadImage,IMAGE_BASE,IDC_ICON1,IMAGE_ICON;,256,256,LR_DEFAULTCOLOR
mov r9d,offset DialogProc
mov qword ptr[rbp-10h],rax;30h-10h=+20h
invoke DialogBoxParam,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local hFile:qword
local szEventName[32]:byte
local szReadWrite:qword ;number of bytes actually read or write
local hResource:qword
local pResource:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_INITDIALOG
je wmINITDIALOG
cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND

xor eax,eax
jmp exit0
wmINITDIALOG:invoke GetDlgItem,,IDC_IMG1
invoke SendMessage,eax,STM_SETIMAGE,IMAGE_ICON,lParam
xor edi,edi;for(DWORD i = 0; i < 16; i++)
@@:; set current event name
invoke sprintf,&szEventName,&Format1,edi
; create new object
invoke CreateEvent,0,0,0,&szEventName
mov EventPipeObject.hEventDataHigh1[rdi*8],rax
; check for errors
or eax,eax;if(EventPipeObject.hEventDataHigh[i] == NULL)
jz wmBYE;exit0;
; create "low" data event handles
; set current event name
invoke sprintf,&szEventName,&Format2,edi
; create new object
invoke CreateEvent,0,0,0,&szEventName
mov EventPipeObject.hEventDataLow1[rdi*8],rax
; check for errors
or eax,eax;if(EventPipeObject.hEventDataLow[i] == NULL)
jz wmBYE;exit0
invoke sprintf,&szEventName,&Format3,edi
; create new object
invoke CreateEvent,0,0,0,&szEventName
mov EventPipeObject.hEventDataHigh2[rdi*8],rax
; check for errors
or eax,eax;if(EventPipeObject.hEventDataHigh[i] == NULL)
jz wmBYE;exit0;
; create "low" data event handles
; set current event name
invoke sprintf,&szEventName,&Format4,edi
; create new object
invoke CreateEvent,0,0,0,&szEventName
mov EventPipeObject.hEventDataLow2[rdi*8],rax
; check for errors
or eax,eax;if(EventPipeObject.hEventDataLow[i] == NULL)
jz wmBYE;exit0
inc edi
cmp edi,EVENT_DATA_COUNT
jb @b
; create acknowledgement event
; create new object
invoke CreateEvent,0,0,0,&Format5
mov EventPipeObject.hEventAck,rax
jmp wmBYE
wmSEND_TXT:invoke GlobalAlloc,GPTR,size_of_buffer
mov p,rax
invoke  GetDlgItemText,hWnddlg,ID_TXT,eax,size_of_buffer
        or      eax,eax
        jz      wmBYE
test eax,1
jz @f
inc eax
@@: mov dwLength,eax
mov edx,offset szWin
        invoke  FindWindow,NULL
        or      eax,eax
        jz      wmBYE
mov edx,WM_USER+1
jmp @0
;-----------------------------------------------------------
wmSEND_ICO:; Отправить изображение второму приложению
        mov edx,p1
invoke FindResource,0,,RT_ICON; find the resource
mov hResource,rax
invoke  SizeofResource,0,eax ; get its size
mov dwLength,eax
invoke LoadResource,0,hResource ; load the resource
invoke LockResource,eax;pResource
mov p,rax
;-------------------------------------------------
and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
mov edx,dwLength
invoke  CreateIconFromResourceEx,eax,,TRUE,30000h;270376,TRUE,30000h
mov [rsp+20h],rax
invoke  SendDlgItemMessage,hWnddlg,IDC_IMG1,STM_SETIMAGE,IMAGE_ICON
xor p1,11b
; Отправить данные получателю
mov edx,offset szWin
        invoke  FindWindow,NULL
        or      eax,eax
        jz      wmBYE
; Отправить данные получателю
mov edx,WM_USER+2
jmp @0
;-----------------------------------------------------------------------
wmSEND_WAV:mov ecx,offset wav_file
invoke CreateFile,,GENERIC_READ,0,0,OPEN_EXISTING,\
        FILE_ATTRIBUTE_ARCHIVE,0
        mov hFile,rax
        invoke GetFileSize,eax,0
mov dwLength,eax
invoke GlobalAlloc,GPTR,eax
invoke GlobalLock,eax
mov p,rax
lea r9d,szReadWrite
mov r8d,dwLength
        invoke ReadFile,hFile,eax,,,0
        invoke CloseHandle,hFile
;-------------------------------------------------------
; Найти окно получателя
mov edx,offset szWin
        invoke  FindWindow,NULL
        or      eax,eax
        jz      wmBYE
; Отправить данные получателю
mov edx,WM_USER+3
;------------------------------------------------
@0:; Отправить данные получателю
mov r9d,dwLength
invoke PostMessage,eax,,hWnddlg
or eax,eax
jz wmBYE;if(EventPipeObject.hEventAck == NULL)
; ---------------------------------------------------------------------------
; send block data
mov rsi,p
xor edi,edi
@@: movzx eax,byte ptr[rdi+rsi]
;set "high" data event
shr al, 4
invoke SetEvent,EventPipeObject.hEventDataHigh1[rax*8]
test eax, eax
jz wmBYE
; set "low" data event
movzx eax,byte ptr[rdi+rsi]
and al,0Fh
invoke SetEvent,EventPipeObject.hEventDataLow1[rax*8]
test eax, eax
jz wmBYE
movzx eax,byte ptr[rdi+rsi+1]
;set "high" data event
shr al, 4
invoke SetEvent,EventPipeObject.hEventDataHigh2[rax*8]
test eax, eax
jz wmBYE
; set "low" data event
movzx eax,byte ptr[rdi+rsi+1]
and al,0Fh
invoke SetEvent,EventPipeObject.hEventDataLow2[rax*8]
test eax, eax
jz wmBYE
; wait for acknowledgement
invoke WaitForSingleObject,EventPipeObject.hEventAck,INFINITE
test eax, eax
jnz wmBYE
add edi,2
cmp edi,dwLength
jb @b
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_ICO
        je      wmSEND_ICO
cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
cmp r8d,BN_CLICKED shl 16 + ID_SEND_WAV
        je      wmSEND_WAV
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE:invoke EndDialog,,0
; Закрываем идентификаторы объектов-событий 
xor edi,edi
@@: invoke CloseHandle,EventPipeObject.hEventDataHigh1[rdi*8]
inc edi
cmp edi,4*EVENT_DATA_COUNT+1
jb @b
wmBYE: mov eax,TRUE
exit0: leave
retn
DialogProc endp
;------------------------------------------------------------
Format1 db "Song_of_the_South_H1%X",0
Format2 db "Song_of_the_South_L1%X",0
Format3 db "Song_of_the_South_H2%X",0
Format4 db "Song_of_the_South_L2%X",0
Format5 db "Song_of_the_South_A",0
p1 dd 1
wav_file db '..\Images\03.wav',0
align 16
EventPipeObject EventPipeObjectStruct <>
szWin db 'EventPipe Reciever',0
p dq ?
dwLength dd ?
end
08s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "EventPipe Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #9 on: August 18, 2022, 12:53:17 PM »
10. Semaphores
10r.asm (Client)
Code: [Select]
; GUI #
include win64a.inc
SEMAPHORE_DATA_COUNT = 16
;time_interval = 10
SemaphoreObjectStruct struct
hSemaphoreDataHigh dq SEMAPHORE_DATA_COUNT dup(?)
hSemaphoreDataLow dq SEMAPHORE_DATA_COUNT dup(?)
hSemaphoreAck dq ?
SemaphoreObjectStruct ends

IDC_DIALOG equ 200
ID_TXT equ 100
ID_ICON equ 102
ID_PROGRESS equ 106
ID_TXT1 equ 107
IDC_ICON1 equ 500
.code
WinMain proc
enter 30h,0
mov r9d,offset DialogProc
and qword ptr[rbp-10h],0
        invoke  DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword

mov hWnddlg,rcx
mov lParam,r9

        cmp edx,WM_INITDIALOG
jne wmBYE
wmINITDIALOG:mov hWnd,rcx
        mov edx,GWL_STYLE
invoke GetWindowLongPtrA
    or eax,WS_THICKFRAME OR WS_MINIMIZEBOX OR WS_MAXIMIZEBOX
mov edx,GWL_STYLE
invoke SetWindowLongPtrA,hWnddlg,,rax
mov r8d,offset WndProc
mov edx,GWL_WNDPROC
invoke SetWindowLongPtrA,hWnddlg
; Найти окно получателя
mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jnz @f;wmBYE
mov edx,offset Error1
mov r8d,offset szAppName
invoke MessageBoxA,hWnddlg,,,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      @f;wmBYE     
mov ecx,offset szService
invoke WinExec,,SW_SHOW
; create "high" data event handles
xor edi,edi;for(DWORD i = 0; i < ; i++)
; set current event name
@@: invoke sprintf,&szSemaphoreName,&Format1,edi
; open existing object
invoke OpenSemaphore,SEMAPHORE_ALL_ACCESS,0,&szSemaphoreName
mov SemaphoreObject.hSemaphoreDataHigh[rdi*8],rax
or eax,eax
jz wmBYE
invoke sprintf,&szSemaphoreName,&Format2,edi
; open existing object
invoke OpenSemaphore,SEMAPHORE_ALL_ACCESS,0,&szSemaphoreName
mov SemaphoreObject.hSemaphoreDataLow[rdi*8],rax
; check for errors
or eax,eax;if(SemaphoreObject.hSemaphoreDataLow[i] == NULL)
jz wmBYE
inc edi
cmp edi,SEMAPHORE_DATA_COUNT
jb @b
; create acknowledgement event
invoke OpenSemaphore,SEMAPHORE_ALL_ACCESS,0,&Format3
mov SemaphoreObject.hSemaphoreAck,rax
;--------------------------------------------------
; Шрифт текста
pushaddr szFont
push FIXED_PITCH+FF_DONTCARE
push PROOF_QUALITY
push CLIP_DEFAULT_PRECIS
push OUT_RASTER_PRECIS
push ANSI_CHARSET
push FALSE
push FALSE
push FALSE
push FW_BOLD
sub esp,20h
        invoke  CreateFont,32,12,0,0               
        mov     hFont,rax

        invoke  GetDlgItem,hWnddlg,ID_PROGRESS
        mov     hProgress,rax
; Установить наш собственный обработчик
mov r8d,offset ProgressWindowProc
        invoke  SetWindowLongPtrA,hProgress,GWL_WNDPROC
        ; Сохранить хэндл предыдущего обработчика
        mov     OldProc,rax
wmBYE: xor eax,eax
leave
retn
DialogProc endp
WndProc proc hWnd:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local text:dword
local ps:PAINTSTRUCT               
local hDC:dword
local rcClient:RECT

mov hWnd,rcx
mov lParam,r9

cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_USER+1
je wmUSER_1
cmp edx,WM_USER+2
je wmUSER_2
cmp edx,WM_USER+3
je wmUSER_3
leave
jmp NtdllDialogWndProc_
;-----------------------------------------------------
wmUSER_1:mov rax,lParam
mov DataLength,rax
inc eax
invoke GlobalAlloc,GPTR,eax
mov p_Text,rax
invoke SemaphoreRecieve,eax
and byte ptr[rdi],0
        invoke  SetDlgItemTextA,hWnd,ID_TXT,p_Text
invoke GlobalFree,p_Text
jmp wmBYE
wmUSER_2:and percent,0
        xor ecx,ecx
mov [rsp+20h],rcx
movr qword ptr[rsp+28h],hThread2
mov r8d,offset TimerFuncProgress
invoke CreateThread,,0,,22
invoke CloseHandle,eax
;------------------------------------------------------
mov rax,lParam
mov DataLength,rax
invoke GlobalAlloc,GPTR,eax
mov r8d,offset TimerFuncICO
; xor ecx,ecx
; mov [rsp+20h],rcx
; movr qword ptr[rsp+28h],hThread2
; invoke CreateThread,,0,,eax
; invoke CloseHandle,eax
jmp @f;wmBYE
wmUSER_3:and percent,0
        xor ecx,ecx
mov [rsp+20h],rcx
movr qword ptr[rsp+28h],hThread2
mov r8d,offset TimerFuncProgress
invoke CreateThread,,0,,139
invoke CloseHandle,eax
;-----------------------------------------------
mov rax,lParam
mov DataLength,rax
invoke GlobalAlloc,GPTR,eax
mov r8d,offset TimerFuncWAV
@@: xor ecx,ecx
mov [rsp+20h],rcx
movr qword ptr[rsp+28h],hThread2
invoke CreateThread,,0,,eax
invoke CloseHandle,eax
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:invoke EndDialog,,0
; Закрываем идентификаторы объектов-событий 
xor edi,edi
@@: invoke CloseHandle,SemaphoreObject.hSemaphoreDataHigh[rdi*8]
inc edi
cmp edi,2*SEMAPHORE_DATA_COUNT+1
jb @b
wmBYE:  mov eax,TRUE
exit0: leave
ret
WndProc endp

TimerFuncICO proc p:qword
mov p,rcx

invoke SemaphoreRecieve
; Создать HICON напрямую из памяти
and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
invoke  CreateIconFromResourceEx,p,DataLength,TRUE,30000h
mov [rsp+20h],rax
invoke  SendDlgItemMessageA,hWnd,ID_ICON,STM_SETIMAGE,IMAGE_ICON
invoke GlobalFree,p
exit2: leave
ret
TimerFuncICO endp

TimerFuncWAV proc p:qword
local lpwiocb:WAVEHDR
local hWaveOut:qword
mov p,rcx

invoke SemaphoreRecieve
WAVE: mov r8,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data) = 14h
        add r8d,14h
        lea ecx,hWaveOut
        xor r9,r9
mov [rsp+20h],r9
mov qword ptr[rsp+28h],WAVE_ALLOWSYNC
        or edx,WAVE_MAPPER
        invoke waveOutOpen
; Подготавливаем заголовок для вывода
lea edx,lpwiocb
mov edi,edx
xor eax,eax
mov ecx,(sizeof WAVEHDR)/8
rep stosq

mov rax,p
mov ecx,eax
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data)+\
;(Type of format)+(Number of Channels)+(Sample Rate)+(Sample Rate*BitsPerSample*Channels/8)+\
;(BitsPerSample*Channels/8)+(Bits per sample)+(“data” chunk header)+(Size of the data section)=2Ch
add eax,2Ch

mov [rdx].WAVEHDR.lpData,rax ;адрес блока данных
mov eax,[rcx+4];размер блока данных
sub eax,2Ch
mov [rdx].WAVEHDR.dwBufferLength,eax ;размер блока данных

invoke waveOutPrepareHeader,hWaveOut,,sizeof WAVEHDR
; Запускаем проигрывание блока
lea edx,lpwiocb
mov rcx,hWaveOut
mov r8d,sizeof WAVEHDR
invoke waveOutWrite
@@: test lpwiocb.dwFlags,WHDR_DONE
jz @b
lea edx,lpwiocb
invoke waveOutUnprepareHeader,hWaveOut,,sizeof WAVEHDR
invoke waveOutClose,hWaveOut
@1: invoke GlobalFree,p
exit2: leave
ret
TimerFuncWAV endp
TimerFuncProgress proc lParam:qword
mov lParam,rcx
; Сформировать строку для отрисовки
@@: mov r8d,percent
mov edx,offset szText
mov ecx,offset buff
        invoke  wsprintfA
; Назначить строку свойством ProgressBar
mov r8d,offset buff
mov edx,offset szProp
        invoke  SetPropA,hProgress
; Назначить значение процента свойством ProgressBar
mov r8d,percent
mov edx,offset szPerc
        invoke  SetPropA,hProgress
; Перерисовать содержимое окна
        invoke  InvalidateRect,hProgress,0,FALSE
        inc     percent
        cmp     percent,101
        je exit0
invoke Sleep,lParam
jmp @b
exit0: leave
ret
TimerFuncProgress endp
SemaphoreRecieve proc p:qword
local dwSemaphoreDataLowValue:byte
local begin:dword
local buffer[20]:byte

mov edi,ecx
add rcx,DataLength
mov EndDataLength,ecx

        invoke GetTickCount
mov begin,eax
lea r8d,buffer
and byte ptr[r8],0
invoke  SetDlgItemTextA,hWnd,ID_TXT1

@@: lea edx,SemaphoreObject.hSemaphoreDataLow
invoke WaitForMultipleObjects,SEMAPHORE_DATA_COUNT,,0,2
cmp eax,SEMAPHORE_DATA_COUNT;if(dwSemaphoreDataLowValue >= SEMAPHORE_DATA_COUNT)
jnb exit1
; wait for "high" data value
mov dwSemaphoreDataLowValue,al
lea edx,SemaphoreObject.hSemaphoreDataHigh
invoke WaitForMultipleObjects,SEMAPHORE_DATA_COUNT,,0,0
; calculate byte value from high/low value
shl al,4;dwSemaphoreDataHighValue * 16
add al,dwSemaphoreDataLowValue
; store byte value
stosb
; set acknowledgement event
invoke ReleaseSemaphore,SemaphoreObject.hSemaphoreAck,1,0
;------------------------------------------------------------------
; increase ptr
exit1: cmp edi,EndDataLength
jb @b
        invoke GetTickCount
sub eax,begin
mov r8d,eax
mov edx,offset fmt
lea ecx,buffer
        invoke  wsprintfA
lea r8d,buffer
invoke  SetDlgItemTextA,hWnd,ID_TXT1
leave
ret
SemaphoreRecieve endp
ProgressWindowProc proc hEdit:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local text:dword
local ps:PAINTSTRUCT               
local hDC:dword
local rcClient:RECT

mov hEdit,rcx
mov uMsg,rdx
mov wParam,r8
mov lParam,r9

cmp edx,WM_PAINT
je wmPAINT
mov [rsp+20h],r9;lParam
mov r9,wParam
mov r8,uMsg
mov rdx,hEdit
        invoke  CallWindowProcA,OldProc
jmp wmBYE
wmPAINT:; Размеры окна
        lea     edx,rcClient
        invoke  GetClientRect,hEdit;,edi
        ; Получить текст из свойств
mov edx,offset szProp
        invoke  GetPropA,hEdit;hProgress
        mov     text,eax
; Начать рисование
        lea     edx,ps
        invoke  BeginPaint,hEdit;hProgress
        mov     hDC,eax
; Шрифт
        invoke  SelectObject,hDC,hFont
        invoke  SetBkMode,hDC,TRANSPARENT
; Отрисовать общий фон
        invoke  GetSysColorBrush,COLOR_WINDOW
        lea     edx,rcClient
        invoke  FillRect,hDC,,eax
; Текст для отрисовки есть?
        cmp     text,0
        je      @f
        invoke  GetSysColor,COLOR_WINDOWTEXT
        invoke  SetTextColor,hDC,eax
mov edx,offset buff
mov qword ptr[rsp+20h],DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER or DT_CENTER
        lea     r9d,rcClient
        invoke  DrawTextA,hDC,,-1               
@@:; Вычислить размеры области для заливки
mov edx,offset szPerc
        invoke  GetPropA,hEdit;hProgress
        mov     ecx,eax
        lea     r9d,rcClient
        mov     eax,[r9].RECT.right
        sub     eax,[r9].RECT.left
        mul     ecx
        xor     edx,edx
        mov     ecx,100
        div     ecx
; Позиция выполненного прогресса
        add     eax,[r9].RECT.left
; Наложить выполненный прогресс
mov ecx,[r9].RECT.left
mov edx,[r9].RECT.top
mov r9d,[r9].RECT.bottom
        invoke  CreateRectRgn,,,eax
        invoke  SelectClipRgn,hDC,eax
        invoke  GetSysColorBrush,COLOR_HIGHLIGHT
lea     edx,rcClient
        invoke  FillRect,hDC,,eax
; Текст для отрисовки есть?
        cmp     text,0
        je      @f
        invoke  GetSysColor,COLOR_HIGHLIGHTTEXT
        invoke  SetTextColor,hDC,eax
mov qword ptr[rsp+20h],DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER or DT_CENTER
mov edx,offset buff
        lea     r9d,rcClient
        invoke  DrawTextA,hDC,,-1
@@: lea     edx,ps
        invoke  EndPaint,hDC
xor eax,eax
wmBYE: leave
retn
ProgressWindowProc endp
;-----------------------------------------------------------------------
.data
hWnd dq ?
Format1 db "Song_of_the_South_H%u",0
Format2 db "Song_of_the_South_L%u",0
Format3 db "Song_of_the_South_A",0
p_Text dq ?
p_ICO dq ?
p_WAV dq ?
szWin db "Semaphore Sender",0
Error1 db "The server is not running.",10,"Run?",0
szAppName db "Semaphore Reciever",0
szService db "10s",0
hThread2 dq ?
fmt db '%u',0
szSemaphoreName db 32 dup(?)
buff db 100 dup(?)
szText  db '%u%% completed',0
percent dd 0
hProgress dq ?
hFont dq ?
szProp db 'text',0
szPerc db 'percent',0
szFont db "Verdana",0
OldProc dq ?
align 16
SemaphoreObject SemaphoreObjectStruct <>
DataLength dq ?
EndDataLength dd ?
end
10r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Semaphore Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "", ID_PROGRESS, STATIC, WS_CHILD | WS_VISIBLE | WS_DISABLED |
WS_BORDER, 2, 22, 146, 19
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "",ID_TXT1, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 149, 45, 60, 13
}
10s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc
ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_DIALOG equ 200
IDC_ICON1 equ 500
IDC_IMG1 equ 104
SEMAPHORE_DATA_COUNT = 16
size_of_buffer = 96
time_interval    = 10
SemaphoreObjectStruct struct
hSemaphoreDataHigh dq SEMAPHORE_DATA_COUNT dup(?)
hSemaphoreDataLow dq SEMAPHORE_DATA_COUNT dup(?)
hSemaphoreAck dq ?
SemaphoreObjectStruct ends
.code
WinMain proc
enter 30h,0
mov r9d,256;cx
mov [rbp-10h],r9
mov qword ptr [rbp-8],LR_DEFAULTCOLOR
invoke LoadImageA,IMAGE_BASE,IDC_ICON1,IMAGE_ICON;,256,256,LR_DEFAULTCOLOR
mov r9d,offset DialogProc
mov qword ptr[rbp-10h],rax;30h-10h=+20h
invoke DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local hFile:qword
local szSemaphoreName[32]:byte
local szReadWrite:qword ;number of bytes actually read or write
local hResource:qword
local pResource:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_INITDIALOG
je wmINITDIALOG
cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND

xor eax,eax
jmp exit0
wmINITDIALOG:invoke GetDlgItem,,IDC_IMG1
invoke SendMessageA,eax,STM_SETIMAGE,IMAGE_ICON,lParam
xor edi,edi;for(DWORD i = 0; i < 16; i++)
@@:; set current Semaphore name
invoke sprintf,&szSemaphoreName,&Format1,edi
; create new object
invoke CreateSemaphore,0,0,1,&szSemaphoreName
mov SemaphoreObject.hSemaphoreDataHigh[rdi*8],rax
; check for errors
or eax,eax;if(SemaphoreObject.hSemaphoreDataHigh[i] == NULL)
jz wmBYE;exit0;
; create "low" data Semaphore handles
; set current Semaphore name
invoke sprintf,&szSemaphoreName,&Format2,edi
; create new object
invoke CreateSemaphore,0,0,1,&szSemaphoreName
mov SemaphoreObject.hSemaphoreDataLow[rdi*8],rax
; check for errors
or eax,eax;if(SemaphoreObject.hSemaphoreDataLow[i] == NULL)
jz wmBYE;exit0
inc edi
cmp edi,SEMAPHORE_DATA_COUNT
jb @b
; create acknowledgement Semaphore
; create new object
invoke CreateSemaphore,0,0,1,&Format3
mov SemaphoreObject.hSemaphoreAck,rax
jmp wmBYE
wmSEND_TXT:invoke GlobalAlloc,GPTR,size_of_buffer
mov p,rax
invoke  GetDlgItemTextA,hWnddlg,ID_TXT,eax,size_of_buffer
        or      eax,eax
        jz      wmBYE
mov dwLength,eax
mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jz      wmBYE
mov edx,WM_USER+1
jmp @0
;-----------------------------------------------------------
wmSEND_ICO:; Отправить изображение второму приложению
        mov edx,p1
invoke FindResource,0,,RT_ICON; find the resource
mov hResource,rax
invoke  SizeofResource,0,eax ; get its size
mov dwLength,eax
invoke LoadResource,0,hResource ; load the resource
invoke LockResource,eax;pResource
mov p,rax
;-------------------------------------------------
and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
mov edx,dwLength
invoke  CreateIconFromResourceEx,eax,,TRUE,30000h;270376,TRUE,30000h
mov [rsp+20h],rax
invoke  SendDlgItemMessageA,hWnddlg,IDC_IMG1,STM_SETIMAGE,IMAGE_ICON
xor p1,11b
; Отправить данные получателю
mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jz      wmBYE
; Отправить данные получателю
mov edx,WM_USER+2
jmp @0
;-----------------------------------------------------------------------
wmSEND_WAV:mov ecx,offset wav_file
invoke CreateFile,,GENERIC_READ,0,0,OPEN_EXISTING,\
        FILE_ATTRIBUTE_ARCHIVE,0
        mov hFile,rax
        invoke GetFileSize,eax,0
mov dwLength,eax
invoke GlobalAlloc,GPTR,eax
invoke GlobalLock,eax
mov p,rax
lea r9d,szReadWrite
mov r8d,dwLength
        invoke ReadFile,hFile,eax,,,0
        invoke CloseHandle,hFile
;-------------------------------------------------------
; Найти окно получателя
mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jz      wmBYE
; Отправить данные получателю
mov edx,WM_USER+3
;------------------------------------------------
@0:; Отправить данные получателю
mov r9d,dwLength
invoke PostMessageA,eax,,hWnddlg
or eax,eax
jz wmBYE;if(SemaphoreObject.hSemaphoreAck == NULL)
; ---------------------------------------------------------------------------
; send block data
mov rsi,p
xor edi,edi
@@: movzx eax,byte ptr[rdi+rsi]
;set "high" data Semaphore
shr al, 4
invoke ReleaseSemaphore,SemaphoreObject.hSemaphoreDataHigh[rax*8],1,0
test eax, eax
jz wmBYE
; set "low" data Semaphore
movzx eax,byte ptr[rdi+rsi]
and al,0Fh
invoke ReleaseSemaphore,SemaphoreObject.hSemaphoreDataLow[rax*8],1,0
test eax, eax
jz wmBYE
; wait for acknowledgement
invoke WaitForSingleObject,SemaphoreObject.hSemaphoreAck,INFINITE
test eax, eax
jnz wmBYE
inc edi
cmp edi,dwLength
jb @b
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_ICO
        je      wmSEND_ICO
cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
cmp r8d,BN_CLICKED shl 16 + ID_SEND_WAV
        je      wmSEND_WAV
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE:invoke EndDialog,,0
; Закрываем идентификаторы объектов-событий 
xor edi,edi
@@: invoke CloseHandle,SemaphoreObject.hSemaphoreDataHigh[rdi*8]
inc edi
cmp edi,2*SEMAPHORE_DATA_COUNT+1
jb @b
wmBYE: mov eax,TRUE
exit0: leave
retn
DialogProc endp
;------------------------------------------------------------
Format1 db "Song_of_the_South_H%u",0
Format2 db "Song_of_the_South_L%u",0
Format3 db "Song_of_the_South_A",0
p1 dd 1
wav_file db '..\Images\03.wav',0
align 16
SemaphoreObject SemaphoreObjectStruct <>
szWin db 'Semaphore Reciever',0
p dq ?
dwLength dd ?
end
10s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Semaphore Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}
« Last Edit: August 18, 2022, 06:17:14 PM by Mikl__ »

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #10 on: August 18, 2022, 01:01:50 PM »
12. WinSockets
12r.asm (Client)
Code: [Select]
; GUI #
include win64a.inc
IDC_DIALOG equ 200
IDC_OUTPUT equ 100
ID_ICON equ 102
IDC_ICON1 equ 500

WINSOCK_VERSION equ 504
SD_RECEIVE equ 0
SD_SEND equ 1
SD_BOTH equ 2

WSADATA struct
  wVersion dw ?;
  wHighVersion dw ?
  szDescription db (WSADESCRIPTION_LEN + 1) dup(?)
  szSystemStatus db (WSASYS_STATUS_LEN + 1) dup(?)
  iMaxSockets dw ?
  iMaxUdpDg dw ?
  lpVendorInfo dq ?
WSADATA ends

S_UN_B STRUCT
  s_b1 BYTE ?
  s_b2 BYTE ?
  s_b3 BYTE ?
  s_b4 BYTE ?
S_UN_B ENDS

S_UN_W STRUCT
  s_w1 WORD ?
  s_w2 WORD ?
S_UN_W ENDS

ADDRESS_UNION UNION
   S_un_b S_UN_B <>
   S_un_w S_UN_W <>
   S_addr DWORD ?
ADDRESS_UNION ENDS

in_addr STRUCT
  S_un ADDRESS_UNION <>
in_addr ENDS

SOCKADDR_IN STRUCT
  sin_family    WORD      ?
  sin_port      WORD      ?
  sin_addr      in_addr <>
  sin_zero      BYTE 8 dup (?)
SOCKADDR_IN ends
.code
WinMain proc
enter 30h,0
mov r9d,offset DialogProc
and qword ptr[rbp-10h],0
        invoke  DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword
local wsa:WSADATA
local clientSocket:qword
local saddr:SOCKADDR_IN;sizeof(saddr)=10h
local addrSize:dword
local buffer[1024]:byte
local lpwiocb:WAVEHDR
local hWaveOut:qword

mov hWnddlg,rcx
mov lParam,r9

        cmp edx,WM_INITDIALOG
je wmINITDIALOG
cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_DESTROY
je wmDESTROY
cmp edx,WM_USER+1
je wmUSER_1
cmp edx,WM_USER+2
je wmUSER_2
cmp edx,WM_USER+3
je wmUSER_3
xor eax,eax
jmp exit0

wmDESTROY:cmp serverSocket,INVALID_SOCKET
jz wmBYE
invoke shutdown,serverSocket,SD_BOTH
invoke closesocket,serverSocket
or serverSocket,INVALID_SOCKET
jmp wmBYE
wmUSER_1:cmp serverSocket,INVALID_SOCKET
jz @f
invoke shutdown,serverSocket,SD_BOTH
invoke closesocket,serverSocket
; Create a stream socket for internet use
; создать сокет
@@: invoke socket,AF_INET,SOCK_STREAM,IPPROTO_TCP
mov serverSocket,rax
cmp eax,INVALID_SOCKET
jz break
; подключить сокет
        mov saddr.sin_family,AF_INET
invoke htonl,INADDR_LOOPBACK
mov saddr.sin_addr.S_un.S_addr,eax
invoke htons,12343; convert port number into network byte order first
mov saddr.sin_port,ax; адрес порта
mov r8d,sizeof saddr
lea edx,saddr
invoke bind,serverSocket
or eax,eax;if (bind (serverSocket, (struct sockaddr*)&saddr, sizeof(saddr)) == 0)
        jnz break
; перевести сокет в состояние "слушать"
invoke listen,serverSocket,256
or eax,eax
jnz break;if (listen (serverSocket, 256) == 0)
; ждем запроса от клиента
mov addrSize,sizeof saddr
lea edx,saddr
lea r8d,addrSize
invoke accept,serverSocket
mov clientSocket,rax
cmp eax,INVALID_SOCKET
jz break;if (clientSocket == INVALID_SOCKET) break;
; запрос пришел - посылаем информацию
@@: lea edx,buffer
invoke recv,clientSocket,,1024,0
;recv is for use with a stream socket
;Parameters:
; #1 socket == socket descriptor
; #2 buffer == address of the memory block to store the incoming data.
; #3 len == the size of the memory block
; #4 flags == flags specifying the behavior of the function. There are two flags you can use:
; MSG_PEEK Peek at the incoming data. The data is copied into the buffer but is not
;removed from the input queue.
; MSG_OOB Process out-of-band data. This flag is usually used when FD_OOB notification
;is received. If the call is successful, it returns the number of bytes read from the socket. If it
;is unsuccessful, the value SOCKET_ERROR is returned. If the return value is 0, the remote socket
;has been closed
        or eax,eax
jnz @b;if (len <= 0)    break
; выводим строку символов
lea r8d,buffer
invoke  SetDlgItemTextA,hWnddlg,IDC_OUTPUT
jmp @0
wmUSER_2:;mov rax,lParam
mov FSize,r9;ax
cmp serverSocket,INVALID_SOCKET
jz @f
invoke shutdown,serverSocket,SD_BOTH
invoke closesocket,serverSocket
@@: invoke socket,AF_INET,SOCK_STREAM,IPPROTO_TCP; Create a stream socket for internet use
mov serverSocket,rax
cmp serverSocket,INVALID_SOCKET
jz break
mov saddr.sin_family,AF_INET
invoke htonl,INADDR_LOOPBACK
mov saddr.sin_addr.S_un.S_addr,eax
invoke htons,12344; convert port number into network byte order first
mov saddr.sin_port,ax
mov r8d,sizeof saddr
lea edx,saddr
invoke bind,serverSocket
or eax,eax;if (bind (serverSocket, (struct sockaddr*)&saddr, sizeof(saddr)) == 0)
jnz break
invoke listen,serverSocket,256
or eax,eax
jnz break;if (listen (serverSocket, 256) == 0)
mov addrSize,sizeof saddr
lea edx,saddr
lea r8d,addrSize
invoke accept,serverSocket
mov clientSocket,rax
cmp eax,INVALID_SOCKET
jz break;if (clientSocket == INVALID_SOCKET) break;
invoke GlobalAlloc,GPTR,FSize
mov p,rax
mov edi,eax
@@: lea edx,buffer
invoke recv,clientSocket,,1024,0
or eax,eax
jz @f
lea esi,buffer
mov ecx,eax;1024
rep movsb
jmp @b;if (len <= 0)    break;
@@: invoke  CreateIconFromResourceEx,p,FSize,TRUE,30000h,256,256,LR_DEFAULTCOLOR
invoke  SendDlgItemMessageA,hWnddlg,ID_ICON,STM_SETIMAGE,IMAGE_ICON,eax
jmp @1
wmUSER_3:;mov rax,lParam
mov FSize,r9;ax
cmp serverSocket,INVALID_SOCKET
jz @f
invoke shutdown,serverSocket,SD_BOTH
invoke closesocket,serverSocket
@@: invoke socket,AF_INET,SOCK_STREAM,IPPROTO_TCP; Create a stream socket for internet use
mov serverSocket,rax
cmp eax,INVALID_SOCKET
jz break
        mov saddr.sin_family,AF_INET
invoke htonl,INADDR_LOOPBACK
mov saddr.sin_addr.S_un.S_addr,eax
invoke htons,12345; convert port number into network byte order first
mov saddr.sin_port,ax
mov r8d,sizeof saddr
lea edx,saddr
invoke bind,serverSocket
or eax,eax;if (bind (serverSocket, (struct sockaddr*)&saddr, sizeof(saddr)) == 0)
jnz break
invoke listen,serverSocket,256
or eax,eax
jnz break;if (listen (serverSocket, 256) == 0)
mov addrSize,sizeof saddr
lea edx,saddr
lea r8d,addrSize
invoke accept,serverSocket
mov clientSocket,rax
cmp eax,INVALID_SOCKET
jz break;if (clientSocket == INVALID_SOCKET) break;
invoke GlobalAlloc,GPTR,FSize
mov p,rax
mov edi,eax
@@: lea edx,buffer
invoke recv,clientSocket,,1024,0
or eax,eax
jz @f
lea esi,buffer
mov ecx,eax;1024
rep movsb
jmp @b;if (len <= 0)    break;
@@: mov r8,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data) = 14h
        add r8d,14h
        invoke waveOutOpen,&hWaveOut,WAVE_MAPPER,,0,0,WAVE_ALLOWSYNC
; Подготавливаем заголовок для вывода
lea edx,lpwiocb
mov edi,edx
xor eax,eax
mov ecx,(sizeof WAVEHDR)/8
rep stosq

mov rax,p
;"RIFF"+(File size)+(File Type Header)+(Format chunk marker)+(Length of format data)+\
;(Type of format)+(Number of Channels)+(Sample Rate)+(Sample Rate*BitsPerSample*Channels/8)+\
;(BitsPerSample*Channels/8)+(Bits per sample)+(“data” chunk header)+(Size of the data section)=2Ch
add rax,2Ch
mov [rdx].WAVEHDR.lpData,rax ;адрес блока данных
mov rax,FSize
sub eax,2Ch
mov [rdx].WAVEHDR.dwBufferLength,eax ;размер блока данных

invoke waveOutPrepareHeader,hWaveOut,,sizeof WAVEHDR
; Запускаем проигрывание блока
invoke waveOutWrite,hWaveOut,&lpwiocb,sizeof WAVEHDR
@@: test lpwiocb.dwFlags,WHDR_DONE
jz @b
invoke waveOutUnprepareHeader,hWaveOut,&lpwiocb,sizeof WAVEHDR
invoke waveOutClose,hWaveOut
;----------------------------------------------------------
@1: invoke GlobalFree,p
; закрыть связь
@0: invoke shutdown,clientSocket,SD_BOTH
; закрыть сокет
invoke closesocket,clientSocket
;This function closes a socket. Every resource of the socket will be released
break: cmp serverSocket,INVALID_SOCKET;if (serverSocket != INVALID_SOCKET)
jz wmBYE
invoke shutdown,serverSocket,SD_BOTH
invoke closesocket,serverSocket
mov serverSocket,INVALID_SOCKET
jmp wmBYE
wmINITDIALOG:;mov hWnd,rcx
; Найти окно отправителя
mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jnz wmBYE
mov edx,offset Error1
mov r8d,offset szAppName
invoke MessageBoxA,hWnddlg,,,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      wmBYE
mov ecx,offset szService
invoke WinExec,,SW_SHOW
;активировать библиотеку сокетов
lea edx,wsa
invoke WSAStartup,WINSOCK_VERSION
jmp wmBYE
;--------------------------------------------------
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: mov eax,TRUE
exit0: leave
retn
DialogProc endp
;-----------------------------------------------------------------------
.data
szWin db "Socket Sender",0
Error1 db "The server is not running.",10,"Run?",0
szAppName db "Socket Reciever",0
szService db "12s",0
serverSocket dq INVALID_SOCKET
;threadHandleTxt dq ?
;threadHandleIco dq ?
;threadHandleWav dq ?
;threadId dd ?
;hWnd dq ?
FSize dq ?
p dq ?
end
12r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Socket Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
}
12s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc
ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_DIALOG equ 200
IDC_ICON1 equ 500
IDC_IMG1 equ 104
WINSOCK_VERSION equ 504
SD_RECEIVE equ 0
SD_SEND equ 1
SD_BOTH equ 2

WSADATA struct
  wVersion dw ?;
  wHighVersion dw ?
  szDescription db (WSADESCRIPTION_LEN + 1) dup(?)
  szSystemStatus db (WSASYS_STATUS_LEN + 1) dup(?)
  iMaxSockets dw ?
  iMaxUdpDg dw ?
  lpVendorInfo dq ?
WSADATA ends

S_UN_B STRUCT
  s_b1 BYTE ?
  s_b2 BYTE ?
  s_b3 BYTE ?
  s_b4 BYTE ?
S_UN_B ENDS

S_UN_W STRUCT
  s_w1 WORD ?
  s_w2 WORD ?
S_UN_W ENDS

ADDRESS_UNION UNION
   S_un_b S_UN_B <>
   S_un_w S_UN_W <>
   S_addr DWORD ?
ADDRESS_UNION ENDS

in_addr STRUCT
  S_un ADDRESS_UNION <>
in_addr ENDS

SOCKADDR_IN STRUCT
  sin_family    dw ?;is the same as af parameter in socket call. You must use AF_INET here.
  sin_port      dw ?;is the port that the socket will use to communicate with the remote socket.
;This value depends on the higher level protocol that you want to use. If you want to connect to
;the remote socket for HTTP, use port 80 (decimal). However, note that the port value MUST be in
;network byte order that is big Endian. So you cannot use the port value per se but you must call
;htons to convert the value to network byte order first. This is one of the most common error the
;newcomers to winsock programming encounter.
  sin_addr      in_addr <>;is the IP address of the remote host. Again, you must convert the
;IP address to network byte order before using it
  sin_zero      BYTE 8 dup(?);is reserved. Don't mess with it
SOCKADDR_IN ends
.code
WinMain proc
enter 30h,0
mov r9d,256;cx
mov [rbp-10h],r9
mov qword ptr [rbp-8],LR_DEFAULTCOLOR
invoke LoadImageA,IMAGE_BASE,IDC_ICON1,IMAGE_ICON;,256,256,LR_DEFAULTCOLOR
mov r9d,offset DialogProc
mov qword ptr[rbp-10h],rax;30h-10h=+20h
invoke DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local hFile:qword
local cbWritten:dword
local hResource:qword
local pResource:qword
local wsa:WSADATA
local port:qword
local FSize:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_INITDIALOG
        je wmINITDIALOG
cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_DESTROY
je wmDESTROY
xor eax,eax
jmp exit0
wmDESTROY:invoke WSACleanup
jmp wmBYE
wmSEND_WAV:mov port,12345
mov type0,WM_USER+3
        mov ecx,offset wav_file
xor r9d,r9d
mov qword ptr[rsp+30h],r9
mov qword ptr[rsp+28h],FILE_ATTRIBUTE_ARCHIVE
mov qword ptr[rsp+20h],OPEN_EXISTING
invoke CreateFile,,GENERIC_READ or GENERIC_WRITE,\
FILE_SHARE_READ or FILE_SHARE_WRITE
        mov hFile,rax
        invoke GetFileSize,eax,0
mov FSize,rax
invoke GlobalAlloc,GPTR,eax
        mov p,rax
lea r9d,cbWritten
and qword ptr[rsp+20h],0
        invoke ReadFile,hFile,eax,FSize
        invoke CloseHandle,hFile
jmp @f
wmSEND_ICO:mov port,12344
mov type0,WM_USER+2
        mov edx,p1
invoke FindResource,0,,RT_ICON; find the resource
mov hResource,rax
invoke  SizeofResource,0,eax ; get its size
mov FSize,rax
invoke LoadResource,0,hResource ; load the resource
invoke LockResource,eax;pResource
mov p,rax
and qword ptr[rsp+30h],LR_DEFAULTCOLOR;LR_DEFAULTCOLOR=0
mov qword ptr[rsp+20h],256
mov qword ptr[rsp+28h],256
invoke  CreateIconFromResourceEx,eax,FSize,TRUE,30000h;270376,TRUE,30000h
mov [rsp+20h],rax
invoke  SendDlgItemMessageA,hWnddlg,IDC_IMG1,STM_SETIMAGE,IMAGE_ICON
xor p1,11b
jmp @f
wmSEND_TXT:mov port,12343
mov type0,WM_USER+1
invoke GlobalAlloc,GPTR,256
        mov p,rax
invoke GetDlgItemTextA,hWnddlg,ID_TXT,eax,256
inc eax
mov FSize,rax

@@: mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jz      wmBYE
; Отправить данные получателю
invoke PostMessageA,eax,type0,hWnddlg,FSize
invoke SendData,p,FSize,port
jmp wmBYE
wmINITDIALOG:invoke GetDlgItem,,IDC_IMG1
invoke SendMessageA,eax,STM_SETIMAGE,IMAGE_ICON,lParam
; активировать библиотеку сокетов
lea edx,wsa
invoke WSAStartup,WINSOCK_VERSION
;An error occured if eax != null, because there's no return value for this api, if there's return,
;there's an error
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_WAV
        je      wmSEND_WAV
        cmp r8d,BN_CLICKED shl 16 + ID_SEND_ICO
        je      wmSEND_ICO
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: mov eax,TRUE
exit0: leave
retn
DialogProc endp
SendData proc buf:qword,len:qword,port:qword
local sock:QWORD
local saddr:SOCKADDR_IN;sizeof(saddr)) =10h
local bytesSent:dword

mov buf,rcx
mov len,rdx
mov port,r8
; создать сокет
invoke socket,AF_INET, SOCK_STREAM, IPPROTO_TCP
mov sock,rax
cmp eax,INVALID_SOCKET
jz exit0;if (sock != INVALID_SOCKET)

mov saddr.sin_family,AF_INET
invoke htonl,INADDR_LOOPBACK
mov saddr.sin_addr.S_un.S_addr,eax
invoke htons,port;12345
mov saddr.sin_port,ax
;After the socket is created, you have two choices: wait for an incoming connection or connect
;to a remote socket. If you want to wait for incoming connection, you must call listen to listen
;for an incoming connection and call accept to establish connection with the remote socket. If you
;want to connect to a remote socket, you must call connect
mov r8d,sizeof saddr;the size of SOCKADDR_IN structure
lea edx,saddr;a pointer to a SOCKADDR_IN structure
invoke connect,sock;socket descriptor of the local socket. You can pass the socket
;descriptor returned by socket call as this parameter
or eax,eax
jnz @0;if (connect (sock,(struct sockaddr*)&saddr,sizeof (saddr)) == 0)
@@: cmp len,0 ;       while (size)
jz @0
;use send to send data on a stream socket and sendto to send data on a datagram socket. I'll
;examine send here since many popular protocols such as HTTP and FTP use stream sockets.
; запрос пришел - посылаем информацию
invoke send,sock,buf,len, 0
;Parameters
; #1 socket == socket descriptor
; #2 buffer == address of the data that you want to send. The data need not be NULL-terminated
;since its size is specified in len parameter.
; #3 len == the size of data to send
; #4 flags == flags specifying the behavior of the function. There are two flags you can use:
; MSG_DONTROUTE : specifies that the data should not be subject to routing. Notice
;the word "should". Some windows socket implementation may ignore this flag.
; MSG_OOB : specifies that the data is out-of-band data.
;Normally we don't use any of these two flags, flags parameter should be 0 in this case.
;If the call is unsuccessful, the value SOCKET_ERROR is returned in eax.
;If it's successful, the actual number of bytes sent is returned in eax. Note that this number
;may not be equal to len parameter.
or eax,eax
jz @0;if (bytesSent <= 0)          break;
sub len,rax;     size -= (uint32_t)bytesSent;
        add buf,rax;    data = (uint8_t*)data + bytesSent;
jmp @b
; закрыть связь
@0:     invoke shutdown,sock,SD_BOTH
; закрыть сокет
invoke closesocket,sock
exit0: leave
ret
SendData endp
;---------------------------------------
.data
szWin db 'Socket Reciever',0
wav_file db '..\Images\03.wav',0
p dq ?
p1 dd 1
type0 dq ?
end
12s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Socket Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}
« Last Edit: August 18, 2022, 06:16:40 PM by Mikl__ »

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #11 on: August 18, 2022, 03:51:46 PM »
09. Mutex
So far, only text transfer, but it is displayed without errors, the version of programs with the transfer of pictures and WAV-files will be later (although it is likely that the mutex mechanism is not designed for such an intensive messaging, but I will try ).
09r.asm (Client)
Code: [Select]
; GUI #
include win64a.inc
MUTEX_DATA_COUNT = 16
MUTEX_ALL_ACCESS = 1F0001h
size_of_buffer = 96
IDC_DIALOG equ 200
ID_TXT equ 100
ID_ICON equ 102
ID_PROGRESS equ 106
ID_TXT1 equ 107
IDC_ICON1 equ 500
.code
WinMain proc
enter 30h,0
mov r9d,offset DialogProc
and qword ptr[rbp-10h],0
        invoke  DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
        invoke  RtlExitUserProcess,NULL
WinMain endp
DialogProc proc hWnddlg:qword,msg:qword,wParam:qword,lParam:qword
local MutexName[256]:word

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_INITDIALOG
jne wmBYE
wmINITDIALOG:mov hWnd,rcx
        mov edx,GWL_STYLE
invoke GetWindowLongPtrA
    or eax,WS_THICKFRAME OR WS_MINIMIZEBOX OR WS_MAXIMIZEBOX
mov edx,GWL_STYLE
invoke SetWindowLongPtrA,hWnddlg,,rax
mov r8d,offset WndProc
mov edx,GWL_WNDPROC
invoke SetWindowLongPtrA,hWnddlg
; Найти окно получателя
mov edx,offset szWin
        invoke  FindWindowA,NULL
        or      eax,eax
        jnz wmBYE
mov edx,offset Error1
mov r8d,offset szAppName
invoke MessageBoxA,hWnddlg,,,MB_ICONEXCLAMATION or MB_YESNO
cmp eax,IDNO
jz      wmBYE
mov ecx,offset szService
invoke WinExec,,SW_SHOW
;------------------------------------
xor edi,edi
@@: lea ecx,MutexName
mov edx,offset fmtH
invoke wsprintfA,,,edi
lea r8d,MutexName
invoke OpenMutex,MUTEX_ALL_ACCESS,FALSE
mov handlesH[rdi*8],rax

lea ecx,MutexName
mov edx,offset fmtL
invoke wsprintfA,,,edi
lea r8d,MutexName
invoke OpenMutex,MUTEX_ALL_ACCESS,FALSE
mov handlesL[rdi*8],rax
inc edi
cmp edi,MUTEX_DATA_COUNT
jb @b
mov r8d,offset Format5
invoke OpenEvent,EVENT_ALL_ACCESS,0
mov hEventAck,rax
mov r9d,offset EVENT_RECEIVER_READY
invoke CreateEvent,NULL, TRUE, FALSE
mov eventReceiverReady,rax
;-----------------------------------------------
; Шрифт текста
pushaddr szFont
push FIXED_PITCH+FF_DONTCARE
push PROOF_QUALITY
push CLIP_DEFAULT_PRECIS
push OUT_RASTER_PRECIS
push ANSI_CHARSET
push FALSE
push FALSE
push FALSE
push FW_BOLD
sub esp,20h
        invoke  CreateFont,32,12,0,0               
        mov     hFont,rax

        invoke  GetDlgItem,hWnddlg,ID_PROGRESS
        mov     hProgress,rax
; Установить наш собственный обработчик
mov r8d,offset ProgressWindowProc
        invoke  SetWindowLongPtrA,hProgress,GWL_WNDPROC
        ; Сохранить хэндл предыдущего обработчика
        mov     OldProc,rax
wmBYE: xor eax,eax
leave
retn
DialogProc endp
WndProc proc hWnd:qword,msg:qword,wParam:qword,lParam:qword
local SizeString:qword
local text:dword
local ps:PAINTSTRUCT               
local hDC:dword
local rcClient:RECT

mov hWnd,rcx
mov lParam,r9

        cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_DESTROY
je wmDESTROY
cmp edx,WM_USER+1
je wmUSER_1
leave
jmp NtdllDialogWndProc_

wmUSER_1:mov SizeString,r9
        xor ecx,ecx
        and percent,ecx
mov [rsp+20h],rcx
movr qword ptr[rsp+28h],hThread2
mov r8d,offset TimerFuncProgress
invoke CreateThread,,0,,1
invoke CloseHandle,eax
movr qword ptr[rsp+28h],threadId
xor ecx,ecx
mov [rsp+20h],rcx
mov r8d,offset ReceiverThreadTxt
invoke CreateThread,,0,,SizeString
invoke CloseHandle,eax
jmp wmBYE
wmDESTROY:invoke CloseHandle,eventReceiverReady
xor edi,edi
@@: invoke CloseHandle,handlesH[rdi*8]
invoke CloseHandle,handlesL[rdi*8]
inc edi
cmp edi,MUTEX_DATA_COUNT
jb @b
jmp wmBYE
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + IDCANCEL
jne wmBYE
wmCLOSE:invoke EndDialog,,0

wmBYE: mov eax,TRUE
exit0: leave
retn
WndProc endp

ReceiverThreadTxt proc SizeString:dword
local index:byte
local value:byte
local buffer[256]:byte
local begin:dword

lea edi,buffer
add ecx,edi
mov SizeString,ecx
and byte ptr[rdi],0
        invoke  SetDlgItemTextA,hWnd,ID_TXT,edi
invoke GetTickCount
mov begin,eax
        invoke  SetDlgItemTextA,hWnd,ID_TXT1,edi

invoke SetEvent,eventReceiverReady
@@: mov edx,offset handlesL
invoke WaitForMultipleObjects,MUTEX_DATA_COUNT,,FALSE,INFINITE
mov index,al
invoke ReleaseMutex,handlesL[rax*8]
        mov edx,offset handlesH
invoke WaitForMultipleObjects,MUTEX_DATA_COUNT,,FALSE,INFINITE
mov value,al
invoke ReleaseMutex,handlesH[rax*8]
mov al,value
shl al,4
or al,index
;----------------------------------------------
stosb
        invoke SetEvent,hEventAck
cmp edi,SizeString
jb @b
;--------------------------------------------------
lea r8d,buffer
        invoke  SetDlgItemTextA,hWnd,ID_TXT
invoke ResetEvent,eventReceiverReady
;--------------------------------------------------
        invoke GetTickCount
sub eax,begin
mov r8d,eax
mov edx,offset fmt
lea ecx,buffer
        invoke  wsprintfA
lea r8d,buffer
invoke  SetDlgItemTextA,hWnd,ID_TXT1
leave
xor eax,eax
ret
ReceiverThreadTxt endp

TimerFuncProgress proc lParam:qword
mov lParam,rcx
; Сформировать строку для отрисовки
@@: mov r8d,percent
mov edx,offset szText
mov ecx,offset buff
        invoke  wsprintfA
; Назначить строку свойством ProgressBar
mov r8d,offset buff
mov edx,offset szProp
        invoke  SetPropA,hProgress
; Назначить значение процента свойством ProgressBar
mov r8d,percent
mov edx,offset szPerc
        invoke  SetPropA,hProgress
; Перерисовать содержимое окна
        invoke  InvalidateRect,hProgress,0,FALSE
        inc     percent
        cmp     percent,101
        je exit0
invoke Sleep,lParam
jmp @b
exit0: leave
ret
TimerFuncProgress endp

ProgressWindowProc proc hEdit:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local text:dword
local ps:PAINTSTRUCT               
local hDC:dword
local rcClient:RECT

mov hEdit,rcx
mov uMsg,rdx
mov wParam,r8
mov lParam,r9
cmp edx,WM_PAINT
je wmPAINT
mov [rsp+20h],r9;lParam
mov r9,wParam
mov r8,uMsg
mov rdx,hEdit
        invoke  CallWindowProcA,OldProc
jmp wmBYE
wmPAINT:; Размеры окна
        lea     edx,rcClient
        invoke  GetClientRect,hEdit;,edi
        ; Получить текст из свойств
mov edx,offset szProp
        invoke  GetPropA,hEdit;hProgress
        mov     text,eax
; Начать рисование
        lea     edx,ps
        invoke  BeginPaint,hEdit;hProgress
        mov     hDC,eax
; Шрифт
        invoke  SelectObject,hDC,hFont
        invoke  SetBkMode,hDC,TRANSPARENT
; Отрисовать общий фон
        invoke  GetSysColorBrush,COLOR_WINDOW
        lea     edx,rcClient
        invoke  FillRect,hDC,,eax
; Текст для отрисовки есть?
        cmp     text,0
        je      @f
        invoke  GetSysColor,COLOR_WINDOWTEXT
        invoke  SetTextColor,hDC,eax
mov edx,offset buff
mov qword ptr[rsp+20h],DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER or DT_CENTER
        lea     r9d,rcClient
        invoke  DrawTextA,hDC,,-1               
@@:; Вычислить размеры области для заливки
mov edx,offset szPerc
        invoke  GetPropA,hEdit;hProgress
        mov     ecx,eax
        lea     r9d,rcClient
        mov     eax,[r9].RECT.right
        sub     eax,[r9].RECT.left
        mul     ecx
        xor     edx,edx
        mov     ecx,100
        div     ecx
; Позиция выполненного прогресса
        add     eax,[r9].RECT.left
; Наложить выполненный прогресс
mov ecx,[r9].RECT.left
mov edx,[r9].RECT.top
mov r9d,[r9].RECT.bottom
        invoke  CreateRectRgn,,,eax
        invoke  SelectClipRgn,hDC,eax
        invoke  GetSysColorBrush,COLOR_HIGHLIGHT
lea     edx,rcClient
        invoke  FillRect,hDC,,eax
; Текст для отрисовки есть?
        cmp     text,0
        je      @f
        invoke  GetSysColor,COLOR_HIGHLIGHTTEXT
        invoke  SetTextColor,hDC,eax
mov qword ptr[rsp+20h],DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER or DT_CENTER
mov edx,offset buff
        lea     r9d,rcClient
        invoke  DrawTextA,hDC,,-1
@@: lea     edx,ps
        invoke  EndPaint,hDC
xor eax,eax
wmBYE: leave
ret
ProgressWindowProc endp
;-----------------------------------------------------------------------
.data
szWin db "Mutex Sender",0
Error1 db "The server is not running.",10,"Run?",0
szAppName db "Mutex Reciever",0
szService db "09s",0
hWnd dq ?
buff db 100 dup(?)
szText  db '%u%% completed',0
percent dd 0
hProgress dq ?
hFont dq ?
szProp db 'text',0
szPerc db 'percent',0
szFont db "Verdana",0
OldProc dq ?
hThread2 dq ?
align 10h
eventReceiverReady dq ?
threadHandle dq ?
threadId dd ?
handlesH dq 16 dup(?)
handlesL dq 16 dup(?)
hEventAck dq ?
fmtH db "MtxDataH:%u",0
fmtL db "MtxDataL:%u",0
Format5 db "Song_of_the_South_A",0
EVENT_RECEIVER_READY     db "EvReceiverReady",0
fmt db '%u',0
end
09r.rc
Code: [Select]
#include "resource.h"
#define IDC_DIALOG 200
#define ID_TXT 100
#define ID_ICON 102
#define ID_PROGRESS 106
#define ID_TXT1 107

IDC_DIALOG DIALOGEX 0,0,212,154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Mutex Reciever"

{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 2,-3,207,24
CONTROL "", ID_TXT, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 5, 5, 199, 13
CONTROL "", ID_PROGRESS, STATIC, WS_CHILD | WS_VISIBLE | WS_DISABLED |
WS_BORDER, 2, 22, 146, 19
CONTROL "Exit", IDCANCEL, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 25, 60, 15
CONTROL "",ID_ICON, STATIC, SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "",ID_TXT1, STATIC, SS_LEFT | SS_NOPREFIX | WS_CHILD |
WS_VISIBLE | WS_BORDER | WS_TABSTOP, 149, 45, 60, 13
}
09s.asm (Server)
Code: [Select]
; GUI #
include win64a.inc
ID_TXT equ 100
ID_SEND_TXT equ 101
ID_SEND_ICO equ 102
ID_SEND_WAV equ 103
IDC_IMG1 equ 104
IDC_DIALOG equ 200
IDC_ICON1 equ 500

MUTEX_DATA_COUNT = 16
size_of_buffer = 96
MUTEX_ALL_ACCESS equ 1F0001h

.code
WinMain proc
enter 30h,0
mov r9d,256;cx
mov [rbp-10h],r9
mov qword ptr [rbp-8],LR_DEFAULTCOLOR
invoke LoadImageA,IMAGE_BASE,IDC_ICON1,IMAGE_ICON;,256,256,LR_DEFAULTCOLOR
mov r9d,offset DialogProc
mov qword ptr[rbp-10h],rax;30h-10h=+20h
invoke DialogBoxParamA,IMAGE_BASE,IDC_DIALOG,HWND_DESKTOP
invoke RtlExitUserProcess,NULL
WinMain endp

DialogProc proc hWnddlg:QWORD,uMsg:QWORD,wParam:QWORD,lParam:QWORD
local MutexName[256]:word
local SizeString:dword
local hFile:qword
local szReadWrite:qword ;number of bytes actually read or write
local hResource:qword
local pResource:qword
local temp:qword

mov hWnddlg,rcx
mov lParam,r9

cmp edx,WM_INITDIALOG
je wmINITDIALOG
cmp edx,WM_CLOSE
je wmCLOSE
cmp edx,WM_COMMAND
je wmCOMMAND
cmp edx,WM_DESTROY
je wmDESTROY
xor eax,eax
jmp exit0
wmINITDIALOG:mov hWnd,rcx
invoke GetDlgItem,,IDC_IMG1
invoke SendMessageA,eax,STM_SETIMAGE,IMAGE_ICON,lParam
;Create Sync Objects
xor edi,edi
@@: lea ecx,MutexName
mov edx,offset fmtH
invoke wsprintfA,,,edi
lea r8d,MutexName
invoke CreateMutex,0,TRUE
mov mutexesH[rdi*8],rax

lea ecx,MutexName
mov edx,offset fmtL
invoke wsprintfA,,,edi
lea r8d,MutexName
invoke CreateMutex,0,TRUE
mov mutexesL[rdi*8],rax
inc edi
cmp edi,MUTEX_DATA_COUNT
jb @b

mov r9d,offset Format5
invoke CreateEvent,0,TRUE,FALSE
mov hEventAck,rax

mov r9d,offset EVENT_RECEIVER_READY
invoke CreateEvent,NULL,TRUE,FALSE
mov eventReceiverReady,rax
jmp wmBYE
wmSEND_TXT:lea r8d,MutexName
invoke GetDlgItemTextA,hWnd,ID_TXT,,256
inc eax
mov SizeString,eax
;-----------------------------------------------
mov edx,offset szWin
invoke  FindWindowA,NULL
invoke PostMessageA,eax,WM_USER+1,hWnddlg,SizeString
;Send Data--------------------------------------
invoke WaitForSingleObject,eventReceiverReady,500       
        lea esi,MutexName
mov eax,esi
add eax,SizeString
mov SizeString,eax
@@: movzx edi,byte ptr[rsi]
and edi,0Fh
invoke ReleaseMutex,mutexesL[rdi*8]
mov rax,mutexesL[rdi*8]
invoke Sleep,1
invoke WaitForSingleObject,mutexesL[rdi*8],INFINITE

movzx edi,byte ptr[rsi]

shr edi,4
invoke ReleaseMutex,mutexesH[rdi*8]
invoke Sleep,1
invoke WaitForSingleObject,mutexesH[rdi*8],INFINITE
        invoke WaitForSingleObject,hEventAck,INFINITE
        inc esi
cmp esi,SizeString;dec SizeString
jb @b
jmp wmBYE
wmSEND_ICO:
jmp wmBYE
wmSEND_WAV:
jmp wmBYE
wmDESTROY:;Close Sync Objects
invoke CloseHandle,eventReceiverReady

xor edi,edi
@@: invoke CloseHandle,mutexesH[rdi*8]
invoke CloseHandle,mutexesL[rdi*8]
inc edi
cmp edi,MUTEX_DATA_COUNT
jb @b
invoke CloseHandle,hEventAck
jmp wmBYE
; ---------------------------------------------------------------------------
wmCOMMAND:cmp r8d,BN_CLICKED shl 16 + ID_SEND_TXT
        je      wmSEND_TXT
cmp     r8d,BN_CLICKED shl 16 + IDCANCEL
        jne     wmBYE
wmCLOSE:invoke EndDialog,,0
wmBYE: mov eax,TRUE
exit0: leave
retn
DialogProc endp
;---------------------------------------
.data
szWin db "Mutex Reciever",0
hWnd dq ?
EVENT_RECEIVER_READY db "EvReceiverReady",0
Format5 db "Song_of_the_South_A",0
fmtH db "MtxDataH:%u",0
fmtL db "MtxDataL:%u",0
p1 dd 2
wav_file db '..\Images\03.wav',0
align 10h
mutexesH dq 16 dup(?)
mutexesL dq 16 dup(?)
eventReceiverReady dq ?
hEventAck dq ?
p dq ?
end
09s.rc
Code: [Select]
#include "resource.h"
#define ID_TXT 100
#define ID_SEND_TXT 101
#define ID_SEND_ICO 102
#define ID_SEND_WAV 103
#define IDC_IMG1 104

#define IDC_DIALOG 200
#define IDC_ICON1 500

IDC_ICON1 ICON "..\\Images\\icon1.ico"
IDC_ICON2 ICON "..\\Images\\icon2.ico"

IDC_DIALOG DIALOGEX 0, 0, 212, 154
STYLE DS_MODALFRAME | DS_CENTER | WS_CAPTION | WS_MINIMIZEBOX |
WS_SYSMENU | WS_VISIBLE | WS_OVERLAPPED | DS_MODALFRAME | DS_3DLOOK
CAPTION "Mutex Sender"
{
CONTROL "",-1,BUTTON,BS_GROUPBOX | WS_CHILD | WS_VISIBLE,2,-1,207,24
CONTROL "",IDC_IMG1,STATIC,SS_ICON | WS_CHILD | WS_VISIBLE,3,40,128,128
CONTROL "Write something and click 'Send Text'",ID_TXT,EDIT,ES_LEFT |
ES_AUTOHSCROLL|WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP,5,7,199,13
CONTROL "Send Text", ID_SEND_TXT, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP, 149, 27, 60, 15
CONTROL "Send ICO", ID_SEND_ICO, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP | WS_DISABLED, 149, 45, 60, 15
CONTROL "Send WAV", ID_SEND_WAV, BUTTON, BS_PUSHBUTTON | WS_CHILD |
WS_VISIBLE | WS_TABSTOP | WS_DISABLED, 149, 65, 60, 15
CONTROL "Exit",IDCANCEL,BUTTON,BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE |
WS_TABSTOP, 149, 85, 60, 15
}
« Last Edit: August 22, 2022, 08:35:08 AM by Mikl__ »

jj2007

  • Member
  • *****
  • Posts: 13932
  • Assembly is fun ;-)
    • MasmBasic
Re: Interprocess communication
« Reply #12 on: August 18, 2022, 06:46:58 PM »
Fantastic tutorial, Mikl :eusa_dance:

Next step would be to test which is the fastest (but I don't volunteer for that one, too much other stuff on my todo list). It might be shared DLLs :cool:

I tried googling "IPC" "shared DLL" "faster" "wm_copydata" and got only 5 results, with VB6 on top (see the last answer in that thread).

Mikl__

  • Member
  • *****
  • Posts: 1345
Re: Interprocess communication
« Reply #13 on: August 18, 2022, 08:53:46 PM »
Ciao, jj2007! Grazie mille per i complimenti!
Tutorial about interprocess communication is here. To repeat these tutorials in masm32.com, I'm missing two things:
  • poor knowledge of English
  • inability to build tables in masm32.com
to your question
Quote
Next step would be to test which is the fastest
I can answer which of the ways are the slowest, these are Interprocess Synchronization: Event Pipes, Mutexes and Semaphores. I even had to maden a progress bar to prevent the user from exiting the program before the data was transferred.
« Last Edit: August 19, 2022, 09:00:14 AM by Mikl__ »

learn64bit

  • Member
  • **
  • Posts: 188
Re: Interprocess communication
« Reply #14 on: August 18, 2022, 11:45:08 PM »
Thanks for share.

I'm reading the "12 WinSockets", I think I need "win64a.inc" and "ws2_32.inc", maybe mine is out dated, or should I download the "IPC.zip" (sorry, I don't know Russian)?