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.
7 #include "base/process/memory.h"
9 #include "third_party/skia/include/core/SkTypes.h"
11 // This implementation of sk_malloc_flags() and friends is similar to
12 // SkMemory_malloc.cpp, except it uses base::UncheckedMalloc and friends
13 // for non-SK_MALLOC_THROW calls.
15 // The name of this file is historic: a previous implementation tried to
16 // use std::set_new_handler() for the same effect, but it didn't actually work.
18 static inline void* throw_on_failure(size_t size
, void* p
) {
19 if (size
> 0 && p
== NULL
) {
20 // If we've got a NULL here, the only reason we should have failed is running out of RAM.
27 SkASSERT(!"sk_throw");
31 void sk_out_of_memory(void) {
32 SkASSERT(!"sk_out_of_memory");
36 void* sk_realloc_throw(void* addr
, size_t size
) {
37 return throw_on_failure(size
, realloc(addr
, size
));
40 void sk_free(void* p
) {
46 // We get lots of bugs filed on us that amount to overcommiting bitmap memory,
47 // then some time later failing to back that VM with physical memory.
48 // They're hard to track down, so in Debug mode we touch all memory right up front.
50 // For malloc, fill is an arbitrary byte and ideally not 0. For calloc, it's got to be 0.
51 static void* prevent_overcommit(int fill
, size_t size
, void* p
) {
52 // We probably only need to touch one byte per page, but memset makes things easy.
53 SkDEBUGCODE(memset(p
, fill
, size
));
57 void* sk_malloc_throw(size_t size
) {
58 return prevent_overcommit(0x42, size
, throw_on_failure(size
, malloc(size
)));
61 static void* sk_malloc_nothrow(size_t size
) {
62 // TODO(b.kelemen): we should always use UncheckedMalloc but currently it
63 // doesn't work as intended everywhere.
66 result
= malloc(size
);
68 // It's the responsibility of the caller to check the return value.
69 ignore_result(base::UncheckedMalloc(size
, &result
));
72 prevent_overcommit(0x47, size
, result
);
77 void* sk_malloc_flags(size_t size
, unsigned flags
) {
78 if (flags
& SK_MALLOC_THROW
) {
79 return sk_malloc_throw(size
);
81 return sk_malloc_nothrow(size
);
84 void* sk_calloc_throw(size_t size
) {
85 return prevent_overcommit(0, size
, throw_on_failure(size
, calloc(size
, 1)));
88 void* sk_calloc(size_t size
) {
89 // TODO(b.kelemen): we should always use UncheckedCalloc but currently it
90 // doesn't work as intended everywhere.
93 result
= calloc(1, size
);
95 // It's the responsibility of the caller to check the return value.
96 ignore_result(base::UncheckedCalloc(size
, 1, &result
));
99 prevent_overcommit(0, size
, result
);