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.
9 #include "base/process/memory.h"
11 #include "third_party/skia/include/core/SkTypes.h"
12 #include "third_party/skia/include/core/SkThread.h"
14 // This implementation of sk_malloc_flags() and friends is identical to
15 // SkMemory_malloc.cpp, except that it disables the CRT's new_handler during
16 // malloc() and calloc() when SK_MALLOC_THROW is not set (because our normal
17 // new_handler itself will crash on failure when using tcmalloc).
19 SK_DECLARE_STATIC_MUTEX(gSkNewHandlerMutex
);
21 static inline void* throw_on_failure(size_t size
, void* p
) {
22 if (size
> 0 && p
== NULL
) {
23 // If we've got a NULL here, the only reason we should have failed is running out of RAM.
30 SkASSERT(!"sk_throw");
34 void sk_out_of_memory(void) {
35 SkASSERT(!"sk_out_of_memory");
39 void* sk_realloc_throw(void* addr
, size_t size
) {
40 return throw_on_failure(size
, realloc(addr
, size
));
43 void sk_free(void* p
) {
49 void* sk_malloc_throw(size_t size
) {
50 return throw_on_failure(size
, malloc(size
));
53 // Platform specific ways to try really hard to get a malloc that won't crash on failure.
54 static void* sk_malloc_nothrow(size_t size
) {
56 // Android doesn't have std::set_new_handler, so we just call malloc.
58 #elif defined(OS_MACOSX) && !defined(OS_IOS)
59 return base::UncheckedMalloc(size
);
61 // This is not really thread safe. It only won't collide with itself, but we're totally
62 // unprotected from races with other code that calls set_new_handler.
63 SkAutoMutexAcquire
lock(gSkNewHandlerMutex
);
64 std::new_handler old_handler
= std::set_new_handler(NULL
);
65 void* p
= malloc(size
);
66 std::set_new_handler(old_handler
);
71 void* sk_malloc_flags(size_t size
, unsigned flags
) {
72 if (flags
& SK_MALLOC_THROW
) {
73 return sk_malloc_throw(size
);
75 return sk_malloc_nothrow(size
);
78 void* sk_calloc_throw(size_t size
) {
79 return throw_on_failure(size
, calloc(size
, 1));
82 // Jump through the same hoops as sk_malloc_nothrow to avoid a crash, but for calloc.
83 void* sk_calloc(size_t size
) {
85 return calloc(size
, 1);
86 #elif defined(OS_MACOSX) && !defined(OS_IOS)
87 return base::UncheckedCalloc(size
, 1);
89 SkAutoMutexAcquire
lock(gSkNewHandlerMutex
);
90 std::new_handler old_handler
= std::set_new_handler(NULL
);
91 void* p
= calloc(size
, 1);
92 std::set_new_handler(old_handler
);