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 "SkTypes.h"
9 
10 #include <stdlib.h>
11 
12 #define SK_DEBUGFAILF(fmt, ...) \
13     SkASSERT((SkDebugf(fmt"\n", __VA_ARGS__), false))
14 
sk_out_of_memory(size_t size)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     abort();
19 }
20 
throw_on_failure(size_t size,void * p)21 static inline void* throw_on_failure(size_t size, void* p) {
22     if (size > 0 && p == nullptr) {
23         // If we've got a nullptr here, the only reason we should have failed is running out of RAM.
24         sk_out_of_memory(size);
25     }
26     return p;
27 }
28 
sk_abort_no_print()29 void sk_abort_no_print() {
30 #ifdef SK_BUILD_FOR_WIN
31     // do not display a system dialog before aborting the process
32     _set_abort_behavior(0, _WRITE_ABORT_MSG);
33 #endif
34     abort();
35 }
36 
sk_out_of_memory(void)37 void sk_out_of_memory(void) {
38     SkDEBUGFAIL("sk_out_of_memory");
39     abort();
40 }
41 
sk_malloc_throw(size_t size)42 void* sk_malloc_throw(size_t size) {
43     return sk_malloc_flags(size, SK_MALLOC_THROW);
44 }
45 
sk_realloc_throw(void * addr,size_t size)46 void* sk_realloc_throw(void* addr, size_t size) {
47     return throw_on_failure(size, realloc(addr, size));
48 }
49 
sk_free(void * p)50 void sk_free(void* p) {
51     if (p) {
52         free(p);
53     }
54 }
55 
sk_malloc_flags(size_t size,unsigned flags)56 void* sk_malloc_flags(size_t size, unsigned flags) {
57     void* p = malloc(size);
58     if (flags & SK_MALLOC_THROW) {
59         return throw_on_failure(size, p);
60     } else {
61         return p;
62     }
63 }
64 
sk_calloc(size_t size)65 void* sk_calloc(size_t size) {
66     return calloc(size, 1);
67 }
68 
sk_calloc_throw(size_t size)69 void* sk_calloc_throw(size_t size) {
70     return throw_on_failure(size, sk_calloc(size));
71 }
72