Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

442 lines
13 KiB

  1. /*
  2. * memory utility functions
  3. *
  4. * global heap functions - allocate and free many small
  5. * pieces of memory by calling global alloc for large pieces
  6. * and breaking them up.
  7. *
  8. * We get memory allocations in units of ALLOCSIZE and hand out blocks
  9. * in units of BLKSIZE. Each allocation has a bitmap (segmap) with one
  10. * bit per block to track the blocks in the allocation that have been
  11. * handed out. All the allocations together are referred to as the heap.
  12. * The bitmap maps the entire allocation, so the first thing done is to
  13. * set the bits to say that the header (including the bitmap itself) has
  14. * already gone. Each allocation contains a count of the number of free
  15. * blocks left in it. This allows us to avoid searching allocations that
  16. * cannot possibly have enough room.
  17. *
  18. * Whenever we hand out some blocks we store the HGLOBAL of that allocation
  19. * immediately before the bit we hand out. This means that the HGLOBAL
  20. * gets stored in a lot of places, but we can always find it from the
  21. * pointer that the caller has. (Obviously we add a handle size to the
  22. * bytes asked for to allow for this). For historical reasons HGLOBALs are
  23. * often referred to as seg handles. The caller knows about the handle to
  24. * the whole heap. Only we know about these other handles.
  25. * All allocations are kept locked.
  26. *
  27. * Requests for more than MAXGALLOC bytes are passed on to GlobalAlloc and
  28. * so have none of this. Likewise when they are freed.
  29. *
  30. * The allocations are chained up so that we can look for free space in all
  31. * of them - BUT to keep speed
  32. * 1. we keep track of the number of free blocks in an allocation and
  33. * only look at the bitmap if it might win.
  34. * 2. When we fail to find free space and so get a new allocation, we chain
  35. * it on the front, so we will then normally allocate from this new first block.
  36. * We only * look further down the chain when the first block fails us.
  37. *
  38. * Multithread safe. An allocation contains a critical section, so
  39. * multiple simultaneous calls to gmem_get and gmem_free will be
  40. * protected.
  41. *
  42. * gmem_freeall should not be called until all other users have finished
  43. * with the heap.
  44. */
  45. #include <precomp.h>
  46. #include "gutilsrc.h" /* for string id */
  47. extern HANDLE hLibInst;
  48. /*
  49. * out-of-memory is not something we regard as normal.
  50. * - if we cannot allocate memory - we put up an abort-retry-ignore
  51. * error, and only return from the function if the user selects ignore.
  52. */
  53. int gmem_panic(void);
  54. /* ensure BLKSIZE is multiple of sizeof(DWORD) */
  55. #define BLKSIZE 16 /* block size in bytes to hand out */
  56. #define ALLOCSIZE 32768 /* allocation size in bytes to get */
  57. #define NBLKS (ALLOCSIZE / BLKSIZE) /* blocks per alloc */
  58. #define MAPSIZE (NBLKS / 8) /* bytes of bitmap needed */
  59. #define MAPLONGS (MAPSIZE / sizeof(DWORD)) /* DWORDS of bitmap needed */
  60. /* Macro to convert a request in bytes to a (rounded up) number of blocks */
  61. #define TO_BLKS(x) (((x) + BLKSIZE - 1) / BLKSIZE)
  62. typedef struct seghdr {
  63. HANDLE hseg; /* The HGLOBAL of this allocation */
  64. CRITICAL_SECTION critsec; /* Critsec for this allocation */
  65. struct seghdr FAR * pnext; /* Next allocation */
  66. long nblocks; /* num free blocks left in this alloc */
  67. DWORD segmap[MAPLONGS]; /* The bitmap */
  68. /* The available storage in an allocation follows immediately */
  69. } SEGHDR, FAR * SEGHDRP;
  70. /* Anything above this size, we alloc directly from global
  71. This must be smaller than ALLOCSIZE - sizeof(SEGHDR) - sizeof(HANDLE)
  72. */
  73. #define MAXGALLOC 20000
  74. /*
  75. * init heap - create first segment.
  76. Return the locked HGLOBAL of the new, initialised heap or NULL if it fails.
  77. */
  78. HANDLE APIENTRY
  79. gmem_init(void)
  80. {
  81. HANDLE hNew;
  82. SEGHDRP hp;
  83. /* Try to allocate. If fails, call gmem_panic.
  84. If user says IGNORE, return NULL, else go round again.
  85. */
  86. do {
  87. hNew = GlobalAlloc(GHND, ALLOCSIZE);/* moveable and Zero-init */
  88. if (hNew == NULL) {
  89. if (gmem_panic() == IDIGNORE) {
  90. return(NULL);
  91. }
  92. }
  93. } while (hNew == NULL);
  94. /* Lock it - or return NULL (unexpected) if it won't */
  95. hp = (SEGHDRP) GlobalLock(hNew);
  96. if (hp == NULL) {
  97. GlobalFree(hNew);
  98. return(NULL);
  99. }
  100. hp->hseg = hNew;
  101. InitializeCriticalSection(&hp->critsec);
  102. hp->pnext = NULL;
  103. gbit_init(hp->segmap, NBLKS);
  104. gbit_alloc(hp->segmap, 1, TO_BLKS(sizeof(SEGHDR)));
  105. hp->nblocks = NBLKS - TO_BLKS(sizeof(SEGHDR));
  106. return(hNew);
  107. } /* gmem_init */
  108. LONG gmemTime = 0; /* time used in musec */
  109. LONG gmemTot = 0; /* number of calls */
  110. LONG APIENTRY gmem_time(void)
  111. { return MulDiv(gmemTime, 1, gmemTot);
  112. }
  113. #ifdef TIMING
  114. LPSTR APIENTRY gmem_get_internal(HANDLE hHeap, int len);
  115. LPSTR APIENTRY
  116. gmem_get(HANDLE hHeap, int len)
  117. {
  118. LPSTR Ret;
  119. LARGE_INTEGER time1, time2, freq;
  120. LONG t1, t2;
  121. QueryPerformanceFrequency(&freq);
  122. if (gmemTot==0) {
  123. char msg[80];
  124. LONG temp = freq.LowPart;
  125. wsprintf(msg, "QPF gave %d", temp);
  126. Trace_Error(NULL, msg, FALSE);
  127. }
  128. ++gmemTot;
  129. QueryPerformanceCounter(&time1);
  130. Ret = gmem_get_internal(hHeap, len);
  131. QueryPerformanceCounter(&time2);
  132. t1 = time1.LowPart;
  133. t2 = time2.LowPart;
  134. gmemTime += t2-t1;
  135. return Ret;
  136. }
  137. #else
  138. /* cause gmem_get_internal to actually be the real gmem_get */
  139. #define gmem_get_internal gmem_get
  140. #endif
  141. /* Return an LPSTR pointing to room for len bytes. Try allocatng
  142. initially from hHeap, but reserve the right to get it from elsewhere.
  143. Return NULL if it fails.
  144. */
  145. LPSTR APIENTRY
  146. gmem_get_internal(HANDLE hHeap, int len)
  147. {
  148. SEGHDRP chainp;
  149. HANDLE hNew;
  150. SEGHDRP hp;
  151. LPSTR chp;
  152. long nblks;
  153. long start;
  154. long nfound;
  155. chp = NULL; /* eliminate spurious compiler warning - generate worse code. */
  156. //{ char msg[80];
  157. // wsprintf(msg, "gmem_get %d bytes", len);
  158. // Trace_File(msg);
  159. //}
  160. /* Zero bytes? Address zero is an adequate place! */
  161. if (len < 1) {
  162. return(NULL);
  163. }
  164. /* The heap is always locked (in gmem_init).
  165. Lock it again to get the pointer then we can safely unlock it.
  166. */
  167. chainp = (SEGHDRP) GlobalLock(hHeap);
  168. GlobalUnlock(hHeap);
  169. /*
  170. * Too big to be worth allocing from heap? - get from globalalloc.
  171. */
  172. if (len > MAXGALLOC) {
  173. /* Try to allocate. If fails, call gmem_panic.
  174. If user says IGNORE, return NULL, else go round again.
  175. */
  176. do {
  177. hNew = GlobalAlloc(GHND, len);
  178. if (hNew == NULL) {
  179. if (gmem_panic() == IDIGNORE) {
  180. return(NULL);
  181. }
  182. }
  183. } while (hNew == NULL);
  184. chp = GlobalLock(hNew);
  185. if (chp == NULL) {
  186. GlobalFree(hNew);
  187. return(NULL);
  188. }
  189. //{ char msg[80];
  190. // wsprintf(msg, " gmem_get direct address ==> %8x", chp);
  191. // Trace_File(msg);
  192. //}
  193. return(chp);
  194. }
  195. /*
  196. * get critical section during all access to the heap itself
  197. */
  198. EnterCriticalSection(&chainp->critsec);
  199. nblks = TO_BLKS(len + sizeof(HANDLE));
  200. for (hp = chainp; hp !=NULL; hp = hp->pnext) {
  201. if (hp->nblocks >= nblks) {
  202. nfound = gbit_findfree(hp->segmap, nblks,NBLKS, &start);
  203. if (nfound >= nblks) {
  204. gbit_alloc(hp->segmap, start, nblks);
  205. hp->nblocks -= nblks;
  206. /* convert blocknr to pointer
  207. * store seg handle in block
  208. * Prepare to return pointer to just after handle.
  209. */
  210. chp = (LPSTR) hp;
  211. chp = &chp[ (start-1) * BLKSIZE];
  212. * ( (HANDLE FAR *) chp) = hp->hseg;
  213. chp += sizeof(HANDLE);
  214. break;
  215. }
  216. }
  217. }
  218. if (hp == NULL) {
  219. // Trace_File("<gmen-get new block>");
  220. /* Try to allocate. If fails, call gmem_panic.
  221. If user says IGNORE, return NULL, else go round again.
  222. */
  223. do {
  224. hNew = GlobalAlloc(GHND, ALLOCSIZE);
  225. if (hNew == NULL) {
  226. if (gmem_panic() == IDIGNORE) {
  227. LeaveCriticalSection(&chainp->critsec);
  228. return(NULL);
  229. }
  230. }
  231. } while (hNew == NULL);
  232. hp = (SEGHDRP) GlobalLock(hNew);
  233. if (hp == NULL) {
  234. LeaveCriticalSection(&chainp->critsec);
  235. GlobalFree(hNew);
  236. return(NULL);
  237. }
  238. hp->pnext = chainp->pnext;
  239. hp->hseg = hNew;
  240. chainp->pnext = hp;
  241. gbit_init(hp->segmap, NBLKS);
  242. gbit_alloc(hp->segmap, 1, TO_BLKS(sizeof(SEGHDR)));
  243. hp->nblocks = NBLKS - TO_BLKS(sizeof(SEGHDR));
  244. nfound = gbit_findfree(hp->segmap, nblks, NBLKS, &start);
  245. if (nfound >= nblks) {
  246. gbit_alloc(hp->segmap, start, nblks);
  247. hp->nblocks -= nblks;
  248. /* convert block nr to pointer */
  249. chp = (LPSTR) hp;
  250. chp = &chp[ (start-1) * BLKSIZE];
  251. /* add a handle into the block and skip past */
  252. * ( (HANDLE FAR *) chp) = hp->hseg;
  253. chp += sizeof(HANDLE);
  254. }
  255. }
  256. /* ASSERT - by now we MUST have found a block. chp cannot be garbage.
  257. This requires that MAXGALLOC is not too large.
  258. */
  259. //{ char msg[80];
  260. // wsprintf(msg, " gmem_get suballoc address ==> %8x\n", chp);
  261. // Trace_File(msg);
  262. //}
  263. LeaveCriticalSection(&chainp->critsec);
  264. memset(chp, 0, len); /* We ask for ZEROINIT memory, but it could have
  265. been already affected by gmem_get; use; gmem_free
  266. */
  267. return(chp);
  268. } /* gmem_get */
  269. void APIENTRY
  270. gmem_free(HANDLE hHeap, LPSTR ptr, int len)
  271. {
  272. SEGHDRP chainp;
  273. SEGHDRP hp;
  274. HANDLE hmem;
  275. long nblks, blknr;
  276. LPSTR chp;
  277. //{ char msg[80];
  278. // wsprintf(msg, " gmem_free address ==> %8x, len %d \n", ptr, len);
  279. // Trace_File(msg);
  280. //}
  281. if (len < 1) {
  282. return;
  283. }
  284. /* In Windiff, things are run on different threads and Exit can result
  285. in a general cleanup. It is possible that the creation of stuff is
  286. in an in-between state at this point. The dogma is that when we
  287. allocate a new structure and tie it into a List or whatever that
  288. will need to be freed later:
  289. EITHER all pointers within the allocated structure are made NULL
  290. before it is chained in
  291. OR the caller of Gmem services undertakes not to try to free any
  292. garbage pointers that are not yet quite built
  293. For this reason, if ptr is NULL, we go home peacefully.
  294. */
  295. if (ptr==NULL) return;
  296. /*
  297. * allocs greater than MAXGALLOC were too big to be worth
  298. * allocing from the heap - they will have been allocated
  299. * directly from globalalloc
  300. */
  301. if (len > MAXGALLOC) {
  302. hmem = GlobalHandle( (LPSTR) ptr);
  303. GlobalUnlock(hmem);
  304. GlobalFree(hmem);
  305. return;
  306. }
  307. chainp = (SEGHDRP) GlobalLock(hHeap);
  308. EnterCriticalSection(&chainp->critsec);
  309. /* just before the ptr we gave the user, is the handle to
  310. * the block.
  311. */
  312. chp = (LPSTR) ptr;
  313. chp -= sizeof(HANDLE);
  314. hmem = * ((HANDLE FAR *) chp);
  315. hp = (SEGHDRP) GlobalLock(hmem);
  316. nblks = TO_BLKS(len + sizeof(HANDLE));
  317. /* convert ptr to block nr */
  318. blknr = TO_BLKS( (unsigned) (chp - (LPSTR) hp) ) + 1;
  319. gbit_free(hp->segmap, blknr, nblks);
  320. hp->nblocks += nblks;
  321. GlobalUnlock(hmem);
  322. LeaveCriticalSection(&chainp->critsec);
  323. GlobalUnlock(hHeap);
  324. }
  325. void APIENTRY
  326. gmem_freeall(HANDLE hHeap)
  327. {
  328. SEGHDRP chainp;
  329. HANDLE hSeg;
  330. chainp = (SEGHDRP) GlobalLock(hHeap);
  331. /* this segment is always locked - so we need to unlock
  332. * it here as well as below
  333. */
  334. GlobalUnlock(hHeap);
  335. /* finished with the critical section -
  336. * caller must ensure that at this point there is no
  337. * longer any contention
  338. */
  339. DeleteCriticalSection(&chainp->critsec);
  340. while (chainp != NULL) {
  341. hSeg = chainp->hseg;
  342. chainp = chainp->pnext;
  343. GlobalUnlock(hSeg);
  344. GlobalFree(hSeg);
  345. }
  346. }
  347. /*
  348. * a memory allocation attempt has failed. return IDIGNORE to ignore the
  349. * error and return NULL to the caller, and IDRETRY to retry the allocation
  350. * attempt.
  351. */
  352. int
  353. gmem_panic(void)
  354. {
  355. int code;
  356. TCHAR szBuff1[MAX_PATH];
  357. TCHAR szBuff2[MAX_PATH];
  358. LoadString(hLibInst,
  359. IDS_MEMORY_ALLOC_FAIL,
  360. szBuff1,
  361. sizeof(szBuff1)/sizeof(szBuff1[0]));
  362. LoadString(hLibInst,
  363. IDS_OUT_OF_MEMORY,
  364. szBuff2,
  365. sizeof(szBuff2)/sizeof(szBuff2[0]));
  366. code = MessageBox(NULL, szBuff1, szBuff2,
  367. MB_ICONSTOP|MB_ABORTRETRYIGNORE);
  368. if (code == IDABORT) {
  369. /* abort this whole process */
  370. ExitProcess(1);
  371. } else {
  372. return(code);
  373. }
  374. return 0;
  375. }