Branch data Line data Source code
1 : : /*
2 : : * Copyright (c) 2019 Intel Corporation
3 : : * Copyright (c) 2026 Qualcomm Technologies, Inc.
4 : : *
5 : : * SPDX-License-Identifier: Apache-2.0
6 : : */
7 : : #include <zephyr/sys/minmax.h>
8 : : #include <zephyr/sys/sys_heap.h>
9 : : #include <zephyr/sys/util.h>
10 : : #include <zephyr/sys/heap_listener.h>
11 : : #include <zephyr/kernel.h>
12 : : #include <zephyr/logging/log.h>
13 : : #include <string.h>
14 : : #include "heap.h"
15 : :
16 : : LOG_MODULE_REGISTER(os_heap, CONFIG_SYS_HEAP_LOG_LEVEL);
17 : : #ifdef CONFIG_MSAN
18 : : #include <sanitizer/msan_interface.h>
19 : : #endif
20 : :
21 : : #ifdef CONFIG_SYS_HEAP_CANARIES_RANDOM
22 : : #include <zephyr/random/random.h>
23 : : #endif
24 : :
25 : : #ifdef CONFIG_SYS_HEAP_SANITIZER_HOOKS
26 : : #include "heap_sanitizer.h"
27 : : #endif
28 : :
29 : : #ifdef CONFIG_SYS_HEAP_CALLER_POINTER
30 : : /*
31 : : * Must be a macro: __builtin_return_address() must be evaluated in the
32 : : * allocator's own stack frame to capture the correct call site.
33 : : */
34 : : #define HEAP_CAPTURE_CALLER() \
35 : : __builtin_return_address(CONFIG_SYS_HEAP_CALLER_LEVEL)
36 : : #endif
37 : :
38 : : #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
39 : : static inline void increase_allocated_bytes(struct z_heap *h, size_t num_bytes)
40 : : {
41 : : h->allocated_bytes += num_bytes;
42 : : h->max_allocated_bytes = max(h->max_allocated_bytes, h->allocated_bytes);
43 : : }
44 : : #endif
45 : :
46 : : #ifdef CONFIG_SYS_HEAP_CANARIES
47 : : #ifdef CONFIG_SYS_HEAP_CANARIES_RANDOM
48 : : #define HEAP_CANARY_MAGIC(h) h->canary_base
49 : : #else
50 : : #define HEAP_CANARY_MAGIC(h) 0x5A6B7C8DU
51 : : #endif
52 : : #define HEAP_CANARY_POISON 0xDEADBEEFU
53 : :
54 : : /*
55 : : * Compute a per-chunk canary from its address and size as well as the
56 : : * base canary to detect misplaced canaries.
57 : : */
58 : : static inline uint32_t compute_canary(struct z_heap *h, chunkid_t c)
59 : : {
60 : : return ((c >> 16) | (c << 16)) ^ chunk_size(h, c) ^ HEAP_CANARY_MAGIC(h);
61 : : }
62 : :
63 : : static inline void set_chunk_canary(struct z_heap *h, chunkid_t c)
64 : : {
65 : : chunk_trailer(h, c)->canary = compute_canary(h, c);
66 : : }
67 : :
68 : : static inline void verify_chunk_canary(struct z_heap *h, chunkid_t c, void *mem)
69 : : {
70 : : uint32_t expected = compute_canary(h, c);
71 : : uint32_t found = chunk_trailer(h, c)->canary;
72 : :
73 : : if (found != expected) {
74 : : if (found == HEAP_CANARY_POISON) {
75 : : LOG_ERR("heap canary: double free at %p", mem);
76 : : } else {
77 : : LOG_ERR("heap canary: corruption at %p", mem);
78 : : }
79 : : k_panic();
80 : : }
81 : : }
82 : :
83 : : static inline void poison_chunk_canary(struct z_heap *h, chunkid_t c)
84 : : {
85 : : chunk_trailer(h, c)->canary = HEAP_CANARY_POISON;
86 : : }
87 : : #else
88 : : #define set_chunk_canary(h, c) do { } while (false)
89 : : #define verify_chunk_canary(h, c, mem) do { } while (false)
90 : : #define poison_chunk_canary(h, c) do { } while (false)
91 : : #endif /* CONFIG_SYS_HEAP_CANARIES */
92 : :
93 : 0 : static void *chunk_mem(struct z_heap *h, chunkid_t c)
94 : : {
95 : 0 : chunk_unit_t *buf = chunk_buf(h);
96 : 0 : uint8_t *ret = ((uint8_t *)&buf[c]) + chunk_header_bytes(h);
97 : :
98 : 0 : CHECK(!(((uintptr_t)ret) & (big_heap(h) ? 7 : 3)));
99 : :
100 : 0 : return ret;
101 : : }
102 : :
103 : 0 : static void free_list_remove_bidx(struct z_heap *h, chunkid_t c, int bidx)
104 : : {
105 : 0 : struct z_heap_bucket *b = &h->buckets[bidx];
106 : :
107 : 0 : CHECK(b->next != 0);
108 : 0 : CHECK(h->avail_buckets & BIT(bidx));
109 : :
110 [ # # ]: 0 : if (next_free_chunk(h, c) == c) {
111 : : /* this is the last chunk */
112 : 0 : h->avail_buckets &= ~BIT(bidx);
113 : 0 : b->next = 0;
114 : : } else {
115 : 0 : chunkid_t first = prev_free_chunk(h, c),
116 : 0 : second = next_free_chunk(h, c);
117 : :
118 : 0 : if (SYS_HEAP_HARDENING_MODERATE &&
119 [ # # ]: 0 : (next_free_chunk(h, first) != c ||
120 [ # # ]: 0 : prev_free_chunk(h, second) != c)) {
121 : 0 : LOG_ERR("heap corruption (free list linkage)");
122 : 0 : k_panic();
123 : : }
124 : :
125 : 0 : b->next = second;
126 : 0 : set_next_free_chunk(h, first, second);
127 : 0 : set_prev_free_chunk(h, second, first);
128 : : }
129 : :
130 : : #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
131 : : h->free_bytes -= chunk_usable_bytes(h, c);
132 : : #endif
133 : 0 : }
134 : :
135 : 0 : static void free_list_remove(struct z_heap *h, chunkid_t c)
136 : : {
137 [ # # ]: 0 : if (!undersized_chunk(h, c)) {
138 : 0 : int bidx = bucket_idx(h, chunk_size(h, c));
139 : 0 : free_list_remove_bidx(h, c, bidx);
140 : : }
141 : 0 : }
142 : :
143 : 0 : static void free_list_add_bidx(struct z_heap *h, chunkid_t c, int bidx)
144 : : {
145 : 0 : struct z_heap_bucket *b = &h->buckets[bidx];
146 : :
147 [ # # ]: 0 : if (b->next == 0U) {
148 : 0 : CHECK((h->avail_buckets & BIT(bidx)) == 0);
149 : :
150 : : /* Empty list, first item */
151 : 0 : h->avail_buckets |= BIT(bidx);
152 : 0 : b->next = c;
153 : 0 : set_prev_free_chunk(h, c, c);
154 : 0 : set_next_free_chunk(h, c, c);
155 : : } else {
156 : 0 : CHECK(h->avail_buckets & BIT(bidx));
157 : :
158 : : /* Insert before (!) the "next" pointer */
159 : 0 : chunkid_t second = b->next;
160 : 0 : chunkid_t first = prev_free_chunk(h, second);
161 : :
162 : 0 : if (SYS_HEAP_HARDENING_MODERATE &&
163 [ # # ]: 0 : next_free_chunk(h, first) != second) {
164 : 0 : LOG_ERR("heap corruption (free list linkage)");
165 : 0 : k_panic();
166 : : }
167 : :
168 : 0 : set_prev_free_chunk(h, c, first);
169 : 0 : set_next_free_chunk(h, c, second);
170 : 0 : set_next_free_chunk(h, first, c);
171 : 0 : set_prev_free_chunk(h, second, c);
172 : : }
173 : :
174 : : #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
175 : : h->free_bytes += chunk_usable_bytes(h, c);
176 : : #endif
177 : 0 : }
178 : :
179 : 0 : static void free_list_add(struct z_heap *h, chunkid_t c)
180 : : {
181 [ # # ]: 0 : if (!undersized_chunk(h, c)) {
182 : 0 : int bidx = bucket_idx(h, chunk_size(h, c));
183 : 0 : free_list_add_bidx(h, c, bidx);
184 : : }
185 : 0 : }
186 : :
187 : : /*
188 : : * Validate a free chunk's structural integrity before trusting its
189 : : * header fields. Called before free list removal or merge operations.
190 : : * @left_trusted: true if the left neighbor was already validated by
191 : : * the caller (e.g. the chunk being freed), false if its canary
192 : : * should be verified to detect overflow into this free chunk.
193 : : */
194 : 0 : static void free_chunk_check(struct z_heap *h, chunkid_t c, bool left_trusted)
195 : : {
196 : 0 : if (SYS_HEAP_HARDENING_MODERATE &&
197 [ # # ]: 0 : (chunk_used(h, c) ||
198 [ # # ]: 0 : left_chunk(h, right_chunk(h, c)) != c ||
199 [ # # ]: 0 : right_chunk(h, left_chunk(h, c)) != c)) {
200 : 0 : LOG_ERR("heap corruption (free chunk linkage)");
201 : 0 : k_panic();
202 : : }
203 : :
204 : : /*
205 : : * Free chunks have no canary of their own, but their header
206 : : * can be corrupted by a buffer overflow from the used chunk
207 : : * to their left:
208 : : *
209 : : * [used_L] [data_L] [trailer_L] [hdr_F] [free...]
210 : : * overflow ------>
211 : : *
212 : : * Validating left's trailer canary before trusting hdr_F's
213 : : * metadata substitutes for a per-free-chunk canary: the
214 : : * overflow must corrupt trailer_L before reaching hdr_F.
215 : : */
216 : 0 : if (SYS_HEAP_HARDENING_FULL && !left_trusted) {
217 : 0 : verify_chunk_canary(h, left_chunk(h, c),
218 : : chunk_mem(h, left_chunk(h, c)));
219 : : }
220 : 0 : }
221 : :
222 : : /* Splits a chunk "lc" into a left chunk and a right chunk at "rc".
223 : : * Leaves both chunks marked "free"
224 : : */
225 : 0 : static void split_chunks(struct z_heap *h, chunkid_t lc, chunkid_t rc)
226 : : {
227 : 0 : CHECK(rc > lc);
228 : 0 : CHECK(rc - lc < chunk_size(h, lc));
229 : :
230 : 0 : chunksz_t sz0 = chunk_size(h, lc);
231 : 0 : chunksz_t lsz = rc - lc;
232 : 0 : chunksz_t rsz = sz0 - lsz;
233 : :
234 : 0 : set_chunk_size(h, lc, lsz);
235 : 0 : set_chunk_size(h, rc, rsz);
236 : 0 : set_left_chunk_size(h, rc, lsz);
237 : 0 : set_left_chunk_size(h, right_chunk(h, rc), rsz);
238 : 0 : }
239 : :
240 : : /* Does not modify free list */
241 : 0 : static void merge_chunks(struct z_heap *h, chunkid_t lc, chunkid_t rc)
242 : : {
243 : 0 : chunksz_t newsz = chunk_size(h, lc) + chunk_size(h, rc);
244 : :
245 : 0 : set_chunk_size(h, lc, newsz);
246 : 0 : set_left_chunk_size(h, right_chunk(h, rc), newsz);
247 : 0 : }
248 : :
249 : 0 : static void free_chunk(struct z_heap *h, chunkid_t c)
250 : : {
251 : 0 : chunkid_t rc = right_chunk(h, c);
252 : :
253 : : /* Merge with free right chunk? */
254 [ # # ]: 0 : if (!chunk_used(h, rc)) {
255 : 0 : free_chunk_check(h, rc, true);
256 : 0 : free_list_remove(h, rc);
257 : 0 : merge_chunks(h, c, rc);
258 : : }
259 : :
260 : 0 : chunkid_t lc = left_chunk(h, c);
261 : :
262 : : /* Merge with free left chunk? */
263 [ # # ]: 0 : if (!chunk_used(h, lc)) {
264 : 0 : free_chunk_check(h, lc, false);
265 : 0 : free_list_remove(h, lc);
266 : 0 : merge_chunks(h, lc, c);
267 : 0 : c = lc;
268 : : } else if (SYS_HEAP_HARDENING_FULL) {
269 : : /*
270 : : * Left neighbor is used. Verify its canary to detect
271 : : * an overflow from the left that corrupted our header
272 : : * (specifically LEFT_SIZE) without touching our trailer.
273 : : */
274 : 0 : verify_chunk_canary(h, lc, chunk_mem(h, lc));
275 : : }
276 : :
277 : 0 : if (SYS_HEAP_HARDENING_FULL) {
278 : 0 : poison_chunk_canary(h, c);
279 : : }
280 : :
281 : 0 : free_list_add(h, c);
282 : 0 : }
283 : :
284 : : /*
285 : : * Return the closest chunk ID corresponding to given memory pointer.
286 : : * Here "closest" is only meaningful in the context of sys_heap_aligned_alloc()
287 : : * where wanted alignment might not always correspond to a chunk header
288 : : * boundary.
289 : : */
290 : 0 : static chunkid_t mem_to_chunkid(struct z_heap *h, void *p)
291 : : {
292 : 0 : uint8_t *mem = p, *base = (uint8_t *)chunk_buf(h);
293 : 0 : return (mem - chunk_header_bytes(h) - base) / CHUNK_UNIT;
294 : : }
295 : :
296 : 0 : void sys_heap_free(struct sys_heap *heap, void *mem)
297 : : {
298 [ # # ]: 0 : if (mem == NULL) {
299 : : return; /* ISO C free() semantics */
300 : : }
301 : 0 : struct z_heap *h = heap->heap;
302 : 0 : chunkid_t c = mem_to_chunkid(h, mem);
303 : :
304 : 0 : if (SYS_HEAP_HARDENING_FULL) {
305 : 0 : verify_chunk_canary(h, c, mem);
306 : : }
307 : :
308 [ # # ]: 0 : if (SYS_HEAP_HARDENING_BASIC && !chunk_used(h, c)) {
309 : 0 : LOG_ERR("heap corruption (double free?) at %p", mem);
310 : 0 : k_panic();
311 : : }
312 : :
313 : : IF_ENABLED(CONFIG_SYS_HEAP_RELEASE_HOOK,
314 : : (sys_heap_release_hook(mem, chunk_usable_bytes(h, c) - mem_align_gap(h, mem));))
315 : :
316 : : /*
317 : : * Header fields are ordered as LEFT_SIZE then SIZE_AND_USED.
318 : : * This places SIZE_AND_USED immediately before the user data,
319 : : * and LEFT_SIZE of the following chunk immediately after:
320 : : *
321 : : * chunk c right_chunk(c)
322 : : * +-----------+---------+-----------+---------+
323 : : * | SIZE (1) | data | L_SIZE (2)| SIZE |
324 : : * +-----------+---------+-----------+---------+
325 : : *
326 : : * A buffer overflow from c's data corrupts field (2).
327 : : * Checking left(right(c)) == c catches this because
328 : : * right(c) reads field (1) and left() reads field (2):
329 : : * the two fields straddle the data buffer, so the
330 : : * round-trip fails if either side was corrupted.
331 : : */
332 : 0 : if (SYS_HEAP_HARDENING_BASIC &&
333 [ # # ]: 0 : left_chunk(h, right_chunk(h, c)) != c) {
334 : 0 : LOG_ERR("heap corruption (buffer overflow?) at %p", mem);
335 : 0 : k_panic();
336 : : }
337 : :
338 : : /*
339 : : * The above check validated SIZE_AND_USED using a field from
340 : : * the next chunk. Now validate LEFT_SIZE: if it was corrupted
341 : : * (by an overflow from the left neighbor or an underflow from
342 : : * our own buffer) then right(left(c)) won't return to c.
343 : : */
344 : 0 : if (SYS_HEAP_HARDENING_MODERATE &&
345 [ # # ]: 0 : right_chunk(h, left_chunk(h, c)) != c) {
346 : 0 : LOG_ERR("heap corruption (left neighbor?) at %p", mem);
347 : 0 : k_panic();
348 : : }
349 : :
350 : 0 : if (SYS_HEAP_HARDENING_EXTREME && !z_heap_full_check(h)) {
351 : : LOG_ERR("heap validation failed");
352 : 0 : k_panic();
353 : : }
354 : :
355 : 0 : set_chunk_used(h, c, false);
356 : : #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
357 : : h->allocated_bytes -= chunk_usable_bytes(h, c);
358 : : #endif
359 : :
360 : 0 : IF_ENABLED(CONFIG_SYS_HEAP_THREAD_STATS, (z_heap_stats_on_free(heap, c, mem)));
361 : :
362 : : #ifdef CONFIG_SYS_HEAP_LISTENER
363 : : heap_listener_notify_free(HEAP_ID_FROM_POINTER(heap), mem,
364 : : chunk_usable_bytes(h, c) - mem_align_gap(h, mem));
365 : : #endif
366 : :
367 : : IF_ENABLED(CONFIG_SYS_HEAP_SANITIZER_HOOKS,
368 : : (heap_sanitizer_on_free(heap, mem,
369 : 0 : chunk_usable_bytes(h, c) - mem_align_gap(h, mem))));
370 : 0 : free_chunk(h, c);
371 : : }
372 : :
373 : 0 : size_t sys_heap_usable_size(struct sys_heap *heap, void *mem)
374 : : {
375 : 0 : struct z_heap *h = heap->heap;
376 : 0 : chunkid_t c = mem_to_chunkid(h, mem);
377 : :
378 : 0 : if (SYS_HEAP_HARDENING_FULL) {
379 : 0 : verify_chunk_canary(h, c, mem);
380 : : }
381 : :
382 : 0 : return chunk_usable_bytes(h, c) - mem_align_gap(h, mem);
383 : : }
384 : :
385 : 0 : static chunkid_t alloc_chunk(struct z_heap *h, chunksz_t sz)
386 : : {
387 : 0 : if (SYS_HEAP_HARDENING_EXTREME && !z_heap_full_check(h)) {
388 : : LOG_ERR("heap validation failed");
389 : 0 : k_panic();
390 : : }
391 : :
392 : 0 : int bi = bucket_idx(h, sz);
393 : 0 : struct z_heap_bucket *b = &h->buckets[bi];
394 : :
395 : 0 : CHECK(bi <= bucket_idx(h, h->end_chunk));
396 : :
397 : : /* First try a bounded count of items from the minimal bucket
398 : : * size. These may not fit, trying (e.g.) three means that
399 : : * (assuming that chunk sizes are evenly distributed[1]) we
400 : : * have a 7/8 chance of finding a match, thus keeping the
401 : : * number of such blocks consumed by allocation higher than
402 : : * the number of smaller blocks created by fragmenting larger
403 : : * ones.
404 : : *
405 : : * [1] In practice, they are never evenly distributed, of
406 : : * course. But even in pathological situations we still
407 : : * maintain our constant time performance and at worst see
408 : : * fragmentation waste of the order of the block allocated
409 : : * only.
410 : : */
411 [ # # ]: 0 : if (b->next != 0U) {
412 : : chunkid_t first = b->next;
413 : : int i = CONFIG_SYS_HEAP_ALLOC_LOOPS;
414 : 0 : do {
415 : 0 : chunkid_t c = b->next;
416 [ # # ]: 0 : if (chunk_size(h, c) >= sz) {
417 : 0 : free_chunk_check(h, c, false);
418 : 0 : free_list_remove_bidx(h, c, bi);
419 : 0 : return c;
420 : : }
421 : 0 : b->next = next_free_chunk(h, c);
422 : 0 : CHECK(b->next != 0);
423 [ # # # # ]: 0 : } while (--i && b->next != first);
424 : : }
425 : :
426 : : /* Otherwise pick the smallest non-empty bucket guaranteed to
427 : : * fit and use that unconditionally.
428 : : */
429 : 0 : uint32_t bmask = h->avail_buckets & ~BIT_MASK(bi + 1);
430 : :
431 [ # # ]: 0 : if (bmask != 0U) {
432 : 0 : int minbucket = __builtin_ctz(bmask);
433 : 0 : chunkid_t c = h->buckets[minbucket].next;
434 : :
435 : 0 : free_chunk_check(h, c, false);
436 : 0 : free_list_remove_bidx(h, c, minbucket);
437 : 0 : CHECK(chunk_size(h, c) >= sz);
438 : 0 : return c;
439 : : }
440 : :
441 : : return 0;
442 : : }
443 : :
444 : 0 : void *sys_heap_alloc(struct sys_heap *heap, size_t bytes)
445 : : {
446 : 0 : struct z_heap *h = heap->heap;
447 : 0 : void *mem;
448 : :
449 [ # # ]: 0 : if (bytes == 0U) {
450 : : return NULL;
451 : : }
452 : :
453 : 0 : chunksz_t chunk_sz = bytes_to_chunksz(h, bytes, 0);
454 : 0 : chunkid_t c = alloc_chunk(h, chunk_sz);
455 : :
456 [ # # ]: 0 : if (c == 0U) {
457 : : return NULL;
458 : : }
459 : :
460 : : /* Split off remainder if any */
461 [ # # ]: 0 : if (chunk_size(h, c) > chunk_sz) {
462 : 0 : split_chunks(h, c, c + chunk_sz);
463 : 0 : free_list_add(h, c + chunk_sz);
464 : : }
465 : :
466 : 0 : set_chunk_used(h, c, true);
467 : 0 : if (SYS_HEAP_HARDENING_FULL) {
468 : 0 : set_chunk_canary(h, c);
469 : : }
470 : :
471 : 0 : mem = chunk_mem(h, c);
472 : : #ifdef CONFIG_SYS_HEAP_CALLER_POINTER
473 : : chunk_trailer(h, c)->caller = HEAP_CAPTURE_CALLER();
474 : : #endif
475 : 0 : IF_ENABLED(CONFIG_SYS_HEAP_THREAD_STATS, (z_heap_stats_on_alloc(heap, c, mem)));
476 : :
477 : : #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
478 : : increase_allocated_bytes(h, chunk_usable_bytes(h, c));
479 : : #endif
480 : :
481 : : #ifdef CONFIG_SYS_HEAP_LISTENER
482 : : heap_listener_notify_alloc(HEAP_ID_FROM_POINTER(heap), mem,
483 : : chunk_usable_bytes(h, c));
484 : : #endif
485 : :
486 : 0 : IF_ENABLED(CONFIG_SYS_HEAP_SANITIZER_HOOKS, (heap_sanitizer_on_alloc(heap, mem, bytes)));
487 : 0 : IF_ENABLED(CONFIG_MSAN, (__msan_allocated_memory(mem, bytes)));
488 : 0 : return mem;
489 : : }
490 : :
491 : 0 : void *sys_heap_noalign_alloc(struct sys_heap *heap, size_t align, size_t bytes)
492 : : {
493 : 0 : ARG_UNUSED(align);
494 : :
495 : 0 : return sys_heap_alloc(heap, bytes);
496 : : }
497 : :
498 : 0 : void *sys_heap_aligned_alloc(struct sys_heap *heap, size_t align, size_t bytes)
499 : : {
500 : 0 : struct z_heap *h = heap->heap;
501 : 0 : size_t gap, rew;
502 : :
503 : : /*
504 : : * Split align and rewind values (if any).
505 : : * We allow for one bit of rewind in addition to the alignment
506 : : * value to efficiently accommodate z_alloc_helper().
507 : : * So if e.g. align = 0x28 (32 | 8) this means we align to a 32-byte
508 : : * boundary and then rewind 8 bytes.
509 : : */
510 : 0 : rew = align & -align;
511 [ # # ]: 0 : if (align != rew) {
512 : 0 : align -= rew;
513 : 0 : gap = min(rew, chunk_header_bytes(h));
514 : : } else {
515 [ # # ]: 0 : if (align <= chunk_header_bytes(h)) {
516 : 0 : return sys_heap_alloc(heap, bytes);
517 : : }
518 : : rew = 0;
519 : : gap = chunk_header_bytes(h);
520 : : }
521 [ # # ]: 0 : __ASSERT((align & (align - 1)) == 0, "align must be a power of 2");
522 : :
523 [ # # ]: 0 : if (bytes == 0) {
524 : : return NULL;
525 : : }
526 : :
527 : : /*
528 : : * Find a free block that is guaranteed to fit.
529 : : * We over-allocate to account for alignment and then free
530 : : * the extra allocations afterwards.
531 : : */
532 : 0 : chunksz_t padded_sz = bytes_to_chunksz(h, bytes, align - gap);
533 : 0 : chunkid_t c0 = alloc_chunk(h, padded_sz);
534 : :
535 [ # # ]: 0 : if (c0 == 0) {
536 : : return NULL;
537 : : }
538 : 0 : uint8_t *mem = chunk_mem(h, c0);
539 : :
540 : : /* Align allocated memory */
541 : 0 : mem = (uint8_t *) ROUND_UP(mem + rew, align) - rew;
542 : 0 : chunk_unit_t *end = (chunk_unit_t *) ROUND_UP(mem + bytes, CHUNK_UNIT);
543 : :
544 : : /* Get corresponding chunks */
545 : 0 : chunkid_t c = mem_to_chunkid(h, mem);
546 : 0 : chunkid_t c_end = end - chunk_buf(h) + CHUNK_TRAILER_SIZE;
547 : 0 : CHECK(c >= c0 && c < c_end && c_end <= c0 + padded_sz);
548 : :
549 : : /* Split and free unused prefix */
550 [ # # ]: 0 : if (c > c0) {
551 : 0 : split_chunks(h, c0, c);
552 : 0 : free_list_add(h, c0);
553 : : }
554 : :
555 : : /* Split and free unused suffix */
556 [ # # ]: 0 : if (right_chunk(h, c) > c_end) {
557 : 0 : split_chunks(h, c, c_end);
558 : 0 : free_list_add(h, c_end);
559 : : }
560 : :
561 : 0 : set_chunk_used(h, c, true);
562 : 0 : if (SYS_HEAP_HARDENING_FULL) {
563 : 0 : set_chunk_canary(h, c);
564 : : }
565 : :
566 : : #ifdef CONFIG_SYS_HEAP_CALLER_POINTER
567 : : chunk_trailer(h, c)->caller = HEAP_CAPTURE_CALLER();
568 : : #endif
569 : 0 : IF_ENABLED(CONFIG_SYS_HEAP_THREAD_STATS, (z_heap_stats_on_alloc(heap, c, mem)));
570 : :
571 : : #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
572 : : increase_allocated_bytes(h, chunk_usable_bytes(h, c));
573 : : #endif
574 : :
575 : : #ifdef CONFIG_SYS_HEAP_LISTENER
576 : : heap_listener_notify_alloc(HEAP_ID_FROM_POINTER(heap), mem,
577 : : chunk_usable_bytes(h, c) - mem_align_gap(h, mem));
578 : : #endif
579 : :
580 : 0 : IF_ENABLED(CONFIG_MSAN, (__msan_allocated_memory(mem, bytes)));
581 : 0 : IF_ENABLED(CONFIG_SYS_HEAP_SANITIZER_HOOKS, (heap_sanitizer_on_alloc(heap, mem, bytes)));
582 : 0 : return mem;
583 : : }
584 : :
585 : 0 : static bool inplace_realloc(struct sys_heap *heap, void *ptr, size_t bytes)
586 : : {
587 : 0 : struct z_heap *h = heap->heap;
588 : :
589 : 0 : chunkid_t c = mem_to_chunkid(h, ptr);
590 : 0 : size_t align_gap = mem_align_gap(h, ptr);
591 : :
592 : 0 : chunksz_t chunks_need = bytes_to_chunksz(h, bytes, align_gap);
593 : :
594 : 0 : if (SYS_HEAP_HARDENING_FULL) {
595 : 0 : verify_chunk_canary(h, c, ptr);
596 : : }
597 [ # # ]: 0 : if (SYS_HEAP_HARDENING_BASIC && !chunk_used(h, c)) {
598 : 0 : LOG_ERR("heap corruption (not in use?) at %p", ptr);
599 : 0 : k_panic();
600 : : }
601 : 0 : if (SYS_HEAP_HARDENING_BASIC &&
602 [ # # ]: 0 : left_chunk(h, right_chunk(h, c)) != c) {
603 : 0 : LOG_ERR("heap corruption (buffer overflow?) at %p", ptr);
604 : 0 : k_panic();
605 : : }
606 : 0 : if (SYS_HEAP_HARDENING_MODERATE &&
607 [ # # ]: 0 : right_chunk(h, left_chunk(h, c)) != c) {
608 : 0 : LOG_ERR("heap corruption (left neighbor?) at %p", ptr);
609 : 0 : k_panic();
610 : : }
611 : 0 : if (SYS_HEAP_HARDENING_EXTREME && !z_heap_full_check(h)) {
612 : : LOG_ERR("heap validation failed");
613 : 0 : k_panic();
614 : : }
615 : :
616 [ # # ]: 0 : if (chunk_size(h, c) == chunks_need) {
617 : : /* We're good already */
618 : : return true;
619 : : }
620 : :
621 : : /*
622 : : * Capture trailer metadata before any resize. split_chunks() and
623 : : * merge_chunks() change chunk_size(h, c), which moves the trailer to
624 : : * a new position; we must write it there after set_chunk_canary().
625 : : */
626 : : #ifdef CONFIG_SYS_HEAP_THREAD_STATS
627 : : struct k_thread *old_owner = NULL;
628 : : size_t old_usable = 0;
629 : :
630 : : if (h->stats != NULL) {
631 : : old_owner = chunk_trailer(h, c)->thread;
632 : : old_usable = chunk_usable_bytes(h, c) - align_gap;
633 : : }
634 : : #endif
635 : : #ifdef CONFIG_SYS_HEAP_CALLER_POINTER
636 : : void *saved_caller = chunk_trailer(h, c)->caller;
637 : : #endif
638 : :
639 [ # # ]: 0 : if (chunk_size(h, c) > chunks_need) {
640 : : /* Shrink in place, split off and free unused suffix */
641 : : #ifdef CONFIG_SYS_HEAP_LISTENER
642 : : size_t bytes_freed = chunk_usable_bytes(h, c) - align_gap;
643 : : #endif
644 : : IF_ENABLED(CONFIG_SYS_HEAP_RELEASE_HOOK,
645 : : (sys_heap_release_hook((uint8_t *)ptr + bytes,
646 : : chunk_usable_bytes(h, c) - align_gap - bytes);))
647 : :
648 : : #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
649 : : h->allocated_bytes -=
650 : : (chunk_size(h, c) - chunks_need) * CHUNK_UNIT;
651 : : #endif
652 : :
653 : 0 : split_chunks(h, c, c + chunks_need);
654 : 0 : set_chunk_used(h, c, true);
655 : 0 : if (SYS_HEAP_HARDENING_FULL) {
656 : 0 : set_chunk_canary(h, c);
657 : : }
658 : :
659 : : /* Restore trailer at the new (smaller) position. */
660 : : #ifdef CONFIG_SYS_HEAP_THREAD_STATS
661 : : z_heap_stats_on_realloc(heap, c, ptr, old_usable, old_owner);
662 : : #endif
663 : : #ifdef CONFIG_SYS_HEAP_CALLER_POINTER
664 : : chunk_trailer(h, c)->caller = saved_caller;
665 : : #endif
666 : :
667 : : /* Left neighbor is c (used, just validated) so only
668 : : * attempt a right merge inline and add to free list.
669 : : */
670 : 0 : chunkid_t suffix = c + chunks_need;
671 : 0 : chunkid_t suffix_rc = right_chunk(h, suffix);
672 : :
673 [ # # ]: 0 : if (!chunk_used(h, suffix_rc)) {
674 : 0 : free_chunk_check(h, suffix_rc, true);
675 : 0 : free_list_remove(h, suffix_rc);
676 : 0 : merge_chunks(h, suffix, suffix_rc);
677 : : }
678 : 0 : free_list_add(h, suffix);
679 : :
680 : : #ifdef CONFIG_SYS_HEAP_LISTENER
681 : : heap_listener_notify_alloc(HEAP_ID_FROM_POINTER(heap), ptr,
682 : : chunk_usable_bytes(h, c) - align_gap);
683 : : heap_listener_notify_free(HEAP_ID_FROM_POINTER(heap), ptr,
684 : : bytes_freed);
685 : : #endif
686 : :
687 : 0 : return true;
688 : : }
689 : :
690 : 0 : chunkid_t rc = right_chunk(h, c);
691 : :
692 [ # # ]: 0 : if (!chunk_used(h, rc) &&
693 [ # # ]: 0 : (chunk_size(h, c) + chunk_size(h, rc) >= chunks_need)) {
694 : : /* Expand: split the right chunk and append */
695 : 0 : chunksz_t split_size = chunks_need - chunk_size(h, c);
696 : :
697 : : #ifdef CONFIG_SYS_HEAP_LISTENER
698 : : size_t bytes_freed = chunk_usable_bytes(h, c) - align_gap;
699 : : #endif
700 : :
701 : : #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
702 : : increase_allocated_bytes(h, split_size * CHUNK_UNIT);
703 : : #endif
704 : :
705 : 0 : free_chunk_check(h, rc, true);
706 : 0 : free_list_remove(h, rc);
707 : :
708 [ # # ]: 0 : if (split_size < chunk_size(h, rc)) {
709 : 0 : split_chunks(h, rc, rc + split_size);
710 : 0 : free_list_add(h, rc + split_size);
711 : : }
712 : :
713 : 0 : merge_chunks(h, c, rc);
714 : 0 : set_chunk_used(h, c, true);
715 : 0 : if (SYS_HEAP_HARDENING_FULL) {
716 : 0 : set_chunk_canary(h, c);
717 : : }
718 : :
719 : 0 : z_heap_stats_on_realloc(heap, c, ptr, old_usable, old_owner);
720 : : #ifdef CONFIG_SYS_HEAP_CALLER_POINTER
721 : : chunk_trailer(h, c)->caller = saved_caller;
722 : : #endif
723 : :
724 : : #ifdef CONFIG_SYS_HEAP_LISTENER
725 : : heap_listener_notify_alloc(HEAP_ID_FROM_POINTER(heap), ptr,
726 : : chunk_usable_bytes(h, c) - align_gap);
727 : : heap_listener_notify_free(HEAP_ID_FROM_POINTER(heap), ptr,
728 : : bytes_freed);
729 : : #endif
730 : :
731 : 0 : return true;
732 : : }
733 : :
734 : : return false;
735 : : }
736 : :
737 : 0 : void *sys_heap_realloc(struct sys_heap *heap, void *ptr, size_t bytes)
738 : : {
739 : : /* special realloc semantics */
740 [ # # ]: 0 : if (ptr == NULL) {
741 : 0 : return sys_heap_alloc(heap, bytes);
742 : : }
743 [ # # ]: 0 : if (bytes == 0) {
744 : 0 : sys_heap_free(heap, ptr);
745 : 0 : return NULL;
746 : : }
747 : :
748 : : #ifdef CONFIG_SYS_HEAP_SANITIZER_HOOKS
749 : : size_t old_usable = sys_heap_usable_size(heap, ptr);
750 : : #endif
751 : :
752 [ # # ]: 0 : if (inplace_realloc(heap, ptr, bytes)) {
753 : : IF_ENABLED(CONFIG_SYS_HEAP_SANITIZER_HOOKS,
754 : : (heap_sanitizer_on_free(heap, ptr, old_usable)));
755 : : IF_ENABLED(CONFIG_SYS_HEAP_SANITIZER_HOOKS,
756 : : (heap_sanitizer_on_alloc(heap, ptr, bytes)));
757 : : return ptr;
758 : : }
759 : :
760 : : /* In-place realloc was not possible: fallback to allocate and copy. */
761 : 0 : void *ptr2 = sys_heap_alloc(heap, bytes);
762 : :
763 [ # # ]: 0 : if (ptr2 != NULL) {
764 : 0 : size_t prev_size = sys_heap_usable_size(heap, ptr);
765 : :
766 : : /*
767 : : * The copy reads the source block's whole usable region, which
768 : : * a sanitizer backend keeps poisoned past the user-requested
769 : : * size. Re-grant access to the full region for the duration of
770 : : * the copy; the free below re-poisons it.
771 : : */
772 : : IF_ENABLED(CONFIG_SYS_HEAP_SANITIZER_HOOKS,
773 : 0 : (heap_sanitizer_on_alloc(heap, ptr, prev_size)));
774 : 0 : memcpy(ptr2, ptr, min(prev_size, bytes));
775 : 0 : sys_heap_free(heap, ptr);
776 : : }
777 : : return ptr2;
778 : : }
779 : :
780 : 0 : void *sys_heap_aligned_realloc(struct sys_heap *heap, void *ptr,
781 : : size_t align, size_t bytes)
782 : : {
783 : : /* special realloc semantics */
784 [ # # ]: 0 : if (ptr == NULL) {
785 : 0 : return sys_heap_aligned_alloc(heap, align, bytes);
786 : : }
787 [ # # ]: 0 : if (bytes == 0) {
788 : 0 : sys_heap_free(heap, ptr);
789 : 0 : return NULL;
790 : : }
791 : :
792 [ # # ]: 0 : __ASSERT((align & (align - 1)) == 0, "align must be a power of 2");
793 : :
794 : : #ifdef CONFIG_SYS_HEAP_SANITIZER_HOOKS
795 : : size_t old_usable = sys_heap_usable_size(heap, ptr);
796 : : #endif
797 : :
798 [ # # # # : 0 : if ((align == 0 || ((uintptr_t)ptr & (align - 1)) == 0) &&
# # ]
799 : 0 : inplace_realloc(heap, ptr, bytes)) {
800 : : IF_ENABLED(CONFIG_SYS_HEAP_SANITIZER_HOOKS,
801 : : (heap_sanitizer_on_free(heap, ptr, old_usable)));
802 : : IF_ENABLED(CONFIG_SYS_HEAP_SANITIZER_HOOKS,
803 : : (heap_sanitizer_on_alloc(heap, ptr, bytes)));
804 : : return ptr;
805 : : }
806 : :
807 : : /*
808 : : * Either ptr is not sufficiently aligned for in-place realloc or
809 : : * in-place realloc was not possible: fallback to allocate and copy.
810 : : */
811 : 0 : void *ptr2 = sys_heap_aligned_alloc(heap, align, bytes);
812 : :
813 [ # # ]: 0 : if (ptr2 != NULL) {
814 : 0 : size_t prev_size = sys_heap_usable_size(heap, ptr);
815 : :
816 : : /*
817 : : * The copy reads the source block's whole usable region, which
818 : : * a sanitizer backend keeps poisoned past the user-requested
819 : : * size. Re-grant access to the full region for the duration of
820 : : * the copy; the free below re-poisons it.
821 : : */
822 : : IF_ENABLED(CONFIG_SYS_HEAP_SANITIZER_HOOKS,
823 : 0 : (heap_sanitizer_on_alloc(heap, ptr, prev_size)));
824 : 0 : memcpy(ptr2, ptr, min(prev_size, bytes));
825 : 0 : sys_heap_free(heap, ptr);
826 : : }
827 : : return ptr2;
828 : : }
829 : :
830 : 0 : void sys_heap_init(struct sys_heap *heap, void *mem, size_t bytes)
831 : : {
832 : 0 : IF_ENABLED(CONFIG_MSAN, (__sanitizer_dtor_callback(mem, bytes)));
833 : :
834 : 0 : if (IS_ENABLED(CONFIG_SYS_HEAP_SMALL_ONLY)) {
835 : : /* Must fit in a 15 bit count of HUNK_UNIT */
836 [ # # ]: 0 : __ASSERT(bytes / CHUNK_UNIT <= 0x7fffU, "heap size is too big");
837 : : } else {
838 : : /* Must fit in a 31 bit count of HUNK_UNIT */
839 : 0 : __ASSERT(bytes / CHUNK_UNIT <= 0x7fffffffU, "heap size is too big");
840 : : }
841 : :
842 : : /* Reserve the end marker chunk's header */
843 [ # # ]: 0 : __ASSERT(bytes > heap_footer_bytes(bytes), "heap size is too small");
844 : : #ifdef CONFIG_SYS_HEAP_SANITIZER_HOOKS
845 : : const size_t orig_bytes = bytes; /* preserve for heap_sanitizer_on_init */
846 : : #endif
847 : 0 : bytes -= heap_footer_bytes(bytes);
848 : :
849 : : /* Round the start up, the end down */
850 : 0 : uintptr_t addr = ROUND_UP(mem, CHUNK_UNIT);
851 : 0 : uintptr_t end = ROUND_DOWN((uint8_t *)mem + bytes, CHUNK_UNIT);
852 : 0 : chunksz_t heap_sz = (end - addr) / CHUNK_UNIT;
853 : :
854 : 0 : CHECK(end > addr);
855 [ # # ]: 0 : __ASSERT(heap_sz > chunksz(sizeof(struct z_heap)), "heap size is too small");
856 : :
857 : 0 : struct z_heap *h = (struct z_heap *)addr;
858 : 0 : heap->heap = h;
859 : 0 : h->end_chunk = heap_sz;
860 : 0 : h->avail_buckets = 0;
861 : :
862 : : #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
863 : : h->free_bytes = 0;
864 : : h->allocated_bytes = 0;
865 : : h->max_allocated_bytes = 0;
866 : : #endif
867 : :
868 : 0 : IF_ENABLED(CONFIG_SYS_HEAP_THREAD_STATS, (z_heap_stats_on_init(heap)));
869 : :
870 : : #if CONFIG_SYS_HEAP_ARRAY_SIZE
871 : : sys_heap_array_save(heap);
872 : : #endif
873 : :
874 : 0 : int nb_buckets = bucket_idx(h, heap_sz) + 1;
875 : 0 : chunksz_t chunk0_size = chunksz(sizeof(struct z_heap) +
876 : 0 : nb_buckets * sizeof(struct z_heap_bucket)) +
877 : : CHUNK_TRAILER_SIZE;
878 : :
879 [ # # ]: 0 : __ASSERT(chunk0_size + min_chunk_size(h) <= heap_sz, "heap size is too small");
880 : :
881 [ # # ]: 0 : for (int i = 0; i < nb_buckets; i++) {
882 : 0 : h->buckets[i].next = 0;
883 : : }
884 : :
885 : : #ifdef CONFIG_SYS_HEAP_CANARIES_RANDOM
886 : : sys_rand_get(&h->canary_base, sizeof(h->canary_base));
887 : : #endif
888 : :
889 : : /* chunk containing our struct z_heap */
890 : 0 : set_chunk_size(h, 0, chunk0_size);
891 : 0 : set_left_chunk_size(h, 0, 0);
892 : 0 : set_chunk_used(h, 0, true);
893 : 0 : if (SYS_HEAP_HARDENING_FULL) {
894 : 0 : set_chunk_canary(h, 0);
895 : : }
896 : :
897 : : /* chunk containing the free heap */
898 : 0 : set_chunk_size(h, chunk0_size, heap_sz - chunk0_size);
899 : 0 : set_left_chunk_size(h, chunk0_size, chunk0_size);
900 : :
901 : : /* the end marker chunk */
902 : 0 : set_chunk_size(h, heap_sz, 0);
903 : 0 : set_left_chunk_size(h, heap_sz, heap_sz - chunk0_size);
904 : 0 : set_chunk_used(h, heap_sz, true);
905 : :
906 : 0 : free_list_add(h, chunk0_size);
907 : :
908 : : #ifdef CONFIG_SYS_HEAP_SANITIZER_HOOKS
909 : : heap_sanitizer_on_init(heap, mem, orig_bytes);
910 : : #endif
911 : 0 : }
|