Assemble memory management and file input and output

Source: Internet
Author: User
Tags readfile win32

In this lesson, we will learn about the basics of memory management and file input/output operations. In addition, we will use the general dialog of the class as our display "device."
Theory:

From the user's point of view, WIN32 's memory management is very simple and straightforward. Each application has its own independent 4G address space, this memory pattern is called the "flat" type of address mode, all of the segment registers or descriptors point to the same starting address, all address offsets are 32-bit length, so that an application without the transformation selector can access their own up to 4G of address space. This memory management pattern is very concise and manageable, and we don't have to deal with annoying "near" and "far" pointers.
There are two main types of APIs under W16: Global and Local. The "global" APIs are allocated in other segments so that they are "far" (far) functions or called far process calls from the memory point of view, and the "local" APIs, as long as they deal with the heap of processes, call them "near" (near) functions or near-process calls. In WIN32, the two memory patterns are the same, regardless of whether you call GlobalAlloc or LocalAlloc, the result is the same.
The process of allocating and using memory is the same:

The GlobalAlloc function is called to allocate a chunk of memory that returns the allocated memory handle.
Call the GlobalLock function to lock a block of memory that takes a memory handle as a parameter and then returns a pointer to the locked block of memory.
You can use this pointer to read and write memory.
Call the GlobalUnlock function to unlock previously locked memory, which invalidates the pointer to the memory block.
Call the GlobalFree function to free the memory block. You must pass the function a memory handle.
In WIN32 you can also use "local" to replace the memory allocation API function with the word "global" in the function "global", that is, with LocalAlloc, LocalLock, and so on.
Using the GMEM_FIXED flag bit when calling function GlobalAlloc can further simplify the operation. With this flag, GLOBAL/LOCALALLOC returns a pointer to the allocated memory instead of a handle, so that you do not have to call Global/locallock to lock the memory, as long as you can simply call Global/localfree when you release the memory. But in this lesson we only use the traditional approach, because there are a lot of source code written in this way elsewhere.

WIN32 's file input/output APIs are almost the same as those seen in DOS (translator note: Perhaps no matter how different the internal implementations may be, it is conceivable that all file systems should have the same functionality as the interface to the application writer, except that the DOS interrupt mode is used to process the file input. The output becomes a call to an API function. The following are the basic steps:

Call the CreateFile function to generate a file that can be applied in many ways, and can be used to open communication ports, pipes, drivers, or consoles in addition to disk files. If successful, a handle to the file or device is returned. You can then use the handle to complete the operation of the file or device.
Call SetFilePointer to move the file pointer to where you want to read and write ...
Then call ReadFile or WriteFile to complete the actual reading and writing. These functions handle the data transfer between the file and the memory itself, so that you do not have to do the miscellaneous chores of allocating memory.
Call CloseHandle to close the file. This function accepts a file handle that was previously opened.
Content:

The following code snippet demonstrates opening an open File dialog box, where the user can choose to open a text file and then open the text file's contents in an edit control, and the user can edit the contents of the text file and choose to save it.

.386
. Model Flat,stdcall
Option Casemap:none
WinMain Proto:D Word,:D Word,:D Word,:D Word
Include \masm32\include\windows.inc
Include \masm32\include\user32.inc
Include \masm32\include\kernel32.inc
Include \masm32\include\comdlg32.inc
Includelib \masm32\lib\user32.lib
Includelib \masm32\lib\kernel32.lib
Includelib \masm32\lib\comdlg32.lib

. const
Idm_open equ 1
Idm_save equ 2
Idm_exit equ 3
MAXSIZE EQU 260
Memsize equ 65535

Editid equ 1; ID of the Edit control

. Data
ClassName db "Win32asmeditclass", 0
AppName db "Win32 ASM Edit", 0
Editclass db "edit", 0
MenuName db "Firstmenu", 0
Ofn OpenFileName <>
Filterstring db "All Files", 0, "*.*", 0
DB "Text Files", 0, "*.txt", 0,0
Buffer db MAXSIZE dup (0)

. Data?
HINSTANCE hinstance?
CommandLine LPSTR?
Hwndedit HWND?; Handle to the Edit control
hfile HANDLE?; File handle
Hmemory HANDLE? HANDLE to the allocated memory block
Pmemory DWORD?;p Ointer to the allocated memory block
Sizereadwrite DWORD?; Number of bytes actually read or write

. Code
Start
Invoke GetModuleHandle, NULL
MOV hinstance,eax
Invoke GetCommandLine
MOV commandline,eax
Invoke WinMain, Hinstance,null,commandline, Sw_showdefault
Invoke Exitprocess,eax

WinMain proc Hinst:hinstance,hprevinst:hinstance,cmdline:lpstr,cmdshow:sdword
Local Wc:wndclassex
Local msg:msg
Local Hwnd:hwnd
MOV wc.cbsize,sizeof wndclassex
mov wc.style, cs_hredraw or Cs_vredraw
mov wc.lpfnwndproc, OFFSET WndProc
MOV wc.cbclsextra,null
MOV wc.cbwndextra,null
Push Hinst
Pop wc.hinstance
MOV wc.hbrbackground,color_window+1
MOV Wc.lpszmenuname,offset MenuName
MOV Wc.lpszclassname,offset ClassName
Invoke Loadicon,null,idi_application
MOV wc.hicon,eax
MOV wc.hiconsm,eax
Invoke Loadcursor,null,idc_arrow
MOV wc.hcursor,eax
Invoke RegisterClassEx, addr WC
Invoke Createwindowex,ws_ex_clientedge,addr classname,addr appname,\
Ws_overlappedwindow,cw_usedefault,\
Cw_usedefault,300,200,null,null,\
Hinst,null
MOV hwnd,eax
Invoke ShowWindow, Hwnd,sw_shownormal
Invoke UpdateWindow, HWND
. While TRUE
Invoke GetMessage, ADDR msg,null,0,0
. Break. IF (!EAX)
Invoke TranslateMessage, ADDR msg
Invoke DispatchMessage, ADDR msg
. Endw
MOV Eax,msg.wparam
Ret
WinMain ENDP

WNDPROC proc uses ebx hwnd:hwnd, Umsg:uint, Wparam:wparam, Lparam:lparam
. IF umsg==wm_create
Invoke Createwindowex,null,addr editclass,null,\
Ws_visible or Ws_child or Es_left or Es_multiline or\
Es_autohscroll or es_autovscroll,0,\
0,0,0,hwnd,editid,\
Hinstance,null
MOV hwndedit,eax
Invoke Setfocus,hwndedit
;==============================================
; Initialize the members of OPENFILENAME structure
;==============================================
MOV ofn.lstructsize,sizeof ofn
Push HWnd
Pop Ofn.hwndowner
Push HINSTANCE
Pop ofn.hinstance
mov ofn.lpstrfilter, OFFSET filterstring
mov ofn.lpstrfile, OFFSET buffer
MOV ofn.nmaxfile,maxsize
. ELSEIF umsg==wm_size
MOV Eax,lparam
MOV edx,eax
SHR edx,16
and EAX,0FFFFH
Invoke Movewindow,hwndedit,0,0,eax,edx,true
. ELSEIF Umsg==wm_destroy
Invoke Postquitmessage,null
. ELSEIF Umsg==wm_command
MOV Eax,wparam
. If lparam==0
. If Ax==idm_open
mov ofn. Flags, ofn_filemustexist or \
Ofn_pathmustexist or Ofn_longnames or\
Ofn_explorer or Ofn_hidereadonly
Invoke GetOpenFileName, ADDR ofn
. If Eax==true
Invoke Createfile,addr buffer,\
Generic_read or generic_write, \
File_share_read or file_share_write,\
Null,open_existing,file_attribute_archive,\
Null
MOV hfile,eax
Invoke Globalalloc,gmem_moveable or Gmem_zeroinit,memsize
MOV hmemory,eax
Invoke Globallock,hmemory
MOV pmemory,eax
Invoke Readfile,hfile,pmemory,memsize-1,addr Sizereadwrite,null
Invoke Sendmessage,hwndedit,wm_settext,null,pmemory
Invoke Closehandle,hfile
Invoke Globalunlock,pmemory
Invoke Globalfree,hmemory
. endif
Invoke Setfocus,hwndedit
. ElseIf Ax==idm_save
mov ofn. Flags,ofn_longnames or\
Ofn_explorer or Ofn_hidereadonly
Invoke GetSaveFileName, ADDR ofn
. If Eax==true
Invoke Createfile,addr buffer,\
Generic_read or generic_write, \
File_share_read or file_share_write,\
Null,create_new,file_attribute_archive,\
Null
MOV hfile,eax
Invoke Globalalloc,gmem_moveable or Gmem_zeroinit,memsize
MOV hmemory,eax
Invoke Globallock,hmemory
MOV pmemory,eax
Invoke Sendmessage,hwndedit,wm_gettext,memsize-1,pmemory
Invoke Writefile,hfile,pmemory,eax,addr Sizereadwrite,null
Invoke Closehandle,hfile
Invoke Globalunlock,pmemory
Invoke Globalfree,hmemory
. endif
Invoke Setfocus,hwndedit
. else
Invoke DestroyWindow, HWnd
. endif
. endif
. ELSE
Invoke Defwindowproc,hwnd,umsg,wparam,lparam
Ret
. ENDIF
XOR Eax,eax
Ret
WndProc ENDP
End Start

--------------------------------------------------------------------------------

Analysis:
Invoke Createwindowex,null,addr editclass,null,\
Ws_visible or Ws_child or Es_left or Es_multiline or\
Es_autohscroll or es_autovscroll,0,\
0,0,0,hwnd,editid,\
Hinstance,null
MOV hwndedit,eax
When processing wm_create messages, we create an edit control. Notice that we set the size of the control to 0, because we'll reset the edit control later to overwrite the entire client area of the parent window.
Note: In this example we do not need to call ShowWindow to display the edit control, because the WS_VISIBLE flag bit has been set in its style at creation time, and this trick can be used when creating a parent window.

;==============================================
; Initialize the members of OPENFILENAME structure
;==============================================
MOV ofn.lstructsize,sizeof ofn
Push HWnd
Pop Ofn.hwndowner
Push HINSTANCE
Pop ofn.hinstance
mov ofn.lpstrfilter, OFFSET filterstring
mov ofn.lpstrfile, OFFSET buffer
MOV ofn.nmaxfile,maxsize

After you create the edit control, we initialize the members of the OFN variable. Because the structure body variable will be used later when you save the file, only the public part you want to use is initialized here. The processing part of the WM_CREATE message is the perfect place to do this initialization.

. ELSEIF umsg==wm_size
MOV Eax,lparam
MOV edx,eax
SHR edx,16
and EAX,0FFFFH
Invoke Movewindow,hwndedit,0,0,eax,edx,true

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.