xref: /aosp_15_r20/external/pigweed/pw_malloc/docs.rst (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1.. _module-pw_malloc:
2
3=========
4pw_malloc
5=========
6.. pigweed-module::
7   :name: pw_malloc
8
9This module defines an interface for replacing the standard libc dynamic memory
10operations.
11
12This facade doesn't implement any heap structure or dynamic memory methods. It
13only requires that backends implements ``pw::malloc::GetSystemAllocator`` and
14optionally ``pw::malloc::InitSystemAllocator``. These functions are called
15before static initialization, and are responsible for initializing global data
16structures required by the ``malloc`` implementation.
17
18The intent of this module is to provide an interface for user-provided dynamic
19memory operations that is compatible with different implementations.
20
21-----
22Setup
23-----
24This module requires the following setup:
25
261. Choose a ``pw_malloc`` backend, or write one yourself.
272. Select a backend in your build system. If using GN build, Specify the
28   ``pw_malloc_BACKEND`` GN build arg to point to the library that provides a
29   ``pw_malloc`` backend. If using the Bazel build, add the constraint value for
30   the backend library that provides a ``pw_malloc`` backend.
313. Add a dependency on the ``pw_malloc`` facade in your targets ``executable``
32   build template, e.g.:
33
34.. code-block::
35
36   template("platform_executable") {
37      target("executable", target_name) {
38         deps = []
39         config = []
40         forward_variables_from(invoker, "*")
41         if (pw_malloc_BACKEND != "") {
42            deps += [ dir_pw_malloc ]
43         }
44      }
45   }
46
47Compile-time configuration
48==========================
49This module has configuration options that globally affect the behavior of
50``pw_malloc`` via compile-time configuration of this module.
51
52.. doxygendefine:: PW_MALLOC_LOCK_TYPE
53.. doxygendefine:: PW_MALLOC_METRICS_TYPE
54.. doxygendefine:: PW_MALLOC_BLOCK_OFFSET_TYPE
55.. doxygendefine:: PW_MALLOC_MIN_BUCKET_SIZE
56.. doxygendefine:: PW_MALLOC_NUM_BUCKETS
57.. doxygendefine:: PW_MALLOC_DUAL_FIRST_FIT_THRESHOLD
58
59See the
60:ref:`module documentation <module-structure-compile-time-configuration>` for
61more details.
62
63Heap initialization
64===================
65You can provide a region of memory to use as heap as either a byte span or a
66pair of addresses to ``pw::malloc::InitSystemAllocator``.
67
68-----
69Usage
70-----
71Once the heap is initialized, you may simply use ``malloc`` and ``free`` as you
72would normally, as well as standard library functions like ``strdup`` and
73built-in routines like ``new`` that use those functions.
74
75If you configured a ``PW_MALLOC_METRICS_TYPE``, you can retrieve metrics using
76``pw::malloc::GetSystemMetrics()``.
77
78.. toctree::
79   :maxdepth: 1
80   :hidden:
81
82   Backends <backends>
83