Win32 Programming Lesson 18: More Memory Mapped Files and the HEAP (Finally, cool stuff!)

Slides:



Advertisements
Similar presentations
Process A process is usually defined as an instance of a running program and consists of two components: A kernel object that the operating system uses.
Advertisements

Data Structures Static and Dynamic.
FILE SYSTEM IMPLEMENTATION
C Programming - Lecture 5
User-Level Memory Management in Linux Programming
1 Optimizing Malloc and Free Professor Jennifer Rexford COS 217 Reading: Section 8.7 in K&R book
1 JMH Associates © 2004, All rights reserved Chapter 5 Memory Management, Memory-Mapped Files, and DLLs.
Read vs. mmap Tan Li. Man mmap #include void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset); int munmap(void *start, size_t.
Chapter 5 Part 1 COSI 11a Prepared by Ross Shaull.
Chapter 3.5 Memory and I/O Systems. Memory Management 2 Only applies to languages with explicit memory management (C, C++) Memory problems are one of.
1 Optimizing Malloc and Free Professor Jennifer Rexford
Memory Management 1 CS502 Spring 2006 Memory Management CS-502 Spring 2006.
CS-3013 & CS-502, Summer 2006 Memory Management1 CS-3013 & CS-502 Summer 2006.
1 Data Structures Data Structures Topic #2. 2 Today’s Agenda Data Abstraction –Given what we talked about last time, we need to step through an example.
The memory allocation problem Define the memory allocation problem Memory organization and memory allocation schemes.
Win32 Programming Lesson 9: Jobs & Thread Basics.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Windows Memory Management, Memory- Mapped Files, and DLLs.
Memory management under Windows The Need for Memory:-  The window environment and most applications that run under it need access to phenomenal amounts.
Moodle (Course Management Systems). Assignments 1 Assignments are a refreshingly simple method for collecting student work. They are a simple and flexible.
Win32 Programming Lesson 13: Thread Pooling (Wow, Java is good for something…)
Files COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
Heap Management. What is really stored on the heap? Housekeeping Users Data Buffer Next Block Data Housekeeping 0x7000 0x7008 int main() { int *x,*y;
Win32 Programming Lesson 16: Virtual Memory. Where are we?  We’ve covered the theory of Windows memory, and poked around some  Now let’s use how to.
Win32 Programming Lesson 1: Why We’re All Here. Why We’re Here…  Okay, maybe that’s too grandiose  Windows – in particular Win32 Thirty-what?  What.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Win32 Programming Lesson 20: Advanced DLL Techniques.
Chapter 3.5 Memory and I/O Systems. 2 Memory Management Memory problems are one of the leading causes of bugs in programs (60-80%) MUCH worse in languages.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
Win32 Programming Lesson 22: DLL Magic Part Deux All your base are belong to us…
Chapter 8 – Main Memory (Pgs ). Overview  Everything to do with memory is complicated by the fact that more than 1 program can be in memory.
Win32 Programming Lesson 7: Kernel Objects. Abstract  Many of the concepts we’ll look at today won’t make complete sense until you use them  However,
1 Data Structures - CSCI 102 CS102 C++ Pointers & Dynamic Objects Prof Tejada.
1 File Systems: Consistency Issues. 2 File Systems: Consistency Issues File systems maintains many data structures  Free list/bit vector  Directories.
Win32 Programming Lesson 14: Introducing Windows Memory (C Rox…)
Writing a Run Time DLL The application loads the DLL using LoadLibrary() or LoadLibraryEx(). The standard search sequence is used by the operating system.
1 Computer Systems II Introduction to Processes. 2 First Two Major Computer System Evolution Steps Led to the idea of multiprogramming (multiple concurrent.
CNIT 127: Exploit Development Ch 8: Windows Overflows Part 2.
Win32 Programming Lesson 17: Memory Mapped Files (Finally, cool stuff again, all this work is getting tedious!)
Processes and Virtual Memory
File Systems cs550 Operating Systems David Monismith.
Memory Management -Memory allocation -Garbage collection.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
C++ 程序语言设计 Chapter 12: Dynamic Object Creation. Outline  Object creation process  Overloading new & delete.
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Lecture 7 Page 1 CS 111 Summer 2013 Dynamic Domain Allocation A concept covered in a previous lecture We’ll just review it here Domains are regions of.
I/O Software CS 537 – Introduction to Operating Systems.
1 Device Controller I/O units typically consist of A mechanical component: the device itself An electronic component: the device controller or adapter.
Lecture 4 Page 1 CS 111 Online Modularity and Memory Clearly, programs must have access to memory We need abstractions that give them the required access.
Memory Mapped I/O Gregory Mortensen CSIS 4330, Advanced Windows Programming – UVSC.
Memory Management.
Jim Fawcett CSE 691 – Software Modeling and Analysis Fall 2000
Chapter 3: Windows7 Part 5.
Dynamic Domain Allocation
Swapping Segmented paging allows us to have non-contiguous allocations
Modularity and Memory Clearly, programs must have access to memory
Chapter 3: Windows7 Part 5.
Optimizing Malloc and Free
O.S Lecture 13 Virtual Memory.
Windows CE Memory Management
Memory Allocation CS 217.
Printed on Monday, December 31, 2018 at 2:03 PM.
Optimizing Dynamic Memory Management
OS – Memory Deallocation
January 15, 2004 Adrienne Noble
C Programming - Lecture 5
Lecture Topics: 11/20 HW 7 What happens on a memory reference Traps
SPL – PS3 C++ Classes.
Memory allocation.
Presentation transcript:

Win32 Programming Lesson 18: More Memory Mapped Files and the HEAP (Finally, cool stuff!)

Where are we?  We’ve gotten pretty familiar with the idea of memory-mapped files but there are some important concepts we haven’t looked at  Finish up today, and then look at the heap

Sharing Data  There are lots of different ways to share data between processes  But the “lowest level” way is really in memory, via a memory-mapped file Two or more processes map the same base address – hence they are sharing the same physical memory

Avoiding the “real” File system  Very inconvenient if every memory-mapped file actually had to exist on disk Imagine that you simply wanted to use the mechanism to pass data, not keep it Can call CreateFileMapping with INVALID_HANDLE_VALUE as the hFile parameter, and the memory-mapped file is backed by the page file

30 Second Quiz  What’s wrong with this code?  HANDLE hFile = CreateFile(...); HANDLE hMap = CreateFileMapping(hFile,...); if (hMap == NULL) return(GetLastError());

Answer…  You’ll get back INVALID_HANDLE_VALUE from the first call  Which means…

MMFExample  Simple program  When it maps the view of the file, it transfers data between the two programs  Nice method of sharing between two processes!

Sparsely Committing…  Remember we talked about how to commit memory for files?  Same discussion for Memory-mapped files – that is, we don’t need to commit all our memory at once

Consider  CELLDATA CellData[200][256];  If sizeof(CELLDATA) is 128 that’s about 6MB.  Better to share as a sparsely-committed file mapping object  If we’re sharing via the paging file, can use SEC_RESERVE or SEC_COMMIT

SEC_RESERVE  When you pass in SEC_RESERVE you don’t actually commit the space  Just returns a HANDLE to the file mapping object  Any attempts to access the memory cause a memory violation

VirtualAlloc (again)  Solution: Call VirtualAlloc to allocate the memory as we use it!

The HEAP  Heap is a fantastic tool for allocating small blocks of memory Perfect for linked lists and trees Advantage: can ignore allocation granularity Disadvantage: slow, with no direct control of physical allocation Better yet, internals not entirely documented

Default  Each process gets a default heap of 1MB  Can specify at link time (/HEAP:)  Used by many Windows/C RTL functions  Access to the HEAP is serialized (why, and what does this mean?)  Can obtain a handle via: HANDLE GetProcessHeap();

More than 1 Heap is a…  Five reasons you might want to do this: Component protection More efficient memory management Local access Avoiding thread sync overhead Quick free

1: Component Protection  Imagine you have two structures: a linked list and a binary tree  If you share one heap, and one has a bug, the problem may show up in the other structure  If we have different heaps, problems tend to be localized (unless you *really* mess up!)

2: Memory Management  Heaps work best when all the objects in them are the same size  Imagine mixing two different sizes; when you free object 1 object 2 may not be a perfect fit  Better to allocate all objects of the same size in the same place

3: Local Access  Swapping to disk is really expensive  Best to keep things you use together close together

4: Avoiding thread-sync issues  Heaps are serialized by default  CPU overhead involved in keeping heap access thread safe  If you tell the system a heap is single- threaded, you can lose this overhead DANGER WILL ROBINSON: YOU ARE NOW RESPONSIBLE FOR THREAD SAFETY!!!

5: Quick free  Instead of freeing things up block by block you can choose to free the entire heap in one go  That’s *really* quick

So… how?  HANDLE HeapCreate( DWORD fdwOptions, SIZE_T dwInitialSize, SIZE_T dwMaximumSize);  Options: 0, HEAP_NO_SERIALIZE, HEAP_GENERATE_EXCEPTIONS  Serialize turns off checking for Alloc and Free  Can manage this yourself via Critical Sections if you want to

HEAP_GENERATE_EXCEPTIONS  Raise an exception whenever an allocation request fails  Basically, it’s just about whether you want to catch exceptions or check return values – depends on the application  Oh… if dwMaximumSize is 0 the size is unlimited…

Allocating Memory from the Heap  PVOID HeapAlloc( HANDLE hHeap, DWORD fdwFlags, SIZE_T dwBytes);  Flags: HEAP_ZERO_MEMORY, HEAP_GENERATE_EXCEPTIONS, HEAP_NO_SERIALIZE  Exceptions: STATUS_NO_MEMORY, STATUS_ACCESS_VIOLATION

Changing the size…  PVOID HeapReAlloc( HANDLE hHeap, DWORD fdwFlags, PVOID pvMem, SIZE_T dwBytes);  New flag: HEAP_REALLOC_IN_PLACE_ONLY  Means that the location won’t change

Obtaining the Size  SIZE_T HeapSize( HANDLE hHeap, DWORD fdwFlags, LPCVOID pvMem);  Flags: 0 or HEAP_NO_SERIALIZE

Freeing a block  BOOL HeapFree( HANDLE hHeap, DWORD fdwFlags, PVOID pvMem);  Flags? You tell me…

Destroying a Heap  BOOL HeapDestroy(HANDLE hHeap);  TRUE on success  You can’t destroy the default heap!

Heaps with C++  Under C you would use malloc  In C++ can use new/delete CSomeClass *pSomeClass = new CSomeClass; delete pSomeClass; Now the clever bit: overload new/delete…

Prototype  class CSomeClass { private: static HANDLE s_hHeap; static UINT s_uNumAllocsInHeap; // Other private data and member functions public: void* operator new (size_t size); void operator delete (void* p); // Other public data and member functions };

Code… HANDLE CSomeClass::s_hHeap = NULL; UINT CSomeClass::s_uNumAllocsInHeap = 0; void* CSomeClass::operator new (size_t size) { if (s_hHeap == NULL) { // Heap does not exist; create it. s_hHeap = HeapCreate(HEAP_NO_SERIALIZE, 0, 0); if (s_hHeap == NULL) return(NULL); } // The heap exists for CSomeClass objects. void* p = HeapAlloc(s_hHeap, 0, size); if (p != NULL) { // Memory was allocated successfully; increment // the count of CSomeClass objects in the heap. s_uNumAllocsInHeap++; } // Return the address of the allocated CSomeClass object. return(p); }

And delete… void CSomeClass::operator delete (void* p) { if (HeapFree(s_hHeap, 0, p)) { // Object was deleted successfully. s_uNumAllocsInHeap--; } if (s_uNumAllocsInHeap == 0) { // If there are no more objects in the heap, // destroy the heap. if (HeapDestroy(s_hHeap)) { // Set the heap handle to NULL // so that the new operator // will know to create a new heap if a // new CSomeClass // object is created. s_hHeap = NULL; } } }

Misc Functions…  DWORD GetProcessHeaps – returns handles to all heaps in the process  BOOL HeapValidate – check that a heap is a-okay…  UINT HeapCompact – coalesce free blocks  HeapLock and HeapUnlock – used for thread sync  HeapWalk – for debugging; lets you enumerate sections/blocks in the heap

Next  Next, it gets difficult DLLs