bh_memory.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #ifndef _BH_MEMORY_H
  6. #define _BH_MEMORY_H
  7. #ifdef __cplusplus
  8. extern "C" {
  9. #endif
  10. #define BH_KB (1024)
  11. #define BH_MB ((BH_KB)*1024)
  12. #define BH_GB ((BH_MB)*1024)
  13. /**
  14. * Initialize memory allocator with a pool, the bh_malloc/bh_free function
  15. * will malloc/free memory from the pool
  16. *
  17. * @param mem the pool buffer
  18. * @param bytes the size bytes of the buffer
  19. *
  20. * @return 0 if success, -1 otherwise
  21. */
  22. int bh_memory_init_with_pool(void *mem, unsigned int bytes);
  23. /**
  24. * Initialize memory allocator with memory allocator, the bh_malloc/bh_free
  25. * function will malloc/free memory with the allocator passed
  26. *
  27. * @param malloc_func the malloc function
  28. * @param free_func the free function
  29. *
  30. * @return 0 if success, -1 otherwise
  31. */
  32. int bh_memory_init_with_allocator(void *malloc_func, void *free_func);
  33. /**
  34. * Destroy memory
  35. */
  36. void bh_memory_destroy();
  37. /**
  38. * Get the pool size of memory, if memory is initialized with allocator,
  39. * return 1GB by default.
  40. */
  41. unsigned bh_memory_pool_size();
  42. #if BEIHAI_ENABLE_MEMORY_PROFILING == 0
  43. /**
  44. * This function allocates a memory chunk from system
  45. *
  46. * @param size bytes need allocate
  47. *
  48. * @return the pointer to memory allocated
  49. */
  50. void* bh_malloc(unsigned int size);
  51. /**
  52. * This function frees memory chunk
  53. *
  54. * @param ptr the pointer to memory need free
  55. */
  56. void bh_free(void *ptr);
  57. #else
  58. void* bh_malloc_profile(const char *file, int line, const char *func, unsigned int size);
  59. void bh_free_profile(const char *file, int line, const char *func, void *ptr);
  60. #define bh_malloc(size) bh_malloc_profile(__FILE__, __LINE__, __func__, size)
  61. #define bh_free(ptr) bh_free_profile(__FILE__, __LINE__, __func__, ptr)
  62. /**
  63. * Print current memory profiling data
  64. *
  65. * @param file file name of the caller
  66. * @param line line of the file of the caller
  67. * @param func function name of the caller
  68. */
  69. void memory_profile_print(const char *file, int line, const char *func, int alloc);
  70. /**
  71. * Summarize memory usage and print it out
  72. * Can use awk to analyze the output like below:
  73. * awk -F: '{print $2,$4,$6,$8,$9}' OFS="\t" ./out.txt | sort -n -r -k 1
  74. */
  75. void memory_usage_summarize();
  76. #endif
  77. #ifdef __cplusplus
  78. }
  79. #endif
  80. #endif /* #ifndef _BH_MEMORY_H */