[Mesa-dev] [PATCH 2/6] util: Move ralloc to a new src/util directory.

Jason Ekstrand jason at jlekstrand.net
Thu Jul 24 17:15:19 PDT 2014


From: Kenneth Graunke <kenneth at whitecape.org>

For a long time, we've wanted a place to put utility code which isn't
directly tied to Mesa or Gallium internals.  This patch creates a new
src/util directory for exactly that purpose, and builds the contents as
libmesautil.la.

ralloc seemed like a good first candidate.  These days, it's directly
used by mesa/main, i965, i915, and r300g, so keeping it in src/glsl
didn't make much sense.

Signed-off-by: Kenneth Graunke <kenneth at whitecape.org>

v2 (Jason Ekstrand): More realloc uses and some scons fixes

Signed-off-by: Jason Ekstrand <jason.ekstrand at intel.com>
---
 configure.ac                                       |   4 +-
 src/Makefile.am                                    |   2 +-
 src/SConscript                                     |   1 +
 src/gallium/drivers/r300/Makefile.am               |   3 +
 src/gallium/drivers/r300/ralloc.c                  |   2 +-
 src/gallium/targets/libgl-xlib/SConscript          |   1 +
 src/glsl/Makefile.am                               |  13 +-
 src/glsl/Makefile.sources                          |   1 -
 src/glsl/SConscript                                |   3 +
 src/glsl/glcpp/glcpp.h                             |   2 +-
 src/glsl/glsl_parser_extras.cpp                    |   2 +-
 src/glsl/glsl_types.h                              |   2 +-
 src/glsl/ir.h                                      |   2 +-
 src/glsl/list.h                                    |   2 +-
 src/glsl/ralloc.c                                  | 492 ---------------------
 src/glsl/ralloc.h                                  | 444 -------------------
 src/glsl/standalone_scaffolding.cpp                |   2 +-
 src/glsl/tests/builtin_variable_test.cpp           |   1 -
 src/glsl/tests/copy_constant_to_storage_tests.cpp  |   2 +-
 src/glsl/tests/general_ir_test.cpp                 |   1 -
 src/glsl/tests/invalidate_locations_test.cpp       |   2 +-
 src/glsl/tests/ralloc_test.cpp                     |  38 --
 src/glsl/tests/sampler_types_test.cpp              |   1 -
 src/glsl/tests/set_uniform_initializer_tests.cpp   |   2 +-
 src/glsl/tests/uniform_initializer_utils.cpp       |   2 +-
 src/glsl/tests/varyings_test.cpp                   |   2 +-
 src/mesa/Makefile.sources                          |   1 +
 src/mesa/SConscript                                |   1 +
 src/mesa/drivers/common/meta.c                     |   2 +-
 src/mesa/drivers/common/meta_blit.c                |   2 +-
 src/mesa/drivers/dri/i915/i830_context.c           |   2 +-
 src/mesa/drivers/dri/i915/i915_context.c           |   2 +-
 src/mesa/drivers/dri/i915/intel_context.c          |   2 +-
 src/mesa/drivers/dri/i965/brw_blorp_blit_eu.cpp    |   2 +-
 src/mesa/drivers/dri/i965/brw_blorp_clear.cpp      |   2 +-
 src/mesa/drivers/dri/i965/brw_clip.c               |   2 +-
 src/mesa/drivers/dri/i965/brw_context.c            |   2 +-
 src/mesa/drivers/dri/i965/brw_eu.c                 |   2 +-
 src/mesa/drivers/dri/i965/brw_eu_emit.c            |   2 +-
 src/mesa/drivers/dri/i965/brw_gs.c                 |   2 +-
 src/mesa/drivers/dri/i965/brw_meta_stencil_blit.c  |   2 +-
 .../drivers/dri/i965/brw_performance_monitor.c     |   2 +-
 src/mesa/drivers/dri/i965/brw_program.c            |   2 +-
 src/mesa/drivers/dri/i965/brw_sf.c                 |   2 +-
 src/mesa/drivers/dri/i965/brw_state_batch.c        |   2 +-
 src/mesa/drivers/dri/i965/brw_vs.c                 |   2 +-
 src/mesa/drivers/dri/i965/brw_wm.c                 |   2 +-
 src/mesa/drivers/dri/i965/gen8_generator.cpp       |   2 +-
 src/mesa/drivers/dri/i965/intel_screen.c           |   2 +-
 src/mesa/drivers/dri/i965/test_eu_compact.c        |   2 +-
 src/mesa/drivers/x11/SConscript                    |   1 +
 src/mesa/main/hash_table.c                         |   2 +-
 src/mesa/main/performance_monitor.c                |   2 +-
 src/mesa/main/pipelineobj.c                        |   2 +-
 src/mesa/main/set.c                                |   2 +-
 src/mesa/main/shaderapi.c                          |   2 +-
 src/mesa/main/shaderobj.c                          |   2 +-
 src/mesa/main/tests/Makefile.am                    |   1 +
 src/mesa/program/register_allocate.c               |   2 +-
 src/util/Makefile.am                               |  53 +++
 src/util/Makefile.sources                          |   2 +
 src/util/SConscript                                |  26 ++
 src/util/ralloc.c                                  | 492 +++++++++++++++++++++
 src/util/ralloc.h                                  | 444 +++++++++++++++++++
 src/util/tests/Makefile.am                         |  40 ++
 src/util/tests/ralloc_test.cpp                     |  38 ++
 66 files changed, 1155 insertions(+), 1031 deletions(-)
 delete mode 100644 src/glsl/ralloc.c
 delete mode 100644 src/glsl/ralloc.h
 delete mode 100644 src/glsl/tests/ralloc_test.cpp
 create mode 100644 src/util/Makefile.am
 create mode 100644 src/util/Makefile.sources
 create mode 100644 src/util/SConscript
 create mode 100644 src/util/ralloc.c
 create mode 100644 src/util/ralloc.h
 create mode 100644 src/util/tests/Makefile.am
 create mode 100644 src/util/tests/ralloc_test.cpp

diff --git a/configure.ac b/configure.ac
index 744e55c..dfbc058 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2264,7 +2264,9 @@ AC_CONFIG_FILES([Makefile
 		src/mesa/drivers/osmesa/osmesa.pc
 		src/mesa/drivers/x11/Makefile
 		src/mesa/main/tests/Makefile
-		src/mesa/main/tests/hash_table/Makefile])
+		src/mesa/main/tests/hash_table/Makefile
+		src/util/Makefile
+		src/util/tests/Makefile])
 
 dnl Sort the dirs alphabetically
 GALLIUM_TARGET_DIRS=`echo $GALLIUM_TARGET_DIRS|tr " " "\n"|sort -u|tr "\n" " "`
diff --git a/src/Makefile.am b/src/Makefile.am
index d4a7090..2634c34 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -19,7 +19,7 @@
 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 # IN THE SOFTWARE.
 
-SUBDIRS = gtest mapi
+SUBDIRS = util gtest mapi
 
 if NEED_OPENGL_COMMON
 SUBDIRS += glsl mesa
diff --git a/src/SConscript b/src/SConscript
index 93a490d..2657bba 100644
--- a/src/SConscript
+++ b/src/SConscript
@@ -4,6 +4,7 @@ Import('*')
 if env['platform'] == 'windows':
     SConscript('getopt/SConscript')
 
+SConscript('util/SConscript')
 SConscript('glsl/SConscript')
 
 if env['hostonly']:
diff --git a/src/gallium/drivers/r300/Makefile.am b/src/gallium/drivers/r300/Makefile.am
index a8aaf22..2c5951b 100644
--- a/src/gallium/drivers/r300/Makefile.am
+++ b/src/gallium/drivers/r300/Makefile.am
@@ -4,6 +4,7 @@ include Makefile.sources
 include $(top_srcdir)/src/gallium/Automake.inc
 
 AM_CFLAGS = \
+	-I$(top_srcdir)/src/util \
 	-I$(top_srcdir)/src/mesa/program \
 	-I$(top_srcdir)/src/mesa \
 	-I$(top_srcdir)/src/glsl \
@@ -17,6 +18,7 @@ check_PROGRAMS = r300_compiler_tests
 TESTS = r300_compiler_tests
 
 r300_compiler_tests_LDADD = libr300.la libr300-helper.la \
+	$(top_builddir)/src/util/libmesautil.la \
 	$(top_builddir)/src/gallium/auxiliary/libgallium.la \
 	$(GALLIUM_COMMON_LIB_DEPS)
 r300_compiler_tests_CPPFLAGS = \
@@ -32,4 +34,5 @@ libr300_la_SOURCES = $(C_SOURCES)
 #
 # Solve this by building them into a separate helper library that can be linked
 # in place of libmesagallium.
+libr300_helper_la_CPPFLAGS = -I$(top_srcdir)/src
 libr300_helper_la_SOURCES = $(HELPER_SOURCES)
diff --git a/src/gallium/drivers/r300/ralloc.c b/src/gallium/drivers/r300/ralloc.c
index c5402db..7ad6def 120000
--- a/src/gallium/drivers/r300/ralloc.c
+++ b/src/gallium/drivers/r300/ralloc.c
@@ -1 +1 @@
-../../../glsl/ralloc.c
\ No newline at end of file
+../../../util/ralloc.c
\ No newline at end of file
diff --git a/src/gallium/targets/libgl-xlib/SConscript b/src/gallium/targets/libgl-xlib/SConscript
index fc0264c..22cf107 100644
--- a/src/gallium/targets/libgl-xlib/SConscript
+++ b/src/gallium/targets/libgl-xlib/SConscript
@@ -27,6 +27,7 @@ if env['gles']:
 env.Prepend(LIBS = [
     st_xlib,
     ws_xlib,
+    mesautil,
     glapi,
     mesa,
     glsl,
diff --git a/src/glsl/Makefile.am b/src/glsl/Makefile.am
index 00261fd..292c8f7 100644
--- a/src/glsl/Makefile.am
+++ b/src/glsl/Makefile.am
@@ -21,6 +21,7 @@
 
 AM_CPPFLAGS = \
 	-I$(top_srcdir)/include \
+	-I$(top_srcdir)/src \
 	-I$(top_srcdir)/src/mapi \
 	-I$(top_srcdir)/src/mesa/ \
 	-I$(top_srcdir)/src/glsl/glcpp \
@@ -34,7 +35,6 @@ include Makefile.sources
 TESTS = glcpp/tests/glcpp-test				\
 	tests/general-ir-test				\
 	tests/optimization-test				\
-	tests/ralloc-test				\
 	tests/sampler-types-test                        \
 	tests/uniform-initializer-test
 
@@ -47,7 +47,6 @@ check_PROGRAMS =					\
 	glcpp/glcpp					\
 	glsl_test					\
 	tests/general-ir-test				\
-	tests/ralloc-test				\
 	tests/sampler-types-test			\
 	tests/uniform-initializer-test
 
@@ -87,14 +86,6 @@ tests_uniform_initializer_test_LDADD =			\
 	$(top_builddir)/src/glsl/libglsl.la		\
 	$(PTHREAD_LIBS)
 
-tests_ralloc_test_SOURCES =				\
-	tests/ralloc_test.cpp				\
-	$(top_builddir)/src/glsl/ralloc.c
-tests_ralloc_test_CFLAGS = $(PTHREAD_CFLAGS)
-tests_ralloc_test_LDADD =				\
-	$(top_builddir)/src/gtest/libgtest.la		\
-	$(PTHREAD_LIBS)
-
 tests_sampler_types_test_SOURCES =			\
 	$(top_srcdir)/src/mesa/program/prog_hash_table.c\
 	$(top_srcdir)/src/mesa/program/symbol_table.c	\
@@ -107,6 +98,8 @@ tests_sampler_types_test_LDADD =			\
 	$(top_builddir)/src/glsl/libglsl.la		\
 	$(PTHREAD_LIBS)
 
+libglcpp_la_LIBADD =					\
+	$(top_builddir)/src/util/libmesautil.la
 libglcpp_la_SOURCES =					\
 	glcpp/glcpp-lex.c				\
 	glcpp/glcpp-parse.c				\
diff --git a/src/glsl/Makefile.sources b/src/glsl/Makefile.sources
index b54eae7..2131dda 100644
--- a/src/glsl/Makefile.sources
+++ b/src/glsl/Makefile.sources
@@ -6,7 +6,6 @@ GLSL_BUILDDIR = $(top_builddir)/src/glsl
 # libglcpp
 
 LIBGLCPP_FILES = \
-	$(GLSL_SRCDIR)/ralloc.c \
 	$(GLSL_SRCDIR)/glcpp/pp.c
 
 LIBGLCPP_GENERATED_FILES = \
diff --git a/src/glsl/SConscript b/src/glsl/SConscript
index dc35477..d1d5993 100644
--- a/src/glsl/SConscript
+++ b/src/glsl/SConscript
@@ -8,12 +8,15 @@ env = env.Clone()
 
 env.Prepend(CPPPATH = [
     '#include',
+    '#src',
     '#src/mapi',
     '#src/mesa',
     '#src/glsl',
     '#src/glsl/glcpp',
 ])
 
+env.Prepend(LIBS = [mesautil])
+
 # Make glcpp-parse.h and glsl_parser.h reachable from the include path.
 env.Append(CPPPATH = [Dir('.').abspath, Dir('glcpp').abspath])
 
diff --git a/src/glsl/glcpp/glcpp.h b/src/glsl/glcpp/glcpp.h
index 64b4872..68ee754 100644
--- a/src/glsl/glcpp/glcpp.h
+++ b/src/glsl/glcpp/glcpp.h
@@ -29,7 +29,7 @@
 
 #include "main/mtypes.h"
 
-#include "../ralloc.h"
+#include "util/ralloc.h"
 
 #include "program/hash_table.h"
 
diff --git a/src/glsl/glsl_parser_extras.cpp b/src/glsl/glsl_parser_extras.cpp
index 890123a..e5c2dfe 100644
--- a/src/glsl/glsl_parser_extras.cpp
+++ b/src/glsl/glsl_parser_extras.cpp
@@ -31,7 +31,7 @@ extern "C" {
 #include "main/shaderobj.h"
 }
 
-#include "ralloc.h"
+#include "util/ralloc.h"
 #include "ast.h"
 #include "glsl_parser_extras.h"
 #include "glsl_parser.h"
diff --git a/src/glsl/glsl_types.h b/src/glsl/glsl_types.h
index 0b63d48..50cd655 100644
--- a/src/glsl/glsl_types.h
+++ b/src/glsl/glsl_types.h
@@ -81,7 +81,7 @@ enum glsl_interface_packing {
 
 #ifdef __cplusplus
 #include "GL/gl.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 
 struct glsl_type {
    GLenum gl_type;
diff --git a/src/glsl/ir.h b/src/glsl/ir.h
index ea19924..de28f87 100644
--- a/src/glsl/ir.h
+++ b/src/glsl/ir.h
@@ -29,7 +29,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 
-#include "ralloc.h"
+#include "util/ralloc.h"
 #include "glsl_types.h"
 #include "list.h"
 #include "ir_visitor.h"
diff --git a/src/glsl/list.h b/src/glsl/list.h
index 3ee6cda..b6c32bc 100644
--- a/src/glsl/list.h
+++ b/src/glsl/list.h
@@ -69,7 +69,7 @@
 #endif
 #include <assert.h>
 
-#include "ralloc.h"
+#include "util/ralloc.h"
 
 struct exec_node {
    struct exec_node *next;
diff --git a/src/glsl/ralloc.c b/src/glsl/ralloc.c
deleted file mode 100644
index 36bc61f..0000000
--- a/src/glsl/ralloc.c
+++ /dev/null
@@ -1,492 +0,0 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice (including the next
- * paragraph) shall be included in all copies or substantial portions of the
- * Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-#include <assert.h>
-#include <stdlib.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdint.h>
-
-/* Android defines SIZE_MAX in limits.h, instead of the standard stdint.h */
-#ifdef ANDROID
-#include <limits.h>
-#endif
-
-/* Some versions of MinGW are missing _vscprintf's declaration, although they
- * still provide the symbol in the import library. */
-#ifdef __MINGW32__
-_CRTIMP int _vscprintf(const char *format, va_list argptr);
-#endif
-
-#include "ralloc.h"
-
-#ifndef va_copy
-#ifdef __va_copy
-#define va_copy(dest, src) __va_copy((dest), (src))
-#else
-#define va_copy(dest, src) (dest) = (src)
-#endif
-#endif
-
-#define CANARY 0x5A1106
-
-struct ralloc_header
-{
-#ifdef DEBUG
-   /* A canary value used to determine whether a pointer is ralloc'd. */
-   unsigned canary;
-#endif
-
-   struct ralloc_header *parent;
-
-   /* The first child (head of a linked list) */
-   struct ralloc_header *child;
-
-   /* Linked list of siblings */
-   struct ralloc_header *prev;
-   struct ralloc_header *next;
-
-   void (*destructor)(void *);
-};
-
-typedef struct ralloc_header ralloc_header;
-
-static void unlink_block(ralloc_header *info);
-static void unsafe_free(ralloc_header *info);
-
-static ralloc_header *
-get_header(const void *ptr)
-{
-   ralloc_header *info = (ralloc_header *) (((char *) ptr) -
-					    sizeof(ralloc_header));
-#ifdef DEBUG
-   assert(info->canary == CANARY);
-#endif
-   return info;
-}
-
-#define PTR_FROM_HEADER(info) (((char *) info) + sizeof(ralloc_header))
-
-static void
-add_child(ralloc_header *parent, ralloc_header *info)
-{
-   if (parent != NULL) {
-      info->parent = parent;
-      info->next = parent->child;
-      parent->child = info;
-
-      if (info->next != NULL)
-	 info->next->prev = info;
-   }
-}
-
-void *
-ralloc_context(const void *ctx)
-{
-   return ralloc_size(ctx, 0);
-}
-
-void *
-ralloc_size(const void *ctx, size_t size)
-{
-   void *block = calloc(1, size + sizeof(ralloc_header));
-   ralloc_header *info;
-   ralloc_header *parent;
-
-   if (unlikely(block == NULL))
-      return NULL;
-   info = (ralloc_header *) block;
-   parent = ctx != NULL ? get_header(ctx) : NULL;
-
-   add_child(parent, info);
-
-#ifdef DEBUG
-   info->canary = CANARY;
-#endif
-
-   return PTR_FROM_HEADER(info);
-}
-
-void *
-rzalloc_size(const void *ctx, size_t size)
-{
-   void *ptr = ralloc_size(ctx, size);
-   if (likely(ptr != NULL))
-      memset(ptr, 0, size);
-   return ptr;
-}
-
-/* helper function - assumes ptr != NULL */
-static void *
-resize(void *ptr, size_t size)
-{
-   ralloc_header *child, *old, *info;
-
-   old = get_header(ptr);
-   info = realloc(old, size + sizeof(ralloc_header));
-
-   if (info == NULL)
-      return NULL;
-
-   /* Update parent and sibling's links to the reallocated node. */
-   if (info != old && info->parent != NULL) {
-      if (info->parent->child == old)
-	 info->parent->child = info;
-
-      if (info->prev != NULL)
-	 info->prev->next = info;
-
-      if (info->next != NULL)
-	 info->next->prev = info;
-   }
-
-   /* Update child->parent links for all children */
-   for (child = info->child; child != NULL; child = child->next)
-      child->parent = info;
-
-   return PTR_FROM_HEADER(info);
-}
-
-void *
-reralloc_size(const void *ctx, void *ptr, size_t size)
-{
-   if (unlikely(ptr == NULL))
-      return ralloc_size(ctx, size);
-
-   assert(ralloc_parent(ptr) == ctx);
-   return resize(ptr, size);
-}
-
-void *
-ralloc_array_size(const void *ctx, size_t size, unsigned count)
-{
-   if (count > SIZE_MAX/size)
-      return NULL;
-
-   return ralloc_size(ctx, size * count);
-}
-
-void *
-rzalloc_array_size(const void *ctx, size_t size, unsigned count)
-{
-   if (count > SIZE_MAX/size)
-      return NULL;
-
-   return rzalloc_size(ctx, size * count);
-}
-
-void *
-reralloc_array_size(const void *ctx, void *ptr, size_t size, unsigned count)
-{
-   if (count > SIZE_MAX/size)
-      return NULL;
-
-   return reralloc_size(ctx, ptr, size * count);
-}
-
-void
-ralloc_free(void *ptr)
-{
-   ralloc_header *info;
-
-   if (ptr == NULL)
-      return;
-
-   info = get_header(ptr);
-   unlink_block(info);
-   unsafe_free(info);
-}
-
-static void
-unlink_block(ralloc_header *info)
-{
-   /* Unlink from parent & siblings */
-   if (info->parent != NULL) {
-      if (info->parent->child == info)
-	 info->parent->child = info->next;
-
-      if (info->prev != NULL)
-	 info->prev->next = info->next;
-
-      if (info->next != NULL)
-	 info->next->prev = info->prev;
-   }
-   info->parent = NULL;
-   info->prev = NULL;
-   info->next = NULL;
-}
-
-static void
-unsafe_free(ralloc_header *info)
-{
-   /* Recursively free any children...don't waste time unlinking them. */
-   ralloc_header *temp;
-   while (info->child != NULL) {
-      temp = info->child;
-      info->child = temp->next;
-      unsafe_free(temp);
-   }
-
-   /* Free the block itself.  Call the destructor first, if any. */
-   if (info->destructor != NULL)
-      info->destructor(PTR_FROM_HEADER(info));
-
-   free(info);
-}
-
-void
-ralloc_steal(const void *new_ctx, void *ptr)
-{
-   ralloc_header *info, *parent;
-
-   if (unlikely(ptr == NULL))
-      return;
-
-   info = get_header(ptr);
-   parent = get_header(new_ctx);
-
-   unlink_block(info);
-
-   add_child(parent, info);
-}
-
-void *
-ralloc_parent(const void *ptr)
-{
-   ralloc_header *info;
-
-   if (unlikely(ptr == NULL))
-      return NULL;
-
-   info = get_header(ptr);
-   return info->parent ? PTR_FROM_HEADER(info->parent) : NULL;
-}
-
-static void *autofree_context = NULL;
-
-static void
-autofree(void)
-{
-   ralloc_free(autofree_context);
-}
-
-void *
-ralloc_autofree_context(void)
-{
-   if (unlikely(autofree_context == NULL)) {
-      autofree_context = ralloc_context(NULL);
-      atexit(autofree);
-   }
-   return autofree_context;
-}
-
-void
-ralloc_set_destructor(const void *ptr, void(*destructor)(void *))
-{
-   ralloc_header *info = get_header(ptr);
-   info->destructor = destructor;
-}
-
-char *
-ralloc_strdup(const void *ctx, const char *str)
-{
-   size_t n;
-   char *ptr;
-
-   if (unlikely(str == NULL))
-      return NULL;
-
-   n = strlen(str);
-   ptr = ralloc_array(ctx, char, n + 1);
-   memcpy(ptr, str, n);
-   ptr[n] = '\0';
-   return ptr;
-}
-
-char *
-ralloc_strndup(const void *ctx, const char *str, size_t max)
-{
-   size_t n;
-   char *ptr;
-
-   if (unlikely(str == NULL))
-      return NULL;
-
-   n = strlen(str);
-   if (n > max)
-      n = max;
-
-   ptr = ralloc_array(ctx, char, n + 1);
-   memcpy(ptr, str, n);
-   ptr[n] = '\0';
-   return ptr;
-}
-
-/* helper routine for strcat/strncat - n is the exact amount to copy */
-static bool
-cat(char **dest, const char *str, size_t n)
-{
-   char *both;
-   size_t existing_length;
-   assert(dest != NULL && *dest != NULL);
-
-   existing_length = strlen(*dest);
-   both = resize(*dest, existing_length + n + 1);
-   if (unlikely(both == NULL))
-      return false;
-
-   memcpy(both + existing_length, str, n);
-   both[existing_length + n] = '\0';
-
-   *dest = both;
-   return true;
-}
-
-
-bool
-ralloc_strcat(char **dest, const char *str)
-{
-   return cat(dest, str, strlen(str));
-}
-
-bool
-ralloc_strncat(char **dest, const char *str, size_t n)
-{
-   /* Clamp n to the string length */
-   size_t str_length = strlen(str);
-   if (str_length < n)
-      n = str_length;
-
-   return cat(dest, str, n);
-}
-
-char *
-ralloc_asprintf(const void *ctx, const char *fmt, ...)
-{
-   char *ptr;
-   va_list args;
-   va_start(args, fmt);
-   ptr = ralloc_vasprintf(ctx, fmt, args);
-   va_end(args);
-   return ptr;
-}
-
-/* Return the length of the string that would be generated by a printf-style
- * format and argument list, not including the \0 byte.
- */
-static size_t
-printf_length(const char *fmt, va_list untouched_args)
-{
-   int size;
-   char junk;
-
-   /* Make a copy of the va_list so the original caller can still use it */
-   va_list args;
-   va_copy(args, untouched_args);
-
-#ifdef _WIN32
-   /* We need to use _vcsprintf to calculate the size as vsnprintf returns -1
-    * if the number of characters to write is greater than count.
-    */
-   size = _vscprintf(fmt, args);
-   (void)junk;
-#else
-   size = vsnprintf(&junk, 1, fmt, args);
-#endif
-   assert(size >= 0);
-
-   va_end(args);
-
-   return size;
-}
-
-char *
-ralloc_vasprintf(const void *ctx, const char *fmt, va_list args)
-{
-   size_t size = printf_length(fmt, args) + 1;
-
-   char *ptr = ralloc_size(ctx, size);
-   if (ptr != NULL)
-      vsnprintf(ptr, size, fmt, args);
-
-   return ptr;
-}
-
-bool
-ralloc_asprintf_append(char **str, const char *fmt, ...)
-{
-   bool success;
-   va_list args;
-   va_start(args, fmt);
-   success = ralloc_vasprintf_append(str, fmt, args);
-   va_end(args);
-   return success;
-}
-
-bool
-ralloc_vasprintf_append(char **str, const char *fmt, va_list args)
-{
-   size_t existing_length;
-   assert(str != NULL);
-   existing_length = *str ? strlen(*str) : 0;
-   return ralloc_vasprintf_rewrite_tail(str, &existing_length, fmt, args);
-}
-
-bool
-ralloc_asprintf_rewrite_tail(char **str, size_t *start, const char *fmt, ...)
-{
-   bool success;
-   va_list args;
-   va_start(args, fmt);
-   success = ralloc_vasprintf_rewrite_tail(str, start, fmt, args);
-   va_end(args);
-   return success;
-}
-
-bool
-ralloc_vasprintf_rewrite_tail(char **str, size_t *start, const char *fmt,
-			      va_list args)
-{
-   size_t new_length;
-   char *ptr;
-
-   assert(str != NULL);
-
-   if (unlikely(*str == NULL)) {
-      // Assuming a NULL context is probably bad, but it's expected behavior.
-      *str = ralloc_vasprintf(NULL, fmt, args);
-      return true;
-   }
-
-   new_length = printf_length(fmt, args);
-
-   ptr = resize(*str, *start + new_length + 1);
-   if (unlikely(ptr == NULL))
-      return false;
-
-   vsnprintf(ptr + *start, new_length + 1, fmt, args);
-   *str = ptr;
-   *start += new_length;
-   return true;
-}
diff --git a/src/glsl/ralloc.h b/src/glsl/ralloc.h
deleted file mode 100644
index 1fe5357..0000000
--- a/src/glsl/ralloc.h
+++ /dev/null
@@ -1,444 +0,0 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice (including the next
- * paragraph) shall be included in all copies or substantial portions of the
- * Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-/**
- * \file ralloc.h
- *
- * ralloc: a recursive memory allocator
- *
- * The ralloc memory allocator creates a hierarchy of allocated
- * objects. Every allocation is in reference to some parent, and
- * every allocated object can in turn be used as the parent of a
- * subsequent allocation. This allows for extremely convenient
- * discarding of an entire tree/sub-tree of allocations by calling
- * ralloc_free on any particular object to free it and all of its
- * children.
- *
- * The conceptual working of ralloc was directly inspired by Andrew
- * Tridgell's talloc, but ralloc is an independent implementation
- * released under the MIT license and tuned for Mesa.
- *
- * talloc is more sophisticated than ralloc in that it includes reference
- * counting and useful debugging features.  However, it is released under
- * a non-permissive open source license.
- */
-
-#ifndef RALLOC_H
-#define RALLOC_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stddef.h>
-#include <stdarg.h>
-#include <stdbool.h>
-#include "main/compiler.h"
-
-/**
- * \def ralloc(ctx, type)
- * Allocate a new object chained off of the given context.
- *
- * This is equivalent to:
- * \code
- * ((type *) ralloc_size(ctx, sizeof(type))
- * \endcode
- */
-#define ralloc(ctx, type)  ((type *) ralloc_size(ctx, sizeof(type)))
-
-/**
- * \def rzalloc(ctx, type)
- * Allocate a new object out of the given context and initialize it to zero.
- *
- * This is equivalent to:
- * \code
- * ((type *) rzalloc_size(ctx, sizeof(type))
- * \endcode
- */
-#define rzalloc(ctx, type) ((type *) rzalloc_size(ctx, sizeof(type)))
-
-/**
- * Allocate a new ralloc context.
- *
- * While any ralloc'd pointer can be used as a context, sometimes it is useful
- * to simply allocate a context with no associated memory.
- *
- * It is equivalent to:
- * \code
- * ((type *) ralloc_size(ctx, 0)
- * \endcode
- */
-void *ralloc_context(const void *ctx);
-
-/**
- * Allocate memory chained off of the given context.
- *
- * This is the core allocation routine which is used by all others.  It
- * simply allocates storage for \p size bytes and returns the pointer,
- * similar to \c malloc.
- */
-void *ralloc_size(const void *ctx, size_t size);
-
-/**
- * Allocate zero-initialized memory chained off of the given context.
- *
- * This is similar to \c calloc with a size of 1.
- */
-void *rzalloc_size(const void *ctx, size_t size);
-
-/**
- * Resize a piece of ralloc-managed memory, preserving data.
- *
- * Similar to \c realloc.  Unlike C89, passing 0 for \p size does not free the
- * memory.  Instead, it resizes it to a 0-byte ralloc context, just like
- * calling ralloc_size(ctx, 0).  This is different from talloc.
- *
- * \param ctx  The context to use for new allocation.  If \p ptr != NULL,
- *             it must be the same as ralloc_parent(\p ptr).
- * \param ptr  Pointer to the memory to be resized.  May be NULL.
- * \param size The amount of memory to allocate, in bytes.
- */
-void *reralloc_size(const void *ctx, void *ptr, size_t size);
-
-/// \defgroup array Array Allocators @{
-
-/**
- * \def ralloc_array(ctx, type, count)
- * Allocate an array of objects chained off the given context.
- *
- * Similar to \c calloc, but does not initialize the memory to zero.
- *
- * More than a convenience function, this also checks for integer overflow when
- * multiplying \c sizeof(type) and \p count.  This is necessary for security.
- *
- * This is equivalent to:
- * \code
- * ((type *) ralloc_array_size(ctx, sizeof(type), count)
- * \endcode
- */
-#define ralloc_array(ctx, type, count) \
-   ((type *) ralloc_array_size(ctx, sizeof(type), count))
-
-/**
- * \def rzalloc_array(ctx, type, count)
- * Allocate a zero-initialized array chained off the given context.
- *
- * Similar to \c calloc.
- *
- * More than a convenience function, this also checks for integer overflow when
- * multiplying \c sizeof(type) and \p count.  This is necessary for security.
- *
- * This is equivalent to:
- * \code
- * ((type *) rzalloc_array_size(ctx, sizeof(type), count)
- * \endcode
- */
-#define rzalloc_array(ctx, type, count) \
-   ((type *) rzalloc_array_size(ctx, sizeof(type), count))
-
-/**
- * \def reralloc(ctx, ptr, type, count)
- * Resize a ralloc-managed array, preserving data.
- *
- * Similar to \c realloc.  Unlike C89, passing 0 for \p size does not free the
- * memory.  Instead, it resizes it to a 0-byte ralloc context, just like
- * calling ralloc_size(ctx, 0).  This is different from talloc.
- *
- * More than a convenience function, this also checks for integer overflow when
- * multiplying \c sizeof(type) and \p count.  This is necessary for security.
- *
- * \param ctx   The context to use for new allocation.  If \p ptr != NULL,
- *              it must be the same as ralloc_parent(\p ptr).
- * \param ptr   Pointer to the array to be resized.  May be NULL.
- * \param type  The element type.
- * \param count The number of elements to allocate.
- */
-#define reralloc(ctx, ptr, type, count) \
-   ((type *) reralloc_array_size(ctx, ptr, sizeof(type), count))
-
-/**
- * Allocate memory for an array chained off the given context.
- *
- * Similar to \c calloc, but does not initialize the memory to zero.
- *
- * More than a convenience function, this also checks for integer overflow when
- * multiplying \p size and \p count.  This is necessary for security.
- */
-void *ralloc_array_size(const void *ctx, size_t size, unsigned count);
-
-/**
- * Allocate a zero-initialized array chained off the given context.
- *
- * Similar to \c calloc.
- *
- * More than a convenience function, this also checks for integer overflow when
- * multiplying \p size and \p count.  This is necessary for security.
- */
-void *rzalloc_array_size(const void *ctx, size_t size, unsigned count);
-
-/**
- * Resize a ralloc-managed array, preserving data.
- *
- * Similar to \c realloc.  Unlike C89, passing 0 for \p size does not free the
- * memory.  Instead, it resizes it to a 0-byte ralloc context, just like
- * calling ralloc_size(ctx, 0).  This is different from talloc.
- *
- * More than a convenience function, this also checks for integer overflow when
- * multiplying \c sizeof(type) and \p count.  This is necessary for security.
- *
- * \param ctx   The context to use for new allocation.  If \p ptr != NULL,
- *              it must be the same as ralloc_parent(\p ptr).
- * \param ptr   Pointer to the array to be resized.  May be NULL.
- * \param size  The size of an individual element.
- * \param count The number of elements to allocate.
- *
- * \return True unless allocation failed.
- */
-void *reralloc_array_size(const void *ctx, void *ptr, size_t size,
-			  unsigned count);
-/// @}
-
-/**
- * Free a piece of ralloc-managed memory.
- *
- * This will also free the memory of any children allocated this context.
- */
-void ralloc_free(void *ptr);
-
-/**
- * "Steal" memory from one context, changing it to another.
- *
- * This changes \p ptr's context to \p new_ctx.  This is quite useful if
- * memory is allocated out of a temporary context.
- */
-void ralloc_steal(const void *new_ctx, void *ptr);
-
-/**
- * Return the given pointer's ralloc context.
- */
-void *ralloc_parent(const void *ptr);
-
-/**
- * Return a context whose memory will be automatically freed at program exit.
- *
- * The first call to this function creates a context and registers a handler
- * to free it using \c atexit.  This may cause trouble if used in a library
- * loaded with \c dlopen.
- */
-void *ralloc_autofree_context(void);
-
-/**
- * Set a callback to occur just before an object is freed.
- */
-void ralloc_set_destructor(const void *ptr, void(*destructor)(void *));
-
-/// \defgroup array String Functions @{
-/**
- * Duplicate a string, allocating the memory from the given context.
- */
-char *ralloc_strdup(const void *ctx, const char *str);
-
-/**
- * Duplicate a string, allocating the memory from the given context.
- *
- * Like \c strndup, at most \p n characters are copied.  If \p str is longer
- * than \p n characters, \p n are copied, and a termining \c '\0' byte is added.
- */
-char *ralloc_strndup(const void *ctx, const char *str, size_t n);
-
-/**
- * Concatenate two strings, allocating the necessary space.
- *
- * This appends \p str to \p *dest, similar to \c strcat, using ralloc_resize
- * to expand \p *dest to the appropriate size.  \p dest will be updated to the
- * new pointer unless allocation fails.
- *
- * The result will always be null-terminated.
- *
- * \return True unless allocation failed.
- */
-bool ralloc_strcat(char **dest, const char *str);
-
-/**
- * Concatenate two strings, allocating the necessary space.
- *
- * This appends at most \p n bytes of \p str to \p *dest, using ralloc_resize
- * to expand \p *dest to the appropriate size.  \p dest will be updated to the
- * new pointer unless allocation fails.
- *
- * The result will always be null-terminated; \p str does not need to be null
- * terminated if it is longer than \p n.
- *
- * \return True unless allocation failed.
- */
-bool ralloc_strncat(char **dest, const char *str, size_t n);
-
-/**
- * Print to a string.
- *
- * This is analogous to \c sprintf, but allocates enough space (using \p ctx
- * as the context) for the resulting string.
- *
- * \return The newly allocated string.
- */
-char *ralloc_asprintf (const void *ctx, const char *fmt, ...) PRINTFLIKE(2, 3);
-
-/**
- * Print to a string, given a va_list.
- *
- * This is analogous to \c vsprintf, but allocates enough space (using \p ctx
- * as the context) for the resulting string.
- *
- * \return The newly allocated string.
- */
-char *ralloc_vasprintf(const void *ctx, const char *fmt, va_list args);
-
-/**
- * Rewrite the tail of an existing string, starting at a given index.
- *
- * Overwrites the contents of *str starting at \p start with newly formatted
- * text, including a new null-terminator.  Allocates more memory as necessary.
- *
- * This can be used to append formatted text when the length of the existing
- * string is already known, saving a strlen() call.
- *
- * \sa ralloc_asprintf_append
- *
- * \param str   The string to be updated.
- * \param start The index to start appending new data at.
- * \param fmt   A printf-style formatting string
- *
- * \p str will be updated to the new pointer unless allocation fails.
- * \p start will be increased by the length of the newly formatted text.
- *
- * \return True unless allocation failed.
- */
-bool ralloc_asprintf_rewrite_tail(char **str, size_t *start,
-				  const char *fmt, ...)
-				  PRINTFLIKE(3, 4);
-
-/**
- * Rewrite the tail of an existing string, starting at a given index.
- *
- * Overwrites the contents of *str starting at \p start with newly formatted
- * text, including a new null-terminator.  Allocates more memory as necessary.
- *
- * This can be used to append formatted text when the length of the existing
- * string is already known, saving a strlen() call.
- *
- * \sa ralloc_vasprintf_append
- *
- * \param str   The string to be updated.
- * \param start The index to start appending new data at.
- * \param fmt   A printf-style formatting string
- * \param args  A va_list containing the data to be formatted
- *
- * \p str will be updated to the new pointer unless allocation fails.
- * \p start will be increased by the length of the newly formatted text.
- *
- * \return True unless allocation failed.
- */
-bool ralloc_vasprintf_rewrite_tail(char **str, size_t *start, const char *fmt,
-				   va_list args);
-
-/**
- * Append formatted text to the supplied string.
- *
- * This is equivalent to
- * \code
- * ralloc_asprintf_rewrite_tail(str, strlen(*str), fmt, ...)
- * \endcode
- *
- * \sa ralloc_asprintf
- * \sa ralloc_asprintf_rewrite_tail
- * \sa ralloc_strcat
- *
- * \p str will be updated to the new pointer unless allocation fails.
- *
- * \return True unless allocation failed.
- */
-bool ralloc_asprintf_append (char **str, const char *fmt, ...)
-			     PRINTFLIKE(2, 3);
-
-/**
- * Append formatted text to the supplied string, given a va_list.
- *
- * This is equivalent to
- * \code
- * ralloc_vasprintf_rewrite_tail(str, strlen(*str), fmt, args)
- * \endcode
- *
- * \sa ralloc_vasprintf
- * \sa ralloc_vasprintf_rewrite_tail
- * \sa ralloc_strcat
- *
- * \p str will be updated to the new pointer unless allocation fails.
- *
- * \return True unless allocation failed.
- */
-bool ralloc_vasprintf_append(char **str, const char *fmt, va_list args);
-/// @}
-
-#ifdef __cplusplus
-} /* end of extern "C" */
-#endif
-
-/**
- * Declare C++ new and delete operators which use ralloc.
- *
- * Placing this macro in the body of a class makes it possible to do:
- *
- * TYPE *var = new(mem_ctx) TYPE(...);
- * delete var;
- *
- * which is more idiomatic in C++ than calling ralloc.
- */
-#define DECLARE_RALLOC_CXX_OPERATORS(TYPE)                               \
-private:                                                                 \
-   static void _ralloc_destructor(void *p)                               \
-   {                                                                     \
-      reinterpret_cast<TYPE *>(p)->~TYPE();                              \
-   }                                                                     \
-public:                                                                  \
-   static void* operator new(size_t size, void *mem_ctx)                 \
-   {                                                                     \
-      void *p = ralloc_size(mem_ctx, size);                              \
-      assert(p != NULL);                                                 \
-      if (!HAS_TRIVIAL_DESTRUCTOR(TYPE))                                 \
-         ralloc_set_destructor(p, _ralloc_destructor);                   \
-      return p;                                                          \
-   }                                                                     \
-                                                                         \
-   static void operator delete(void *p)                                  \
-   {                                                                     \
-      /* The object's destructor is guaranteed to have already been      \
-       * called by the delete operator at this point -- Make sure it's   \
-       * not called again.                                               \
-       */                                                                \
-      if (!HAS_TRIVIAL_DESTRUCTOR(TYPE))                                 \
-         ralloc_set_destructor(p, NULL);                                 \
-      ralloc_free(p);                                                    \
-   }
-
-
-#endif
diff --git a/src/glsl/standalone_scaffolding.cpp b/src/glsl/standalone_scaffolding.cpp
index 809732c..abdd83a 100644
--- a/src/glsl/standalone_scaffolding.cpp
+++ b/src/glsl/standalone_scaffolding.cpp
@@ -31,7 +31,7 @@
 
 #include <assert.h>
 #include <string.h>
-#include "ralloc.h"
+#include "util/ralloc.h"
 
 void
 _mesa_warning(struct gl_context *ctx, const char *fmt, ...)
diff --git a/src/glsl/tests/builtin_variable_test.cpp b/src/glsl/tests/builtin_variable_test.cpp
index 5076f8c..11e384a 100644
--- a/src/glsl/tests/builtin_variable_test.cpp
+++ b/src/glsl/tests/builtin_variable_test.cpp
@@ -25,7 +25,6 @@
 #include "main/compiler.h"
 #include "main/mtypes.h"
 #include "main/macros.h"
-#include "ralloc.h"
 #include "ir.h"
 #include "glsl_parser_extras.h"
 #include "glsl_symbol_table.h"
diff --git a/src/glsl/tests/copy_constant_to_storage_tests.cpp b/src/glsl/tests/copy_constant_to_storage_tests.cpp
index 6ab2084..65a9d50 100644
--- a/src/glsl/tests/copy_constant_to_storage_tests.cpp
+++ b/src/glsl/tests/copy_constant_to_storage_tests.cpp
@@ -24,7 +24,7 @@
 #include "main/compiler.h"
 #include "main/mtypes.h"
 #include "main/macros.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 #include "uniform_initializer_utils.h"
 
 namespace linker {
diff --git a/src/glsl/tests/general_ir_test.cpp b/src/glsl/tests/general_ir_test.cpp
index 862fa19..882642d 100644
--- a/src/glsl/tests/general_ir_test.cpp
+++ b/src/glsl/tests/general_ir_test.cpp
@@ -24,7 +24,6 @@
 #include "main/compiler.h"
 #include "main/mtypes.h"
 #include "main/macros.h"
-#include "ralloc.h"
 #include "ir.h"
 
 TEST(ir_variable_constructor, interface)
diff --git a/src/glsl/tests/invalidate_locations_test.cpp b/src/glsl/tests/invalidate_locations_test.cpp
index 997592f..ba94d7e 100644
--- a/src/glsl/tests/invalidate_locations_test.cpp
+++ b/src/glsl/tests/invalidate_locations_test.cpp
@@ -24,7 +24,7 @@
 #include "main/compiler.h"
 #include "main/mtypes.h"
 #include "main/macros.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 #include "ir.h"
 #include "linker.h"
 
diff --git a/src/glsl/tests/ralloc_test.cpp b/src/glsl/tests/ralloc_test.cpp
deleted file mode 100644
index c0a870a..0000000
--- a/src/glsl/tests/ralloc_test.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright © 2012 Intel Corporation
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice (including the next
- * paragraph) shall be included in all copies or substantial portions of the
- * Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-#include <gtest/gtest.h>
-#include <string.h>
-
-#include "ralloc.h"
-
-/**
- * \name Basic functionality
- */
-/*@{*/
-TEST(ralloc_test, null_parent)
-{
-   void *mem_ctx = ralloc_context(NULL);
-
-   EXPECT_EQ(NULL, ralloc_parent(mem_ctx));
-}
-/*@}*/
diff --git a/src/glsl/tests/sampler_types_test.cpp b/src/glsl/tests/sampler_types_test.cpp
index 86d329a..04dd65e 100644
--- a/src/glsl/tests/sampler_types_test.cpp
+++ b/src/glsl/tests/sampler_types_test.cpp
@@ -24,7 +24,6 @@
 #include "main/compiler.h"
 #include "main/mtypes.h"
 #include "main/macros.h"
-#include "ralloc.h"
 #include "ir.h"
 
 /**
diff --git a/src/glsl/tests/set_uniform_initializer_tests.cpp b/src/glsl/tests/set_uniform_initializer_tests.cpp
index be202b3..1d4169b 100644
--- a/src/glsl/tests/set_uniform_initializer_tests.cpp
+++ b/src/glsl/tests/set_uniform_initializer_tests.cpp
@@ -24,7 +24,7 @@
 #include "main/compiler.h"
 #include "main/mtypes.h"
 #include "main/macros.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 #include "uniform_initializer_utils.h"
 
 namespace linker {
diff --git a/src/glsl/tests/uniform_initializer_utils.cpp b/src/glsl/tests/uniform_initializer_utils.cpp
index 5e86c24..c61ef0d 100644
--- a/src/glsl/tests/uniform_initializer_utils.cpp
+++ b/src/glsl/tests/uniform_initializer_utils.cpp
@@ -23,7 +23,7 @@
 #include <gtest/gtest.h>
 #include "main/mtypes.h"
 #include "main/macros.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 #include "uniform_initializer_utils.h"
 #include <stdio.h>
 
diff --git a/src/glsl/tests/varyings_test.cpp b/src/glsl/tests/varyings_test.cpp
index 662fc0e..4573529 100644
--- a/src/glsl/tests/varyings_test.cpp
+++ b/src/glsl/tests/varyings_test.cpp
@@ -24,7 +24,7 @@
 #include "main/compiler.h"
 #include "main/mtypes.h"
 #include "main/macros.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 #include "ir.h"
 #include "program/hash_table.h"
 
diff --git a/src/mesa/Makefile.sources b/src/mesa/Makefile.sources
index fdfb2d2..8a04980 100644
--- a/src/mesa/Makefile.sources
+++ b/src/mesa/Makefile.sources
@@ -352,6 +352,7 @@ MESA_GALLIUM_FILES = \
 
 INCLUDE_DIRS = \
 	-I$(top_srcdir)/include \
+	-I$(top_srcdir)/src \
 	-I$(top_srcdir)/src/glsl \
 	-I$(top_builddir)/src/glsl \
 	-I$(top_srcdir)/src/glsl/glcpp \
diff --git a/src/mesa/SConscript b/src/mesa/SConscript
index fbfaccc..a674a1b 100644
--- a/src/mesa/SConscript
+++ b/src/mesa/SConscript
@@ -11,6 +11,7 @@ from sys import executable as python_cmd
 env = env.Clone()
 
 env.Append(CPPPATH = [
+    '#/src',
     '#/src/mapi',
     '#/src/glsl',
     '#/src/mesa',
diff --git a/src/mesa/drivers/common/meta.c b/src/mesa/drivers/common/meta.c
index b12898f..606b604 100644
--- a/src/mesa/drivers/common/meta.c
+++ b/src/mesa/drivers/common/meta.c
@@ -84,7 +84,7 @@
 #include "drivers/common/meta.h"
 #include "main/enums.h"
 #include "main/glformats.h"
-#include "../glsl/ralloc.h"
+#include "util/ralloc.h"
 
 /** Return offset in bytes of the field within a vertex struct */
 #define OFFSET(FIELD) ((void *) offsetof(struct vertex, FIELD))
diff --git a/src/mesa/drivers/common/meta_blit.c b/src/mesa/drivers/common/meta_blit.c
index bbf0c3c..31c88e1 100644
--- a/src/mesa/drivers/common/meta_blit.c
+++ b/src/mesa/drivers/common/meta_blit.c
@@ -49,7 +49,7 @@
 #include "main/viewport.h"
 #include "swrast/swrast.h"
 #include "drivers/common/meta.h"
-#include "../glsl/ralloc.h"
+#include "util/ralloc.h"
 
 /** Return offset in bytes of the field within a vertex struct */
 #define OFFSET(FIELD) ((void *) offsetof(struct vertex, FIELD))
diff --git a/src/mesa/drivers/dri/i915/i830_context.c b/src/mesa/drivers/dri/i915/i830_context.c
index 0d46dba..299e54d 100644
--- a/src/mesa/drivers/dri/i915/i830_context.c
+++ b/src/mesa/drivers/dri/i915/i830_context.c
@@ -35,7 +35,7 @@
 #include "tnl/t_context.h"
 #include "tnl/t_pipeline.h"
 #include "intel_tris.h"
-#include "../glsl/ralloc.h"
+#include "util/ralloc.h"
 
 /***************************************
  * Mesa's Driver Functions
diff --git a/src/mesa/drivers/dri/i915/i915_context.c b/src/mesa/drivers/dri/i915/i915_context.c
index 44b0d8b..7f43896 100644
--- a/src/mesa/drivers/dri/i915/i915_context.c
+++ b/src/mesa/drivers/dri/i915/i915_context.c
@@ -40,7 +40,7 @@
 #include "swrast/swrast.h"
 #include "swrast_setup/swrast_setup.h"
 #include "tnl/tnl.h"
-#include "../glsl/ralloc.h"
+#include "util/ralloc.h"
 
 #include "i915_reg.h"
 #include "i915_program.h"
diff --git a/src/mesa/drivers/dri/i915/intel_context.c b/src/mesa/drivers/dri/i915/intel_context.c
index 09fe371..3104776 100644
--- a/src/mesa/drivers/dri/i915/intel_context.c
+++ b/src/mesa/drivers/dri/i915/intel_context.c
@@ -56,7 +56,7 @@
 #include "intel_mipmap_tree.h"
 
 #include "utils.h"
-#include "../glsl/ralloc.h"
+#include "util/ralloc.h"
 
 int INTEL_DEBUG = (0);
 
diff --git a/src/mesa/drivers/dri/i965/brw_blorp_blit_eu.cpp b/src/mesa/drivers/dri/i965/brw_blorp_blit_eu.cpp
index c1676a9..9459d5c 100644
--- a/src/mesa/drivers/dri/i965/brw_blorp_blit_eu.cpp
+++ b/src/mesa/drivers/dri/i965/brw_blorp_blit_eu.cpp
@@ -21,7 +21,7 @@
  * IN THE SOFTWARE.
  */
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 #include "brw_blorp_blit_eu.h"
 #include "brw_blorp.h"
 
diff --git a/src/mesa/drivers/dri/i965/brw_blorp_clear.cpp b/src/mesa/drivers/dri/i965/brw_blorp_clear.cpp
index df34c72..ffbcd1a 100644
--- a/src/mesa/drivers/dri/i965/brw_blorp_clear.cpp
+++ b/src/mesa/drivers/dri/i965/brw_blorp_clear.cpp
@@ -28,7 +28,7 @@ extern "C" {
 #include "main/renderbuffer.h"
 }
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 #include "intel_fbo.h"
 
diff --git a/src/mesa/drivers/dri/i965/brw_clip.c b/src/mesa/drivers/dri/i965/brw_clip.c
index cf51d8e..d6ccfa4 100644
--- a/src/mesa/drivers/dri/i965/brw_clip.c
+++ b/src/mesa/drivers/dri/i965/brw_clip.c
@@ -42,7 +42,7 @@
 #include "brw_state.h"
 #include "brw_clip.h"
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 #define FRONT_UNFILLED_BIT  0x1
 #define BACK_UNFILLED_BIT   0x2
diff --git a/src/mesa/drivers/dri/i965/brw_context.c b/src/mesa/drivers/dri/i965/brw_context.c
index c47ad36..40ce602 100644
--- a/src/mesa/drivers/dri/i965/brw_context.c
+++ b/src/mesa/drivers/dri/i965/brw_context.c
@@ -65,7 +65,7 @@
 #include "swrast_setup/swrast_setup.h"
 #include "tnl/tnl.h"
 #include "tnl/t_pipeline.h"
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 /***************************************
  * Mesa's Driver Functions
diff --git a/src/mesa/drivers/dri/i965/brw_eu.c b/src/mesa/drivers/dri/i965/brw_eu.c
index a400b44..b4d5d88 100644
--- a/src/mesa/drivers/dri/i965/brw_eu.c
+++ b/src/mesa/drivers/dri/i965/brw_eu.c
@@ -34,7 +34,7 @@
 #include "brw_defines.h"
 #include "brw_eu.h"
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 /**
  * Converts a BRW_REGISTER_TYPE_* enum to a short string (F, UD, and so on).
diff --git a/src/mesa/drivers/dri/i965/brw_eu_emit.c b/src/mesa/drivers/dri/i965/brw_eu_emit.c
index 12424bd..446d149 100644
--- a/src/mesa/drivers/dri/i965/brw_eu_emit.c
+++ b/src/mesa/drivers/dri/i965/brw_eu_emit.c
@@ -34,7 +34,7 @@
 #include "brw_defines.h"
 #include "brw_eu.h"
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 /***********************************************************************
  * Internal helper for constructing instructions
diff --git a/src/mesa/drivers/dri/i965/brw_gs.c b/src/mesa/drivers/dri/i965/brw_gs.c
index 8570f7a..fbd728f 100644
--- a/src/mesa/drivers/dri/i965/brw_gs.c
+++ b/src/mesa/drivers/dri/i965/brw_gs.c
@@ -43,7 +43,7 @@
 #include "brw_state.h"
 #include "brw_gs.h"
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 static void compile_ff_gs_prog(struct brw_context *brw,
                                struct brw_ff_gs_prog_key *key)
diff --git a/src/mesa/drivers/dri/i965/brw_meta_stencil_blit.c b/src/mesa/drivers/dri/i965/brw_meta_stencil_blit.c
index bdd642b..0b47426 100644
--- a/src/mesa/drivers/dri/i965/brw_meta_stencil_blit.c
+++ b/src/mesa/drivers/dri/i965/brw_meta_stencil_blit.c
@@ -57,7 +57,7 @@
 #include "main/blend.h"
 #include "main/varray.h"
 #include "main/shaderapi.h"
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 #include "drivers/common/meta.h"
 #include "brw_meta_util.h"
diff --git a/src/mesa/drivers/dri/i965/brw_performance_monitor.c b/src/mesa/drivers/dri/i965/brw_performance_monitor.c
index 3312b10..edfa3d2 100644
--- a/src/mesa/drivers/dri/i965/brw_performance_monitor.c
+++ b/src/mesa/drivers/dri/i965/brw_performance_monitor.c
@@ -50,7 +50,7 @@
 #include "main/mtypes.h"
 #include "main/performance_monitor.h"
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 #include "brw_context.h"
 #include "brw_defines.h"
diff --git a/src/mesa/drivers/dri/i965/brw_program.c b/src/mesa/drivers/dri/i965/brw_program.c
index cff1188..d782b4f 100644
--- a/src/mesa/drivers/dri/i965/brw_program.c
+++ b/src/mesa/drivers/dri/i965/brw_program.c
@@ -38,7 +38,7 @@
 #include "program/program.h"
 #include "program/programopt.h"
 #include "tnl/tnl.h"
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 #include "glsl/ir.h"
 
 #include "brw_context.h"
diff --git a/src/mesa/drivers/dri/i965/brw_sf.c b/src/mesa/drivers/dri/i965/brw_sf.c
index c9f3a9f..dc6135e 100644
--- a/src/mesa/drivers/dri/i965/brw_sf.c
+++ b/src/mesa/drivers/dri/i965/brw_sf.c
@@ -45,7 +45,7 @@
 #include "brw_sf.h"
 #include "brw_state.h"
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 static void compile_sf_prog( struct brw_context *brw,
 			     struct brw_sf_prog_key *key )
diff --git a/src/mesa/drivers/dri/i965/brw_state_batch.c b/src/mesa/drivers/dri/i965/brw_state_batch.c
index d86a588..45dca69 100644
--- a/src/mesa/drivers/dri/i965/brw_state_batch.c
+++ b/src/mesa/drivers/dri/i965/brw_state_batch.c
@@ -32,7 +32,7 @@
 #include "brw_state.h"
 #include "intel_batchbuffer.h"
 #include "main/imports.h"
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 static void
 brw_track_state_batch(struct brw_context *brw,
diff --git a/src/mesa/drivers/dri/i965/brw_vs.c b/src/mesa/drivers/dri/i965/brw_vs.c
index e0f32b3..19b1d3b 100644
--- a/src/mesa/drivers/dri/i965/brw_vs.c
+++ b/src/mesa/drivers/dri/i965/brw_vs.c
@@ -38,7 +38,7 @@
 #include "program/prog_print.h"
 #include "program/prog_parameter.h"
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 static inline void assign_vue_slot(struct brw_vue_map *vue_map,
                                    int varying)
diff --git a/src/mesa/drivers/dri/i965/brw_wm.c b/src/mesa/drivers/dri/i965/brw_wm.c
index 15fcc1f..6e068d3 100644
--- a/src/mesa/drivers/dri/i965/brw_wm.c
+++ b/src/mesa/drivers/dri/i965/brw_wm.c
@@ -40,7 +40,7 @@
 #include "program/program.h"
 #include "intel_mipmap_tree.h"
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 /**
  * Return a bitfield where bit n is set if barycentric interpolation mode n
diff --git a/src/mesa/drivers/dri/i965/gen8_generator.cpp b/src/mesa/drivers/dri/i965/gen8_generator.cpp
index 1f03c81..e837dc3 100644
--- a/src/mesa/drivers/dri/i965/gen8_generator.cpp
+++ b/src/mesa/drivers/dri/i965/gen8_generator.cpp
@@ -32,7 +32,7 @@ extern "C" {
 #include "brw_context.h"
 } /* extern "C" */
 
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 #include "brw_eu.h"
 #include "brw_reg.h"
 #include "gen8_generator.h"
diff --git a/src/mesa/drivers/dri/i965/intel_screen.c b/src/mesa/drivers/dri/i965/intel_screen.c
index 5b0cbf3..5ebf1d5 100644
--- a/src/mesa/drivers/dri/i965/intel_screen.c
+++ b/src/mesa/drivers/dri/i965/intel_screen.c
@@ -37,7 +37,7 @@
 #include "main/fbobject.h"
 #include "main/version.h"
 #include "swrast/s_renderbuffer.h"
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 
 #include "utils.h"
 #include "xmlpool.h"
diff --git a/src/mesa/drivers/dri/i965/test_eu_compact.c b/src/mesa/drivers/dri/i965/test_eu_compact.c
index 92b6dd5..d95d2c0 100644
--- a/src/mesa/drivers/dri/i965/test_eu_compact.c
+++ b/src/mesa/drivers/dri/i965/test_eu_compact.c
@@ -24,7 +24,7 @@
 #include <stdlib.h>
 #include <stdio.h>
 #include <stdbool.h>
-#include "glsl/ralloc.h"
+#include "util/ralloc.h"
 #include "brw_context.h"
 #include "brw_eu.h"
 
diff --git a/src/mesa/drivers/x11/SConscript b/src/mesa/drivers/x11/SConscript
index b1b854d..320cece 100644
--- a/src/mesa/drivers/x11/SConscript
+++ b/src/mesa/drivers/x11/SConscript
@@ -16,6 +16,7 @@ env.Prepend(LIBPATH = env['X11_LIBPATH'])
 
 env.Prepend(LIBS = [
     glapi,
+    mesautil,
     glsl,
     mesa,
 ])
diff --git a/src/mesa/main/hash_table.c b/src/mesa/main/hash_table.c
index ad8f898..b51dada 100644
--- a/src/mesa/main/hash_table.c
+++ b/src/mesa/main/hash_table.c
@@ -45,7 +45,7 @@
 
 #include "main/hash_table.h"
 #include "main/macros.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 
 static const uint32_t deleted_key_value;
 
diff --git a/src/mesa/main/performance_monitor.c b/src/mesa/main/performance_monitor.c
index c26eda4..c02910e 100644
--- a/src/mesa/main/performance_monitor.c
+++ b/src/mesa/main/performance_monitor.c
@@ -43,7 +43,7 @@
 #include "mtypes.h"
 #include "performance_monitor.h"
 #include "bitset.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 
 void
 _mesa_init_performance_monitors(struct gl_context *ctx)
diff --git a/src/mesa/main/pipelineobj.c b/src/mesa/main/pipelineobj.c
index 90c1d00..017d425 100644
--- a/src/mesa/main/pipelineobj.c
+++ b/src/mesa/main/pipelineobj.c
@@ -44,7 +44,7 @@
 #include "main/uniforms.h"
 #include "program/program.h"
 #include "program/prog_parameter.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 #include <stdbool.h>
 #include "../glsl/glsl_parser_extras.h"
 #include "../glsl/ir_uniform.h"
diff --git a/src/mesa/main/set.c b/src/mesa/main/set.c
index 989e5de..52c1dab 100644
--- a/src/mesa/main/set.c
+++ b/src/mesa/main/set.c
@@ -36,7 +36,7 @@
 
 #include "macros.h"
 #include "set.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 
 /*
  * From Knuth -- a good choice for hash/rehash values is p, p-2 where
diff --git a/src/mesa/main/shaderapi.c b/src/mesa/main/shaderapi.c
index 2bbef35..85b9753 100644
--- a/src/mesa/main/shaderapi.c
+++ b/src/mesa/main/shaderapi.c
@@ -52,7 +52,7 @@
 #include "program/program.h"
 #include "program/prog_print.h"
 #include "program/prog_parameter.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 #include <stdbool.h>
 #include "../glsl/glsl_parser_extras.h"
 #include "../glsl/ir.h"
diff --git a/src/mesa/main/shaderobj.c b/src/mesa/main/shaderobj.c
index b9feff4..693e9a2 100644
--- a/src/mesa/main/shaderobj.c
+++ b/src/mesa/main/shaderobj.c
@@ -40,7 +40,7 @@
 #include "program/program.h"
 #include "program/prog_parameter.h"
 #include "program/hash_table.h"
-#include "ralloc.h"
+#include "util/ralloc.h"
 
 /**********************************************************************/
 /*** Shader object functions                                        ***/
diff --git a/src/mesa/main/tests/Makefile.am b/src/mesa/main/tests/Makefile.am
index 0d3a51f..3c7c1b5 100644
--- a/src/mesa/main/tests/Makefile.am
+++ b/src/mesa/main/tests/Makefile.am
@@ -5,6 +5,7 @@ AM_CFLAGS = \
 	$(PTHREAD_CFLAGS)
 AM_CPPFLAGS = \
 	-I$(top_srcdir)/src/gtest/include \
+	-I$(top_srcdir)/src \
 	-I$(top_srcdir)/src/mapi \
 	-I$(top_srcdir)/src/mesa \
 	-I$(top_builddir)/src/mesa \
diff --git a/src/mesa/program/register_allocate.c b/src/mesa/program/register_allocate.c
index 6fac690..549154e 100644
--- a/src/mesa/program/register_allocate.c
+++ b/src/mesa/program/register_allocate.c
@@ -71,8 +71,8 @@
  */
 
 #include <stdbool.h>
-#include <ralloc.h>
 
+#include "util/ralloc.h"
 #include "main/imports.h"
 #include "main/macros.h"
 #include "main/mtypes.h"
diff --git a/src/util/Makefile.am b/src/util/Makefile.am
new file mode 100644
index 0000000..1ed70c2
--- /dev/null
+++ b/src/util/Makefile.am
@@ -0,0 +1,53 @@
+# Copyright © 2014 Intel Corporation
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the "Software"),
+# to deal in the Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute, sublicense,
+# and/or sell copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice (including the next
+# paragraph) shall be included in all copies or substantial portions of the
+# Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+# IN THE SOFTWARE.
+
+SUBDIRS = . tests
+
+include Makefile.sources
+
+noinst_LTLIBRARIES = libmesautil.la
+
+libmesautil_la_CPPFLAGS = \
+	$(DEFINES) \
+	-I$(top_srcdir)/include \
+	-I$(top_srcdir)/src/mesa \
+	$(VISIBILITY_CFLAGS)
+
+libmesautil_la_SOURCES = $(MESA_UTIL_FILES)
+
+### Tests:
+
+CFLAGS_FOR_TESTS = $(PTHREAD_CFLAGS)
+CPPFLAGS_FOR_TESTS = \
+	$(libmesautil_la_CPPFLAGS) \
+	-I$(top_srcdir)/src/gtest/include
+LDADD_FOR_TESTS =                               \
+	$(top_builddir)/src/gtest/libgtest.la   \
+	$(top_builddir)/src/util/libmesautil.la \
+	$(PTHREAD_LIBS)
+
+TESTS = tests/ralloc_test
+check_PROGRAMS = $(TESTS)
+
+tests_ralloc_test_SOURCES = tests/ralloc_test.cpp
+tests_ralloc_test_CFLAGS = $(CFLAGS_FOR_TESTS)
+tests_ralloc_test_CPPFLAGS = $(CPPFLAGS_FOR_TESTS)
+tests_ralloc_test_LDADD = $(LDADD_FOR_TESTS)
diff --git a/src/util/Makefile.sources b/src/util/Makefile.sources
new file mode 100644
index 0000000..c4c79ca
--- /dev/null
+++ b/src/util/Makefile.sources
@@ -0,0 +1,2 @@
+MESA_UTIL_FILES := \
+	ralloc.c
diff --git a/src/util/SConscript b/src/util/SConscript
new file mode 100644
index 0000000..9653ef6
--- /dev/null
+++ b/src/util/SConscript
@@ -0,0 +1,26 @@
+import common
+
+Import('*')
+
+from sys import executable as python_cmd
+
+env = env.Clone()
+
+env.Prepend(CPPPATH = [
+    '#include',
+    '#src/mesa',
+    '#src/util',
+])
+
+# parse Makefile.sources
+source_lists = env.ParseSourceList('Makefile.sources')
+
+mesautil_sources = source_lists['MESA_UTIL_FILES']
+
+mesautil = env.ConvenienceLibrary(
+    target = 'mesautil',
+    source = mesautil_sources,
+)
+
+env.Alias('mesautil', mesautil)
+Export('mesautil')
diff --git a/src/util/ralloc.c b/src/util/ralloc.c
new file mode 100644
index 0000000..36bc61f
--- /dev/null
+++ b/src/util/ralloc.c
@@ -0,0 +1,492 @@
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#include <assert.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdint.h>
+
+/* Android defines SIZE_MAX in limits.h, instead of the standard stdint.h */
+#ifdef ANDROID
+#include <limits.h>
+#endif
+
+/* Some versions of MinGW are missing _vscprintf's declaration, although they
+ * still provide the symbol in the import library. */
+#ifdef __MINGW32__
+_CRTIMP int _vscprintf(const char *format, va_list argptr);
+#endif
+
+#include "ralloc.h"
+
+#ifndef va_copy
+#ifdef __va_copy
+#define va_copy(dest, src) __va_copy((dest), (src))
+#else
+#define va_copy(dest, src) (dest) = (src)
+#endif
+#endif
+
+#define CANARY 0x5A1106
+
+struct ralloc_header
+{
+#ifdef DEBUG
+   /* A canary value used to determine whether a pointer is ralloc'd. */
+   unsigned canary;
+#endif
+
+   struct ralloc_header *parent;
+
+   /* The first child (head of a linked list) */
+   struct ralloc_header *child;
+
+   /* Linked list of siblings */
+   struct ralloc_header *prev;
+   struct ralloc_header *next;
+
+   void (*destructor)(void *);
+};
+
+typedef struct ralloc_header ralloc_header;
+
+static void unlink_block(ralloc_header *info);
+static void unsafe_free(ralloc_header *info);
+
+static ralloc_header *
+get_header(const void *ptr)
+{
+   ralloc_header *info = (ralloc_header *) (((char *) ptr) -
+					    sizeof(ralloc_header));
+#ifdef DEBUG
+   assert(info->canary == CANARY);
+#endif
+   return info;
+}
+
+#define PTR_FROM_HEADER(info) (((char *) info) + sizeof(ralloc_header))
+
+static void
+add_child(ralloc_header *parent, ralloc_header *info)
+{
+   if (parent != NULL) {
+      info->parent = parent;
+      info->next = parent->child;
+      parent->child = info;
+
+      if (info->next != NULL)
+	 info->next->prev = info;
+   }
+}
+
+void *
+ralloc_context(const void *ctx)
+{
+   return ralloc_size(ctx, 0);
+}
+
+void *
+ralloc_size(const void *ctx, size_t size)
+{
+   void *block = calloc(1, size + sizeof(ralloc_header));
+   ralloc_header *info;
+   ralloc_header *parent;
+
+   if (unlikely(block == NULL))
+      return NULL;
+   info = (ralloc_header *) block;
+   parent = ctx != NULL ? get_header(ctx) : NULL;
+
+   add_child(parent, info);
+
+#ifdef DEBUG
+   info->canary = CANARY;
+#endif
+
+   return PTR_FROM_HEADER(info);
+}
+
+void *
+rzalloc_size(const void *ctx, size_t size)
+{
+   void *ptr = ralloc_size(ctx, size);
+   if (likely(ptr != NULL))
+      memset(ptr, 0, size);
+   return ptr;
+}
+
+/* helper function - assumes ptr != NULL */
+static void *
+resize(void *ptr, size_t size)
+{
+   ralloc_header *child, *old, *info;
+
+   old = get_header(ptr);
+   info = realloc(old, size + sizeof(ralloc_header));
+
+   if (info == NULL)
+      return NULL;
+
+   /* Update parent and sibling's links to the reallocated node. */
+   if (info != old && info->parent != NULL) {
+      if (info->parent->child == old)
+	 info->parent->child = info;
+
+      if (info->prev != NULL)
+	 info->prev->next = info;
+
+      if (info->next != NULL)
+	 info->next->prev = info;
+   }
+
+   /* Update child->parent links for all children */
+   for (child = info->child; child != NULL; child = child->next)
+      child->parent = info;
+
+   return PTR_FROM_HEADER(info);
+}
+
+void *
+reralloc_size(const void *ctx, void *ptr, size_t size)
+{
+   if (unlikely(ptr == NULL))
+      return ralloc_size(ctx, size);
+
+   assert(ralloc_parent(ptr) == ctx);
+   return resize(ptr, size);
+}
+
+void *
+ralloc_array_size(const void *ctx, size_t size, unsigned count)
+{
+   if (count > SIZE_MAX/size)
+      return NULL;
+
+   return ralloc_size(ctx, size * count);
+}
+
+void *
+rzalloc_array_size(const void *ctx, size_t size, unsigned count)
+{
+   if (count > SIZE_MAX/size)
+      return NULL;
+
+   return rzalloc_size(ctx, size * count);
+}
+
+void *
+reralloc_array_size(const void *ctx, void *ptr, size_t size, unsigned count)
+{
+   if (count > SIZE_MAX/size)
+      return NULL;
+
+   return reralloc_size(ctx, ptr, size * count);
+}
+
+void
+ralloc_free(void *ptr)
+{
+   ralloc_header *info;
+
+   if (ptr == NULL)
+      return;
+
+   info = get_header(ptr);
+   unlink_block(info);
+   unsafe_free(info);
+}
+
+static void
+unlink_block(ralloc_header *info)
+{
+   /* Unlink from parent & siblings */
+   if (info->parent != NULL) {
+      if (info->parent->child == info)
+	 info->parent->child = info->next;
+
+      if (info->prev != NULL)
+	 info->prev->next = info->next;
+
+      if (info->next != NULL)
+	 info->next->prev = info->prev;
+   }
+   info->parent = NULL;
+   info->prev = NULL;
+   info->next = NULL;
+}
+
+static void
+unsafe_free(ralloc_header *info)
+{
+   /* Recursively free any children...don't waste time unlinking them. */
+   ralloc_header *temp;
+   while (info->child != NULL) {
+      temp = info->child;
+      info->child = temp->next;
+      unsafe_free(temp);
+   }
+
+   /* Free the block itself.  Call the destructor first, if any. */
+   if (info->destructor != NULL)
+      info->destructor(PTR_FROM_HEADER(info));
+
+   free(info);
+}
+
+void
+ralloc_steal(const void *new_ctx, void *ptr)
+{
+   ralloc_header *info, *parent;
+
+   if (unlikely(ptr == NULL))
+      return;
+
+   info = get_header(ptr);
+   parent = get_header(new_ctx);
+
+   unlink_block(info);
+
+   add_child(parent, info);
+}
+
+void *
+ralloc_parent(const void *ptr)
+{
+   ralloc_header *info;
+
+   if (unlikely(ptr == NULL))
+      return NULL;
+
+   info = get_header(ptr);
+   return info->parent ? PTR_FROM_HEADER(info->parent) : NULL;
+}
+
+static void *autofree_context = NULL;
+
+static void
+autofree(void)
+{
+   ralloc_free(autofree_context);
+}
+
+void *
+ralloc_autofree_context(void)
+{
+   if (unlikely(autofree_context == NULL)) {
+      autofree_context = ralloc_context(NULL);
+      atexit(autofree);
+   }
+   return autofree_context;
+}
+
+void
+ralloc_set_destructor(const void *ptr, void(*destructor)(void *))
+{
+   ralloc_header *info = get_header(ptr);
+   info->destructor = destructor;
+}
+
+char *
+ralloc_strdup(const void *ctx, const char *str)
+{
+   size_t n;
+   char *ptr;
+
+   if (unlikely(str == NULL))
+      return NULL;
+
+   n = strlen(str);
+   ptr = ralloc_array(ctx, char, n + 1);
+   memcpy(ptr, str, n);
+   ptr[n] = '\0';
+   return ptr;
+}
+
+char *
+ralloc_strndup(const void *ctx, const char *str, size_t max)
+{
+   size_t n;
+   char *ptr;
+
+   if (unlikely(str == NULL))
+      return NULL;
+
+   n = strlen(str);
+   if (n > max)
+      n = max;
+
+   ptr = ralloc_array(ctx, char, n + 1);
+   memcpy(ptr, str, n);
+   ptr[n] = '\0';
+   return ptr;
+}
+
+/* helper routine for strcat/strncat - n is the exact amount to copy */
+static bool
+cat(char **dest, const char *str, size_t n)
+{
+   char *both;
+   size_t existing_length;
+   assert(dest != NULL && *dest != NULL);
+
+   existing_length = strlen(*dest);
+   both = resize(*dest, existing_length + n + 1);
+   if (unlikely(both == NULL))
+      return false;
+
+   memcpy(both + existing_length, str, n);
+   both[existing_length + n] = '\0';
+
+   *dest = both;
+   return true;
+}
+
+
+bool
+ralloc_strcat(char **dest, const char *str)
+{
+   return cat(dest, str, strlen(str));
+}
+
+bool
+ralloc_strncat(char **dest, const char *str, size_t n)
+{
+   /* Clamp n to the string length */
+   size_t str_length = strlen(str);
+   if (str_length < n)
+      n = str_length;
+
+   return cat(dest, str, n);
+}
+
+char *
+ralloc_asprintf(const void *ctx, const char *fmt, ...)
+{
+   char *ptr;
+   va_list args;
+   va_start(args, fmt);
+   ptr = ralloc_vasprintf(ctx, fmt, args);
+   va_end(args);
+   return ptr;
+}
+
+/* Return the length of the string that would be generated by a printf-style
+ * format and argument list, not including the \0 byte.
+ */
+static size_t
+printf_length(const char *fmt, va_list untouched_args)
+{
+   int size;
+   char junk;
+
+   /* Make a copy of the va_list so the original caller can still use it */
+   va_list args;
+   va_copy(args, untouched_args);
+
+#ifdef _WIN32
+   /* We need to use _vcsprintf to calculate the size as vsnprintf returns -1
+    * if the number of characters to write is greater than count.
+    */
+   size = _vscprintf(fmt, args);
+   (void)junk;
+#else
+   size = vsnprintf(&junk, 1, fmt, args);
+#endif
+   assert(size >= 0);
+
+   va_end(args);
+
+   return size;
+}
+
+char *
+ralloc_vasprintf(const void *ctx, const char *fmt, va_list args)
+{
+   size_t size = printf_length(fmt, args) + 1;
+
+   char *ptr = ralloc_size(ctx, size);
+   if (ptr != NULL)
+      vsnprintf(ptr, size, fmt, args);
+
+   return ptr;
+}
+
+bool
+ralloc_asprintf_append(char **str, const char *fmt, ...)
+{
+   bool success;
+   va_list args;
+   va_start(args, fmt);
+   success = ralloc_vasprintf_append(str, fmt, args);
+   va_end(args);
+   return success;
+}
+
+bool
+ralloc_vasprintf_append(char **str, const char *fmt, va_list args)
+{
+   size_t existing_length;
+   assert(str != NULL);
+   existing_length = *str ? strlen(*str) : 0;
+   return ralloc_vasprintf_rewrite_tail(str, &existing_length, fmt, args);
+}
+
+bool
+ralloc_asprintf_rewrite_tail(char **str, size_t *start, const char *fmt, ...)
+{
+   bool success;
+   va_list args;
+   va_start(args, fmt);
+   success = ralloc_vasprintf_rewrite_tail(str, start, fmt, args);
+   va_end(args);
+   return success;
+}
+
+bool
+ralloc_vasprintf_rewrite_tail(char **str, size_t *start, const char *fmt,
+			      va_list args)
+{
+   size_t new_length;
+   char *ptr;
+
+   assert(str != NULL);
+
+   if (unlikely(*str == NULL)) {
+      // Assuming a NULL context is probably bad, but it's expected behavior.
+      *str = ralloc_vasprintf(NULL, fmt, args);
+      return true;
+   }
+
+   new_length = printf_length(fmt, args);
+
+   ptr = resize(*str, *start + new_length + 1);
+   if (unlikely(ptr == NULL))
+      return false;
+
+   vsnprintf(ptr + *start, new_length + 1, fmt, args);
+   *str = ptr;
+   *start += new_length;
+   return true;
+}
diff --git a/src/util/ralloc.h b/src/util/ralloc.h
new file mode 100644
index 0000000..1fe5357
--- /dev/null
+++ b/src/util/ralloc.h
@@ -0,0 +1,444 @@
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+/**
+ * \file ralloc.h
+ *
+ * ralloc: a recursive memory allocator
+ *
+ * The ralloc memory allocator creates a hierarchy of allocated
+ * objects. Every allocation is in reference to some parent, and
+ * every allocated object can in turn be used as the parent of a
+ * subsequent allocation. This allows for extremely convenient
+ * discarding of an entire tree/sub-tree of allocations by calling
+ * ralloc_free on any particular object to free it and all of its
+ * children.
+ *
+ * The conceptual working of ralloc was directly inspired by Andrew
+ * Tridgell's talloc, but ralloc is an independent implementation
+ * released under the MIT license and tuned for Mesa.
+ *
+ * talloc is more sophisticated than ralloc in that it includes reference
+ * counting and useful debugging features.  However, it is released under
+ * a non-permissive open source license.
+ */
+
+#ifndef RALLOC_H
+#define RALLOC_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stddef.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include "main/compiler.h"
+
+/**
+ * \def ralloc(ctx, type)
+ * Allocate a new object chained off of the given context.
+ *
+ * This is equivalent to:
+ * \code
+ * ((type *) ralloc_size(ctx, sizeof(type))
+ * \endcode
+ */
+#define ralloc(ctx, type)  ((type *) ralloc_size(ctx, sizeof(type)))
+
+/**
+ * \def rzalloc(ctx, type)
+ * Allocate a new object out of the given context and initialize it to zero.
+ *
+ * This is equivalent to:
+ * \code
+ * ((type *) rzalloc_size(ctx, sizeof(type))
+ * \endcode
+ */
+#define rzalloc(ctx, type) ((type *) rzalloc_size(ctx, sizeof(type)))
+
+/**
+ * Allocate a new ralloc context.
+ *
+ * While any ralloc'd pointer can be used as a context, sometimes it is useful
+ * to simply allocate a context with no associated memory.
+ *
+ * It is equivalent to:
+ * \code
+ * ((type *) ralloc_size(ctx, 0)
+ * \endcode
+ */
+void *ralloc_context(const void *ctx);
+
+/**
+ * Allocate memory chained off of the given context.
+ *
+ * This is the core allocation routine which is used by all others.  It
+ * simply allocates storage for \p size bytes and returns the pointer,
+ * similar to \c malloc.
+ */
+void *ralloc_size(const void *ctx, size_t size);
+
+/**
+ * Allocate zero-initialized memory chained off of the given context.
+ *
+ * This is similar to \c calloc with a size of 1.
+ */
+void *rzalloc_size(const void *ctx, size_t size);
+
+/**
+ * Resize a piece of ralloc-managed memory, preserving data.
+ *
+ * Similar to \c realloc.  Unlike C89, passing 0 for \p size does not free the
+ * memory.  Instead, it resizes it to a 0-byte ralloc context, just like
+ * calling ralloc_size(ctx, 0).  This is different from talloc.
+ *
+ * \param ctx  The context to use for new allocation.  If \p ptr != NULL,
+ *             it must be the same as ralloc_parent(\p ptr).
+ * \param ptr  Pointer to the memory to be resized.  May be NULL.
+ * \param size The amount of memory to allocate, in bytes.
+ */
+void *reralloc_size(const void *ctx, void *ptr, size_t size);
+
+/// \defgroup array Array Allocators @{
+
+/**
+ * \def ralloc_array(ctx, type, count)
+ * Allocate an array of objects chained off the given context.
+ *
+ * Similar to \c calloc, but does not initialize the memory to zero.
+ *
+ * More than a convenience function, this also checks for integer overflow when
+ * multiplying \c sizeof(type) and \p count.  This is necessary for security.
+ *
+ * This is equivalent to:
+ * \code
+ * ((type *) ralloc_array_size(ctx, sizeof(type), count)
+ * \endcode
+ */
+#define ralloc_array(ctx, type, count) \
+   ((type *) ralloc_array_size(ctx, sizeof(type), count))
+
+/**
+ * \def rzalloc_array(ctx, type, count)
+ * Allocate a zero-initialized array chained off the given context.
+ *
+ * Similar to \c calloc.
+ *
+ * More than a convenience function, this also checks for integer overflow when
+ * multiplying \c sizeof(type) and \p count.  This is necessary for security.
+ *
+ * This is equivalent to:
+ * \code
+ * ((type *) rzalloc_array_size(ctx, sizeof(type), count)
+ * \endcode
+ */
+#define rzalloc_array(ctx, type, count) \
+   ((type *) rzalloc_array_size(ctx, sizeof(type), count))
+
+/**
+ * \def reralloc(ctx, ptr, type, count)
+ * Resize a ralloc-managed array, preserving data.
+ *
+ * Similar to \c realloc.  Unlike C89, passing 0 for \p size does not free the
+ * memory.  Instead, it resizes it to a 0-byte ralloc context, just like
+ * calling ralloc_size(ctx, 0).  This is different from talloc.
+ *
+ * More than a convenience function, this also checks for integer overflow when
+ * multiplying \c sizeof(type) and \p count.  This is necessary for security.
+ *
+ * \param ctx   The context to use for new allocation.  If \p ptr != NULL,
+ *              it must be the same as ralloc_parent(\p ptr).
+ * \param ptr   Pointer to the array to be resized.  May be NULL.
+ * \param type  The element type.
+ * \param count The number of elements to allocate.
+ */
+#define reralloc(ctx, ptr, type, count) \
+   ((type *) reralloc_array_size(ctx, ptr, sizeof(type), count))
+
+/**
+ * Allocate memory for an array chained off the given context.
+ *
+ * Similar to \c calloc, but does not initialize the memory to zero.
+ *
+ * More than a convenience function, this also checks for integer overflow when
+ * multiplying \p size and \p count.  This is necessary for security.
+ */
+void *ralloc_array_size(const void *ctx, size_t size, unsigned count);
+
+/**
+ * Allocate a zero-initialized array chained off the given context.
+ *
+ * Similar to \c calloc.
+ *
+ * More than a convenience function, this also checks for integer overflow when
+ * multiplying \p size and \p count.  This is necessary for security.
+ */
+void *rzalloc_array_size(const void *ctx, size_t size, unsigned count);
+
+/**
+ * Resize a ralloc-managed array, preserving data.
+ *
+ * Similar to \c realloc.  Unlike C89, passing 0 for \p size does not free the
+ * memory.  Instead, it resizes it to a 0-byte ralloc context, just like
+ * calling ralloc_size(ctx, 0).  This is different from talloc.
+ *
+ * More than a convenience function, this also checks for integer overflow when
+ * multiplying \c sizeof(type) and \p count.  This is necessary for security.
+ *
+ * \param ctx   The context to use for new allocation.  If \p ptr != NULL,
+ *              it must be the same as ralloc_parent(\p ptr).
+ * \param ptr   Pointer to the array to be resized.  May be NULL.
+ * \param size  The size of an individual element.
+ * \param count The number of elements to allocate.
+ *
+ * \return True unless allocation failed.
+ */
+void *reralloc_array_size(const void *ctx, void *ptr, size_t size,
+			  unsigned count);
+/// @}
+
+/**
+ * Free a piece of ralloc-managed memory.
+ *
+ * This will also free the memory of any children allocated this context.
+ */
+void ralloc_free(void *ptr);
+
+/**
+ * "Steal" memory from one context, changing it to another.
+ *
+ * This changes \p ptr's context to \p new_ctx.  This is quite useful if
+ * memory is allocated out of a temporary context.
+ */
+void ralloc_steal(const void *new_ctx, void *ptr);
+
+/**
+ * Return the given pointer's ralloc context.
+ */
+void *ralloc_parent(const void *ptr);
+
+/**
+ * Return a context whose memory will be automatically freed at program exit.
+ *
+ * The first call to this function creates a context and registers a handler
+ * to free it using \c atexit.  This may cause trouble if used in a library
+ * loaded with \c dlopen.
+ */
+void *ralloc_autofree_context(void);
+
+/**
+ * Set a callback to occur just before an object is freed.
+ */
+void ralloc_set_destructor(const void *ptr, void(*destructor)(void *));
+
+/// \defgroup array String Functions @{
+/**
+ * Duplicate a string, allocating the memory from the given context.
+ */
+char *ralloc_strdup(const void *ctx, const char *str);
+
+/**
+ * Duplicate a string, allocating the memory from the given context.
+ *
+ * Like \c strndup, at most \p n characters are copied.  If \p str is longer
+ * than \p n characters, \p n are copied, and a termining \c '\0' byte is added.
+ */
+char *ralloc_strndup(const void *ctx, const char *str, size_t n);
+
+/**
+ * Concatenate two strings, allocating the necessary space.
+ *
+ * This appends \p str to \p *dest, similar to \c strcat, using ralloc_resize
+ * to expand \p *dest to the appropriate size.  \p dest will be updated to the
+ * new pointer unless allocation fails.
+ *
+ * The result will always be null-terminated.
+ *
+ * \return True unless allocation failed.
+ */
+bool ralloc_strcat(char **dest, const char *str);
+
+/**
+ * Concatenate two strings, allocating the necessary space.
+ *
+ * This appends at most \p n bytes of \p str to \p *dest, using ralloc_resize
+ * to expand \p *dest to the appropriate size.  \p dest will be updated to the
+ * new pointer unless allocation fails.
+ *
+ * The result will always be null-terminated; \p str does not need to be null
+ * terminated if it is longer than \p n.
+ *
+ * \return True unless allocation failed.
+ */
+bool ralloc_strncat(char **dest, const char *str, size_t n);
+
+/**
+ * Print to a string.
+ *
+ * This is analogous to \c sprintf, but allocates enough space (using \p ctx
+ * as the context) for the resulting string.
+ *
+ * \return The newly allocated string.
+ */
+char *ralloc_asprintf (const void *ctx, const char *fmt, ...) PRINTFLIKE(2, 3);
+
+/**
+ * Print to a string, given a va_list.
+ *
+ * This is analogous to \c vsprintf, but allocates enough space (using \p ctx
+ * as the context) for the resulting string.
+ *
+ * \return The newly allocated string.
+ */
+char *ralloc_vasprintf(const void *ctx, const char *fmt, va_list args);
+
+/**
+ * Rewrite the tail of an existing string, starting at a given index.
+ *
+ * Overwrites the contents of *str starting at \p start with newly formatted
+ * text, including a new null-terminator.  Allocates more memory as necessary.
+ *
+ * This can be used to append formatted text when the length of the existing
+ * string is already known, saving a strlen() call.
+ *
+ * \sa ralloc_asprintf_append
+ *
+ * \param str   The string to be updated.
+ * \param start The index to start appending new data at.
+ * \param fmt   A printf-style formatting string
+ *
+ * \p str will be updated to the new pointer unless allocation fails.
+ * \p start will be increased by the length of the newly formatted text.
+ *
+ * \return True unless allocation failed.
+ */
+bool ralloc_asprintf_rewrite_tail(char **str, size_t *start,
+				  const char *fmt, ...)
+				  PRINTFLIKE(3, 4);
+
+/**
+ * Rewrite the tail of an existing string, starting at a given index.
+ *
+ * Overwrites the contents of *str starting at \p start with newly formatted
+ * text, including a new null-terminator.  Allocates more memory as necessary.
+ *
+ * This can be used to append formatted text when the length of the existing
+ * string is already known, saving a strlen() call.
+ *
+ * \sa ralloc_vasprintf_append
+ *
+ * \param str   The string to be updated.
+ * \param start The index to start appending new data at.
+ * \param fmt   A printf-style formatting string
+ * \param args  A va_list containing the data to be formatted
+ *
+ * \p str will be updated to the new pointer unless allocation fails.
+ * \p start will be increased by the length of the newly formatted text.
+ *
+ * \return True unless allocation failed.
+ */
+bool ralloc_vasprintf_rewrite_tail(char **str, size_t *start, const char *fmt,
+				   va_list args);
+
+/**
+ * Append formatted text to the supplied string.
+ *
+ * This is equivalent to
+ * \code
+ * ralloc_asprintf_rewrite_tail(str, strlen(*str), fmt, ...)
+ * \endcode
+ *
+ * \sa ralloc_asprintf
+ * \sa ralloc_asprintf_rewrite_tail
+ * \sa ralloc_strcat
+ *
+ * \p str will be updated to the new pointer unless allocation fails.
+ *
+ * \return True unless allocation failed.
+ */
+bool ralloc_asprintf_append (char **str, const char *fmt, ...)
+			     PRINTFLIKE(2, 3);
+
+/**
+ * Append formatted text to the supplied string, given a va_list.
+ *
+ * This is equivalent to
+ * \code
+ * ralloc_vasprintf_rewrite_tail(str, strlen(*str), fmt, args)
+ * \endcode
+ *
+ * \sa ralloc_vasprintf
+ * \sa ralloc_vasprintf_rewrite_tail
+ * \sa ralloc_strcat
+ *
+ * \p str will be updated to the new pointer unless allocation fails.
+ *
+ * \return True unless allocation failed.
+ */
+bool ralloc_vasprintf_append(char **str, const char *fmt, va_list args);
+/// @}
+
+#ifdef __cplusplus
+} /* end of extern "C" */
+#endif
+
+/**
+ * Declare C++ new and delete operators which use ralloc.
+ *
+ * Placing this macro in the body of a class makes it possible to do:
+ *
+ * TYPE *var = new(mem_ctx) TYPE(...);
+ * delete var;
+ *
+ * which is more idiomatic in C++ than calling ralloc.
+ */
+#define DECLARE_RALLOC_CXX_OPERATORS(TYPE)                               \
+private:                                                                 \
+   static void _ralloc_destructor(void *p)                               \
+   {                                                                     \
+      reinterpret_cast<TYPE *>(p)->~TYPE();                              \
+   }                                                                     \
+public:                                                                  \
+   static void* operator new(size_t size, void *mem_ctx)                 \
+   {                                                                     \
+      void *p = ralloc_size(mem_ctx, size);                              \
+      assert(p != NULL);                                                 \
+      if (!HAS_TRIVIAL_DESTRUCTOR(TYPE))                                 \
+         ralloc_set_destructor(p, _ralloc_destructor);                   \
+      return p;                                                          \
+   }                                                                     \
+                                                                         \
+   static void operator delete(void *p)                                  \
+   {                                                                     \
+      /* The object's destructor is guaranteed to have already been      \
+       * called by the delete operator at this point -- Make sure it's   \
+       * not called again.                                               \
+       */                                                                \
+      if (!HAS_TRIVIAL_DESTRUCTOR(TYPE))                                 \
+         ralloc_set_destructor(p, NULL);                                 \
+      ralloc_free(p);                                                    \
+   }
+
+
+#endif
diff --git a/src/util/tests/Makefile.am b/src/util/tests/Makefile.am
new file mode 100644
index 0000000..a2b5498
--- /dev/null
+++ b/src/util/tests/Makefile.am
@@ -0,0 +1,40 @@
+# Copyright © 2014 Intel Corporation
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the "Software"),
+# to deal in the Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute, sublicense,
+# and/or sell copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice (including the next
+# paragraph) shall be included in all copies or substantial portions of the
+# Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+# IN THE SOFTWARE.
+
+AM_CFLAGS = \
+	$(PTHREAD_CFLAGS)
+AM_CPPFLAGS = \
+	-I$(top_srcdir)/include \
+	-I$(top_srcdir)/src \
+	-I$(top_srcdir)/src/util \
+	-I$(top_srcdir)/src/mesa \
+	-I$(top_srcdir)/src/gtest/include \
+	$(DEFINES) $(INCLUDE_DIRS)
+
+LDADD = \
+	$(top_builddir)/src/gtest/libgtest.la \
+	$(top_builddir)/src/util/libmesautil.la \
+	$(PTHREAD_LIBS)
+
+TESTS = ralloc_test
+check_PROGRAMS = $(TESTS)
+
+ralloc_test_SOURCES = ralloc_test.cpp
diff --git a/src/util/tests/ralloc_test.cpp b/src/util/tests/ralloc_test.cpp
new file mode 100644
index 0000000..c0a870a
--- /dev/null
+++ b/src/util/tests/ralloc_test.cpp
@@ -0,0 +1,38 @@
+/*
+ * Copyright © 2012 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+#include <gtest/gtest.h>
+#include <string.h>
+
+#include "ralloc.h"
+
+/**
+ * \name Basic functionality
+ */
+/*@{*/
+TEST(ralloc_test, null_parent)
+{
+   void *mem_ctx = ralloc_context(NULL);
+
+   EXPECT_EQ(NULL, ralloc_parent(mem_ctx));
+}
+/*@}*/
-- 
2.0.1



More information about the mesa-dev mailing list