C Collections

ccollections · Overview

ccollections

ccollections - library-wide conventions of c_collections: Return codes, fatal errors, custom allocators, timeouts, thread safety and fork()

C Collections (libccollections, -lccollections)

#include <ccollections/common.h>
 
typedef enum { ... } ccol_retval;
 
typedef struct ccol_memmgmt_procs {
  ccol_malloc  malloc;
  ccol_free    free;
  ccol_calloc  calloc;
  ccol_realloc realloc;
} ccol_memmgmt_procs;

Every other public header includes common.h, which holds the types and
rules that all modules of the library share. This page states those
rules once, and the page of each function only describes where that
function differs from them.

Each container module comes in two layers. The type-inferred macros,
such as chmap_insert(3) and cvec_push(3), take values of the declared
types and call ccol__fatal_err() when an operation fails. Below them are
the raw functions, such as chashmap_insert_elem(3), which take cmap_pair
arguments and return a ccol_retval. A raw function never stops the
process on a failure that it can report, so it is the layer to use when
a failure is an expected result that you handle yourself.
 
The two layers are named apart. A typed macro carries the short name of
the handle (cvec_, cstr_, chmap_, cbmap_, ccache_), and a function, or a
macro of the raw layer such as chashmap_destroy(3), carries the name of
the module (cvector_, cstring_, chashmap_, cbstmap_, clrucache_). For
the raw calls a typed program needs as well, the typed layer has short
aliases with the same behaviour: cvec_size(3) for cvector_size(3),
chmap_reset(3) for chashmap_reset(3), ccache_destroy(3) for
clrucache_destroy(3), and so on.

ccol_retval is zero for success and negative for a failure. Every
enumerator has an explicit value that does not change within a major
version, so comparing with 0 is as correct as comparing with
ccol_success:
 
  ccol_success                             0
  ccol_not_enough_memory                  -1
  ccol_key_already_present                -2
  ccol_key_not_found                      -3
  ccol_invalid_args                       -4
  ccol_not_permitted                      -5
  ccol_timed_out                          -6
  ccol_container_full                     -7
  ccol_container_empty                    -8
  ccol_msg_too_large                      -9
  ccol_http_transfer_aborted             -10
  ccol_http_invalid_url                  -11
  ccol_http_too_many_redirects           -12
  ccol_http_tls_cert_load_failed         -13
  ccol_http_tls_cert_verification_failed -14
  ccol_http_tls_handshake_failed         -15
  ccol_http_host_resolution_failed       -16
  ccol_http_connection_failed            -17
  ccol_unexpected_failure                -18
 
The page of each function lists the codes it can return and what each
one means for that function. ccol_retval_to_str(3) gives the name of a
code as a string.

Many calls report the cause of a failure through an out-parameter named
err or err_str. The library owns every such string and the caller must
never free it. Most modules hand out a string literal, which is valid for
the whole life of the process. cjson and cyaml hand out a pointer into a
buffer of the calling thread, since their message names a position in
the input. That text is valid until the next failing call of the same
kind on the same thread, so copy it if you need it later. An
out-parameter that the caller does own is never named err, and its page
names the function that frees it.

A programming error is fatal: A NULL where the call needs a valid
handle, an index out of bounds, a stale handle, or a missing key given
to a _get macro. So is a failure inside a typed macro, such as a failed
allocation in chmap_insert(3). In all of these cases the library calls
ccol__fatal_err(), which writes two lines like these to stderr:
 
  <file>:<line>: fatal: <message>
  <file>:<line>: ccol_assert failed: false
 
and then stops the process with abort(3), which raises SIGABRT. NDEBUG
and every other compilation setting leave this alone, since the checks
are part of the contract and are never compiled out. The map macros
also write a hex dump of the key that caused the failure before the
fatal line.

Every module that allocates memory accepts a ccol_memmgmt_procs * when
it creates an object, through the *_mp or *_full form of the
constructor (for cmempool it is an argument of the constructor itself).
A NULL pointer selects the standard malloc(3), calloc(3), realloc(3) and
free(3), and so does a constructor form that takes no table.
 
A table that is not NULL must hold four non-NULL functions, and each one
must behave exactly like its standard counterpart, alignment included.
Every block that malloc, calloc and realloc return must be aligned for
any object type, which is _Alignof(max_align_t), 16 bytes on x86-64 and
aarch64. The containers put entries that need that alignment at the
start of a block, so with a less aligned block every access to such an
entry is undefined behavior. An arena or pool allocator may hand out
smaller blocks, so such an allocator must round each block up.
 
An object frees all its memory through the same table, which is why a
destroy takes no allocator argument. The functions must stay valid
until the last call to them, and for every module except cmempool that
last call happens before the destroy of the object returns. Keep the
ccol_memmgmt_procs struct itself valid until that destroy too, unless
the object keeps its own copy of the struct, which the page of its
constructor tells you. clrucache, cjson and cyaml keep a copy, so with
them you can release the struct once the creating call has returned.
 
The exception is a cmempool or crmempool that threads share.
Its allocator can run after cmempool_destroy() returns, and even
after main() returns; see cmempool_destroy(3).
 
The functions of a table are called from the thread that does the
operation, so a table for a thread-safe object must hold thread-safe
functions.

Every timeout, deadline, interval and duration of the public API is a
uint64_t count of microseconds, and the name of every such parameter or
field ends in _us. No public signature takes a struct timespec, a time_t
or a long count of time, so the width of time_t in an application
doesn't have to match the width in the library.
 
A timeout is turned into an absolute deadline on CLOCK_MONOTONIC, so a
change of the wall clock never makes a wait longer or shorter. The
arithmetic is 64 bits on every target and saturates: A value too large
for a deadline, UINT64_MAX for example, becomes the latest deadline the
clock can hold and never wraps into one in the past. Where a system call
takes a coarser unit of time, the remaining time is rounded up, so a
wait never ends before its deadline.
 
For the timed calls of cthreadcomm and cthreadpool, a timeout of 0 does
not wait. The call does exactly what its try_ variant does and returns
that variant's result, ccol_container_full or ccol_container_empty for
example, and never ccol_timed_out. The untimed call waits without a
limit. For every other field, the field's page says what 0 means: No
limit, or the default.

A name with a double underscore after its prefix, such as
cvector__destroy, ccol__fatal_err or CCOL__ERR_STR, is internal. An
installed header declares it because a public macro or inline
function expands into it, so a program compiled against the header
refers to it, but the program must not call, define or redefine it
by name. No name of the library begins with an underscore, and none
ends in _t or _MAX, so none is a name that ISO C reserves for the
compiler and the C library or POSIX for the system's headers. A type
is its plain prefixed name, such as ccol_retval or chttpsvr_req, and
a callback type ends in _fn.
 
On ELF systems every symbol that libccollections.so.2 exports carries
the version node CCOL_2, and the library binds its calls to its own
exported functions when it is linked. A function of the same name in
another object of the process, LD_PRELOAD included, never receives a
call that the library makes. A call that the program makes is bound
through the version node on glibc and FreeBSD, so it reaches this
library unless the other object has no version information at all;
musl and OpenBSD don't use symbol versions. On macOS every imported
symbol records the library that defines it.
 
Compile-time switches go to the build of the library through
EXTRA_CFLAGS, for example make EXTRA_CFLAGS="-DNAME=VALUE".
 
CCOL_FORK_SAFETY_REQUIRED (default 1)
    With 1, the build includes the pthread_atfork() handlers of
    cthreadpool, cthreadcomm, clogger, chttpserver and chttpclient,
    which keep a fork() from handing the child one of their internal
    locks in a locked state. With 0 they are left out and no fork() of
    the process pays for them; the setting changes nothing else about
    thread safety. With 0, the caller must not call fork() while
    another thread can hold one of those locks. A program that never
    calls fork() is safe with either setting, and so is one that calls
    fork() only in the two supported patterns below.
 
CMEMPOOL_COMPACT_LAYOUT (default 0)
    Selects the compact entry layout of cmempool. A translation unit
    that declares a buffer with
    CMEMPOOL_DECLARE_PREALLOCATED_BUFFER(3) must use the same
    setting as the library, or the link fails with an undefined
    reference. See that page.
 
CMEMPOOL_DYNAMIC_TLS
    With 1, the per-thread fast paths of the library use the general
    thread-local storage model, so dlopen(3) of the library always
    succeeds. With 0 they use the initial-exec model. If the build
    doesn't set it, it is 0 with glibc and on FreeBSD and 1 on every
    other system. It changes no interface.

There are only two supported ways to use fork(2) with a cthreadpool,
cthreadcomm, clogger, chttpserver or chttpclient handle:
 
  1. Call fork() before you create the handle, so that each process
     creates its own handles.
  2. Create the handle, then call fork() and immediately call exec(3)
     in the child.
 
A child that carries on without exec() while a handle from before the
fork() is live is not supported. fork() does not copy the threads that
these handles need, so a handle from the parent can do no work in the
child, and there is no way to make it work there again.
 
Every descriptor the library creates is closed on exec, so a child that
calls exec() keeps none of them. On macOS a socket, an accepted socket
and a pipe take two calls to become closed on exec, and a fork() from
another thread waits a few microseconds until both calls are done. This
wait does not depend on CCOL_FORK_SAFETY_REQUIRED. posix_spawn(3) runs
no fork handler, so it does not wait. On macOS, a program that calls
posix_spawn() while another thread can create a socket through the
library must pass the POSIX_SPAWN_CLOEXEC_DEFAULT flag to
posix_spawnattr_setflags(3), and name each descriptor that the child
must keep with posix_spawn_file_actions_addinherit_np(3).

A component that moves data between threads, or that provides a shared
service, does its own synchronisation. A component for data work inside
one thread does none.
 
No internal locks (put a lock around a shared instance yourself):
  cvector, chashmap, cbstmap, cstring, cjson, cyaml
 
Internal synchronisation (several threads can call at the same time):
  cmempool, crmempool (unless created single-threaded),
  ccircq, cdynmq, cchan,
  ceventloop, clrucache, clogger, cthreadpool, chttpclient,
  chttpserver
 
Separate objects of a module without locks share no state, so two
threads can each use their own object. The pages of the synchronised
modules list the few calls that the caller must serialise, two destroys
of one handle for example.
 
The pthread wrappers of common.h (ccol__mutex and the rest) exist for
the portability of the library itself and are not part of the API. Use
pthreads or C11 <threads.h> to protect your own data.

#include <stdio.h>
#include <string.h>
#include <ccollections/chashmap.h>
 
int main(void) {
  chmap_construct(ports, char *, int);
  chmap_insert(ports, "http", 80);
 
  const char *name = "gopher";
  cmap_pair key = { (void *)name, strlen(name) + 1 };
  int port;
  ccol_retval rv = chashmap_get_elem_copy(ports, &key, &port,
                                            sizeof(port));
  if (rv != ccol_success)
    printf("%s: %s\n", name, ccol_retval_to_str(rv));
 
  chmap_destroy(ports);
  return 0;
}

ccol_retval_to_str(3), ccol_version(3), ccol_scoped_ptr(3), ccol_scoped_ptr_mp(3), ccol_scoped_ptr_release(3), ccol_fixed_width_data_type_size(3), cmempool_destroy(3), CMEMPOOL_DECLARE_PREALLOCATED_BUFFER(3), ccol_determine_ccol_data_type(3), citerators(7), chttp(7), chttpserver(7), clrucache(7), cmempool(7), csort(7), cthreadpool(7)