Shared Heap Pitfalls

Posted by: Sue Loh

I just saw someone on our newsgroups make a recommendation that to get past the Windows CE 32MB per-process VM limitation, you can use shared heaps to make your allocations.  I would like to explain some of the pitfalls of choosing that route.

First off, by "shared heap" we are talking about HeapCreate with HEAP_SHARED_READONLY.
https://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcecoreos5/html/wce50lrfHeapCreate.asp

It's something new as of CE 5.0.  The HeapCreate call will reserve a chunk of memory from the shared memory area, and you can alloc small pieces at a time using HeapAlloc.  So, it sounds great right?  No more 32MB limit.  Why don't people usually talk about this approach to escape the 32MB limitation on WinCE?

Shared heaps have some VERY BIG caveats.  For one, they were really intended to be used in a client/server environment, so that a server can give out memory that clients can read, but not write.  They are set up so that only trusted applications can write to them.  Untrusted applications can only read.  The documentation says that the process which created the heap is the only one which can write, but that's not true -- all kernel mode threads can write the heap and all other threads can only read the heap.  [I'll have to get someone to fix the docs.]  On devices like PocketPC which run in all-kernel-mode, all applications are trusted.  However on SmartPhone and other devices which use a trust model that is not the case.  So, if you're expecting to use shared heaps as if they were regular heaps, your application(s) must be trusted.

For another thing, since the memory is in the shared memory area, EVERYBODY can read it.  So on devices where security is important -- don't store anything secret there!

Finally, because of that intended client/server model, where create / alloc / write operations are only possible in a server, using it as if it was a normal heap inside an application is somewhat unsupported.  Our documentation doesn't have a big red "no!" sign in it, but I'll see if I can change that.  It may not really keep working in the future.  It is possible that applications which use shared heaps as a way to share writeable memory between processes will be broken in the future.  It is called "HEAP_SHARED_READONLY" after all.  If your intent is to share writeable memory between processes, then I MUST discourage you from using shared heaps.  You would be better off writing yourself a simple heap manager and using it on top of a named memory-mapped file instead.  That's the primary way to share memory between processes in Windows CE.