Monday, March 22, 2010

Dangers of C library

I just read through Ulrich Drepper's Defensive Programming article. He highlights dangers of C library, provides safer alternatives for commonly used idioms and introduces a number of tools for pinpointing problems in code.

These are my rather unstructured notes of things most interesting to me.


Syntax for forward declarations within paramer list and array size annotation for future checks
int addvec(int n; int arr[n], int n)

tools for formatting an arbitrarily long string
aprintf() which allocates the buffer, for constant format string only
FILE *open_memstream(), for an ostringstream -like in-memory file

fast string handling within stack
strdupa() and alloca()

parsing strings of arbitrary size
%as format string with buffer allocated by scanf

parsing simple delimited files with arbitrary length of lines
ssize_t getdelim()
ssize_t getline()

practical examples of using file descriptor variants of regular functions for avoiding race conditions
eg. chown -> fchown

O_NOFOLLOW for avoiding dereferencing symbolic links

mapping a function over a directory tree with ntfw()

create temporary files only with mkstemp() or tmpfile()

unix domain socket authentication
getsockopt(SO_PEERCRED)

proper randomness
  • initstate() from /dev/random
  • random()
_FORTIFY_SOURCE for compiling in runtime memory checks around standard C runtime.

use of __attribute__ __deprecated__ and concept of .gnu.warning -sections within ELF.



good overview of tools

MALLOC_PERTURB
  • forces unitialized memory to contain given garbage
mtrace()
  • output a trace file with malloc and free operations for single threaded programs
mcheck()
dmalloc
  • replaces malloc
electric fence
  • inserts protected pages around allocated memory, over freed memory
valgrind
  • virtual machine for IA-32 only
mudflap
  • gcc4 inserted instrumentation and library for memory checking
catchsegv / libsegfault
  • dump backtrace on crash
_GLIBCXX_DEBUG - templates with assertions

No comments:

Post a Comment