Ignore:
Timestamp:
Aug 11, 2009, 11:22:41 PM (16 years ago)
Author:
[email protected]
Message:

Make it harder to misuse try* allocation routines
https://bugs.webkit.org/show_bug.cgi?id=27469

Reviewed by Gavin Barraclough

Jump through a few hoops to make it much harder to accidentally
miss null-checking of values returned by the try-* allocation
routines.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/JavaScriptCore/wtf/FastMalloc.h

    r47010 r47092  
    2323
    2424#include "Platform.h"
     25#include "PossiblyNull.h"
    2526#include <stdlib.h>
    2627#include <new>
     
    3435    void* fastRealloc(void*, size_t);
    3536
    36     // These functions return 0 if an allocation fails.
    37     void* tryFastMalloc(size_t);
    38     void* tryFastZeroedMalloc(size_t);
    39     void* tryFastCalloc(size_t numElements, size_t elementSize);
    40     void* tryFastRealloc(void*, size_t);
     37    struct TryMallocReturnValue {
     38        TryMallocReturnValue(void* data)
     39            : m_data(data)
     40        {
     41        }
     42        TryMallocReturnValue(const TryMallocReturnValue& source)
     43            : m_data(source.m_data)
     44        {
     45            source.m_data = 0;
     46        }
     47        ~TryMallocReturnValue() { ASSERT(!m_data); }
     48        template <typename T> bool getValue(T& data) WARN_UNUSED_RETURN;
     49        template <typename T> operator PossiblyNull<T>()
     50        {
     51            T value;
     52            getValue(value);
     53            return PossiblyNull<T>(value);
     54        }
     55    private:
     56        mutable void* m_data;
     57    };
     58   
     59    template <typename T> bool TryMallocReturnValue::getValue(T& data) {
     60        union u { void* data; T target; } res;
     61        res.data = m_data;
     62        data = res.target;
     63        bool returnValue = !!m_data;
     64        m_data = 0;
     65        return returnValue;
     66    }
     67
     68    TryMallocReturnValue tryFastMalloc(size_t n);
     69    TryMallocReturnValue tryFastZeroedMalloc(size_t n);
     70    TryMallocReturnValue tryFastCalloc(size_t n_elements, size_t element_size);
     71    TryMallocReturnValue tryFastRealloc(void* p, size_t n);
    4172
    4273    void fastFree(void*);
Note: See TracChangeset for help on using the changeset viewer.