Global memory in windows programming

Creating Named Shared Memory

To share data, multiple processes can use memory-mapped files that the system paging file stores.

First Process

The first process creates the file mapping object by calling the CreateFileMapping function with INVALID_HANDLE_VALUE and a name for the object. By using the PAGE_READWRITE flag, the process has read/write permission to the memory through any file views that are created.

Then the process uses the file mapping object handle that CreateFileMapping returns in a call to MapViewOfFile to create a view of the file in the process address space. The MapViewOfFile function returns a pointer to the file view, pBuf . The process then uses the CopyMemory function to write a string to the view that can be accessed by other processes.

Prefixing the file mapping object names with «Global\» allows processes to communicate with each other even if they are in different terminal server sessions. This requires that the first process must have the SeCreateGlobalPrivilege privilege.

When the process no longer needs access to the file mapping object, it should call the CloseHandle function. When all handles are closed, the system can free the section of the paging file that the object uses.

Second Process

A second process can access the string written to the shared memory by the first process by calling the OpenFileMapping function specifying the same name for the mapping object as the first process. Then it can use the MapViewOfFile function to obtain a pointer to the file view, pBuf . The process can display this string as it would any other string. In this example, the message box displayed contains the message «Message from first process» that was written by the first process.

GlobalMemoryStatus function (winbase.h)

[GlobalMemoryStatus can return incorrect information. Use the GlobalMemoryStatusEx function instead.]

Retrieves information about the system’s current usage of both physical and virtual memory.

Syntax

Parameters

A pointer to a MEMORYSTATUS structure. The GlobalMemoryStatus function stores information about current memory availability into this structure.

Return value

Remarks

On computers with more than 4 GB of memory, the GlobalMemoryStatus function can return incorrect information, reporting a value of –1 to indicate an overflow. For this reason, applications should use the GlobalMemoryStatusEx function instead.

On Intel x86 computers with more than 2 GB and less than 4 GB of memory, the GlobalMemoryStatus function will always return 2 GB in the dwTotalPhys member of the MEMORYSTATUS structure. Similarly, if the total available memory is between 2 and 4 GB, the dwAvailPhys member of the MEMORYSTATUS structure will be rounded down to 2 GB. If the executable is linked using the /LARGEADDRESSAWARE linker option, then the GlobalMemoryStatus function will return the correct amount of physical memory in both members.

The information returned by the GlobalMemoryStatus function is volatile. There is no guarantee that two sequential calls to this function will return the same information.

Windows Programming/Memory Subsystem

C programmers will undoubtedly be familiar with the stdlib memory allocation functions, malloc, realloc, calloc, etc. These functions are based off a number of other functions in the Win32 API that deal with memory segments.

Contents

Windows Memory [ edit | edit source ]

When talking about the memory subsystem, there are 4 distinct types of memory that Windows manages, and each type of memory has a number of different functions to allocate and free that memory.

Virtual Memory The Virtual Memory subsystem allocates and manages memory by pages. This means that memory can only be allocated in blocks of 4 Kbytes (or larger, depending on processor architecture) at a time. This is a fantastically large amount of memory for most applications, and using the virtual memory functions in most programs is overkill. However, some programs do need use of entire pages for storage, so the Virtual Memory subsystem can be used for that. Heap Memory The heap is an area of memory that usually takes up a whole page, or a fraction of a page. Each process is allocated a heap immediately by windows, called the process heap. The stdlib functions such as malloc will allocate memory from this memory region. The heap can be divided up into small memory segments, for use with variables and dynamic storage. Global Memory Windows maintains at least 1 page of memory for use as general-purpose global memory. This memory can be read or written by any process running on the computer, using the global memory functions. Data in the global memory space can be shared among various programs, and items sent to the windows clipboard are generally stored in global memory (so it can be «pasted» into any program). Global memory is limited, so it should not be used without a specific need. LocalMemory Local memory has similarities to both global memory and heap memory. It is local to the process, but the memory is managed by the Windows memory manager, and not by the program. We will discuss this later.

Читайте также:  Custom folders in windows

Virtual Memory Subsystem [ edit | edit source ]

The virtual memory functions, as explained above, allocate memory in terms of pages. Pages are generally 4 Kbytes of memory, so most applications won’t need to allocate an entire page (much less more then 1 page). The Virtual memory system is essentially the primitive function base that the other memory functions utilize to perform their tasks. For instance, the heap is comprised of 1 or more pages, and the heap functions will allocate pages using the virtual memory system when needed.

When virtual memory blocks are allocated, they are not actually being utilized, they are simply reserved by the system for future use. Other functions need to be used to segment the virtual memory pages into useful segments. Since virtual memory is allocated by pages, a number of special paging features can be used on virtual memory that can not be used on other types of memory. For instance, pages can be locked (to prevent read/write access), or they can be protected from any particular access mode (read, write, execute).

That said, there are a number of functions in the virtual memory subsystem that can be used:

VirtualAlloc VirtualFree VirtualProtect VirtualLock VirtualQuery

Heap Memory [ edit | edit source ]

Each program is provided with a default process heap, but a process may optionally allocate any number of additional heaps, if more storage is needed. The heap functions will manage their virtual memory usage automatically, and therefore heaps can be set to grow if they are being filled up with data. If a heap is allowed to grow automatically, the heap functions will automatically allocate additional pages as needed. On the x86 architecture the heap grows in size towards higher memory addresses.

To use heap memory, a heap must first be allocated (or a handle must be obtained to the default heap). Once you have obtained a handle to a heap, you can pass that handle to the memory allocation functions, to allocate memory from that particular heap.

The stdlib memory functions (malloc, realloc, calloc, free) are all used very similarly to the heap functions, so programmers familiar with the stdlib functions may be able to figure out what many of the heap functions are doing, by examining their names:

HeapCreate Allocates a heap, and returns a handle to that heap. All the other heap functions will use this handle to uniquely identify the particular heap that you are accessing. By maintaining multiple handles, your program may interface with multiple separate heaps. HeapDestroy This function closes a heap handle, and deallocates the heap memory so that other processes can use it. GetProcessHeap This function returns a handle to the default process heap. Each program gets a default heap when it is loaded, and in most applications this should be enough space to store data items. HeapAlloc Similar to the STDLIB «malloc» function, HeapAlloc allocates storage space on the heap, and returns a pointer to that space. HeapReAlloc Similar to the STDLIB «realloc» function, HeapReAlloc reallocates the storage space of a variable to be a different size. HeapFree Frees a memory object on the heap. Attempts to use the same pointer to access memory after it has been freed will cause an error.

Global Memory [ edit | edit source ]

Windows maintains a certain amount of global heap memory. This memory is limited compared to regular process heaps, and should not be accessed unless global memory is specially required.

When data has been written to the global memory, you don’t get a pointer to that data, but instead you get a handle for that data. Once you give your data to the global memory manager, the system is in charge of it. Remember, a handle is not a pointer, and should never be used as one. The system will manage the memory in the global memory section, moving it between pages, and defragmenting it, et cetera. Data doesn’t reside within a single segment

Читайте также:  System windows control grid

GlobalAlloc GlobalFree GlobalDiscard GlobalLock GlobalUnlock GlobalFlags GlobalSize GlobalHandle

Local Memory [ edit | edit source ]

Local memory, in this sense, is not the kind of storage that programs utilize internally, on the stack and otherwise. Instead, Windows manages a special section of memory that it dubs to be «Local Memory», and it provides a number of functions to allocate and manage this special memory. Local memory is similar to global memory in the sense that data is written to the local location, and the system returns a handle to that data. The system will manage the data, just like in global memory. The local functions are named very similarly to the global memory functions. However, the global memory and local memory functions should never be mixed. For instance, a global memory handle should never be closed with the LocalFree function.

LocalAlloc LocalFree LocalDiscard LocalFlags LocalLock LocalReAlloc LocalUnlock LocalHandle

Viewing and Editing Memory in WinDbg

In WinDbg, you can view and edit memory by entering commands or by using a Memory window.

Debugger Command Window

You can view memory by entering one of the Display Memory commands in the Debugger Command window. You can edit memory by entering one of the Enter Values commands in the Debugger Command window. For more information, see Accessing Memory by Virtual Address and Accessing Memory by Physical Address.

Opening a Memory Window

To open a Memory window, choose Memory from the View menu. (You can also press ALT+5 or select the Memory button () on the toolbar. ALT+SHIFT+5 closes the active Memory window.)

The following screen shot shows an example of a Memory window.

Using a Memory Window

The Memory window displays data in several columns. The column on the left side of the window shows the beginning address of each line. The remaining columns display the requested information, from left to right. If you select Bytes in the Display format menu, the ASCII characters that correspond to these bytes are displayed in the right side of the window.

NoteВ В By default, the Memory window displays virtual memory. This type of memory is the only type of memory that is available in user mode. In kernel mode, you can use the Memory Options dialog box to display physical memory and other data spaces. The Memory Options dialog box is described later in this topic.

In the Memory window, you can do the following:

To write to memory, select inside the Memory window and type new data. You can edit only hexadecimal data—you cannot directly edit ASCII and Unicode characters. Changes take effect as soon as you type new information.

To see other sections of memory, use the Previous and Next buttons on the Memory window toolbar, or press the PAGE UP or PAGE DOWN keys. These buttons and keys display the immediately preceding or following sections of memory. If you request an invalid page, an error message appears.

To navigate within the window, use the RIGHT ARROW, LEFT ARROW, UP ARROW, and DOWN ARROW keys. If you use these keys to move off of the page, a new page is displayed. Before you use these keys, you should resize the Memory window so that it does not have scroll bars. This sizing enables you to distinguish between the actual page edge and the window cutoff.

To change the memory location that is being viewed, enter a new address into the address box at the top of the Memory window. Note that the Memory window refreshes its display while you enter an address, so you could get error messages before you have completed typing the address. NoteВ В The address that you enter into the box is interpreted in the current radix. If the current radix is not 16, you should prefix a hexadecimal address with 0x. To change the default radix, use the n (Set Number Base) command in the Debugger Command window. The display within the Memory window itself is not affected by the current radix.

To change the data type that the window uses to display memory, use the Display format menu in the Memory window toolbar. Supported data types include short words, double words, and quad-words; short, long, and quad integers and unsigned integers; 10-byte, 16-byte, 32-byte, and 64-byte real numbers; ASCII characters; Unicode characters; and hexadecimal bytes. The display of hexadecimal bytes includes ASCII characters as well.

Читайте также:  Как открыть другое окно windows

The Memory window has a toolbar that contains two buttons, a menu, and a box and has a shortcut menu with additional commands. To access the menu, select and hold (or right-click) the title bar or select the icon near the upper-right corner of the window (). The toolbar and shortcut menu contain the following choices:

(Toolbar only) The address box enables you to specify a new address or offset. The exact meaning of this box depends on the memory type you are viewing. For example, if you are viewing virtual memory, the box enables you to specify a new virtual address or offset.

(Toolbar only) Display format enables you to select a new display format.

(Toolbar and menu) Previous (on the toolbar) and Previous page (on the shortcut menu) cause the previous section of memory to be displayed.

(Toolbar and menu) Next (on the toolbar) and Next page (on the shortcut menu) cause the next section of memory to be displayed.

(Menu only) Toolbar turns the toolbar on and off.

(Menu only) Auto-fit columns ensures that the number of columns displayed in the Memory window fits the width of the Memory window.

(Menu only) Dock or Undock causes the window to enter or leave the docked state.

(Menu only) Move to new dock closes the Memory window and opens it in a new dock.

(Menu only) Set as tab-dock target for window type sets the selected Memory window as the tab-dock target for other Memory windows. All Memory windows that are opened after one is chosen as the tab-dock target are automatically grouped with that window in a tabbed collection.

(Menu only) Always floating causes the window to remain undocked even if it is dragged to a docking location.

(Menu only) Move with frame causes the window to move when the WinDbg frame is moved, even if the window is undocked. For more information about docked, tabbed, and floating windows, see Positioning the Windows.

(Menu only) Properties opens the Memory Options dialog box, which is described in the following section within this topic.

(Menu only) Help opens this topic in the Debugging Tools for Windows documentation.

(Menu only) Close closes this window.

Memory Options Dialog Box

When you select Properties on the shortcut menu, the Memory Options dialog box appears.

In kernel mode, there are six memory types available as tabs in this dialog box: Virtual Memory, Physical Memory, Bus Data, Control Data, I/O (I/O port information), and MSR (model-specific register information). Select the tab that corresponds to the information that you want to access.

In user mode, only the Virtual Memory tab is available.

Each tab enables you to specify the memory that you want to display:

In the Virtual Memory tab, in the Offset box, specify the address or offset of the beginning of the memory range that you want to view.

In the Physical Memory tab, in the Offset box, specify the physical address of the beginning of the memory range that you want to view. The Memory window can display only described, cacheable physical memory. If you want to display physical memory that has other attributes, use the d* (Display Memory) command or the !d\* extension.

In the Bus Data tab, in the Bus Data Type menu, specify the bus data type. Then, use the Bus number, Slot number, and Offset boxes to specify the bus data that you want to view.

In the Control Data tab, use the Processor and Offset text boxes to specify the control data that you want to view.

In the I/O tab, in the Interface Type menu, specify the I/O interface type. Use the Bus number, Address space, and Offset boxes to specify the data that you want to view.

In the MSR tab, in the MSR box, specify the model-specific register that you want to view.

Each tab also includes a Display format menu. This menu has the same effect as the Display format menu in the Memory window.

Select OK in the Memory Options dialog box to cause your changes to take effect.

Additional Information

For more information about memory manipulation and a description of other memory-related commands, see Reading and Writing Memory.

Оцените статью