• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
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 #if defined(IS_FUZZING_WITH_AFL)
19     exit(1);
20 #else
21     abort();
22 #endif
23 }
24 
throw_on_failure(size_t size,void * p)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 
sk_abort_no_print()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 #elif defined(__clang__)
41     __builtin_debugtrap();
42 #else
43     abort();
44 #endif
45 }
46 
sk_out_of_memory(void)47 void sk_out_of_memory(void) {
48     SkDEBUGFAIL("sk_out_of_memory");
49 #if defined(IS_FUZZING_WITH_AFL)
50     exit(1);
51 #else
52     abort();
53 #endif
54 }
55 
sk_realloc_throw(void * addr,size_t size)56 void* sk_realloc_throw(void* addr, size_t size) {
57     return throw_on_failure(size, realloc(addr, size));
58 }
59 
sk_free(void * p)60 void sk_free(void* p) {
61     if (p) {
62         free(p);
63     }
64 }
65 
sk_malloc_flags(size_t size,unsigned flags)66 void* sk_malloc_flags(size_t size, unsigned flags) {
67     void* p;
68     if (flags & SK_MALLOC_ZERO_INITIALIZE) {
69         p = calloc(size, 1);
70     } else {
71         p = malloc(size);
72     }
73     if (flags & SK_MALLOC_THROW) {
74         return throw_on_failure(size, p);
75     } else {
76         return p;
77     }
78 }
79