Home | History | Annotate | Download | only in ext
      1 // Copyright (c) 2012 The Chromium 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 #include <stdio.h>
      6 #include <stdlib.h>
      7 #include <new>
      8 
      9 #include "base/process/memory.h"
     10 
     11 #include "third_party/skia/include/core/SkTypes.h"
     12 #include "third_party/skia/include/core/SkThread.h"
     13 
     14 // This implementation of sk_malloc_flags() and friends is identical
     15 // to SkMemory_malloc.c, except that it disables the CRT's new_handler
     16 // during malloc(), when SK_MALLOC_THROW is not set (ie., when
     17 // sk_malloc_flags() would not abort on NULL).
     18 
     19 SK_DECLARE_STATIC_MUTEX(gSkNewHandlerMutex);
     20 
     21 void sk_throw() {
     22     SkASSERT(!"sk_throw");
     23     abort();
     24 }
     25 
     26 void sk_out_of_memory(void) {
     27     SkASSERT(!"sk_out_of_memory");
     28     abort();
     29 }
     30 
     31 void* sk_malloc_throw(size_t size) {
     32     return sk_malloc_flags(size, SK_MALLOC_THROW);
     33 }
     34 
     35 void* sk_realloc_throw(void* addr, size_t size) {
     36     void* p = realloc(addr, size);
     37     if (size == 0) {
     38         return p;
     39     }
     40     if (p == NULL) {
     41         sk_throw();
     42     }
     43     return p;
     44 }
     45 
     46 void sk_free(void* p) {
     47     if (p) {
     48         free(p);
     49     }
     50 }
     51 
     52 void* sk_malloc_flags(size_t size, unsigned flags) {
     53     void* p;
     54 #if defined(ANDROID)
     55     // Android doesn't have std::set_new_handler.
     56     p = malloc(size);
     57 #else
     58     if (!(flags & SK_MALLOC_THROW)) {
     59 #if defined(OS_MACOSX) && !defined(OS_IOS)
     60       p = base::UncheckedMalloc(size);
     61 #else
     62       SkAutoMutexAcquire lock(gSkNewHandlerMutex);
     63       std::new_handler old_handler = std::set_new_handler(NULL);
     64       p = malloc(size);
     65       std::set_new_handler(old_handler);
     66 #endif
     67     } else {
     68       p = malloc(size);
     69     }
     70 #endif
     71     if (p == NULL) {
     72         if (flags & SK_MALLOC_THROW) {
     73             sk_throw();
     74         }
     75     }
     76     return p;
     77 }
     78