Home | History | Annotate | Download | only in fxcrt
      1 // Copyright 2014 PDFium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
      6 
      7 #include <stdlib.h>  // For abort().
      8 
      9 #include "core/include/fxcrt/fx_memory.h"
     10 
     11 void* FXMEM_DefaultAlloc(size_t byte_size, int flags) {
     12   return (void*)malloc(byte_size);
     13 }
     14 void* FXMEM_DefaultRealloc(void* pointer, size_t new_size, int flags) {
     15   return realloc(pointer, new_size);
     16 }
     17 void FXMEM_DefaultFree(void* pointer, int flags) {
     18   free(pointer);
     19 }
     20 
     21 NEVER_INLINE void FX_OutOfMemoryTerminate() {
     22   // Termimate cleanly if we can, else crash at a specific address (0xbd).
     23   abort();
     24   reinterpret_cast<void (*)()>(0xbd)();
     25 }
     26 
     27 CFX_GrowOnlyPool::CFX_GrowOnlyPool(size_t trunk_size) {
     28   m_TrunkSize = trunk_size;
     29   m_pFirstTrunk = NULL;
     30 }
     31 CFX_GrowOnlyPool::~CFX_GrowOnlyPool() {
     32   FreeAll();
     33 }
     34 struct _FX_GrowOnlyTrunk {
     35   size_t m_Size;
     36   size_t m_Allocated;
     37   _FX_GrowOnlyTrunk* m_pNext;
     38 };
     39 void CFX_GrowOnlyPool::FreeAll() {
     40   _FX_GrowOnlyTrunk* pTrunk = (_FX_GrowOnlyTrunk*)m_pFirstTrunk;
     41   while (pTrunk) {
     42     _FX_GrowOnlyTrunk* pNext = pTrunk->m_pNext;
     43     FX_Free(pTrunk);
     44     pTrunk = pNext;
     45   }
     46   m_pFirstTrunk = NULL;
     47 }
     48 void* CFX_GrowOnlyPool::Alloc(size_t size) {
     49   size = (size + 3) / 4 * 4;
     50   _FX_GrowOnlyTrunk* pTrunk = (_FX_GrowOnlyTrunk*)m_pFirstTrunk;
     51   while (pTrunk) {
     52     if (pTrunk->m_Size - pTrunk->m_Allocated >= size) {
     53       void* p = (uint8_t*)(pTrunk + 1) + pTrunk->m_Allocated;
     54       pTrunk->m_Allocated += size;
     55       return p;
     56     }
     57     pTrunk = pTrunk->m_pNext;
     58   }
     59   size_t alloc_size = size > m_TrunkSize ? size : m_TrunkSize;
     60   pTrunk = (_FX_GrowOnlyTrunk*)FX_Alloc(uint8_t,
     61                                         sizeof(_FX_GrowOnlyTrunk) + alloc_size);
     62   pTrunk->m_Size = alloc_size;
     63   pTrunk->m_Allocated = size;
     64   pTrunk->m_pNext = (_FX_GrowOnlyTrunk*)m_pFirstTrunk;
     65   m_pFirstTrunk = pTrunk;
     66   return pTrunk + 1;
     67 }
     68