Changeset bcb14b5


Ignore:
Timestamp:
Aug 29, 2018, 6:07:15 PM (6 years ago)
Author:
Peter A. Buhr <pabuhr@…>
Branches:
ADT, aaron-thesis, arm-eh, ast-experimental, cleanup-dtors, deferred_resn, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, no_list, persistent-indexer, pthread-emulation, qualifiedEnum
Children:
d69f4bb
Parents:
dfb7c96
Message:

first code review updates

File:
1 edited

Legend:

Unmodified
Added
Removed
  • libcfa/src/heap.cfa

    rdfb7c96 rbcb14b5  
    1 // #comment TD : this file uses both spaces and tabs for indentation
    2 
    31//
    42// Cforall Version 1.0.0 Copyright (C) 2017 University of Waterloo
     
    1210// Created On       : Tue Dec 19 21:58:35 2017
    1311// Last Modified By : Peter A. Buhr
    14 // Last Modified On : Sat Aug 11 08:22:16 2018
    15 // Update Count     : 495
     12// Last Modified On : Thu Aug 23 06:11:44 2018
     13// Update Count     : 511
    1614//
    1715
     
    2523
    2624// #comment TD : Many of these should be merged into math I believe
    27 #include "bits/align.hfa"                                                                       // libPow2
    28 #include "bits/defs.hfa"                                                                        // likely, unlikely
    29 #include "bits/locks.hfa"                                                                       // __spinlock_t
     25#include "bits/align.hfa"                                                               // libPow2
     26#include "bits/defs.hfa"                                                                // likely, unlikely
     27#include "bits/locks.hfa"                                                               // __spinlock_t
    3028#include "startup.hfa"                                                                  // STARTUP_PRIORITY_MEMORY
    31 #include "stdlib.hfa"                                                                           // bsearchl
     29#include "stdlib.hfa"                                                                   // bsearchl
    3230#include "malloc.h"
    3331
     
    151149
    152150extern "C" {
    153 void heapAppStart() {                                                                   // called by __cfaabi_appready_startup
    154         allocFree = 0;
    155 } // heapAppStart
    156 
    157 void heapAppStop() {                                                                    // called by __cfaabi_appready_startdown
    158         fclose( stdin ); fclose( stdout );
    159         checkUnfreed();
    160 } // heapAppStop
     151        void heapAppStart() {                                                           // called by __cfaabi_appready_startup
     152                allocFree = 0;
     153        } // heapAppStart
     154
     155        void heapAppStop() {                                                            // called by __cfaabi_appready_startdown
     156                fclose( stdin ); fclose( stdout );
     157                checkUnfreed();
     158        } // heapAppStop
    161159} // extern "C"
    162160#endif // __CFA_DEBUG__
     
    167165
    168166        struct Storage {
    169             struct Header {                                                                     // header
     167                struct Header {                                                                 // header
    170168                        union Kind {
    171169                                struct RealHeader {
    172170                                        union {
    173                                                 // #comment TD : this code use byte size but the comment uses bit size
    174 
    175                                                 struct {                                                // 32-bit word => 64-bit header, 64-bit word => 128-bit header
     171                                                struct {                                                // 4-byte word => 8-byte header, 8-byte word => 16-byte header
    176172                                                        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ && __SIZEOF_POINTER__ == 4
    177173                                                        uint32_t padding;                       // unused, force home/blocksize to overlay alignment in fake header
    178                                                         #endif // __ORDER_BIG_ENDIAN__ && __U_WORDSIZE__ == 32
     174                                                        #endif // __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ && __SIZEOF_POINTER__ == 4
    179175
    180176                                                        union {
     
    189185                                                        #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ && __SIZEOF_POINTER__ == 4
    190186                                                        uint32_t padding;                       // unused, force home/blocksize to overlay alignment in fake header
    191                                                         #endif // __ORDER_LITTLE_ENDIAN__ && __U_WORDSIZE__ == 32
    192 
     187                                                        #endif // __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ && __SIZEOF_POINTER__ == 4
    193188                                                };
    194 
    195                                                 // #comment TD : C++ code
     189                                                // future code
    196190                                                #if BUCKLOCK == LOCKFREE
    197191                                                Stack<Storage>::Link next;              // freed block points next freed block of same size (double-wide)
     
    211205                                } fake; // FakeHeader
    212206                        } kind; // Kind
    213             } header; // Header
    214             char pad[ALIGN - sizeof( Header )];
    215             char data[0];                                                                       // storage
     207                } header; // Header
     208                char pad[ALIGN - sizeof( Header )];
     209                char data[0];                                                                   // storage
    216210        }; // Storage
    217211
     
    220214        struct FreeHeader {
    221215                #if BUCKLOCK == SPINLOCK
    222             __spinlock_t lock;                                                          // must be first field for alignment
    223             Storage * freeList;
     216                __spinlock_t lock;                                                              // must be first field for alignment
     217                Storage * freeList;
    224218                #elif BUCKLOCK == LOCKFREE
    225                 // #comment TD : C++ code
    226             StackLF<Storage> freeList;
     219                // future code
     220                StackLF<Storage> freeList;
    227221                #else
    228                         #error undefined lock type for bucket lock
     222                #error undefined lock type for bucket lock
    229223                #endif // SPINLOCK
    230             size_t blockSize;                                                           // size of allocations on this list
     224                size_t blockSize;                                                               // size of allocations on this list
    231225        }; // FreeHeader
    232226
     
    249243static unsigned int maxBucketsUsed;                                             // maximum number of buckets in use
    250244
    251 // #comment TD : This array is not const but it feels like it should be
    252245// Powers of 2 are common allocation sizes, so make powers of 2 generate the minimum required size.
    253 static unsigned int bucketSizes[NoBucketSizes] @= {             // different bucket sizes
     246static const unsigned int bucketSizes[NoBucketSizes] @= { // different bucket sizes
    254247        16, 32, 48, 64,
    255248        64 + sizeof(HeapManager.Storage), 96, 112, 128, 128 + sizeof(HeapManager.Storage), 160, 192, 224,
     
    279272// #comment TD : The return type of this function should be commented
    280273static inline bool setMmapStart( size_t value ) {
    281         if ( value < pageSize || bucketSizes[NoBucketSizes - 1] < value ) return true;
     274  if ( value < pageSize || bucketSizes[NoBucketSizes - 1] < value ) return true;
    282275        mmapStart = value;                                                                      // set global
    283276
     
    313306        sbrk( (char *)libCeiling( (long unsigned int)End, libAlign() ) - End ); // move start of heap to multiple of alignment
    314307        heapBegin = heapEnd = sbrk( 0 );                                        // get new start point
    315 } // HeapManager
     308                           } // HeapManager
    316309
    317310
     
    323316        // } // if
    324317        #endif // __STATISTICS__
    325 } // ~HeapManager
     318                                } // ~HeapManager
    326319
    327320
     
    329322void memory_startup( void ) {
    330323        #ifdef __CFA_DEBUG__
    331         if ( unlikely( heapBoot ) ) {                                   // check for recursion during system boot
     324        if ( unlikely( heapBoot ) ) {                                           // check for recursion during system boot
    332325                // DO NOT USE STREAMS AS THEY MAY BE UNAVAILABLE AT THIS POINT.
    333326                abort( "boot() : internal error, recursively invoked during system boot." );
     
    336329        #endif // __CFA_DEBUG__
    337330
    338         // #comment TD : This assertion seems redundent with the above code
    339         assert( heapManager.heapBegin == 0 );
     331        assert( heapManager.heapBegin == 0 );                           // always perform check, done once
    340332        heapManager{};
    341333} // memory_startup
     
    374366        char helpText[512];
    375367        __cfaabi_dbg_bits_print_buffer( helpText, sizeof(helpText),
    376                         "\nHeap statistics:\n"
    377                         "  malloc: calls %u / storage %llu\n"
    378                         "  calloc: calls %u / storage %llu\n"
    379                         "  memalign: calls %u / storage %llu\n"
    380                         "  cmemalign: calls %u / storage %llu\n"
    381                         "  realloc: calls %u / storage %llu\n"
    382                         "  free: calls %u / storage %llu\n"
    383                         "  mmap: calls %u / storage %llu\n"
    384                         "  munmap: calls %u / storage %llu\n"
    385                         "  sbrk: calls %u / storage %llu\n",
    386                         malloc_calls, malloc_storage,
    387                         calloc_calls, calloc_storage,
    388                         memalign_calls, memalign_storage,
    389                         cmemalign_calls, cmemalign_storage,
    390                         realloc_calls, realloc_storage,
    391                         free_calls, free_storage,
    392                         mmap_calls, mmap_storage,
    393                         munmap_calls, munmap_storage,
    394                         sbrk_calls, sbrk_storage
     368                                                                        "\nHeap statistics:\n"
     369                                                                        "  malloc: calls %u / storage %llu\n"
     370                                                                        "  calloc: calls %u / storage %llu\n"
     371                                                                        "  memalign: calls %u / storage %llu\n"
     372                                                                        "  cmemalign: calls %u / storage %llu\n"
     373                                                                        "  realloc: calls %u / storage %llu\n"
     374                                                                        "  free: calls %u / storage %llu\n"
     375                                                                        "  mmap: calls %u / storage %llu\n"
     376                                                                        "  munmap: calls %u / storage %llu\n"
     377                                                                        "  sbrk: calls %u / storage %llu\n",
     378                                                                        malloc_calls, malloc_storage,
     379                                                                        calloc_calls, calloc_storage,
     380                                                                        memalign_calls, memalign_storage,
     381                                                                        cmemalign_calls, cmemalign_storage,
     382                                                                        realloc_calls, realloc_storage,
     383                                                                        free_calls, free_storage,
     384                                                                        mmap_calls, mmap_storage,
     385                                                                        munmap_calls, munmap_storage,
     386                                                                        sbrk_calls, sbrk_storage
    395387                );
    396388} // printStats
    397389
    398 // #comment TD : Why do we have this?
    399 static int printStatsXML( FILE * stream ) {
     390static int printStatsXML( FILE * stream ) {                             // see malloc_info
    400391        char helpText[512];
    401392        int len = snprintf( helpText, sizeof(helpText),
     
    431422static inline void noMemory() {
    432423        abort( "Heap memory exhausted at %zu bytes.\n"
    433                         "Possible cause is very large memory allocation and/or large amount of unfreed storage allocated by the program or system/library routines.",
    434                         ((char *)(sbrk( 0 )) - (char *)(heapManager.heapBegin)) );
     424                   "Possible cause is very large memory allocation and/or large amount of unfreed storage allocated by the program or system/library routines.",
     425                   ((char *)(sbrk( 0 )) - (char *)(heapManager.heapBegin)) );
    435426} // noMemory
    436427
     
    444435
    445436static inline bool setHeapExpand( size_t value ) {
    446         if ( heapExpand < pageSize ) return true;
     437  if ( heapExpand < pageSize ) return true;
    447438        heapExpand = value;
    448439        return false;
     
    453444        if ( unlikely( check ) ) {                                                      // bad address ?
    454445                abort( "Attempt to %s storage %p with address outside the heap.\n"
    455                                 "Possible cause is duplicate free on same block or overwriting of memory.",
    456                                 name, addr );
     446                           "Possible cause is duplicate free on same block or overwriting of memory.",
     447                           name, addr );
    457448        } // if
    458449} // checkHeader
     
    484475
    485476        #ifdef __CFA_DEBUG__
    486                         checkHeader( addr < heapBegin || header < (HeapManager.Storage.Header *)heapBegin, name, addr ); // bad low address ?
     477        checkHeader( addr < heapBegin || header < (HeapManager.Storage.Header *)heapBegin, name, addr ); // bad low address ?
    487478        #endif // __CFA_DEBUG__
    488479
     
    490481        //               It's called as the first statement of both branches of the last if, with the same parameters in all cases
    491482
    492                 // header may be safe to dereference
    493                 fakeHeader( header, size, alignment );
     483        // header may be safe to dereference
     484        fakeHeader( header, size, alignment );
    494485        #ifdef __CFA_DEBUG__
    495                         checkHeader( header < (HeapManager.Storage.Header *)heapBegin || (HeapManager.Storage.Header *)heapEnd < header, name, addr ); // bad address ? (offset could be + or -)
     486        checkHeader( header < (HeapManager.Storage.Header *)heapBegin || (HeapManager.Storage.Header *)heapEnd < header, name, addr ); // bad address ? (offset could be + or -)
    496487        #endif // __CFA_DEBUG__
    497488
    498                 freeElem = (HeapManager.FreeHeader *)((size_t)header->kind.real.home & -3);
     489        freeElem = (HeapManager.FreeHeader *)((size_t)header->kind.real.home & -3);
    499490        #ifdef __CFA_DEBUG__
    500                         if ( freeElem < &freeLists[0] || &freeLists[NoBucketSizes] <= freeElem ) {
    501                         abort( "Attempt to %s storage %p with corrupted header.\n"
    502                                 "Possible cause is duplicate free on same block or overwriting of header information.",
    503                                         name, addr );
    504                         } // if
     491        if ( freeElem < &freeLists[0] || &freeLists[NoBucketSizes] <= freeElem ) {
     492                abort( "Attempt to %s storage %p with corrupted header.\n"
     493                          "Possible cause is duplicate free on same block or overwriting of header information.",
     494                           name, addr );
     495        } // if
    505496        #endif // __CFA_DEBUG__
    506                 size = freeElem->blockSize;
    507                 return false;
     497        size = freeElem->blockSize;
     498        return false;
    508499} // headers
    509500
     
    521512                        return 0;
    522513                } // if
    523 #ifdef __STATISTICS__
     514                #ifdef __STATISTICS__
    524515                sbrk_calls += 1;
    525516                sbrk_storage += increase;
    526 #endif // __STATISTICS__
    527 #ifdef __CFA_DEBUG__
     517                #endif // __STATISTICS__
     518                #ifdef __CFA_DEBUG__
    528519                // Set new memory to garbage so subsequent uninitialized usages might fail.
    529520                memset( (char *)heapEnd + heapRemaining, '\377', increase );
    530 #endif // __CFA_DEBUG__
     521                #endif // __CFA_DEBUG__
    531522                rem = heapRemaining + increase - size;
    532523        } // if
     
    560551
    561552                #if defined( SPINLOCK )
    562                         lock( freeElem->lock __cfaabi_dbg_ctx2 );
    563                         block = freeElem->freeList;                                             // remove node from stack
     553                lock( freeElem->lock __cfaabi_dbg_ctx2 );
     554                block = freeElem->freeList;                                             // remove node from stack
    564555                #else
    565                         block = freeElem->freeList.pop();
     556                block = freeElem->freeList.pop();
    566557                #endif // SPINLOCK
    567558                if ( unlikely( block == 0 ) ) {                                 // no free block ?
     
    569560                        unlock( freeElem->lock );
    570561                        #endif // SPINLOCK
     562
    571563                        // Freelist for that size was empty, so carve it out of the heap if there's enough left, or get some more
    572564                        // and then carve it off.
    573565
    574566                        block = (HeapManager.Storage *)extend( tsize ); // mutual exclusion on call
    575                         if ( unlikely( block == 0 ) ) return 0;
     567  if ( unlikely( block == 0 ) ) return 0;
    576568                        #if defined( SPINLOCK )
    577569                } else {
     
    582574
    583575                block->header.kind.real.home = freeElem;                // pointer back to free list of apropriate size
    584                 } else {                                                                                        // large size => mmap
     576        } else {                                                                                        // large size => mmap
    585577                tsize = libCeiling( tsize, pageSize );                  // must be multiple of page size
    586578                #ifdef __STATISTICS__
    587                         __atomic_add_fetch( &mmap_calls, 1, __ATOMIC_SEQ_CST );
    588                         __atomic_add_fetch( &mmap_storage, tsize, __ATOMIC_SEQ_CST );
     579                __atomic_add_fetch( &mmap_calls, 1, __ATOMIC_SEQ_CST );
     580                __atomic_add_fetch( &mmap_storage, tsize, __ATOMIC_SEQ_CST );
    589581                #endif // __STATISTICS__
    590582                block = (HeapManager.Storage *)mmap( 0, tsize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, mmapFd, 0 );
     
    593585                        abort( "(HeapManager &)0x%p.doMalloc() : internal error, mmap failure, size:%zu error:%d.", &heapManager, tsize, errno );
    594586                } // if
    595 #ifdef __CFA_DEBUG__
     587                #ifdef __CFA_DEBUG__
    596588                // Set new memory to garbage so subsequent uninitialized usages might fail.
    597589                memset( block, '\377', tsize );
    598 #endif // __CFA_DEBUG__
     590                #endif // __CFA_DEBUG__
    599591                block->header.kind.real.blockSize = tsize;              // storage size for munmap
    600                 } // if
    601 
    602                 void * area = &(block->data);                                           // adjust off header to user bytes
     592        } // if
     593
     594        void * area = &(block->data);                                           // adjust off header to user bytes
    603595
    604596        #ifdef __CFA_DEBUG__
    605                         assert( ((uintptr_t)area & (libAlign() - 1)) == 0 ); // minimum alignment ?
    606                         __atomic_add_fetch( &allocFree, tsize, __ATOMIC_SEQ_CST );
    607                 if ( traceHeap() ) {
    608                         enum { BufferSize = 64 };
    609                         char helpText[BufferSize];
    610                         int len = snprintf( helpText, BufferSize, "%p = Malloc( %zu ) (allocated %zu)\n", area, size, tsize );
    611                         // int len = snprintf( helpText, BufferSize, "Malloc %p %zu\n", area, size );
    612                         __cfaabi_dbg_bits_write( helpText, len );
    613                 } // if
     597        assert( ((uintptr_t)area & (libAlign() - 1)) == 0 ); // minimum alignment ?
     598        __atomic_add_fetch( &allocFree, tsize, __ATOMIC_SEQ_CST );
     599        if ( traceHeap() ) {
     600                enum { BufferSize = 64 };
     601                char helpText[BufferSize];
     602                int len = snprintf( helpText, BufferSize, "%p = Malloc( %zu ) (allocated %zu)\n", area, size, tsize );
     603                // int len = snprintf( helpText, BufferSize, "Malloc %p %zu\n", area, size );
     604                __cfaabi_dbg_bits_write( helpText, len );
     605        } // if
    614606        #endif // __CFA_DEBUG__
    615607
     
    620612static inline void doFree( void * addr ) with ( heapManager ) {
    621613        #ifdef __CFA_DEBUG__
    622                 if ( unlikely( heapManager.heapBegin == 0 ) ) {
    623                         abort( "doFree( %p ) : internal error, called before heap is initialized.", addr );
    624                 } // if
     614        if ( unlikely( heapManager.heapBegin == 0 ) ) {
     615                abort( "doFree( %p ) : internal error, called before heap is initialized.", addr );
     616        } // if
    625617        #endif // __CFA_DEBUG__
    626618
     
    631623        if ( headers( "free", addr, header, freeElem, size, alignment ) ) { // mmapped ?
    632624                #ifdef __STATISTICS__
    633                         __atomic_add_fetch( &munmap_calls, 1, __ATOMIC_SEQ_CST );
    634                         __atomic_add_fetch( &munmap_storage, size, __ATOMIC_SEQ_CST );
     625                __atomic_add_fetch( &munmap_calls, 1, __ATOMIC_SEQ_CST );
     626                __atomic_add_fetch( &munmap_storage, size, __ATOMIC_SEQ_CST );
    635627                #endif // __STATISTICS__
    636628                if ( munmap( header, size ) == -1 ) {
    637629                        #ifdef __CFA_DEBUG__
    638630                        abort( "Attempt to deallocate storage %p not allocated or with corrupt header.\n"
    639                                         "Possible cause is invalid pointer.",
    640                                         addr );
     631                                   "Possible cause is invalid pointer.",
     632                                   addr );
    641633                        #endif // __CFA_DEBUG__
    642634                } // if
    643                 } else {
     635        } else {
    644636                #ifdef __CFA_DEBUG__
    645                         // Set free memory to garbage so subsequent usages might fail.
    646                         memset( ((HeapManager.Storage *)header)->data, '\377', freeElem->blockSize - sizeof( HeapManager.Storage ) );
     637                // Set free memory to garbage so subsequent usages might fail.
     638                memset( ((HeapManager.Storage *)header)->data, '\377', freeElem->blockSize - sizeof( HeapManager.Storage ) );
    647639                #endif // __CFA_DEBUG__
    648640
    649641                #ifdef __STATISTICS__
    650                         free_storage += size;
     642                free_storage += size;
    651643                #endif // __STATISTICS__
    652644                #if defined( SPINLOCK )
    653                         lock( freeElem->lock __cfaabi_dbg_ctx2 );               // acquire spin lock
    654                         header->kind.real.next = freeElem->freeList;    // push on stack
    655                         freeElem->freeList = (HeapManager.Storage *)header;
    656                         unlock( freeElem->lock );                                               // release spin lock
     645                lock( freeElem->lock __cfaabi_dbg_ctx2 );               // acquire spin lock
     646                header->kind.real.next = freeElem->freeList;    // push on stack
     647                freeElem->freeList = (HeapManager.Storage *)header;
     648                unlock( freeElem->lock );                                               // release spin lock
    657649                #else
    658                         freeElem->freeList.push( *(HeapManager.Storage *)header );
     650                freeElem->freeList.push( *(HeapManager.Storage *)header );
    659651                #endif // SPINLOCK
    660                 } // if
     652        } // if
    661653
    662654        #ifdef __CFA_DEBUG__
    663                  __atomic_add_fetch( &allocFree, -size, __ATOMIC_SEQ_CST );
    664                 if ( traceHeap() ) {
    665                         char helpText[64];
    666                         int len = snprintf( helpText, sizeof(helpText), "Free( %p ) size:%zu\n", addr, size );
    667                         __cfaabi_dbg_bits_write( helpText, len );
    668                 } // if
     655        __atomic_add_fetch( &allocFree, -size, __ATOMIC_SEQ_CST );
     656        if ( traceHeap() ) {
     657                char helpText[64];
     658                int len = snprintf( helpText, sizeof(helpText), "Free( %p ) size:%zu\n", addr, size );
     659                __cfaabi_dbg_bits_write( helpText, len );
     660        } // if
    669661        #endif // __CFA_DEBUG__
    670662} // doFree
     
    674666        size_t total = 0;
    675667        #ifdef __STATISTICS__
    676                 __cfaabi_dbg_bits_acquire();
    677                 __cfaabi_dbg_bits_print_nolock( "\nBin lists (bin size : free blocks on list)\n" );
     668        __cfaabi_dbg_bits_acquire();
     669        __cfaabi_dbg_bits_print_nolock( "\nBin lists (bin size : free blocks on list)\n" );
    678670        #endif // __STATISTICS__
    679671        for ( unsigned int i = 0; i < maxBucketsUsed; i += 1 ) {
     
    695687
    696688                #ifdef __STATISTICS__
    697                         __cfaabi_dbg_bits_print_nolock( "%7zu, %-7u  ", size, N );
    698                         if ( (i + 1) % 8 == 0 ) __cfaabi_dbg_bits_print_nolock( "\n" );
     689                __cfaabi_dbg_bits_print_nolock( "%7zu, %-7u  ", size, N );
     690                if ( (i + 1) % 8 == 0 ) __cfaabi_dbg_bits_print_nolock( "\n" );
    699691                #endif // __STATISTICS__
    700692        } // for
    701693        #ifdef __STATISTICS__
    702                 __cfaabi_dbg_bits_print_nolock( "\ntotal free blocks:%zu\n", total );
    703                 __cfaabi_dbg_bits_release();
     694        __cfaabi_dbg_bits_print_nolock( "\ntotal free blocks:%zu\n", total );
     695        __cfaabi_dbg_bits_release();
    704696        #endif // __STATISTICS__
    705697        return (char *)heapEnd - (char *)heapBegin - total;
    706698} // checkFree
    707699
    708 // #comment TD : This is not a good name, plus this feels like it could easily be folded into doMalloc
    709 static inline void * malloc2( size_t size ) {                   // necessary for malloc statistics
     700
     701static inline void * mallocNoStats( size_t size ) {             // necessary for malloc statistics
    710702        assert( heapManager.heapBegin != 0 );
    711703        void * area = doMalloc( size );
    712704        if ( unlikely( area == 0 ) ) errno = ENOMEM;            // POSIX
    713705        return area;
    714 } // malloc2
    715 
    716 
    717 static inline void * memalign2( size_t alignment, size_t size ) { // necessary for malloc statistics
    718 #ifdef __CFA_DEBUG__
     706} // mallocNoStats
     707
     708
     709static inline void * memalignNoStats( size_t alignment, size_t size ) { // necessary for malloc statistics
     710        #ifdef __CFA_DEBUG__
    719711        checkAlign( alignment );                                                        // check alignment
    720 #endif // __CFA_DEBUG__
     712        #endif // __CFA_DEBUG__
    721713
    722714        // if alignment <= default alignment, do normal malloc as two headers are unnecessary
    723         if ( unlikely( alignment <= libAlign() ) ) return malloc2( size );
     715  if ( unlikely( alignment <= libAlign() ) ) return mallocNoStats( size );
    724716
    725717        // Allocate enough storage to guarantee an address on the alignment boundary, and sufficient space before it for
     
    732724        // subtract libAlign() because it is already the minimum alignment
    733725        // add sizeof(Storage) for fake header
    734         // #comment TD : this is the only place that calls doMalloc without calling malloc2, why ?
     726        // #comment TD : this is the only place that calls doMalloc without calling mallocNoStats, why ?
    735727        char * area = (char *)doMalloc( size + alignment - libAlign() + sizeof(HeapManager.Storage) );
    736         if ( unlikely( area == 0 ) ) return area;
     728  if ( unlikely( area == 0 ) ) return area;
    737729
    738730        // address in the block of the "next" alignment address
     
    749741
    750742        return user;
    751 } // memalign2
     743} // memalignNoStats
    752744
    753745
    754746extern "C" {
    755         // The malloc() function allocates size bytes and returns a pointer to the
    756         // allocated memory. The memory is not initialized. If size is 0, then malloc()
    757         // returns either NULL, or a unique pointer value that can later be successfully
    758         // passed to free().
     747        // The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not
     748        // initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be
     749        // successfully passed to free().
    759750        void * malloc( size_t size ) {
    760751                #ifdef __STATISTICS__
    761                         __atomic_add_fetch( &malloc_calls, 1, __ATOMIC_SEQ_CST );
    762                         __atomic_add_fetch( &malloc_storage, size, __ATOMIC_SEQ_CST );
    763                 #endif // __STATISTICS__
    764 
    765                 return malloc2( size );
    766                 } // malloc
    767 
    768         // The calloc() function allocates memory for an array of nmemb elements of
    769         // size bytes each and returns a pointer to the allocated memory. The memory
    770         // is set to zero. If nmemb or size is 0, then calloc() returns either NULL,
    771         // or a unique pointer value that can later be successfully passed to free().
    772                 void * calloc( size_t noOfElems, size_t elemSize ) {
     752                __atomic_add_fetch( &malloc_calls, 1, __ATOMIC_SEQ_CST );
     753                __atomic_add_fetch( &malloc_storage, size, __ATOMIC_SEQ_CST );
     754                #endif // __STATISTICS__
     755
     756                return mallocNoStats( size );
     757        } // malloc
     758
     759        // The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to
     760        // the allocated memory. The memory is set to zero. If nmemb or size is 0, then calloc() returns either NULL, or a
     761        // unique pointer value that can later be successfully passed to free().
     762        void * calloc( size_t noOfElems, size_t elemSize ) {
    773763                size_t size = noOfElems * elemSize;
    774764                #ifdef __STATISTICS__
    775                         __atomic_add_fetch( &calloc_calls, 1, __ATOMIC_SEQ_CST );
    776                         __atomic_add_fetch( &calloc_storage, size, __ATOMIC_SEQ_CST );
    777                 #endif // __STATISTICS__
    778 
    779                 char * area = (char *)malloc2( size );
    780                 if ( unlikely( area == 0 ) ) return 0;
     765                __atomic_add_fetch( &calloc_calls, 1, __ATOMIC_SEQ_CST );
     766                __atomic_add_fetch( &calloc_storage, size, __ATOMIC_SEQ_CST );
     767                #endif // __STATISTICS__
     768
     769                char * area = (char *)mallocNoStats( size );
     770          if ( unlikely( area == 0 ) ) return 0;
    781771
    782772                HeapManager.Storage.Header * header;
     
    790780                        memset( area, '\0', asize - sizeof(HeapManager.Storage) ); // set to zeros
    791781
    792                 header->kind.real.blockSize |= 2;               // mark as zero filled
     782                header->kind.real.blockSize |= 2;                               // mark as zero filled
    793783                return area;
    794                 } // calloc
     784        } // calloc
    795785
    796786        // #comment TD : Document this function
     
    798788                size_t size = noOfElems * elemSize;
    799789                #ifdef __STATISTICS__
    800                         __atomic_add_fetch( &cmemalign_calls, 1, __ATOMIC_SEQ_CST );
    801                         __atomic_add_fetch( &cmemalign_storage, size, __ATOMIC_SEQ_CST );
    802                 #endif // __STATISTICS__
    803 
    804                 char * area = (char *)memalign2( alignment, size );
    805                 if ( unlikely( area == 0 ) ) return 0;
     790                __atomic_add_fetch( &cmemalign_calls, 1, __ATOMIC_SEQ_CST );
     791                __atomic_add_fetch( &cmemalign_storage, size, __ATOMIC_SEQ_CST );
     792                #endif // __STATISTICS__
     793
     794                char * area = (char *)memalignNoStats( alignment, size );
     795          if ( unlikely( area == 0 ) ) return 0;
    806796                HeapManager.Storage.Header * header;
    807797                HeapManager.FreeHeader * freeElem;
     
    811801                // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
    812802                if ( ! mapped )
    813                 #endif // __CFA_DEBUG__
     803                        #endif // __CFA_DEBUG__
    814804                        memset( area, '\0', asize - ( (char *)area - (char *)header ) ); // set to zeros
    815805                header->kind.real.blockSize |= 2;                               // mark as zero filled
    816806
    817807                return area;
    818                 } // cmemalign
    819 
    820         // The realloc() function changes the size of the memory block pointed to by
    821         // ptr to size bytes. The contents will be unchanged in the range from the
    822         // start of the region up to the minimum of the old and new sizes. If the new
    823         // size is larger than the old size, the added memory will not be initialized.
    824         // If ptr is NULL, then the call is equivalent to malloc(size), for all values
    825         // of size; if size is equal to zero, and ptr is not NULL, then the call is
    826         // equivalent to free(ptr). Unless ptr is NULL, it must have been returned by
    827         // an earlier call to malloc(), calloc() or realloc(). If the area pointed to
    828         // was moved, a free(ptr) is done.
    829                 void * realloc( void * addr, size_t size ) {
    830                 #ifdef __STATISTICS__
    831                         __atomic_add_fetch( &realloc_calls, 1, __ATOMIC_SEQ_CST );
    832                 #endif // __STATISTICS__
    833 
    834                 if ( unlikely( addr == 0 ) ) return malloc2( size ); // special cases
    835                 if ( unlikely( size == 0 ) ) { free( addr ); return 0; }
     808        } // cmemalign
     809
     810        // The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be
     811        // unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size
     812        // is larger than the old size, the added memory will not be initialized.  If ptr is NULL, then the call is
     813        // equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call
     814        // is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(),
     815        // calloc() or realloc(). If the area pointed to was moved, a free(ptr) is done.
     816        void * realloc( void * addr, size_t size ) {
     817                #ifdef __STATISTICS__
     818                __atomic_add_fetch( &realloc_calls, 1, __ATOMIC_SEQ_CST );
     819                #endif // __STATISTICS__
     820
     821          if ( unlikely( addr == 0 ) ) return mallocNoStats( size ); // special cases
     822          if ( unlikely( size == 0 ) ) { free( addr ); return 0; }
    836823
    837824                HeapManager.Storage.Header * header;
     
    848835
    849836                #ifdef __STATISTICS__
    850                         __atomic_add_fetch( &realloc_storage, size, __ATOMIC_SEQ_CST );
     837                __atomic_add_fetch( &realloc_storage, size, __ATOMIC_SEQ_CST );
    851838                #endif // __STATISTICS__
    852839
     
    855842                        area = memalign( alignment, size );                     // create new area
    856843                } else {
    857                         area = malloc2( size ); // create new area
     844                        area = mallocNoStats( size );                           // create new area
    858845                } // if
    859                 if ( unlikely( area == 0 ) ) return 0;
     846          if ( unlikely( area == 0 ) ) return 0;
    860847                if ( unlikely( header->kind.real.blockSize & 2 ) ) { // previous request zero fill (calloc/cmemalign) ?
    861848                        assert( (header->kind.real.blockSize & 1) == 0 );
     
    864851                        // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
    865852                        if ( ! mapped )
    866                         #endif // __CFA_DEBUG__
     853                                #endif // __CFA_DEBUG__
    867854                                memset( (char *)area + usize, '\0', asize - ( (char *)area - (char *)header ) - usize ); // zero-fill back part
    868855                        header->kind.real.blockSize |= 2;                       // mark new request as zero fill
     
    874861
    875862
    876         // The obsolete function memalign() allocates size bytes and returns
    877         // a pointer to the allocated memory. The memory address will be a
    878         // multiple of alignment, which must be a power of two.
    879         void * memalign( size_t alignment, size_t size ) __attribute__ ((deprecated));
    880                 void * memalign( size_t alignment, size_t size ) {
     863        // The obsolete function memalign() allocates size bytes and returns a pointer to the allocated memory. The memory
     864        // address will be a multiple of alignment, which must be a power of two.
     865        void * memalign( size_t alignment, size_t size ) {
    881866                #ifdef __STATISTICS__
    882867                __atomic_add_fetch( &memalign_calls, 1, __ATOMIC_SEQ_CST );
     
    884869                #endif // __STATISTICS__
    885870
    886                 void * area = memalign2( alignment, size );
     871                void * area = memalignNoStats( alignment, size );
    887872
    888873                return area;
    889                 } // memalign
    890 
    891         // The function aligned_alloc() is the same as memalign(), except for
    892         // the added restriction that size should be a multiple of alignment.
     874        } // memalign
     875
     876        // The function aligned_alloc() is the same as memalign(), except for the added restriction that size should be a
     877        // multiple of alignment.
    893878        void * aligned_alloc( size_t alignment, size_t size ) {
    894879                return memalign( alignment, size );
     
    896881
    897882
    898         // The function posix_memalign() allocates size bytes and places the address
    899         // of the allocated memory in *memptr. The address of the allocated memory
    900         // will be a multiple of alignment, which must be a power of two and a multiple
    901         // of sizeof(void *). If size is 0, then posix_memalign() returns either NULL,
    902         // or a unique pointer value that can later be successfully passed to free(3).
     883        // The function posix_memalign() allocates size bytes and places the address of the allocated memory in *memptr. The
     884        // address of the allocated memory will be a multiple of alignment, which must be a power of two and a multiple of
     885        // sizeof(void *). If size is 0, then posix_memalign() returns either NULL, or a unique pointer value that can later
     886        // be successfully passed to free(3).
    903887        int posix_memalign( void ** memptr, size_t alignment, size_t size ) {
    904                 if ( alignment < sizeof(void *) || ! libPow2( alignment ) ) return EINVAL; // check alignment
     888          if ( alignment < sizeof(void *) || ! libPow2( alignment ) ) return EINVAL; // check alignment
    905889                * memptr = memalign( alignment, size );
    906                 if ( unlikely( * memptr == 0 ) ) return ENOMEM;
     890          if ( unlikely( * memptr == 0 ) ) return ENOMEM;
    907891                return 0;
    908892        } // posix_memalign
    909893
    910         // The obsolete function valloc() allocates size bytes and returns a pointer
    911         // to the allocated memory. The memory address will be a multiple of the page size.
    912         // It is equivalent to memalign(sysconf(_SC_PAGESIZE),size).
    913         void * valloc( size_t size ) __attribute__ ((deprecated));
     894        // The obsolete function valloc() allocates size bytes and returns a pointer to the allocated memory. The memory
     895        // address will be a multiple of the page size.  It is equivalent to memalign(sysconf(_SC_PAGESIZE),size).
    914896        void * valloc( size_t size ) {
    915897                return memalign( pageSize, size );
     
    917899
    918900
    919         // The free() function frees the memory space pointed to by ptr, which must
    920         // have been returned by a previous call to malloc(), calloc() or realloc().
    921         // Otherwise, or if free(ptr) has already been called before, undefined
    922         // behavior occurs. If ptr is NULL, no operation is performed.
     901        // The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to
     902        // malloc(), calloc() or realloc().  Otherwise, or if free(ptr) has already been called before, undefined behavior
     903        // occurs. If ptr is NULL, no operation is performed.
    923904        void free( void * addr ) {
    924905                #ifdef __STATISTICS__
    925                         __atomic_add_fetch( &free_calls, 1, __ATOMIC_SEQ_CST );
     906                __atomic_add_fetch( &free_calls, 1, __ATOMIC_SEQ_CST );
    926907                #endif // __STATISTICS__
    927908
     
    931912                if ( unlikely( addr == 0 ) ) {                                  // special case
    932913                        #ifdef __CFA_DEBUG__
    933                                 if ( traceHeap() ) {
    934                                         #define nullmsg "Free( 0x0 ) size:0\n"
    935                                         // Do not debug print free( 0 ), as it can cause recursive entry from sprintf.
    936                                         __cfaabi_dbg_bits_write( nullmsg, sizeof(nullmsg) - 1 );
    937                                 } // if
     914                        if ( traceHeap() ) {
     915                                #define nullmsg "Free( 0x0 ) size:0\n"
     916                                // Do not debug print free( 0 ), as it can cause recursive entry from sprintf.
     917                                __cfaabi_dbg_bits_write( nullmsg, sizeof(nullmsg) - 1 );
     918                        } // if
    938919                        #endif // __CFA_DEBUG__
    939920                        return;
     
    943924        } // free
    944925
    945         // The mallopt() function adjusts parameters that control the behavior of the
    946         // memory-allocation functions (see malloc(3)). The param argument specifies
    947         // the parameter to be modified, and value specifies the new value for that
     926        // The mallopt() function adjusts parameters that control the behavior of the memory-allocation functions (see
     927        // malloc(3)). The param argument specifies the parameter to be modified, and value specifies the new value for that
    948928        // parameter.
    949                 int mallopt( int option, int value ) {
     929        int mallopt( int option, int value ) {
    950930                choose( option ) {
    951                         case M_TOP_PAD:
    952                                 if ( setHeapExpand( value ) ) fallthru default;
    953                         case M_MMAP_THRESHOLD:
    954                                 if ( setMmapStart( value ) ) fallthru default;
    955                         default:
    956                                 // #comment TD : 1 for unsopported feels wrong
    957                                 return 1;                                                                       // success, or unsupported
     931                  case M_TOP_PAD:
     932                        if ( setHeapExpand( value ) ) fallthru default;
     933                  case M_MMAP_THRESHOLD:
     934                        if ( setMmapStart( value ) ) fallthru default;
     935                  default:
     936                        // #comment TD : 1 for unsopported feels wrong
     937                        return 1;                                                                       // success, or unsupported
    958938                } // switch
    959939                return 0;                                                                               // error
    960940        } // mallopt
    961941
    962         // The malloc_trim() function attempts to release free memory at the top
    963         // of the heap (by calling sbrk(2) with a suitable argument).
     942        // The malloc_trim() function attempts to release free memory at the top of the heap (by calling sbrk(2) with a
     943        // suitable argument).
    964944        int malloc_trim( size_t ) {
    965945                return 0;                                                                               // => impossible to release memory
    966946        } // malloc_trim
    967947
    968         // The malloc_usable_size() function returns the number of usable bytes in the
    969         // block pointed to by ptr, a pointer to a block of memory allocated by
    970         // malloc(3) or a related function.
    971                 size_t malloc_usable_size( void * addr ) {
    972                 if ( unlikely( addr == 0 ) ) return 0;                  // null allocation has 0 size
     948        // The malloc_usable_size() function returns the number of usable bytes in the block pointed to by ptr, a pointer to
     949        // a block of memory allocated by malloc(3) or a related function.
     950        size_t malloc_usable_size( void * addr ) {
     951          if ( unlikely( addr == 0 ) ) return 0;                        // null allocation has 0 size
    973952
    974953                HeapManager.Storage.Header * header;
     
    982961
    983962
    984                 // #comment TD : Document this function
     963    // The malloc_alignment() function returns the alignment of the allocation.
    985964        size_t malloc_alignment( void * addr ) {
    986                 if ( unlikely( addr == 0 ) ) return libAlign(); // minimum alignment
     965          if ( unlikely( addr == 0 ) ) return libAlign();       // minimum alignment
    987966                HeapManager.Storage.Header * header = (HeapManager.Storage.Header *)( (char *)addr - sizeof(HeapManager.Storage) );
    988967                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
     
    991970                        return libAlign ();                                                     // minimum alignment
    992971                } // if
    993                 } // malloc_alignment
    994 
    995 
    996                 // #comment TD : Document this function
     972        } // malloc_alignment
     973
     974
     975    // The malloc_zero_fill() function returns true if the allocation is zero filled, i.e., initially allocated by calloc().
    997976        bool malloc_zero_fill( void * addr ) {
    998                 if ( unlikely( addr == 0 ) ) return false;              // null allocation is not zero fill
     977          if ( unlikely( addr == 0 ) ) return false;            // null allocation is not zero fill
    999978
    1000979                HeapManager.Storage.Header * header = (HeapManager.Storage.Header *)( (char *)addr - sizeof(HeapManager.Storage) );
     
    1003982                } // if
    1004983                return (header->kind.real.blockSize & 2) != 0;  // zero filled (calloc/cmemalign) ?
    1005                 } // malloc_zero_fill
    1006 
    1007 
    1008         // #comment TD : Document this function
     984        } // malloc_zero_fill
     985
     986
     987    // The malloc_stats() function prints (on default standard error) statistics about memory allocated by malloc(3) and
     988    // related functions.
    1009989        void malloc_stats( void ) {
    1010990                #ifdef __STATISTICS__
    1011                         printStats();
    1012                         if ( checkFree() ) checkFree( heapManager );
    1013                 #endif // __STATISTICS__
    1014                 } // malloc_stats
    1015 
    1016         // #comment TD : Document this function
    1017                 int malloc_stats_fd( int fd ) {
    1018                 #ifdef __STATISTICS__
    1019                         int temp = statfd;
    1020                         statfd = fd;
    1021                         return temp;
     991                printStats();
     992                if ( checkFree() ) checkFree( heapManager );
     993                #endif // __STATISTICS__
     994        } // malloc_stats
     995
     996        // The malloc_stats_fd() function changes the file descripter where malloc_stats() writes the statistics.
     997        int malloc_stats_fd( int fd ) {
     998                #ifdef __STATISTICS__
     999                int temp = statfd;
     1000                statfd = fd;
     1001                return temp;
    10221002                #else
    1023                         return -1;
    1024                 #endif // __STATISTICS__
    1025                 } // malloc_stats_fd
    1026 
    1027 
    1028         // #comment TD : Document this function
     1003                return -1;
     1004                #endif // __STATISTICS__
     1005        } // malloc_stats_fd
     1006
     1007        // The malloc_info() function exports an XML string that describes the current state of the memory-allocation
     1008        // implementation in the caller.  The string is printed on the file stream stream.  The exported string includes
     1009        // information about all arenas (see malloc(3)).
    10291010        int malloc_info( int options, FILE * stream ) {
    10301011                return printStatsXML( stream );
     
    10321013
    10331014
    1034         // #comment TD : What are these two functions for?
     1015        // The malloc_get_state() function records the current state of all malloc(3) internal bookkeeping variables (but
     1016        // not the actual contents of the heap or the state of malloc_hook(3) functions pointers).  The state is recorded in
     1017        // a system-dependent opaque data structure dynamically allocated via malloc(3), and a pointer to that data
     1018        // structure is returned as the function result.  (It is the caller's responsibility to free(3) this memory.)
    10351019        void * malloc_get_state( void ) {
    1036                 return 0;
     1020                return 0;                                                                               // unsupported
    10371021        } // malloc_get_state
    10381022
     1023
     1024        // The malloc_set_state() function restores the state of all malloc(3) internal bookkeeping variables to the values
     1025        // recorded in the opaque data structure pointed to by state.
    10391026        int malloc_set_state( void * ptr ) {
    1040                 return 0;
     1027                return 0;                                                                               // unsupported
    10411028        } // malloc_set_state
    10421029} // extern "C"
Note: See TracChangeset for help on using the changeset viewer.