1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2  * vim: sw=2 ts=4 et :
3  */
4 /* This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 
8 #include "mozilla/mozalloc.h"
9 #include <windows.h>
10 
11 #if !defined(MOZ_MEMORY)
12 #  include <malloc.h>
13 #  define malloc_impl malloc
14 #  define calloc_impl calloc
15 #  define realloc_impl realloc
16 #  define free_impl free
17 #endif
18 
19 // Warning: C4273: 'HeapAlloc': inconsistent dll linkage
20 // The Windows headers define HeapAlloc as dllimport, but we define it as
21 // dllexport, which is a voluntary inconsistency.
22 #pragma warning(disable : 4273)
23 
24 MFBT_API
HeapAlloc(_In_ HANDLE hHeap,_In_ DWORD dwFlags,_In_ SIZE_T dwBytes)25 LPVOID WINAPI HeapAlloc(_In_ HANDLE hHeap, _In_ DWORD dwFlags,
26                         _In_ SIZE_T dwBytes) {
27   if (dwFlags & HEAP_ZERO_MEMORY) {
28     return calloc_impl(1, dwBytes);
29   }
30   return malloc_impl(dwBytes);
31 }
32 
33 MFBT_API
HeapReAlloc(_In_ HANDLE hHeap,_In_ DWORD dwFlags,_In_ LPVOID lpMem,_In_ SIZE_T dwBytes)34 LPVOID WINAPI HeapReAlloc(_In_ HANDLE hHeap, _In_ DWORD dwFlags,
35                           _In_ LPVOID lpMem, _In_ SIZE_T dwBytes) {
36   // The HeapReAlloc contract is that failures preserve the existing
37   // allocation. We can't try to realloc in-place without possibly
38   // freeing the original allocation, breaking the contract.
39   // We also can't guarantee we zero all the memory from the end of
40   // the original allocation to the end of the new one because of the
41   // difference between the originally requested size and what
42   // malloc_usable_size would return us.
43   // So for both cases, just tell the caller we can't do what they
44   // requested.
45   if (dwFlags & (HEAP_REALLOC_IN_PLACE_ONLY | HEAP_ZERO_MEMORY)) {
46     return NULL;
47   }
48   return realloc_impl(lpMem, dwBytes);
49 }
50 
51 MFBT_API
HeapFree(_In_ HANDLE hHeap,_In_ DWORD dwFlags,_In_ LPVOID lpMem)52 BOOL WINAPI HeapFree(_In_ HANDLE hHeap, _In_ DWORD dwFlags, _In_ LPVOID lpMem) {
53   free_impl(lpMem);
54   return true;
55 }
56