Home | History | Annotate | Download | only in ports
      1 /*
      2  * Copyright 2011 Google Inc.
      3  *
      4  * Use of this source code is governed by a BSD-style license that can be
      5  * found in the LICENSE file.
      6  */
      7 
      8 #include "SkMalloc.h"
      9 
     10 #include <cstdlib>
     11 
     12 #define SK_DEBUGFAILF(fmt, ...) \
     13     SkASSERT((SkDebugf(fmt"\n", __VA_ARGS__), false))
     14 
     15 static inline void sk_out_of_memory(size_t size) {
     16     SK_DEBUGFAILF("sk_out_of_memory (asked for " SK_SIZE_T_SPECIFIER " bytes)",
     17                   size);
     18 #if defined(IS_FUZZING_WITH_AFL)
     19     exit(1);
     20 #else
     21     abort();
     22 #endif
     23 }
     24 
     25 static inline void* throw_on_failure(size_t size, void* p) {
     26     if (size > 0 && p == nullptr) {
     27         // If we've got a nullptr here, the only reason we should have failed is running out of RAM.
     28         sk_out_of_memory(size);
     29     }
     30     return p;
     31 }
     32 
     33 void sk_abort_no_print() {
     34 #if defined(SK_BUILD_FOR_WIN) && defined(SK_IS_BOT)
     35     // do not display a system dialog before aborting the process
     36     _set_abort_behavior(0, _WRITE_ABORT_MSG);
     37 #endif
     38 #if defined(SK_DEBUG) && defined(SK_BUILD_FOR_WIN)
     39     __debugbreak();
     40 #else
     41     abort();
     42 #endif
     43 }
     44 
     45 void sk_out_of_memory(void) {
     46     SkDEBUGFAIL("sk_out_of_memory");
     47 #if defined(IS_FUZZING_WITH_AFL)
     48     exit(1);
     49 #else
     50     abort();
     51 #endif
     52 }
     53 
     54 void* sk_realloc_throw(void* addr, size_t size) {
     55     return throw_on_failure(size, realloc(addr, size));
     56 }
     57 
     58 void sk_free(void* p) {
     59     if (p) {
     60         free(p);
     61     }
     62 }
     63 
     64 void* sk_malloc_flags(size_t size, unsigned flags) {
     65     void* p;
     66     if (flags & SK_MALLOC_ZERO_INITIALIZE) {
     67         p = calloc(size, 1);
     68     } else {
     69         p = malloc(size);
     70     }
     71     if (flags & SK_MALLOC_THROW) {
     72         return throw_on_failure(size, p);
     73     } else {
     74         return p;
     75     }
     76 }
     77