# search

module: build_assert
author: dinesh
title: build_assert - routines for build-time assertions
desc:
  This code provides routines which will cause compilation to fail should some
  assertion be untrue: such failures are preferable to run-time assertions,
  but much more limited since they can only depends on compile-time constants.

  These assertions are most useful when two parts of the code must be kept in
  sync: it is better to avoid such cases if possible, but seconds best is to
  detect invalid changes at build time.

  For example, a tricky piece of code might rely on a certain element being at
  the start of the structure.  To ensure that future changes don t break it,
  you would catch such changes in your code like so:

  Example:
  	char *foo_string(struct foo *foo)
  	{
  		// This trick requires that the string be first in the structure
  		BUILD_ASSERT(offsetof(struct foo, string) == 0);
  		return (char *)foo;
  	}


module: alloc
author: dinesh
title: alloc - memory allocator routines
depends: ccan/build_assert
desc:
  The alloc module implements a simple allocator which you can use to
  dynamically allocate space within a region of memory.  This can be useful
  for suballocations within a given region, or a memory-mapped file.

  All metadata is kept within the memory handed to the allocator: you only
  need hand the pointer and the size of the memory to each call.

  The region contents is always in offsets, so it can be mapped in different
  places, but is not endian-safe.

  Example:
  	#include <sys/mman.h>
  	#include <unistd.h>
  	#include <sys/types.h>
  	#include <err.h>
  	#include "alloc/alloc.h"

  	static void usage(const char *name)
  	{
  		errx(1, "Usage: %s --create <mapfile>\n"
  		     " %s --check <mapfile>\n"
  		     " %s --alloc <mapfile>\n"
  		     " %s --free=<offset> <mapfile>\n", name, name, name);
  	}

  	// Create a memory mapped file, and allocate from within it
  	int main(int argc, char *argv[])
  	{
  		void *a, *p;
  		int fd;
  		enum { CREATE, CHECK, ALLOC, FREE } cmd;

  		if (argc != 3)
  			usage(argv[0]);

  		if (strcmp(argv[1], "--create") == 0)
  			cmd = CREATE;
  		else if (strcmp(argv[1], "--check") == 0)
  			cmd = CHECK;
  		else if (strcmp(argv[1], "--alloc") == 0)
  			cmd = ALLOC;
  		else if (strncmp(argv[1], "--free=", strlen("--free=")) == 0)
  			cmd = FREE;
  		else
  			usage(argv[0]);

  		if (cmd == CREATE) {
  			fd = open(argv[2], O_RDWR|O_CREAT|O_EXCL, 0600);
  			if (fd < 0)
  				err(1, "Could not create %s", argv[2]);
  			if (ftruncate(fd, 1048576) != 0)
  				err(1, "Could not set length on %s", argv[2]);
  		} else {
  			fd = open(argv[2], O_RDWR);
  			if (fd < 0)
  				err(1, "Could not open %s", argv[2]);
  		}

  		a = mmap(NULL, 1048576, PROT_READ|PROT_WRITE, MAP_SHARED, fd,0);
  		if (a == MAP_FAILED)
  			err(1, "Could not map %s", argv[2]);

  		switch (cmd) {
  		case CREATE:
  			alloc_init(a, 1048576);
  			break;
  		case CHECK:
  			if (!alloc_check(a, 1048576))
  				err(1, "Region is corrupt");
  			break;
  		case ALLOC:
  			p = alloc_get(a, 1048576, 1024, 16);
  			if (!p)
  				errx(1, "Could not allocate");
  			printf("%zu\n", (char *)p - (char *)a);
  			break;
  		case FREE:
  			p = (char *)a + atol(argv[1] + strlen("--free="));
  			alloc_free(a, 1048576, p);
  			break;
  		}
  		return 0;
  	}


module: alignof
author: dinesh
title: alignof - ALIGNOF() macro to determine alignment of a type.
depends: ccan/build_assert
desc:
  Many platforms have requirements that certain types must be aligned
  to certain address boundaries, such as ints needing to be on 4-byte
  boundaries.  Attempting to access variables with incorrect
  alignment may cause performance loss or even program failure (eg. a
  bus signal).

  There are times which it s useful to be able to programatically
  access these requirements, such as for dynamic allocators.

  Example:
  	#include <stdio.h>
  	#include "alignof/alignoff.h"

  	int main(int argc, char *argv[])
  	{
  		char arr[sizeof(int)];

  		if ((unsigned long)arr % ALIGNOF(int)) {
  			printf("arr %p CANNOT hold an int\n", arr);
  			exit(1);
  		} else {
  			printf("arr %p CAN hold an int\n", arr);
  			exit(0);
  		}
  	}


module: hash
author: dinesh
title: hash - routines for hashing bytes
desc:
  When creating a hash table it s important to have a hash function
  which mixes well and is fast.  This package supplies such functions.

  The hash functions come in two flavors: the normal ones and the
  stable ones.  The normal ones can vary from machine-to-machine and
  may change if we find better or faster hash algorithms in future.
  The stable ones will always give the same results on any computer,
  and on any version of this package.


module: check_type
author: dinesh
title: check_type - routines for compile time type checking
desc:
  C has fairly weak typing: ints get automatically converted to longs, signed
  to unsigned, etc.  There are some cases where this is best avoided, and
  these macros provide methods for evoking warnings (or build errors) when
  a precise type isn t used.

  On compilers which don t support typeof() these routines are less effective,
  since they have to use sizeof() which can only distiguish between types of
  different size.


module: container_of
author: dinesh
title: container_of - routine for upcasting
depends: ccan/check_type
desc:
  It is often convenient to create code where the caller registers a pointer
  to a generic structure and a callback.  The callback might know that the
  pointer points to within a larger structure, and container_of gives a
  convenient and fairly type-safe way of returning to the enclosing structure.

  This idiom is an alternative to providing a void * pointer for every
  callback.

  Example:
  	struct info
  	{
  		int my_stuff;
  		struct timer timer;
  	};

  	static void my_timer_callback(struct timer *timer)
  	{
  		struct info *info = container_of(timer, struct info, timer);
  		printf("my_stuff is %u\n", info->my_stuff);
  	}

  	int main()
  	{
  		struct info info = { .my_stuff = 1 };

  		register_timer(&info.timer);
  		...


module: list
author: dinesh
title: list - double linked list routines
depends:
  ccan/container_of
  ccan/check_type

desc:
  The list header contains routines for manipulating double linked lists.
  It defines two types: struct list_head used for anchoring lists, and
  struct list_node which is usually embedded in the structure which is placed
  in the list.

  Example:
  	#include <err.h>
  	#include "list/list.h"

  	struct parent {
  		const char *name;
  		struct list_head children;
  		unsigned int num_children;
  	};

  	struct child {
  		const char *name;
  		struct list_node list;
  	};

  	int main(int argc, char *argv[])
  	{
  		struct parent p;
  		struct child *c;
  		unsigned int i;

  		if (argc < 2)
  			errx(1, "Usage: %s parent children...", argv[0]);

  		p.name = argv[1];
  		for (i = 2; i < argc, i++) {
  			c = malloc(sizeof(*c));
  			c->name = argv[i];
  			list_add(&p.children, &c->list);
  			p.num_children++;
  		}

  		printf("%s has %u children:", p.name, p.num_children);
  		list_for_each(&p.children, c, list)
  			printf("%s ", c->name);
  		printf("\n");
  		return 0;
  	}


module: noerr
author: dinesh
title: noerr - routines for cleaning up without blatting errno
desc:
  It is a good idea to follow the standard C convention of setting errno in
  your own helper functions.  Unfortunately, care must be taken in the error
  paths as most standard functions can (and do) overwrite errno, even if they
  succeed.

  Example:
  	#include <sys/types.h>
  	#include <sys/stat.h>
  	#include <fcntl.h>

  	bool write_string_to_file(const char *file, const char *string)
  	{
  		int ret, fd = open(file, O_WRONLY|O_CREAT|O_EXCL, 0600);
  		if (fd < 0)
  			return false;
  		ret = write(fd, string, strlen(string));
  		if (ret < 0) {
  			// Preserve errno from write above.
  			close_noerr(fd);
  			unlink_noerr(file);
  			return false;
  		}
  		if (close(fd) != 0) {
  			// Again, preserve errno.
  			unlink_noerr(file);
  			return false;
  		}
  		// A short write means out of space.
  		if (ret < strlen(string)) {
  			unlink(file);
  			errno = ENOSPC;
  			return false;
  		}
  		return true;
  	}


module: typesafe_cb
author: dinesh
title: typesafe_cb - macros for safe callbacks.
desc:
  The basis of the typesafe_cb header is cast_if_type(): a
  conditional cast macro.   If an expression exactly matches a given
  type, it is cast to the target type, otherwise it is left alone.

  This allows us to create functions which take a small number of
  specific types, rather than being forced to use a void *.  In
  particular, it is useful for creating typesafe callbacks as the
  helpers typesafe_cb(), typesafe_cb_preargs() and
  typesafe_cb_postargs() demonstrate.

  The standard way of passing arguments to callback functions in C is
  to use a void pointer, which the callback then casts back to the
  expected type.  This unfortunately subverts the type checking the
  compiler would perform if it were a direct call.  Here s an example:

  	static void my_callback(void *_obj)
  	{
  		struct obj *obj = _obj;
  		...
  	}
  	...
  		register_callback(my_callback, &my_obj);

  If we wanted to use the natural type for my_callback (ie. "void
  my_callback(struct obj *obj)"), we could make register_callback()
  take a void * as its first argument, but this would subvert all
  type checking.  We really want register_callback() to accept only
  the exactly correct function type to match the argument, or a
  function which takes a void *.

  This is where typesafe_cb() comes in: it uses cast_if_type() to
  cast the callback function if it matches the argument type:

  	void _register_callback(void (*cb)(void *arg), void *arg);
  	#define register_callback(cb, arg)				\
  		_register_callback(typesafe_cb(void, (cb), (arg)), (arg))

  On compilers which don t support the extensions required
  cast_if_type() and friend become an unconditional cast, so your
  code will compile but you won t get type checking.


module: tap
author: dinesh
title: tap - Test Anything Protocol
desc:
  The tap package produces simple-to-parse mainly-human-readable test
  output to assist in the writing of test cases.  It is based on the
  (now-defunct) libtap, which is based on Perl s CPAN TAP module.  Its
  output can be parsed by a harness such as CPAN s Prove.

  CCAN testcases are expected to output the TAP format, usually using
  this package.

  For more information about TAP, see:
  	http://en.wikipedia.org/wiki/Test_Anything_Protocol

  Based on the original libtap, Copyright (c) 2004 Nik Clayton.

  Example:
  	#include <string.h>
  	#include "tap/tap.h"

  	// Run some simple (but overly chatty) tests on strcmp().
  	int main(int argc, char *argv[])
  	{
  		const char a[] = "a", another_a[] = "a";
  		const char b[] = "b";
  		const char ab[] = "ab";

  		plan_tests(4);
  		diag("Testing different pointers (%p/%p) with same contents",
  		     a, another_a);
  		ok1(strcmp(a, another_a) == 0);

  		diag(" a  comes before  b ");
  		ok1(strcmp(a, b) < 0);
  		ok1(strcmp(b, a) > 0);

  		diag(" ab  comes after  a ");
  		ok1(strcmp(ab, a) > 0);
  		return exit_status();
  	}


module: talloc
author: dinesh
title: talloc - tree allocator routines
depends: ccan/typesafe_cb
desc:
  Talloc is a hierarchical memory pool system with destructors: you keep your
  objects in heirarchies reflecting their lifetime.  Every pointer returned
  from talloc() is itself a valid talloc context, from which other talloc()s
  can be attached.  This means you can do this:

   struct foo *X = talloc(mem_ctx, struct foo);
   X->name = talloc_strdup(X, "foo");

  and the pointer X->name would be a "child" of the talloc context "X" which
  is itself a child of mem_ctx.  So if you do talloc_free(mem_ctx) then it is
  all destroyed, whereas if you do talloc_free(X) then just X and X->name are
  destroyed, and if you do talloc_free(X->name) then just the name element of
  X is destroyed.

  If you think about this, then what this effectively gives you is an n-ary
  tree, where you can free any part of the tree with talloc_free().

  Talloc has been measured with a time overhead of around 4% over glibc
  malloc, and 48/80 bytes per allocation (32/64 bit).

  This version is based on svn://svnanon.samba.org/samba/branches/SAMBA_4_0/source/lib/talloc revision 23158.

  Example:
  	#include <stdio.h>
  	#include <stdarg.h>
  	#include <err.h>
  	#include "talloc/talloc.h"

  	// A structure containing a popened comman.
  	struct command
  	{
  		FILE *f;
  		const char *command;
  	};

  	// When struct command is freed, we also want to pclose pipe.
  	static int close_cmd(struct command *cmd)
  	{
  		pclose(cmd->f);
  		// 0 means "we succeeded, continue freeing"
  		return 0;
  	}

  	// This function opens a writable pipe to the given command.
  	struct command *open_output_cmd(const void *ctx, char *fmt, ...)
  	{
  		va_list ap;
  		struct command *cmd = talloc(ctx, struct command);

  		if (!cmd)
  			return NULL;

  		va_start(ap, fmt);
  		cmd->command = talloc_vasprintf(cmd, fmt, ap);
  		va_end(ap);
  		if (!cmd->command) {
  			talloc_free(cmd);
  			return NULL;
  		}

  		cmd->f = popen(cmd->command, "w");
  		if (!cmd->f) {
  			talloc_free(cmd);
  			return NULL;
  		}
  		talloc_set_destructor(cmd, close_cmd);
  		return cmd;
  	}

  	int main(int argc, char *argv[])
  	{
  		struct command *cmd;

  		if (argc != 2)
  			errx(1, "Usage: %s <command>\n");

  		cmd = open_output_cmd(NULL, "%s hello", argv[1]);
  		if (!cmd)
  			err(1, "Running  %s hello ", argv[1]);
  		fprintf(cmd->f, "This is a test\n");
  		talloc_free(cmd);
  		return 0;
  	}


module: string
author: dinesh
title: string - string helper routines
depends:
  ccan/talloc
  ccan/noerr
  ccan/typesafe_cb

desc:
  This is a grab bag of modules for string operations, designed to enhance
  the standard string.h.

  Example:
  	#include "string/string.h"

  	int main(int argc, char *argv[])
  	{
  		if (argv[1] && streq(argv[1], "--verbose"))
  			printf("verbose set\n");
  		if (argv[1] && strstarts(argv[1], "--"))
  			printf("Some option set\n");
  		if (argv[1] && strends(argv[1], "cow-powers"))
  			printf("Magic option set\n");
  		return 0;
  	}


