fix checkwps
[maemo-rb.git] / firmware / buflib.c
blob43fc4bd3ded28d36d9df9d0ae09a7fe504e60025
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * This is a memory allocator designed to provide reasonable management of free
11 * space and fast access to allocated data. More than one allocator can be used
12 * at a time by initializing multiple contexts.
14 * Copyright (C) 2009 Andrew Mahone
15 * Copyright (C) 2011 Thomas Martitz
18 * This program is free software; you can redistribute it and/or
19 * modify it under the terms of the GNU General Public License
20 * as published by the Free Software Foundation; either version 2
21 * of the License, or (at your option) any later version.
23 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
24 * KIND, either express or implied.
26 ****************************************************************************/
28 #include <stdlib.h> /* for abs() */
29 #include <stdio.h> /* for snprintf() */
30 #include "buflib.h"
31 #include "string-extra.h" /* strlcpy() */
32 #include "debug.h"
33 #include "buffer.h"
34 #include "system.h" /* for ALIGN_*() */
36 /* The main goal of this design is fast fetching of the pointer for a handle.
37 * For that reason, the handles are stored in a table at the end of the buffer
38 * with a fixed address, so that returning the pointer for a handle is a simple
39 * table lookup. To reduce the frequency with which allocated blocks will need
40 * to be moved to free space, allocations grow up in address from the start of
41 * the buffer. The buffer is treated as an array of union buflib_data. Blocks
42 * start with a length marker, which is included in their length. Free blocks
43 * are marked by negative length. Allocated blocks have a positiv length marker,
44 * and additional metadata forllowing that: It follows a pointer
45 * (union buflib_data*) to the corresponding handle table entry. so that it can
46 * be quickly found and updated during compaction. After that follows
47 * the pointer to the struct buflib_callbacks associated with this allocation
48 * (may be NULL). That pointer follows a variable length character array
49 * containing the nul-terminated string identifier of the allocation. After this
50 * array there's a length marker for the length of the character array including
51 * this length marker (counted in n*sizeof(union buflib_data)), which allows
52 * to find the start of the character array (and therefore the start of the
53 * entire block) when only the handle or payload start is known.
55 * Example:
56 * |<- alloc block #1 ->|<- unalloc block ->|<- alloc block #2 ->|<-handle table->|
57 * |L|H|C|cccc|L2|XXXXXX|-L|YYYYYYYYYYYYYYYY|L|H|C|cc|L2|XXXXXXXXXXXXX|AAA|
59 * L - length marker (negative if block unallocated)
60 * H - handle table enry pointer
61 * C - pointer to struct buflib_callbacks
62 * c - variable sized string identifier
63 * L2 - second length marker for string identifier
64 * X - actual payload
65 * Y - unallocated space
67 * A - pointer to start of payload (first X) in the handle table (may be null)
69 * The blocks can be walked by jumping the abs() of the L length marker, i.e.
70 * union buflib_data* L;
71 * for(L = start; L < end; L += abs(L->val)) { .... }
74 * The allocator functions are passed a context struct so that two allocators
75 * can be run, for example, one per core may be used, with convenience wrappers
76 * for the single-allocator case that use a predefined context.
79 #define B_ALIGN_DOWN(x) \
80 ALIGN_DOWN(x, sizeof(union buflib_data))
82 #define B_ALIGN_UP(x) \
83 ALIGN_UP(x, sizeof(union buflib_data))
85 #ifdef DEBUG
86 #include <stdio.h>
87 #define BDEBUGF DEBUGF
88 #else
89 #define BDEBUGF(...) do { } while(0)
90 #endif
92 #define IS_MOVABLE(a) (!a[2].ops || a[2].ops->move_callback)
93 static union buflib_data* find_first_free(struct buflib_context *ctx);
94 static union buflib_data* find_block_before(struct buflib_context *ctx,
95 union buflib_data* block,
96 bool is_free);
97 /* Initialize buffer manager */
98 void
99 buflib_init(struct buflib_context *ctx, void *buf, size_t size)
101 union buflib_data *bd_buf = buf;
103 /* Align on sizeof(buflib_data), to prevent unaligned access */
104 ALIGN_BUFFER(bd_buf, size, sizeof(union buflib_data));
105 size /= sizeof(union buflib_data);
106 /* The handle table is initialized with no entries */
107 ctx->handle_table = bd_buf + size;
108 ctx->last_handle = bd_buf + size;
109 ctx->first_free_handle = bd_buf + size - 1;
110 ctx->buf_start = bd_buf;
111 /* A marker is needed for the end of allocated data, to make sure that it
112 * does not collide with the handle table, and to detect end-of-buffer.
114 ctx->alloc_end = bd_buf;
115 ctx->compact = true;
117 BDEBUGF("buflib initialized with %d.%2d kiB", size / 1024, (size%1000)/10);
120 /* Allocate a new handle, returning 0 on failure */
121 static inline
122 union buflib_data* handle_alloc(struct buflib_context *ctx)
124 union buflib_data *handle;
125 /* first_free_handle is a lower bound on free handles, work through the
126 * table from there until a handle containing NULL is found, or the end
127 * of the table is reached.
129 for (handle = ctx->first_free_handle; handle >= ctx->last_handle; handle--)
130 if (!handle->alloc)
131 break;
132 /* If the search went past the end of the table, it means we need to extend
133 * the table to get a new handle.
135 if (handle < ctx->last_handle)
137 if (handle >= ctx->alloc_end)
138 ctx->last_handle--;
139 else
140 return NULL;
142 handle->val = -1;
143 return handle;
146 /* Free one handle, shrinking the handle table if it's the last one */
147 static inline
148 void handle_free(struct buflib_context *ctx, union buflib_data *handle)
150 handle->alloc = 0;
151 /* Update free handle lower bound if this handle has a lower index than the
152 * old one.
154 if (handle > ctx->first_free_handle)
155 ctx->first_free_handle = handle;
156 if (handle == ctx->last_handle)
157 ctx->last_handle++;
158 else
159 ctx->compact = false;
162 /* Get the start block of an allocation */
163 static union buflib_data* handle_to_block(struct buflib_context* ctx, int handle)
165 union buflib_data* name_field =
166 (union buflib_data*)buflib_get_name(ctx, handle);
168 return name_field - 3;
171 /* Shrink the handle table, returning true if its size was reduced, false if
172 * not
174 static inline
175 bool
176 handle_table_shrink(struct buflib_context *ctx)
178 bool rv;
179 union buflib_data *handle;
180 for (handle = ctx->last_handle; !(handle->alloc); handle++);
181 if (handle > ctx->first_free_handle)
182 ctx->first_free_handle = handle - 1;
183 rv = handle != ctx->last_handle;
184 ctx->last_handle = handle;
185 return rv;
189 /* If shift is non-zero, it represents the number of places to move
190 * blocks in memory. Calculate the new address for this block,
191 * update its entry in the handle table, and then move its contents.
193 * Returns false if moving was unsucessful
194 * (NULL callback or BUFLIB_CB_CANNOT_MOVE was returned)
196 static bool
197 move_block(struct buflib_context* ctx, union buflib_data* block, int shift)
199 char* new_start;
200 union buflib_data *new_block, *tmp = block[1].handle;
201 struct buflib_callbacks *ops = block[2].ops;
202 if (!IS_MOVABLE(block))
203 return false;
205 int handle = ctx->handle_table - tmp;
206 BDEBUGF("%s(): moving \"%s\"(id=%d) by %d(%d)\n", __func__, block[3].name,
207 handle, shift, shift*sizeof(union buflib_data));
208 new_block = block + shift;
209 new_start = tmp->alloc + shift*sizeof(union buflib_data);
211 /* disable IRQs to make accessing the buffer from interrupt context safe. */
212 /* protect the move callback, as a cached global pointer might be updated
213 * in it. and protect "tmp->alloc = new_start" for buflib_get_data() */
214 disable_irq();
215 /* call the callback before moving */
216 if (ops)
218 if (ops->move_callback(handle, tmp->alloc, new_start)
219 == BUFLIB_CB_CANNOT_MOVE)
221 enable_irq();
222 return false;
226 tmp->alloc = new_start; /* update handle table */
227 memmove(new_block, block, block->val * sizeof(union buflib_data));
229 enable_irq();
230 return true;
233 /* Compact allocations and handle table, adjusting handle pointers as needed.
234 * Return true if any space was freed or consolidated, false otherwise.
236 static bool
237 buflib_compact(struct buflib_context *ctx)
239 BDEBUGF("%s(): Compacting!\n", __func__);
240 union buflib_data *block,
241 *first_free = find_first_free(ctx);
242 int shift = 0, len;
243 /* Store the results of attempting to shrink the handle table */
244 bool ret = handle_table_shrink(ctx);
245 for(block = first_free; block < ctx->alloc_end; block += len)
247 len = block->val;
248 /* This block is free, add its length to the shift value */
249 if (len < 0)
251 shift += len;
252 len = -len;
253 continue;
255 /* attempt to fill any hole */
256 if (-first_free->val >= block->val)
258 intptr_t size = -first_free->val;
259 union buflib_data* next_block = block + block->val;
260 if (move_block(ctx, block, first_free - block))
262 /* moving was successful. Move alloc_end down if necessary */
263 if (ctx->alloc_end == next_block)
264 ctx->alloc_end = block;
265 /* Mark the block behind the just moved as free
266 * be careful to not overwrite an existing block */
267 if (size != block->val)
269 first_free += block->val;
270 first_free->val = block->val - size; /* negative */
272 continue;
275 /* attempt move the allocation by shift */
276 if (shift)
278 /* failing to move creates a hole,
279 * therefore mark this block as not allocated */
280 union buflib_data* target_block = block + shift;
281 if (!move_block(ctx, block, shift))
283 target_block->val = shift; /* this is a hole */
284 shift = 0;
286 else
287 { /* need to update the next free block, since the above hole
288 * handling might make shift 0 before alloc_end is reached */
289 union buflib_data* new_free = target_block + target_block->val;
290 new_free->val = shift;
294 /* Move the end-of-allocation mark, and return true if any new space has
295 * been freed.
297 ctx->alloc_end += shift;
298 ctx->compact = true;
299 return ret || shift;
302 /* Compact the buffer by trying both shrinking and moving.
304 * Try to move first. If unsuccesfull, try to shrink. If that was successful
305 * try to move once more as there might be more room now.
307 static bool
308 buflib_compact_and_shrink(struct buflib_context *ctx, unsigned shrink_hints)
310 bool result = false;
311 /* if something compacted before already there will be no further gain */
312 if (!ctx->compact)
313 result = buflib_compact(ctx);
314 if (!result)
316 union buflib_data *this, *before;
317 for(this = ctx->buf_start, before = this;
318 this < ctx->alloc_end;
319 before = this, this += abs(this->val))
321 if (this->val > 0 && this[2].ops
322 && this[2].ops->shrink_callback)
324 int ret;
325 int handle = ctx->handle_table - this[1].handle;
326 char* data = this[1].handle->alloc;
327 bool last = (this+this->val) == ctx->alloc_end;
328 unsigned pos_hints = shrink_hints & BUFLIB_SHRINK_POS_MASK;
329 /* adjust what we ask for if there's free space in the front
330 * this isn't too unlikely assuming this block is
331 * shrinkable but not movable */
332 if (pos_hints == BUFLIB_SHRINK_POS_FRONT
333 && before != this && before->val < 0)
335 size_t free_space = (-before->val) * sizeof(union buflib_data);
336 size_t wanted = shrink_hints & BUFLIB_SHRINK_SIZE_MASK;
337 if (wanted < free_space) /* no shrink needed? */
338 continue;
339 wanted -= free_space;
340 shrink_hints = pos_hints | wanted;
342 ret = this[2].ops->shrink_callback(handle, shrink_hints,
343 data, (char*)(this+this->val)-data);
344 result |= (ret == BUFLIB_CB_OK);
345 /* this might have changed in the callback (if
346 * it shrinked from the top), get it again */
347 this = handle_to_block(ctx, handle);
348 /* could also change with shrinking from back */
349 if (last)
350 ctx->alloc_end = this + this->val;
353 /* shrinking was successful at least once, try compaction again */
354 if (result)
355 result |= buflib_compact(ctx);
358 return result;
361 /* Shift buffered items by size units, and update handle pointers. The shift
362 * value must be determined to be safe *before* calling.
364 static void
365 buflib_buffer_shift(struct buflib_context *ctx, int shift)
367 memmove(ctx->buf_start + shift, ctx->buf_start,
368 (ctx->alloc_end - ctx->buf_start) * sizeof(union buflib_data));
369 union buflib_data *handle;
370 for (handle = ctx->last_handle; handle < ctx->handle_table; handle++)
371 if (handle->alloc)
372 handle->alloc += shift;
373 ctx->buf_start += shift;
374 ctx->alloc_end += shift;
377 /* Shift buffered items up by size bytes, or as many as possible if size == 0.
378 * Set size to the number of bytes freed.
380 void*
381 buflib_buffer_out(struct buflib_context *ctx, size_t *size)
383 if (!ctx->compact)
384 buflib_compact(ctx);
385 size_t avail = ctx->last_handle - ctx->alloc_end;
386 size_t avail_b = avail * sizeof(union buflib_data);
387 if (*size && *size < avail_b)
389 avail = (*size + sizeof(union buflib_data) - 1)
390 / sizeof(union buflib_data);
391 avail_b = avail * sizeof(union buflib_data);
393 *size = avail_b;
394 void *ret = ctx->buf_start;
395 buflib_buffer_shift(ctx, avail);
396 return ret;
399 /* Shift buffered items down by size bytes */
400 void
401 buflib_buffer_in(struct buflib_context *ctx, int size)
403 size /= sizeof(union buflib_data);
404 buflib_buffer_shift(ctx, -size);
407 /* Allocate a buffer of size bytes, returning a handle for it */
409 buflib_alloc(struct buflib_context *ctx, size_t size)
411 return buflib_alloc_ex(ctx, size, "<anonymous>", NULL);
414 /* Allocate a buffer of size bytes, returning a handle for it.
416 * The additional name parameter gives the allocation a human-readable name,
417 * the ops parameter points to caller-implemented callbacks for moving and
418 * shrinking. NULL for default callbacks (which do nothing but don't
419 * prevent moving or shrinking)
423 buflib_alloc_ex(struct buflib_context *ctx, size_t size, const char *name,
424 struct buflib_callbacks *ops)
426 union buflib_data *handle, *block;
427 size_t name_len = name ? B_ALIGN_UP(strlen(name)+1) : 0;
428 bool last;
429 /* This really is assigned a value before use */
430 int block_len;
431 size += name_len;
432 size = (size + sizeof(union buflib_data) - 1) /
433 sizeof(union buflib_data)
434 /* add 4 objects for alloc len, pointer to handle table entry and
435 * name length, and the ops pointer */
436 + 4;
437 handle_alloc:
438 handle = handle_alloc(ctx);
439 if (!handle)
441 /* If allocation has failed, and compaction has succeded, it may be
442 * possible to get a handle by trying again.
444 union buflib_data* last_block = find_block_before(ctx,
445 ctx->alloc_end, false);
446 struct buflib_callbacks* ops = last_block[2].ops;
447 unsigned hints = 0;
448 if (!ops || !ops->shrink_callback)
449 { /* the last one isn't shrinkable
450 * make room in front of a shrinkable and move this alloc */
451 hints = BUFLIB_SHRINK_POS_FRONT;
452 hints |= last_block->val * sizeof(union buflib_data);
454 else if (ops && ops->shrink_callback)
455 { /* the last is shrinkable, make room for handles directly */
456 hints = BUFLIB_SHRINK_POS_BACK;
457 hints |= 16*sizeof(union buflib_data);
459 /* buflib_compact_and_shrink() will compact and move last_block()
460 * if possible */
461 if (buflib_compact_and_shrink(ctx, hints))
462 goto handle_alloc;
463 return -1;
466 buffer_alloc:
467 /* need to re-evaluate last before the loop because the last allocation
468 * possibly made room in its front to fit this, so last would be wrong */
469 last = false;
470 for (block = find_first_free(ctx);;block += block_len)
472 /* If the last used block extends all the way to the handle table, the
473 * block "after" it doesn't have a header. Because of this, it's easier
474 * to always find the end of allocation by saving a pointer, and always
475 * calculate the free space at the end by comparing it to the
476 * last_handle pointer.
478 if(block == ctx->alloc_end)
480 last = true;
481 block_len = ctx->last_handle - block;
482 if ((size_t)block_len < size)
483 block = NULL;
484 break;
486 block_len = block->val;
487 /* blocks with positive length are already allocated. */
488 if(block_len > 0)
489 continue;
490 block_len = -block_len;
491 /* The search is first-fit, any fragmentation this causes will be
492 * handled at compaction.
494 if ((size_t)block_len >= size)
495 break;
497 if (!block)
499 /* Try compacting if allocation failed */
500 unsigned hint = BUFLIB_SHRINK_POS_FRONT |
501 ((size*sizeof(union buflib_data))&BUFLIB_SHRINK_SIZE_MASK);
502 if (buflib_compact_and_shrink(ctx, hint))
504 goto buffer_alloc;
505 } else {
506 handle->val=1;
507 handle_free(ctx, handle);
508 return -2;
512 /* Set up the allocated block, by marking the size allocated, and storing
513 * a pointer to the handle.
515 union buflib_data *name_len_slot;
516 block->val = size;
517 block[1].handle = handle;
518 block[2].ops = ops;
519 strcpy(block[3].name, name);
520 name_len_slot = (union buflib_data*)B_ALIGN_UP(block[3].name + name_len);
521 name_len_slot->val = 1 + name_len/sizeof(union buflib_data);
522 handle->alloc = (char*)(name_len_slot + 1);
524 block += size;
525 /* alloc_end must be kept current if we're taking the last block. */
526 if (last)
527 ctx->alloc_end = block;
528 /* Only free blocks *before* alloc_end have tagged length. */
529 else if ((size_t)block_len > size)
530 block->val = size - block_len;
531 /* Return the handle index as a positive integer. */
532 return ctx->handle_table - handle;
535 static union buflib_data*
536 find_first_free(struct buflib_context *ctx)
538 union buflib_data* ret = ctx->buf_start;
539 while(ret < ctx->alloc_end)
541 if (ret->val < 0)
542 break;
543 ret += ret->val;
545 /* ret is now either a free block or the same as alloc_end, both is fine */
546 return ret;
549 /* Finds the free block before block, and returns NULL if it's not free */
550 static union buflib_data*
551 find_block_before(struct buflib_context *ctx, union buflib_data* block,
552 bool is_free)
554 union buflib_data *ret = ctx->buf_start,
555 *next_block = ret;
557 /* find the block that's before the current one */
558 while (next_block < block)
560 ret = next_block;
561 next_block += abs(ret->val);
564 /* If next_block == block, the above loop didn't go anywhere. If it did,
565 * and the block before this one is empty, that is the wanted one
567 if (next_block == block && ret < block)
569 if (is_free && ret->val >= 0) /* NULL if found block isn't free */
570 return NULL;
571 return ret;
573 return NULL;
576 /* Free the buffer associated with handle_num. */
578 buflib_free(struct buflib_context *ctx, int handle_num)
580 union buflib_data *handle = ctx->handle_table - handle_num,
581 *freed_block = handle_to_block(ctx, handle_num),
582 *block, *next_block;
583 /* We need to find the block before the current one, to see if it is free
584 * and can be merged with this one.
586 block = find_block_before(ctx, freed_block, true);
587 if (block)
589 block->val -= freed_block->val;
591 else
593 /* Otherwise, set block to the newly-freed block, and mark it free, before
594 * continuing on, since the code below exects block to point to a free
595 * block which may have free space after it.
597 block = freed_block;
598 block->val = -block->val;
600 next_block = block - block->val;
601 /* Check if we are merging with the free space at alloc_end. */
602 if (next_block == ctx->alloc_end)
603 ctx->alloc_end = block;
604 /* Otherwise, the next block might still be a "normal" free block, and the
605 * mid-allocation free means that the buffer is no longer compact.
607 else {
608 ctx->compact = false;
609 if (next_block->val < 0)
610 block->val += next_block->val;
612 handle_free(ctx, handle);
613 handle->alloc = NULL;
615 return 0; /* unconditionally */
618 static size_t
619 free_space_at_end(struct buflib_context* ctx)
621 /* subtract 5 elements for
622 * val, handle, name_len, ops and the handle table entry*/
623 ptrdiff_t diff = (ctx->last_handle - ctx->alloc_end - 5);
624 diff -= 16; /* space for future handles */
625 diff *= sizeof(union buflib_data); /* make it bytes */
626 diff -= 16; /* reserve 16 for the name */
628 if (diff > 0)
629 return diff;
630 else
631 return 0;
634 /* Return the maximum allocatable memory in bytes */
635 size_t
636 buflib_available(struct buflib_context* ctx)
638 union buflib_data *this;
639 size_t free_space = 0, max_free_space = 0;
641 /* make sure buffer is as contiguous as possible */
642 if (!ctx->compact)
643 buflib_compact(ctx);
645 /* now look if there's free in holes */
646 for(this = find_first_free(ctx); this < ctx->alloc_end; this += abs(this->val))
648 if (this->val < 0)
650 free_space += -this->val;
651 continue;
653 /* an unmovable section resets the count as free space
654 * can't be contigous */
655 if (!IS_MOVABLE(this))
657 if (max_free_space < free_space)
658 max_free_space = free_space;
659 free_space = 0;
663 /* select the best */
664 max_free_space = MAX(max_free_space, free_space);
665 max_free_space *= sizeof(union buflib_data);
666 max_free_space = MAX(max_free_space, free_space_at_end(ctx));
668 if (max_free_space > 0)
669 return max_free_space;
670 else
671 return 0;
675 * Allocate all available (as returned by buflib_available()) memory and return
676 * a handle to it
678 * This grabs a lock which can only be unlocked by buflib_free() or
679 * buflib_shrink(), to protect from further allocations (which couldn't be
680 * serviced anyway).
683 buflib_alloc_maximum(struct buflib_context* ctx, const char* name, size_t *size, struct buflib_callbacks *ops)
685 /* limit name to 16 since that's what buflib_available() accounts for it */
686 char buf[16];
688 *size = buflib_available(ctx);
689 if (*size <= 0) /* OOM */
690 return -1;
692 strlcpy(buf, name, sizeof(buf));
694 return buflib_alloc_ex(ctx, *size, buf, ops);
697 /* Shrink the allocation indicated by the handle according to new_start and
698 * new_size. Grow is not possible, therefore new_start and new_start + new_size
699 * must be within the original allocation
701 bool
702 buflib_shrink(struct buflib_context* ctx, int handle, void* new_start, size_t new_size)
704 char* oldstart = buflib_get_data(ctx, handle);
705 char* newstart = new_start;
706 char* newend = newstart + new_size;
708 /* newstart must be higher and new_size not "negative" */
709 if (newstart < oldstart || newend < newstart)
710 return false;
711 union buflib_data *block = handle_to_block(ctx, handle),
712 *old_next_block = block + block->val,
713 /* newstart isn't necessarily properly aligned but it
714 * needn't be since it's only dereferenced by the user code */
715 *aligned_newstart = (union buflib_data*)B_ALIGN_DOWN(newstart),
716 *aligned_oldstart = (union buflib_data*)B_ALIGN_DOWN(oldstart),
717 *new_next_block = (union buflib_data*)B_ALIGN_UP(newend),
718 *new_block, metadata_size;
720 /* growing is not supported */
721 if (new_next_block > old_next_block)
722 return false;
724 metadata_size.val = aligned_oldstart - block;
725 /* update val and the handle table entry */
726 new_block = aligned_newstart - metadata_size.val;
727 block[0].val = new_next_block - new_block;
729 block[1].handle->alloc = newstart;
730 if (block != new_block)
732 /* move metadata over, i.e. pointer to handle table entry and name
733 * This is actually the point of no return. Data in the allocation is
734 * being modified, and therefore we must successfully finish the shrink
735 * operation */
736 memmove(new_block, block, metadata_size.val*sizeof(metadata_size));
737 /* mark the old block unallocated */
738 block->val = block - new_block;
739 /* find the block before in order to merge with the new free space */
740 union buflib_data *free_before = find_block_before(ctx, block, true);
741 if (free_before)
742 free_before->val += block->val;
744 /* We didn't handle size changes yet, assign block to the new one
745 * the code below the wants block whether it changed or not */
746 block = new_block;
749 /* Now deal with size changes that create free blocks after the allocation */
750 if (old_next_block != new_next_block)
752 if (ctx->alloc_end == old_next_block)
753 ctx->alloc_end = new_next_block;
754 else if (old_next_block->val < 0)
755 { /* enlarge next block by moving it up */
756 new_next_block->val = old_next_block->val - (old_next_block - new_next_block);
758 else if (old_next_block != new_next_block)
759 { /* creating a hole */
760 /* must be negative to indicate being unallocated */
761 new_next_block->val = new_next_block - old_next_block;
765 return true;
768 const char* buflib_get_name(struct buflib_context *ctx, int handle)
770 union buflib_data *data = ALIGN_DOWN(buflib_get_data(ctx, handle), sizeof (*data));
771 size_t len = data[-1].val;
772 if (len <= 1)
773 return NULL;
774 return data[-len].name;
777 #ifdef BUFLIB_DEBUG_BLOCKS
778 void buflib_print_allocs(struct buflib_context *ctx,
779 void (*print)(int, const char*))
781 union buflib_data *this, *end = ctx->handle_table;
782 char buf[128];
783 for(this = end - 1; this >= ctx->last_handle; this--)
785 if (!this->alloc) continue;
787 int handle_num;
788 const char *name;
789 union buflib_data *block_start, *alloc_start;
790 intptr_t alloc_len;
792 handle_num = end - this;
793 alloc_start = buflib_get_data(ctx, handle_num);
794 name = buflib_get_name(ctx, handle_num);
795 block_start = (union buflib_data*)name - 3;
796 alloc_len = block_start->val * sizeof(union buflib_data);
798 snprintf(buf, sizeof(buf),
799 "%s(%d):\t%p\n"
800 " \t%p\n"
801 " \t%ld\n",
802 name?:"(null)", handle_num, block_start, alloc_start, alloc_len);
803 /* handle_num is 1-based */
804 print(handle_num - 1, buf);
808 void buflib_print_blocks(struct buflib_context *ctx,
809 void (*print)(int, const char*))
811 char buf[128];
812 int i = 0;
813 for(union buflib_data* this = ctx->buf_start;
814 this < ctx->alloc_end;
815 this += abs(this->val))
817 snprintf(buf, sizeof(buf), "%8p: val: %4ld (%s)",
818 this, this->val,
819 this->val > 0? this[3].name:"<unallocated>");
820 print(i++, buf);
823 #endif
825 #ifdef BUFLIB_DEBUG_BLOCK_SINGLE
826 int buflib_get_num_blocks(struct buflib_context *ctx)
828 int i = 0;
829 for(union buflib_data* this = ctx->buf_start;
830 this < ctx->alloc_end;
831 this += abs(this->val))
833 i++;
835 return i;
838 void buflib_print_block_at(struct buflib_context *ctx, int block_num,
839 char* buf, size_t bufsize)
841 union buflib_data* this = ctx->buf_start;
842 while(block_num > 0 && this < ctx->alloc_end)
844 this += abs(this->val);
845 block_num -= 1;
847 snprintf(buf, bufsize, "%8p: val: %4ld (%s)",
848 this, (long)this->val,
849 this->val > 0? this[3].name:"<unallocated>");
852 #endif