]> git.wh0rd.org - fontconfig.git/blobdiff - src/fccache.c
Emit and verify machine signature (sizeof (stuff) + endianness) in cache
[fontconfig.git] / src / fccache.c
index 3a7cb6ced0495d57bb050c59936443d1a6c1d83f..2255b3b3e0a70e547055719fc3adeef9d5da84d5 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * $RCSId: xc/lib/fontconfig/src/fccache.c,v 1.12 2002/08/22 07:36:44 keithp Exp $
  *
- * Copyright © 2000 Keith Packard
+ * Copyright Â© 2000 Keith Packard
  *
  * Permission to use, copy, modify, distribute, and sell this software and its
  * documentation for any purpose is hereby granted without fee, provided that
  * PERFORMANCE OF THIS SOFTWARE.
  */
 
+#include <fcntl.h>
+#include <dirent.h>
+#include <sys/mman.h>
+#include <sys/utsname.h>
 #include "fcint.h"
 
+#define ENDIAN_TEST 0x12345678
+#define MACHINE_SIGNATURE_SIZE 9 + 5*19 + 1
+
+static char *
+FcCacheProduceMachineSignature (void);
+
 /*
  * POSIX has broken stdio so that getc must do thread-safe locking,
  * this is a serious performance problem for applications doing large
 
 #define FC_DBG_CACHE_REF    1024
 
+#define PAGESIZE 8192
+
+static FcBool force;
+
 static FcChar8 *
 FcCacheReadString (FILE *f, FcChar8 *dest, int len)
 {
@@ -188,9 +202,19 @@ FcCacheWritePath (FILE *f, const FcChar8 *dir, const FcChar8 *file)
     if (dir)
        if (!FcCacheWriteChars (f, dir))
            return FcFalse;
+#ifdef _WIN32
+    if (dir &&
+       dir[strlen((const char *) dir) - 1] != '/' &&
+       dir[strlen((const char *) dir) - 1] != '\\')
+    {
+       if (!FcCacheWriteChars (f, "\\"))
+           return FcFalse;
+    }
+#else
     if (dir && dir[strlen((const char *) dir) - 1] != '/')
        if (PUTC ('/', f) == EOF)
            return FcFalse;
+#endif
     if (!FcCacheWriteChars (f, file))
        return FcFalse;
     if (PUTC ('"', f) == EOF)
@@ -235,13 +259,62 @@ FcCacheWriteTime (FILE *f, time_t t)
     return FcCacheWriteUlong (f, (unsigned long) t);
 }
 
+static FcChar8 *
+FcCacheReadString2 (int fd, FcChar8 *dest, int len)
+{
+    FcChar8    c;
+    FcBool     escape;
+    int                size;
+    int                i;
+
+    if (len == 0)
+       return FcFalse;
+    
+    size = len;
+    i = 0;
+    escape = FcFalse;
+    while (read (fd, &c, 1) == 1)
+    {
+       if (!escape)
+       {
+           switch (c) {
+           case '"':
+               c = '\0';
+               break;
+           case '\\':
+               escape = FcTrue;
+               continue;
+           }
+       }
+       if (i == size)
+       {
+           dest[i++] = 0;
+           return dest;
+       }
+       dest[i++] = c;
+       if (c == '\0')
+           return dest;
+       escape = FcFalse;
+    }
+    return 0;
+}
+
+static FcBool
+FcCacheWriteString2 (int fd, const FcChar8 *chars)
+{
+    if (write (fd, chars, strlen(chars)+1) != strlen(chars)+1)
+       return FcFalse;
+    return FcTrue;
+}
+
 static FcBool
 FcCacheFontSetAdd (FcFontSet       *set,
                   FcStrSet         *dirs,
                   const FcChar8    *dir,
                   int              dir_len,
                   const FcChar8    *file,
-                  const FcChar8    *name)
+                  const FcChar8    *name,
+                  FcConfig         *config)
 {
     FcChar8    path_buf[8192], *path;
     int                len;
@@ -258,10 +331,17 @@ FcCacheFontSetAdd (FcFontSet          *set,
            return FcFalse;
     }
     strncpy ((char *) path, (const char *) dir, dir_len);
+#ifdef _WIN32
+    if (dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\' )
+       path[dir_len++] = '\\';
+#else
     if (dir[dir_len - 1] != '/')
        path[dir_len++] = '/';
+#endif
     strcpy ((char *) path + dir_len, (const char *) file);
-    if (!FcStrCmp (name, FC_FONT_FILE_DIR))
+    if (config && !FcConfigAcceptFilename (config, path))
+       ret = FcTrue;
+    else if (!FcStrCmp (name, FC_FONT_FILE_DIR))
     {
        if (FcDebug () & FC_DBG_CACHEV)
            printf (" dir cache dir \"%s\"\n", path);
@@ -276,10 +356,18 @@ FcCacheFontSetAdd (FcFontSet          *set,
        font = FcNameParse (name);
        if (font)
        {
+           FcChar8 *family;
+           
            if (FcDebug () & FC_DBG_CACHEV)
                printf (" dir cache file \"%s\"\n", file);
            ret = FcPatternAddString (font, FC_FILE, path);
-           if (ret)
+           /*
+            * Make sure the pattern has the file name as well as
+            * already containing at least one family name.
+            */
+           if (ret && 
+               FcPatternGetString (font, FC_FAMILY, 0, &family) == FcResultMatch &&
+               (!config || FcConfigAcceptFont (config, font)))
            {
                frozen = FcPatternFreeze (font);
                ret = (frozen != 0);
@@ -309,14 +397,14 @@ FcCacheHash (const FcChar8 *string, int len)
  * Verify the saved timestamp for a file
  */
 FcBool
-FcGlobalCacheCheckTime (FcGlobalCacheInfo *info)
+FcGlobalCacheCheckTime (const FcChar8 *file, FcGlobalCacheInfo *info)
 {
     struct stat            statb;
 
-    if (stat ((char *) info->file, &statb) < 0)
+    if (stat ((char *) file, &statb) < 0)
     {
        if (FcDebug () & FC_DBG_CACHE)
-           printf (" file missing\n");
+           printf (" file %s missing\n", file);
        return FcFalse;
     }
     if (statb.st_mtime != info->time)
@@ -361,7 +449,7 @@ FcFilePathInfoGet (const FcChar8    *path)
     FcFilePathInfo  i;
     FcChar8        *slash;
 
-    slash = (FcChar8 *) strrchr ((const char *) path, '/');
+    slash = FcStrLastSlash (path);
     if (slash)
     {
         i.dir = path;
@@ -524,7 +612,8 @@ FcBool
 FcGlobalCacheScanDir (FcFontSet                *set,
                      FcStrSet          *dirs,
                      FcGlobalCache     *cache,
-                     const FcChar8     *dir)
+                     const FcChar8     *dir,
+                     FcConfig          *config)
 {
     FcGlobalCacheDir   *d = FcGlobalCacheDirGet (cache, dir,
                                                  strlen ((const char *) dir),
@@ -549,7 +638,7 @@ FcGlobalCacheScanDir (FcFontSet             *set,
      * See if the timestamp recorded in the global cache
      * matches the directory time, if not, return False
      */
-    if (!FcGlobalCacheCheckTime (&d->info))
+    if (!FcGlobalCacheCheckTime (d->info.file, &d->info))
     {
        if (FcDebug () & FC_DBG_CACHE)
            printf ("\tdir cache entry time mismatch\n");
@@ -567,7 +656,7 @@ FcGlobalCacheScanDir (FcFontSet             *set,
                printf ("FcGlobalCacheScanDir add file %s\n", f->info.file);
            any_in_cache = FcTrue;
            if (!FcCacheFontSetAdd (set, dirs, dir, dir_len,
-                                   f->info.file, f->name))
+                                   f->info.file, f->name, config))
            {
                cache->broken = FcTrue;
                return FcFalse;
@@ -583,7 +672,7 @@ FcGlobalCacheScanDir (FcFontSet             *set,
        
         any_in_cache = FcTrue;
        if (!FcCacheFontSetAdd (set, dirs, dir, dir_len,
-                               info.base, FC_FONT_FILE_DIR))
+                               info.base, FC_FONT_FILE_DIR, config))
        {
            cache->broken = FcTrue;
            return FcFalse;
@@ -633,7 +722,7 @@ FcGlobalCacheFileGet (FcGlobalCache *cache,
        }
     }
     if (count)
-       *count = max;
+       *count = max + 1;
     return match;
 }
     
@@ -840,9 +929,11 @@ FcGlobalCacheSave (FcGlobalCache    *cache,
     if (cache->broken)
        return FcFalse;
 
+#if defined (HAVE_GETUID) && defined (HAVE_GETEUID)
     /* Set-UID programs can't safely update the cache */
     if (getuid () != geteuid ())
        return FcFalse;
+#endif
     
     atomic = FcAtomicCreate (cache_file);
     if (!atomic)
@@ -927,21 +1018,118 @@ bail0:
     return FcFalse;
 }
 
+/* 
+ * Find the next presumably-mmapable offset after the current file
+ * pointer.
+ */
+static int
+FcCacheNextOffset(off_t w)
+{
+    if (w % PAGESIZE == 0) 
+       return w;
+    else
+       return ((w / PAGESIZE)+1)*PAGESIZE;
+}
+
+/* return the address of the segment for the provided arch,
+ * or -1 if arch not found */
+static off_t
+FcCacheSkipToArch (int fd, const char * arch)
+{
+    char candidate_arch_machine_name_count[MACHINE_SIGNATURE_SIZE + 9];
+    char * candidate_arch;
+    off_t current_arch_start = 0;
+
+    /* skip arches that are not the current arch */
+    while (1)
+    {
+       long bs;
+
+       lseek (fd, current_arch_start, SEEK_SET);
+       if (FcCacheReadString2 (fd, candidate_arch_machine_name_count, 
+                               sizeof (candidate_arch_machine_name_count)) == 0)
+           break;
+       if (!strlen(candidate_arch_machine_name_count))
+           return -1;
+       bs = strtol(candidate_arch_machine_name_count, &candidate_arch, 16);
+       candidate_arch++; /* skip leading space */
+
+       if (strcmp (candidate_arch, arch)==0)
+           break;
+       current_arch_start += bs;
+    }
+
+    if (strcmp (candidate_arch, arch)!=0)
+       return -1;
+
+    return current_arch_start;
+}
+
+/* Cuts out the segment at the file pointer (moves everything else
+ * down to cover it), and leaves the file pointer at the end of the
+ * file. */
+#define BUF_SIZE 8192
+
+static FcBool 
+FcCacheMoveDown (int fd, off_t start)
+{
+    char * buf = malloc (BUF_SIZE);
+    char candidate_arch_machine_name[MACHINE_SIGNATURE_SIZE + 9];
+    long bs;
+    int c, bytes_skipped;
+
+    if (!buf)
+       return FcFalse;
+
+    lseek (fd, start, SEEK_SET);
+    if (FcCacheReadString2 (fd, candidate_arch_machine_name, 
+                          sizeof (candidate_arch_machine_name)) == 0)
+       goto done;
+    if (!strlen(candidate_arch_machine_name))
+       goto done;
+
+    bs = strtol(candidate_arch_machine_name, 0, 16);
+    if (bs == 0)
+       goto done;
+
+    bytes_skipped = 0;
+    do
+    {
+       lseek (fd, start+bs+bytes_skipped, SEEK_SET);
+       if ((c = read (fd, buf, BUF_SIZE)) <= 0)
+           break;
+       lseek (fd, start+bytes_skipped, SEEK_SET);
+       if (write (fd, buf, c) < 0)
+           goto bail;
+       bytes_skipped += c;
+    }
+    while (c > 0);
+    lseek (fd, start+bytes_skipped, SEEK_SET);
+
+ done:
+    free (buf);
+    return FcTrue;
+
+ bail:
+    free (buf);
+    return FcFalse;
+}
+
 FcBool
 FcDirCacheValid (const FcChar8 *dir)
 {
-    FcChar8    *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
-    struct stat        file_stat, dir_stat;
+    FcChar8     *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
+    struct stat file_stat, dir_stat;
 
     if (stat ((char *) dir, &dir_stat) < 0)
     {
-       FcStrFree (cache_file);
-       return FcFalse;
+        FcStrFree (cache_file);
+        return FcFalse;
     }
     if (stat ((char *) cache_file, &file_stat) < 0)
     {
-       FcStrFree (cache_file);
-       return FcFalse;
+        FcStrFree (cache_file);
+        return FcFalse;
     }
     FcStrFree (cache_file);
     /*
@@ -949,191 +1137,376 @@ FcDirCacheValid (const FcChar8 *dir)
      * the cache file, the cache is not valid
      */
     if (dir_stat.st_mtime - file_stat.st_mtime > 0)
-       return FcFalse;
+        return FcFalse;
     return FcTrue;
 }
 
-FcBool
-FcDirCacheReadDir (FcFontSet *set, FcStrSet *dirs, const FcChar8 *dir)
+static int
+FcCacheReadDirs (FcConfig * config, FcGlobalCache * cache, 
+                FcStrList *list, FcFontSet * set)
 {
-    FcChar8        *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
-    FILE           *f;
-    FcChar8        *base;
-    int                    id;
-    int                    dir_len;
-    FcChar8        file_buf[8192], *file;
-    FcChar8        name_buf[8192], *name;
-    FcBool         ret = FcFalse;
+    DIR                        *d;
+    struct dirent      *e;
+    int                        ret = 0;
+    FcChar8            *dir;
+    FcChar8            *file, *base;
+    FcStrSet           *subdirs;
+    FcStrList          *sublist;
+    struct stat                statb;
 
-    if (!cache_file)
-       goto bail0;
-    
-    if (FcDebug () & FC_DBG_CACHE)
-       printf ("FcDirCacheReadDir cache_file \"%s\"\n", cache_file);
-    
-    f = fopen ((char *) cache_file, "r");
-    if (!f)
+    /*
+     * Now scan all of the directories into separate databases
+     * and write out the results
+     */
+    while ((dir = FcStrListNext (list)))
     {
-       if (FcDebug () & FC_DBG_CACHE)
-           printf (" no cache file\n");
-       goto bail1;
-    }
+       /* freed below */
+       file = (FcChar8 *) malloc (strlen ((char *) dir) + 1 + FC_MAX_FILE_LEN + 1);
+       if (!file)
+           return FcFalse;
 
-    if (!FcDirCacheValid (dir))
-    {
-       if (FcDebug () & FC_DBG_CACHE)
-           printf (" cache file older than directory\n");
-       goto bail2;
-    }
-    
-    base = (FcChar8 *) strrchr ((char *) cache_file, '/');
-    if (!base)
-       goto bail2;
-    base++;
-    dir_len = base - cache_file;
-    
-    file = 0;
-    name = 0;
-    while ((file = FcCacheReadString (f, file_buf, sizeof (file_buf))) &&
-          FcCacheReadInt (f, &id) &&
-          (name = FcCacheReadString (f, name_buf, sizeof (name_buf))))
-    {
-       if (!FcCacheFontSetAdd (set, dirs, cache_file, dir_len,
-                               file, name))
-           goto bail3;
-       if (file != file_buf)
+       strcpy ((char *) file, (char *) dir);
+       strcat ((char *) file, "/");
+       base = file + strlen ((char *) file);
+
+       subdirs = FcStrSetCreate ();
+       if (!subdirs)
+       {
+           fprintf (stderr, "Can't create directory set\n");
+           ret++;
            free (file);
-       if (name != name_buf)
-           free (name);
-       file = name = 0;
-    }
-    if (FcDebug () & FC_DBG_CACHE)
-       printf (" cache loaded\n");
-    
-    ret = FcTrue;
-bail3:
-    if (file && file != file_buf)
+           continue;
+       }
+       
+       if (access ((char *) dir, X_OK) < 0)
+       {
+           switch (errno) {
+           case ENOENT:
+           case ENOTDIR:
+           case EACCES:
+               break;
+           default:
+               fprintf (stderr, "\"%s\": ", dir);
+               perror ("");
+               ret++;
+           }
+           FcStrSetDestroy (subdirs);
+           free (file);
+           continue;
+       }
+       if (stat ((char *) dir, &statb) == -1)
+       {
+           fprintf (stderr, "\"%s\": ", dir);
+           perror ("");
+           FcStrSetDestroy (subdirs);
+           ret++;
+           free (file);
+           continue;
+       }
+       if (!S_ISDIR (statb.st_mode))
+       {
+           fprintf (stderr, "\"%s\": not a directory, skipping\n", dir);
+           FcStrSetDestroy (subdirs);
+           free (file);
+           continue;
+       }
+       d = opendir ((char *) dir);
+       if (!d)
+       {
+           FcStrSetDestroy (subdirs);
+           free (file);
+           continue;
+       }
+       while ((e = readdir (d)))
+       {
+           if (e->d_name[0] != '.' && strlen (e->d_name) < FC_MAX_FILE_LEN)
+           {
+               strcpy ((char *) base, (char *) e->d_name);
+               if (FcFileIsDir (file) && !FcStrSetAdd (subdirs, file))
+                   ret++;
+           }
+       }
+       closedir (d);
+       if (!FcDirCacheValid (dir) || !FcDirCacheRead (set, dir))
+       {
+           if (FcDebug () & FC_DBG_FONTSET)
+               printf ("scan dir %s\n", dir);
+           FcDirScanConfig (set, subdirs, cache, 
+                            config->blanks, dir, FcFalse, config);
+       }
+       sublist = FcStrListCreate (subdirs);
+       FcStrSetDestroy (subdirs);
+       if (!sublist)
+       {
+           fprintf (stderr, "Can't create subdir list in \"%s\"\n", dir);
+           ret++;
+           free (file);
+           continue;
+       }
+       ret += FcCacheReadDirs (config, cache, sublist, set);
        free (file);
-    if (name && name != name_buf)
-       free (name);
-bail2:
-    fclose (f);
-bail1:
-    FcStrFree (cache_file);
-bail0:
+    }
+    FcStrListDone (list);
     return ret;
 }
 
-/*
- * return the path from the directory containing 'cache' to 'file'
- */
-
-static const FcChar8 *
-FcFileBaseName (const FcChar8 *cache, const FcChar8 *file)
+FcFontSet *
+FcCacheRead (FcConfig *config, FcGlobalCache * cache)
 {
-    const FcChar8   *cache_slash;
+    FcFontSet * s = FcFontSetCreate();
+    if (!s) 
+       return 0;
 
-    cache_slash = (const FcChar8 *) strrchr ((const char *) cache, '/');
-    if (cache_slash && !strncmp ((const char *) cache, (const char *) file,
-                                (cache_slash + 1) - cache))
-       return file + ((cache_slash + 1) - cache);
-    return file;
+    if (force)
+       goto bail;
+
+    if (FcCacheReadDirs (config, cache, FcConfigGetConfigDirs (config), s))
+       goto bail;
+
+    return s;
+
+ bail:
+    FcFontSetDestroy (s);
+    return 0;
 }
 
+/* read serialized state from the cache file */
 FcBool
-FcDirCacheWriteDir (FcFontSet *set, FcStrSet *dirs, const FcChar8 *dir)
+FcDirCacheRead (FcFontSet * set, const FcChar8 *dir)
 {
-    FcChar8        *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
-    FcPattern      *font;
-    FILE           *f;
-    FcChar8        *name;
-    const FcChar8   *file, *base;
-    int                    n;
-    int                    id;
-    FcBool         ret;
-    FcStrList      *list;
-
+    FcChar8         *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
+    int fd;
+    FcCache metadata;
+    void * current_dir_block;
+    char * current_arch_machine_name;
+    char candidate_arch_machine_name[9+MACHINE_SIGNATURE_SIZE];
+    off_t current_arch_start = 0;
+
+    if (force)
+       goto bail;
     if (!cache_file)
-       goto bail0;
-    if (FcDebug () & FC_DBG_CACHE)
-       printf ("FcDirCacheWriteDir cache_file \"%s\"\n", cache_file);
-    
-    f = fopen ((char *) cache_file, "w");
-    if (!f)
-    {
-       if (FcDebug () & FC_DBG_CACHE)
-           printf (" can't create \"%s\"\n", cache_file);
+        goto bail;
+
+    current_arch_machine_name = FcCacheProduceMachineSignature();
+    fd = open(cache_file, O_RDONLY);
+    if (fd == -1)
+        goto bail;
+
+    current_arch_start = FcCacheSkipToArch(fd, current_arch_machine_name);
+    if (current_arch_start < 0)
+        goto bail1;
+
+    lseek (fd, current_arch_start, SEEK_SET);
+    if (FcCacheReadString2 (fd, candidate_arch_machine_name, 
+                          sizeof (candidate_arch_machine_name)) == 0)
        goto bail1;
-    }
-    
-    list = FcStrListCreate (dirs);
-    if (!list)
-       goto bail2;
-    
-    while ((dir = FcStrListNext (list)))
-    {
-       base = FcFileBaseName (cache_file, dir);
-       if (!FcCacheWriteString (f, base))
-           goto bail3;
-       if (PUTC (' ', f) == EOF)
-           goto bail3;
-       if (!FcCacheWriteInt (f, 0))
-           goto bail3;
-        if (PUTC (' ', f) == EOF)
-           goto bail3;
-       if (!FcCacheWriteString (f, FC_FONT_FILE_DIR))
-           goto bail3;
-       if (PUTC ('\n', f) == EOF)
-           goto bail3;
-    }
+
+    // sanity check for endianness issues
+    read(fd, &metadata, sizeof(FcCache));
+    if (metadata.magic != FC_CACHE_MAGIC)
+        goto bail1;
+
+    if (!metadata.count)
+       goto bail1;
+
+    off_t pos = FcCacheNextOffset (lseek(fd, 0, SEEK_CUR));
+    current_dir_block = mmap (0, metadata.count, 
+                             PROT_READ, MAP_SHARED, fd, pos);
+    if (current_dir_block == MAP_FAILED)
+       perror("");
     
-    for (n = 0; n < set->nfont; n++)
+    if (!FcFontSetUnserialize (metadata, set, current_dir_block))
+       goto bail1;
+       
+    close(fd);
+    free (cache_file);
+    return FcTrue;
+
+ bail1:
+    close(fd);
+ bail:
+    free (cache_file);
+    return FcFalse;
+}
+
+/* write serialized state to the cache file */
+FcBool
+FcDirCacheWrite (int bank, FcFontSet *set, const FcChar8 *dir)
+{
+    FcChar8         *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
+    int fd, bytes_to_write, metadata_bytes;
+    FcCache metadata;
+    off_t current_arch_start = 0, truncate_to;
+    char * current_arch_machine_name, * header;
+    void * current_dir_block, *final_dir_block;
+
+    if (!cache_file)
+        goto bail;
+
+    FcFontSetNewBank();
+    bytes_to_write = FcFontSetNeededBytes (set);
+    metadata_bytes = FcCacheNextOffset (sizeof (FcCache));
+
+    if (!bytes_to_write)
     {
-       font = set->fonts[n];
-       if (FcPatternGetString (font, FC_FILE, 0, (FcChar8 **) &file) != FcResultMatch)
-           goto bail3;
-       base = FcFileBaseName (cache_file, file);
-       if (FcPatternGetInteger (font, FC_INDEX, 0, &id) != FcResultMatch)
-           goto bail3;
-       if (FcDebug () & FC_DBG_CACHEV)
-           printf (" write file \"%s\"\n", base);
-       if (!FcCacheWriteString (f, base))
-           goto bail3;
-       if (PUTC (' ', f) == EOF)
-           goto bail3;
-       if (!FcCacheWriteInt (f, id))
-           goto bail3;
-        if (PUTC (' ', f) == EOF)
-           goto bail3;
-       name = FcNameUnparse (font);
-       if (!name)
-           goto bail3;
-       ret = FcCacheWriteString (f, name);
-       FcStrFree (name);
-       if (!ret)
-           goto bail3;
-       if (PUTC ('\n', f) == EOF)
-           goto bail3;
+       unlink (cache_file);
+       free (cache_file);
+       return FcTrue;
     }
-    
-    FcStrListDone (list);
 
-    if (fclose (f) == EOF)
-       goto bail1;
-    
-    FcStrFree (cache_file);
+    current_dir_block = malloc (bytes_to_write);
+    memset (&metadata, 0, sizeof(FcCache));
+    metadata.count = bytes_to_write;
+    metadata.bank = bank;
+    if (!current_dir_block)
+       goto bail;
+    final_dir_block = FcFontSetDistributeBytes (&metadata, current_dir_block);
+
+    if ((char *)current_dir_block + bytes_to_write != final_dir_block)
+       goto bail;
+                             
+    if (!FcFontSetSerialize (bank, set))
+       goto bail;
 
     if (FcDebug () & FC_DBG_CACHE)
-       printf (" cache written\n");
+        printf ("FcDirCacheWriteDir cache_file \"%s\"\n", cache_file);
+
+    fd = open(cache_file, O_RDWR | O_CREAT, 0666);
+    if (fd == -1)
+        goto bail;
+
+    current_arch_machine_name = FcCacheProduceMachineSignature ();
+    current_arch_start = FcCacheSkipToArch(fd, current_arch_machine_name);
+    if (current_arch_start < 0)
+       current_arch_start = FcCacheNextOffset (lseek(fd, 0, SEEK_END));
+
+    if (!FcCacheMoveDown(fd, current_arch_start))
+       goto bail1;
+
+    current_arch_start = lseek(fd, 0, SEEK_CUR);
+    if (ftruncate (fd, current_arch_start) == -1)
+       goto bail1;
+
+    /* now write the address of the next offset */
+    truncate_to = FcCacheNextOffset (FcCacheNextOffset (current_arch_start + metadata_bytes) + bytes_to_write) - current_arch_start;
+
+    header = malloc (10 + strlen (current_arch_machine_name));
+    sprintf (header, "%8x ", (int)truncate_to);
+    strcat (header, current_arch_machine_name);
+    if (!FcCacheWriteString2 (fd, header))
+       goto bail1;
+
+    metadata.magic = FC_CACHE_MAGIC;
+    write (fd, &metadata, sizeof(FcCache));
+    lseek (fd, FcCacheNextOffset (lseek(fd, 0, SEEK_END)), SEEK_SET);
+    write (fd, current_dir_block, bytes_to_write);
+
+    /* this actually serves to pad out the cache file, if needed */
+    if (ftruncate (fd, current_arch_start + truncate_to) == -1)
+       goto bail1;
+
+    close(fd);
     return FcTrue;
-    
-bail3:
-    FcStrListDone (list);
-bail2:
-    fclose (f);
-bail1:
-    unlink ((char *) cache_file);
-    FcStrFree (cache_file);
-bail0:
+
+ bail1:
+    free (current_dir_block);
+    free (current_arch_machine_name);
+ bail:
+    unlink (cache_file);
+    free (cache_file);
     return FcFalse;
 }
+
+static char *
+FcCacheProduceMachineSignature ()
+{
+    static char buf[MACHINE_SIGNATURE_SIZE];
+    int magic = ENDIAN_TEST;
+    char * m = (char *)&magic;
+
+    sprintf (buf, "%2x%2x%2x%2x "
+            "%4x %4x %4x %4x %4x %4x %4x %4x %4x %4x %4x %4x "
+            "%4x %4x %4x %4x %4x %4x %4x\n", 
+            m[0], m[1], m[2], m[3],
+            sizeof (char),
+            sizeof (char *),
+            sizeof (int),
+            sizeof (FcPattern),
+            sizeof (FcPatternEltPtr),
+            sizeof (struct _FcPatternElt *),
+            sizeof (FcPatternElt),
+            sizeof (FcObjectPtr),
+            sizeof (FcValueListPtr),
+            sizeof (FcValue),
+            sizeof (FcValueBinding),
+            sizeof (struct _FcValueList *),
+            sizeof (FcCharSet),
+            sizeof (FcCharLeaf **),
+            sizeof (FcChar16 *),
+            sizeof (FcChar16),
+            sizeof (FcCharLeaf),
+            sizeof (FcChar32),
+            sizeof (FcCache));
+
+    return buf;
+}
+
+/* if true, ignore the cache file */
+void
+FcCacheForce (FcBool f)
+{
+    force = f;
+}
+
+static int banks_ptr = 0, banks_alloc = 0;
+static int * bankId = 0;
+
+int
+FcCacheBankCount (void)
+{
+    return banks_ptr;
+}
+
+FcBool
+FcCacheHaveBank (int bank)
+{
+    int i;
+
+    if (bank < FC_BANK_FIRST)
+       return FcTrue;
+
+    for (i = 0; i < banks_ptr; i++)
+       if (bankId[i] == bank)
+           return FcTrue;
+
+    return FcFalse;
+}
+
+int
+FcCacheBankToIndex (int bank)
+{
+    static int lastBank = FC_BANK_DYNAMIC, lastIndex = -1;
+    int i;
+    int * b;
+
+    if (bank == lastBank)
+       return lastIndex;
+
+    for (i = 0; i < banks_ptr; i++)
+       if (bankId[i] == bank)
+           return i;
+
+    if (banks_ptr >= banks_alloc)
+    {
+       b = realloc (bankId, (banks_alloc + 4) * sizeof(int));
+       if (!b)
+           return -1;
+
+       bankId = b;
+       banks_alloc += 4;
+    }
+
+    i = banks_ptr++;
+    bankId[i] = bank;
+    return i;
+}