SkMemory_malloc.cpp 1.7 KB

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