ralloc.c revision b8e80941
1/*
2 * Copyright © 2010 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24#include <assert.h>
25#include <stdlib.h>
26#include <stdarg.h>
27#include <stdio.h>
28#include <string.h>
29#include <stdint.h>
30
31/* Some versions of MinGW are missing _vscprintf's declaration, although they
32 * still provide the symbol in the import library. */
33#ifdef __MINGW32__
34_CRTIMP int _vscprintf(const char *format, va_list argptr);
35#endif
36
37#include "ralloc.h"
38
39#ifndef va_copy
40#ifdef __va_copy
41#define va_copy(dest, src) __va_copy((dest), (src))
42#else
43#define va_copy(dest, src) (dest) = (src)
44#endif
45#endif
46
47#define CANARY 0x5A1106
48
49/* Align the header's size so that ralloc() allocations will return with the
50 * same alignment as a libc malloc would have (8 on 32-bit GLIBC, 16 on
51 * 64-bit), avoiding performance penalities on x86 and alignment faults on
52 * ARM.
53 */
54struct
55#ifdef _MSC_VER
56 __declspec(align(8))
57#elif defined(__LP64__)
58 __attribute__((aligned(16)))
59#else
60 __attribute__((aligned(8)))
61#endif
62   ralloc_header
63{
64#ifndef NDEBUG
65   /* A canary value used to determine whether a pointer is ralloc'd. */
66   unsigned canary;
67#endif
68
69   struct ralloc_header *parent;
70
71   /* The first child (head of a linked list) */
72   struct ralloc_header *child;
73
74   /* Linked list of siblings */
75   struct ralloc_header *prev;
76   struct ralloc_header *next;
77
78   void (*destructor)(void *);
79};
80
81typedef struct ralloc_header ralloc_header;
82
83static void unlink_block(ralloc_header *info);
84static void unsafe_free(ralloc_header *info);
85
86static ralloc_header *
87get_header(const void *ptr)
88{
89   ralloc_header *info = (ralloc_header *) (((char *) ptr) -
90					    sizeof(ralloc_header));
91   assert(info->canary == CANARY);
92   return info;
93}
94
95#define PTR_FROM_HEADER(info) (((char *) info) + sizeof(ralloc_header))
96
97static void
98add_child(ralloc_header *parent, ralloc_header *info)
99{
100   if (parent != NULL) {
101      info->parent = parent;
102      info->next = parent->child;
103      parent->child = info;
104
105      if (info->next != NULL)
106	 info->next->prev = info;
107   }
108}
109
110void *
111ralloc_context(const void *ctx)
112{
113   return ralloc_size(ctx, 0);
114}
115
116void *
117ralloc_size(const void *ctx, size_t size)
118{
119   void *block = malloc(size + sizeof(ralloc_header));
120   ralloc_header *info;
121   ralloc_header *parent;
122
123   if (unlikely(block == NULL))
124      return NULL;
125
126   info = (ralloc_header *) block;
127   /* measurements have shown that calloc is slower (because of
128    * the multiplication overflow checking?), so clear things
129    * manually
130    */
131   info->parent = NULL;
132   info->child = NULL;
133   info->prev = NULL;
134   info->next = NULL;
135   info->destructor = NULL;
136
137   parent = ctx != NULL ? get_header(ctx) : NULL;
138
139   add_child(parent, info);
140
141#ifndef NDEBUG
142   info->canary = CANARY;
143#endif
144
145   return PTR_FROM_HEADER(info);
146}
147
148void *
149rzalloc_size(const void *ctx, size_t size)
150{
151   void *ptr = ralloc_size(ctx, size);
152
153   if (likely(ptr))
154      memset(ptr, 0, size);
155
156   return ptr;
157}
158
159/* helper function - assumes ptr != NULL */
160static void *
161resize(void *ptr, size_t size)
162{
163   ralloc_header *child, *old, *info;
164
165   old = get_header(ptr);
166   info = realloc(old, size + sizeof(ralloc_header));
167
168   if (info == NULL)
169      return NULL;
170
171   /* Update parent and sibling's links to the reallocated node. */
172   if (info != old && info->parent != NULL) {
173      if (info->parent->child == old)
174	 info->parent->child = info;
175
176      if (info->prev != NULL)
177	 info->prev->next = info;
178
179      if (info->next != NULL)
180	 info->next->prev = info;
181   }
182
183   /* Update child->parent links for all children */
184   for (child = info->child; child != NULL; child = child->next)
185      child->parent = info;
186
187   return PTR_FROM_HEADER(info);
188}
189
190void *
191reralloc_size(const void *ctx, void *ptr, size_t size)
192{
193   if (unlikely(ptr == NULL))
194      return ralloc_size(ctx, size);
195
196   assert(ralloc_parent(ptr) == ctx);
197   return resize(ptr, size);
198}
199
200void *
201ralloc_array_size(const void *ctx, size_t size, unsigned count)
202{
203   if (count > SIZE_MAX/size)
204      return NULL;
205
206   return ralloc_size(ctx, size * count);
207}
208
209void *
210rzalloc_array_size(const void *ctx, size_t size, unsigned count)
211{
212   if (count > SIZE_MAX/size)
213      return NULL;
214
215   return rzalloc_size(ctx, size * count);
216}
217
218void *
219reralloc_array_size(const void *ctx, void *ptr, size_t size, unsigned count)
220{
221   if (count > SIZE_MAX/size)
222      return NULL;
223
224   return reralloc_size(ctx, ptr, size * count);
225}
226
227void
228ralloc_free(void *ptr)
229{
230   ralloc_header *info;
231
232   if (ptr == NULL)
233      return;
234
235   info = get_header(ptr);
236   unlink_block(info);
237   unsafe_free(info);
238}
239
240static void
241unlink_block(ralloc_header *info)
242{
243   /* Unlink from parent & siblings */
244   if (info->parent != NULL) {
245      if (info->parent->child == info)
246	 info->parent->child = info->next;
247
248      if (info->prev != NULL)
249	 info->prev->next = info->next;
250
251      if (info->next != NULL)
252	 info->next->prev = info->prev;
253   }
254   info->parent = NULL;
255   info->prev = NULL;
256   info->next = NULL;
257}
258
259static void
260unsafe_free(ralloc_header *info)
261{
262   /* Recursively free any children...don't waste time unlinking them. */
263   ralloc_header *temp;
264   while (info->child != NULL) {
265      temp = info->child;
266      info->child = temp->next;
267      unsafe_free(temp);
268   }
269
270   /* Free the block itself.  Call the destructor first, if any. */
271   if (info->destructor != NULL)
272      info->destructor(PTR_FROM_HEADER(info));
273
274   free(info);
275}
276
277void
278ralloc_steal(const void *new_ctx, void *ptr)
279{
280   ralloc_header *info, *parent;
281
282   if (unlikely(ptr == NULL))
283      return;
284
285   info = get_header(ptr);
286   parent = new_ctx ? get_header(new_ctx) : NULL;
287
288   unlink_block(info);
289
290   add_child(parent, info);
291}
292
293void
294ralloc_adopt(const void *new_ctx, void *old_ctx)
295{
296   ralloc_header *new_info, *old_info, *child;
297
298   if (unlikely(old_ctx == NULL))
299      return;
300
301   old_info = get_header(old_ctx);
302   new_info = get_header(new_ctx);
303
304   /* If there are no children, bail. */
305   if (unlikely(old_info->child == NULL))
306      return;
307
308   /* Set all the children's parent to new_ctx; get a pointer to the last child. */
309   for (child = old_info->child; child->next != NULL; child = child->next) {
310      child->parent = new_info;
311   }
312   child->parent = new_info;
313
314   /* Connect the two lists together; parent them to new_ctx; make old_ctx empty. */
315   child->next = new_info->child;
316   if (child->next)
317      child->next->prev = child;
318   new_info->child = old_info->child;
319   old_info->child = NULL;
320}
321
322void *
323ralloc_parent(const void *ptr)
324{
325   ralloc_header *info;
326
327   if (unlikely(ptr == NULL))
328      return NULL;
329
330   info = get_header(ptr);
331   return info->parent ? PTR_FROM_HEADER(info->parent) : NULL;
332}
333
334void
335ralloc_set_destructor(const void *ptr, void(*destructor)(void *))
336{
337   ralloc_header *info = get_header(ptr);
338   info->destructor = destructor;
339}
340
341char *
342ralloc_strdup(const void *ctx, const char *str)
343{
344   size_t n;
345   char *ptr;
346
347   if (unlikely(str == NULL))
348      return NULL;
349
350   n = strlen(str);
351   ptr = ralloc_array(ctx, char, n + 1);
352   memcpy(ptr, str, n);
353   ptr[n] = '\0';
354   return ptr;
355}
356
357char *
358ralloc_strndup(const void *ctx, const char *str, size_t max)
359{
360   size_t n;
361   char *ptr;
362
363   if (unlikely(str == NULL))
364      return NULL;
365
366   n = strnlen(str, max);
367   ptr = ralloc_array(ctx, char, n + 1);
368   memcpy(ptr, str, n);
369   ptr[n] = '\0';
370   return ptr;
371}
372
373/* helper routine for strcat/strncat - n is the exact amount to copy */
374static bool
375cat(char **dest, const char *str, size_t n)
376{
377   char *both;
378   size_t existing_length;
379   assert(dest != NULL && *dest != NULL);
380
381   existing_length = strlen(*dest);
382   both = resize(*dest, existing_length + n + 1);
383   if (unlikely(both == NULL))
384      return false;
385
386   memcpy(both + existing_length, str, n);
387   both[existing_length + n] = '\0';
388
389   *dest = both;
390   return true;
391}
392
393
394bool
395ralloc_strcat(char **dest, const char *str)
396{
397   return cat(dest, str, strlen(str));
398}
399
400bool
401ralloc_strncat(char **dest, const char *str, size_t n)
402{
403   return cat(dest, str, strnlen(str, n));
404}
405
406bool
407ralloc_str_append(char **dest, const char *str,
408                  size_t existing_length, size_t str_size)
409{
410   char *both;
411   assert(dest != NULL && *dest != NULL);
412
413   both = resize(*dest, existing_length + str_size + 1);
414   if (unlikely(both == NULL))
415      return false;
416
417   memcpy(both + existing_length, str, str_size);
418   both[existing_length + str_size] = '\0';
419
420   *dest = both;
421
422   return true;
423}
424
425char *
426ralloc_asprintf(const void *ctx, const char *fmt, ...)
427{
428   char *ptr;
429   va_list args;
430   va_start(args, fmt);
431   ptr = ralloc_vasprintf(ctx, fmt, args);
432   va_end(args);
433   return ptr;
434}
435
436/* Return the length of the string that would be generated by a printf-style
437 * format and argument list, not including the \0 byte.
438 */
439static size_t
440printf_length(const char *fmt, va_list untouched_args)
441{
442   int size;
443   char junk;
444
445   /* Make a copy of the va_list so the original caller can still use it */
446   va_list args;
447   va_copy(args, untouched_args);
448
449#ifdef _WIN32
450   /* We need to use _vcsprintf to calculate the size as vsnprintf returns -1
451    * if the number of characters to write is greater than count.
452    */
453   size = _vscprintf(fmt, args);
454   (void)junk;
455#else
456   size = vsnprintf(&junk, 1, fmt, args);
457#endif
458   assert(size >= 0);
459
460   va_end(args);
461
462   return size;
463}
464
465char *
466ralloc_vasprintf(const void *ctx, const char *fmt, va_list args)
467{
468   size_t size = printf_length(fmt, args) + 1;
469
470   char *ptr = ralloc_size(ctx, size);
471   if (ptr != NULL)
472      vsnprintf(ptr, size, fmt, args);
473
474   return ptr;
475}
476
477bool
478ralloc_asprintf_append(char **str, const char *fmt, ...)
479{
480   bool success;
481   va_list args;
482   va_start(args, fmt);
483   success = ralloc_vasprintf_append(str, fmt, args);
484   va_end(args);
485   return success;
486}
487
488bool
489ralloc_vasprintf_append(char **str, const char *fmt, va_list args)
490{
491   size_t existing_length;
492   assert(str != NULL);
493   existing_length = *str ? strlen(*str) : 0;
494   return ralloc_vasprintf_rewrite_tail(str, &existing_length, fmt, args);
495}
496
497bool
498ralloc_asprintf_rewrite_tail(char **str, size_t *start, const char *fmt, ...)
499{
500   bool success;
501   va_list args;
502   va_start(args, fmt);
503   success = ralloc_vasprintf_rewrite_tail(str, start, fmt, args);
504   va_end(args);
505   return success;
506}
507
508bool
509ralloc_vasprintf_rewrite_tail(char **str, size_t *start, const char *fmt,
510			      va_list args)
511{
512   size_t new_length;
513   char *ptr;
514
515   assert(str != NULL);
516
517   if (unlikely(*str == NULL)) {
518      // Assuming a NULL context is probably bad, but it's expected behavior.
519      *str = ralloc_vasprintf(NULL, fmt, args);
520      *start = strlen(*str);
521      return true;
522   }
523
524   new_length = printf_length(fmt, args);
525
526   ptr = resize(*str, *start + new_length + 1);
527   if (unlikely(ptr == NULL))
528      return false;
529
530   vsnprintf(ptr + *start, new_length + 1, fmt, args);
531   *str = ptr;
532   *start += new_length;
533   return true;
534}
535
536/***************************************************************************
537 * Linear allocator for short-lived allocations.
538 ***************************************************************************
539 *
540 * The allocator consists of a parent node (2K buffer), which requires
541 * a ralloc parent, and child nodes (allocations). Child nodes can't be freed
542 * directly, because the parent doesn't track them. You have to release
543 * the parent node in order to release all its children.
544 *
545 * The allocator uses a fixed-sized buffer with a monotonically increasing
546 * offset after each allocation. If the buffer is all used, another buffer
547 * is allocated, sharing the same ralloc parent, so all buffers are at
548 * the same level in the ralloc hierarchy.
549 *
550 * The linear parent node is always the first buffer and keeps track of all
551 * other buffers.
552 */
553
554#define MIN_LINEAR_BUFSIZE 2048
555#define SUBALLOC_ALIGNMENT 8
556#define LMAGIC 0x87b9c7d3
557
558struct
559#ifdef _MSC_VER
560 __declspec(align(8))
561#elif defined(__LP64__)
562 __attribute__((aligned(16)))
563#else
564 __attribute__((aligned(8)))
565#endif
566   linear_header {
567#ifndef NDEBUG
568   unsigned magic;   /* for debugging */
569#endif
570   unsigned offset;  /* points to the first unused byte in the buffer */
571   unsigned size;    /* size of the buffer */
572   void *ralloc_parent;          /* new buffers will use this */
573   struct linear_header *next;   /* next buffer if we have more */
574   struct linear_header *latest; /* the only buffer that has free space */
575
576   /* After this structure, the buffer begins.
577    * Each suballocation consists of linear_size_chunk as its header followed
578    * by the suballocation, so it goes:
579    *
580    * - linear_size_chunk
581    * - allocated space
582    * - linear_size_chunk
583    * - allocated space
584    * etc.
585    *
586    * linear_size_chunk is only needed by linear_realloc.
587    */
588};
589
590struct linear_size_chunk {
591   unsigned size; /* for realloc */
592   unsigned _padding;
593};
594
595typedef struct linear_header linear_header;
596typedef struct linear_size_chunk linear_size_chunk;
597
598#define LINEAR_PARENT_TO_HEADER(parent) \
599   (linear_header*) \
600   ((char*)(parent) - sizeof(linear_size_chunk) - sizeof(linear_header))
601
602/* Allocate the linear buffer with its header. */
603static linear_header *
604create_linear_node(void *ralloc_ctx, unsigned min_size)
605{
606   linear_header *node;
607
608   min_size += sizeof(linear_size_chunk);
609
610   if (likely(min_size < MIN_LINEAR_BUFSIZE))
611      min_size = MIN_LINEAR_BUFSIZE;
612
613   node = ralloc_size(ralloc_ctx, sizeof(linear_header) + min_size);
614   if (unlikely(!node))
615      return NULL;
616
617#ifndef NDEBUG
618   node->magic = LMAGIC;
619#endif
620   node->offset = 0;
621   node->size = min_size;
622   node->ralloc_parent = ralloc_ctx;
623   node->next = NULL;
624   node->latest = node;
625   return node;
626}
627
628void *
629linear_alloc_child(void *parent, unsigned size)
630{
631   linear_header *first = LINEAR_PARENT_TO_HEADER(parent);
632   linear_header *latest = first->latest;
633   linear_header *new_node;
634   linear_size_chunk *ptr;
635   unsigned full_size;
636
637   assert(first->magic == LMAGIC);
638   assert(!latest->next);
639
640   size = ALIGN_POT(size, SUBALLOC_ALIGNMENT);
641   full_size = sizeof(linear_size_chunk) + size;
642
643   if (unlikely(latest->offset + full_size > latest->size)) {
644      /* allocate a new node */
645      new_node = create_linear_node(latest->ralloc_parent, size);
646      if (unlikely(!new_node))
647         return NULL;
648
649      first->latest = new_node;
650      latest->latest = new_node;
651      latest->next = new_node;
652      latest = new_node;
653   }
654
655   ptr = (linear_size_chunk *)((char*)&latest[1] + latest->offset);
656   ptr->size = size;
657   latest->offset += full_size;
658
659   assert((uintptr_t)&ptr[1] % SUBALLOC_ALIGNMENT == 0);
660   return &ptr[1];
661}
662
663void *
664linear_alloc_parent(void *ralloc_ctx, unsigned size)
665{
666   linear_header *node;
667
668   if (unlikely(!ralloc_ctx))
669      return NULL;
670
671   size = ALIGN_POT(size, SUBALLOC_ALIGNMENT);
672
673   node = create_linear_node(ralloc_ctx, size);
674   if (unlikely(!node))
675      return NULL;
676
677   return linear_alloc_child((char*)node +
678                             sizeof(linear_header) +
679                             sizeof(linear_size_chunk), size);
680}
681
682void *
683linear_zalloc_child(void *parent, unsigned size)
684{
685   void *ptr = linear_alloc_child(parent, size);
686
687   if (likely(ptr))
688      memset(ptr, 0, size);
689   return ptr;
690}
691
692void *
693linear_zalloc_parent(void *parent, unsigned size)
694{
695   void *ptr = linear_alloc_parent(parent, size);
696
697   if (likely(ptr))
698      memset(ptr, 0, size);
699   return ptr;
700}
701
702void
703linear_free_parent(void *ptr)
704{
705   linear_header *node;
706
707   if (unlikely(!ptr))
708      return;
709
710   node = LINEAR_PARENT_TO_HEADER(ptr);
711   assert(node->magic == LMAGIC);
712
713   while (node) {
714      void *ptr = node;
715
716      node = node->next;
717      ralloc_free(ptr);
718   }
719}
720
721void
722ralloc_steal_linear_parent(void *new_ralloc_ctx, void *ptr)
723{
724   linear_header *node;
725
726   if (unlikely(!ptr))
727      return;
728
729   node = LINEAR_PARENT_TO_HEADER(ptr);
730   assert(node->magic == LMAGIC);
731
732   while (node) {
733      ralloc_steal(new_ralloc_ctx, node);
734      node->ralloc_parent = new_ralloc_ctx;
735      node = node->next;
736   }
737}
738
739void *
740ralloc_parent_of_linear_parent(void *ptr)
741{
742   linear_header *node = LINEAR_PARENT_TO_HEADER(ptr);
743   assert(node->magic == LMAGIC);
744   return node->ralloc_parent;
745}
746
747void *
748linear_realloc(void *parent, void *old, unsigned new_size)
749{
750   unsigned old_size = 0;
751   ralloc_header *new_ptr;
752
753   new_ptr = linear_alloc_child(parent, new_size);
754
755   if (unlikely(!old))
756      return new_ptr;
757
758   old_size = ((linear_size_chunk*)old)[-1].size;
759
760   if (likely(new_ptr && old_size))
761      memcpy(new_ptr, old, MIN2(old_size, new_size));
762
763   return new_ptr;
764}
765
766/* All code below is pretty much copied from ralloc and only the alloc
767 * calls are different.
768 */
769
770char *
771linear_strdup(void *parent, const char *str)
772{
773   unsigned n;
774   char *ptr;
775
776   if (unlikely(!str))
777      return NULL;
778
779   n = strlen(str);
780   ptr = linear_alloc_child(parent, n + 1);
781   if (unlikely(!ptr))
782      return NULL;
783
784   memcpy(ptr, str, n);
785   ptr[n] = '\0';
786   return ptr;
787}
788
789char *
790linear_asprintf(void *parent, const char *fmt, ...)
791{
792   char *ptr;
793   va_list args;
794   va_start(args, fmt);
795   ptr = linear_vasprintf(parent, fmt, args);
796   va_end(args);
797   return ptr;
798}
799
800char *
801linear_vasprintf(void *parent, const char *fmt, va_list args)
802{
803   unsigned size = printf_length(fmt, args) + 1;
804
805   char *ptr = linear_alloc_child(parent, size);
806   if (ptr != NULL)
807      vsnprintf(ptr, size, fmt, args);
808
809   return ptr;
810}
811
812bool
813linear_asprintf_append(void *parent, char **str, const char *fmt, ...)
814{
815   bool success;
816   va_list args;
817   va_start(args, fmt);
818   success = linear_vasprintf_append(parent, str, fmt, args);
819   va_end(args);
820   return success;
821}
822
823bool
824linear_vasprintf_append(void *parent, char **str, const char *fmt, va_list args)
825{
826   size_t existing_length;
827   assert(str != NULL);
828   existing_length = *str ? strlen(*str) : 0;
829   return linear_vasprintf_rewrite_tail(parent, str, &existing_length, fmt, args);
830}
831
832bool
833linear_asprintf_rewrite_tail(void *parent, char **str, size_t *start,
834                             const char *fmt, ...)
835{
836   bool success;
837   va_list args;
838   va_start(args, fmt);
839   success = linear_vasprintf_rewrite_tail(parent, str, start, fmt, args);
840   va_end(args);
841   return success;
842}
843
844bool
845linear_vasprintf_rewrite_tail(void *parent, char **str, size_t *start,
846                              const char *fmt, va_list args)
847{
848   size_t new_length;
849   char *ptr;
850
851   assert(str != NULL);
852
853   if (unlikely(*str == NULL)) {
854      *str = linear_vasprintf(parent, fmt, args);
855      *start = strlen(*str);
856      return true;
857   }
858
859   new_length = printf_length(fmt, args);
860
861   ptr = linear_realloc(parent, *str, *start + new_length + 1);
862   if (unlikely(ptr == NULL))
863      return false;
864
865   vsnprintf(ptr + *start, new_length + 1, fmt, args);
866   *str = ptr;
867   *start += new_length;
868   return true;
869}
870
871/* helper routine for strcat/strncat - n is the exact amount to copy */
872static bool
873linear_cat(void *parent, char **dest, const char *str, unsigned n)
874{
875   char *both;
876   unsigned existing_length;
877   assert(dest != NULL && *dest != NULL);
878
879   existing_length = strlen(*dest);
880   both = linear_realloc(parent, *dest, existing_length + n + 1);
881   if (unlikely(both == NULL))
882      return false;
883
884   memcpy(both + existing_length, str, n);
885   both[existing_length + n] = '\0';
886
887   *dest = both;
888   return true;
889}
890
891bool
892linear_strcat(void *parent, char **dest, const char *str)
893{
894   return linear_cat(parent, dest, str, strlen(str));
895}
896