Memory-mapped files for the Assembly tutorial

Source: Internet
Author: User
Tags include win32 advantage

In this lesson we'll talk about memory-mapped files and demonstrate how to use them. You will find that using memory-mapped files is very simple.

Theory:

If you have studied the example of the previous lesson carefully, you will find that it has a serious flaw: what if you want to read more than the system allocates memory blocks? What if you want to search for a string that just exceeds the bounds of the memory block? For the first question, you might say, just keep reading and not solve it. As for the second question, you will also say that you can do some special processing on the boundary of the memory block, such as putting a bit of flag on it. It really works, but it's very difficult to deal with the complexity of the problem. The second problem is the famous boundary judgment problem, which is caused by many errors in the program. Think about how good it would be if we could allocate a large chunk of memory that could hold the entire file, so that these two problems are solved? Yes, WIN32 's memory-mapped file does allow us to allocate a memory that can be large enough to exist in reality.

With memory-mapped files you can assume that the operating system has loaded all the files into memory for you, and then just move the file pointer to read and write. This way you don't even need to invoke API functions that allocate, free chunks of memory and file input/output, and you can use this as a way to share data between different processes. Using a memory-mapped file does not actually involve actual file operations, it is more like reserving a visible memory space for each process. As for using a memory-mapped file as a way to share data between processes, be extra careful because you have to deal with data synchronization issues, or your application may be likely to get outdated or incorrect data or even crashes. In this lesson we will focus on memory-mapped files and will not involve synchronization between processes. Memory-mapped files in WIN32 are widely used, such as: even the core modules of the system---the PE format file loader is also used in memory-mapped files, because the PE format file is not loaded into memory at one time, for example, it only loads the necessary load in the first load of the part, While other parts are loaded when used, this is just the advantage of the memory-mapped file. Most file accesses in practice are similar to the PE loader, so you should take full advantage of memory-mapped files when dealing with this type of problem.

The memory-mapped file itself has some limitations, such as once you generate a memory-mapped file, you cannot change its size during that session. Therefore, memory-mapped files are useful for read-only files and for file operations that do not affect their size. This does not mean, of course, that for file operations that can cause a change in size, you can't use memory to insinuate files, you can estimate the possible size of the file after the operation, and then generate a memory-mapped file of this size, and then the length of the file can grow to such a size. We've explained enough, and then we'll look at the details of the implementation:

Call CreateFile to open the file you want to map.

Call CreateFileMapping, which requires passing in the handle returned by the previous CreateFile, which generates a memory-mapped object based on the file object created by the CreateFile function.

Call the MapViewOfFile function to map an entire file's area or entire file to memory. The function returns a pointer to the first byte mapped to memory.

Use this pointer to read and write files.

Call UnmapViewOfFile to unlock file mappings.

Call CloseHandle to close the memory-mapped file. Note the handle of the memory-mapped file must be passed in.

Call CloseHandle to close the file. Note You must pass in the handle of the file created by CreateFile.

Example:

The following example allows a user to open a file through the Open File dialog box and then open the file with a memory-mapped file, and if successful, the window's title bar displays the name of the open file, and you can save the name by selecting the "File/save" menu item. The program will save the contents of the open file in a new file. Note that you simply do not have the function to allocate memory like GlobalAlloc in this whole process.

.386
. Model Flat,stdcall
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
. Data
ClassName db "Win32asmfilemappingclass", 0
AppName db "Win32 ASM File Mapping Example", 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)
Hmapfile HANDLE 0; Handle to the memory mapped file, must is
; initialized with 0 because we also use it as
A flag in Wm_destroy section too
. Data?
HINSTANCE hinstance?
CommandLine LPSTR?
Hfileread HANDLE?; Handle to the source file
Hfilewrite HANDLE?; Handle to the output file
Hmenu HANDLE?
Pmemory DWORD?; Pointer to the "data in the" source file
Sizewritten DWORD?; Number of bytes actually written by WriteFile
. 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:dword
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 Hwnd:hwnd, Umsg:uint, Wparam:wparam, Lparam:lparam
. IF umsg==wm_create
Invoke Getmenu,hwnd obtain the menu handle
MOV hmenu,eax
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_destroy
. If hmapfile!=0
Call Closemapfile
. endif
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, \
0,\
Null,open_existing,file_attribute_archive,\
Null
MOV hfileread,eax
Invoke Createfilemapping,hfileread,null,page_readonly,0,0,null
MOV hmapfile,eax
MOV Eax,offset buffer
MOVZX Edx,ofn.nfileoffset
Add Eax,edx
Invoke Setwindowtext,hwnd,eax
Invoke enablemenuitem,hmenu,idm_open,mf_grayed
Invoke enablemenuitem,hmenu,idm_save,mf_enabled
. endif
. 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 hfilewrite,eax
Invoke mapviewoffile,hmapfile,file_map_read,0,0,0
MOV pmemory,eax
Invoke Getfilesize,hfileread,null
Invoke Writefile,hfilewrite,pmemory,eax,addr Sizewritten,null
Invoke Unmapviewoffile,pmemory
Call Closemapfile
Invoke Closehandle,hfilewrite
Invoke Setwindowtext,hwnd,addr AppName
Invoke enablemenuitem,hmenu,idm_open,mf_enabled
Invoke enablemenuitem,hmenu,idm_save,mf_grayed
. endif
. else
Invoke DestroyWindow, HWnd
. endif
. endif
. ELSE
Invoke Defwindowproc,hwnd,umsg,wparam,lparam
Ret
. ENDIF
XOR Eax,eax
Ret
WndProc ENDP
Closemapfile PROC
Invoke Closehandle,hmapfile
MOV hmapfile,0
Invoke Closehandle,hfileread
Ret
Closemapfile ENDP
End Start

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.