Bug 59456 - Adding a --sysroot like option to fc-cache
[platform/upstream/fontconfig.git] / src / fccache.c
1 /*
2  * Copyright © 2000 Keith Packard
3  * Copyright © 2005 Patrick Lam
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and its
6  * documentation for any purpose is hereby granted without fee, provided that
7  * the above copyright notice appear in all copies and that both that
8  * copyright notice and this permission notice appear in supporting
9  * documentation, and that the name of the author(s) not be used in
10  * advertising or publicity pertaining to distribution of the software without
11  * specific, written prior permission.  The authors make no
12  * representations about the suitability of this software for any purpose.  It
13  * is provided "as is" without express or implied warranty.
14  *
15  * THE AUTHOR(S) DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
16  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
17  * EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR
18  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
19  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
20  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21  * PERFORMANCE OF THIS SOFTWARE.
22  */
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26 #include "fcint.h"
27 #include "fcarch.h"
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <fcntl.h>
31 #include <dirent.h>
32 #include <string.h>
33 #include <sys/types.h>
34 #include <assert.h>
35 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
36 #  include <unistd.h>
37 #  include <sys/mman.h>
38 #endif
39
40 #ifndef O_BINARY
41 #define O_BINARY 0
42 #endif
43
44
45 struct MD5Context {
46         FcChar32 buf[4];
47         FcChar32 bits[2];
48         unsigned char in[64];
49 };
50
51 static void MD5Init(struct MD5Context *ctx);
52 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len);
53 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx);
54 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16]);
55
56 #define CACHEBASE_LEN (1 + 32 + 1 + sizeof (FC_ARCHITECTURE) + sizeof (FC_CACHE_SUFFIX))
57
58 static FcBool
59 FcCacheIsMmapSafe (int fd)
60 {
61     enum {
62       MMAP_NOT_INITIALIZED = 0,
63       MMAP_USE,
64       MMAP_DONT_USE,
65       MMAP_CHECK_FS,
66     } status;
67     static void *static_status;
68
69     status = (intptr_t) fc_atomic_ptr_get (&static_status);
70
71     if (status == MMAP_NOT_INITIALIZED)
72     {
73         const char *env = getenv ("FONTCONFIG_USE_MMAP");
74         FcBool use;
75         if (env && FcNameBool ((const FcChar8 *) env, &use))
76             status =  use ? MMAP_USE : MMAP_DONT_USE;
77         else
78             status = MMAP_CHECK_FS;
79         (void) fc_atomic_ptr_cmpexch (&static_status, NULL, (void *) status);
80     }
81
82     if (status == MMAP_CHECK_FS)
83         return FcIsFsMmapSafe (fd);
84     else
85         return status == MMAP_USE;
86
87 }
88
89 static const char bin2hex[] = { '0', '1', '2', '3',
90                                 '4', '5', '6', '7',
91                                 '8', '9', 'a', 'b',
92                                 'c', 'd', 'e', 'f' };
93
94 static FcChar8 *
95 FcDirCacheBasename (const FcChar8 * dir, FcChar8 cache_base[CACHEBASE_LEN])
96 {
97     unsigned char       hash[16];
98     FcChar8             *hex_hash;
99     int                 cnt;
100     struct MD5Context   ctx;
101
102     MD5Init (&ctx);
103     MD5Update (&ctx, (const unsigned char *)dir, strlen ((const char *) dir));
104
105     MD5Final (hash, &ctx);
106
107     cache_base[0] = '/';
108     hex_hash = cache_base + 1;
109     for (cnt = 0; cnt < 16; ++cnt)
110     {
111         hex_hash[2*cnt  ] = bin2hex[hash[cnt] >> 4];
112         hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
113     }
114     hex_hash[2*cnt] = 0;
115     strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
116
117     return cache_base;
118 }
119
120 FcBool
121 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
122 {
123     FcChar8     *cache_hashed = NULL;
124     FcChar8     cache_base[CACHEBASE_LEN];
125     FcStrList   *list;
126     FcChar8     *cache_dir;
127     const FcChar8 *sysroot = FcConfigGetSysRoot (config);
128
129     FcDirCacheBasename (dir, cache_base);
130
131     list = FcStrListCreate (config->cacheDirs);
132     if (!list)
133         return FcFalse;
134         
135     while ((cache_dir = FcStrListNext (list)))
136     {
137         if (sysroot)
138             cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
139         else
140             cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
141         if (!cache_hashed)
142             break;
143         (void) unlink ((char *) cache_hashed);
144         FcStrFree (cache_hashed);
145     }
146     FcStrListDone (list);
147     /* return FcFalse if something went wrong */
148     if (cache_dir)
149         return FcFalse;
150     return FcTrue;
151 }
152
153 static int
154 FcDirCacheOpenFile (const FcChar8 *cache_file, struct stat *file_stat)
155 {
156     int fd;
157
158 #ifdef _WIN32
159     if (FcStat (cache_file, file_stat) < 0)
160         return -1;
161 #endif
162     fd = FcOpen((char *) cache_file, O_RDONLY | O_BINARY);
163     if (fd < 0)
164         return fd;
165 #ifndef _WIN32
166     if (fstat (fd, file_stat) < 0)
167     {
168         close (fd);
169         return -1;
170     }
171 #endif
172     return fd;
173 }
174
175 /*
176  * Look for a cache file for the specified dir. Attempt
177  * to use each one we find, stopping when the callback
178  * indicates success
179  */
180 static FcBool
181 FcDirCacheProcess (FcConfig *config, const FcChar8 *dir,
182                    FcBool (*callback) (int fd, struct stat *fd_stat,
183                                        struct stat *dir_stat, void *closure),
184                    void *closure, FcChar8 **cache_file_ret)
185 {
186     int         fd = -1;
187     FcChar8     cache_base[CACHEBASE_LEN];
188     FcStrList   *list;
189     FcChar8     *cache_dir;
190     struct stat file_stat, dir_stat;
191     FcBool      ret = FcFalse;
192
193     if (FcStatChecksum (dir, &dir_stat) < 0)
194         return FcFalse;
195
196     FcDirCacheBasename (dir, cache_base);
197
198     list = FcStrListCreate (config->cacheDirs);
199     if (!list)
200         return FcFalse;
201         
202     while ((cache_dir = FcStrListNext (list)))
203     {
204         const FcChar8 *sysroot = FcConfigGetSysRoot (config);
205         FcChar8 *cache_hashed;
206
207         if (sysroot)
208             cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
209         else
210             cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
211         if (!cache_hashed)
212             break;
213         fd = FcDirCacheOpenFile (cache_hashed, &file_stat);
214         if (fd >= 0) {
215             ret = (*callback) (fd, &file_stat, &dir_stat, closure);
216             close (fd);
217             if (ret)
218             {
219                 if (cache_file_ret)
220                     *cache_file_ret = cache_hashed;
221                 else
222                     FcStrFree (cache_hashed);
223                 break;
224             }
225         }
226         FcStrFree (cache_hashed);
227     }
228     FcStrListDone (list);
229
230     return ret;
231 }
232
233 #define FC_CACHE_MIN_MMAP   1024
234
235 /*
236  * Skip list element, make sure the 'next' pointer is the last thing
237  * in the structure, it will be allocated large enough to hold all
238  * of the necessary pointers
239  */
240
241 typedef struct _FcCacheSkip FcCacheSkip;
242
243 struct _FcCacheSkip {
244     FcCache         *cache;
245     FcRef           ref;
246     intptr_t        size;
247     dev_t           cache_dev;
248     ino_t           cache_ino;
249     time_t          cache_mtime;
250     FcCacheSkip     *next[1];
251 };
252
253 /*
254  * The head of the skip list; pointers for every possible level
255  * in the skip list, plus the largest level in the list
256  */
257
258 #define FC_CACHE_MAX_LEVEL  16
259
260 /* Protected by cache_lock below */
261 static FcCacheSkip      *fcCacheChains[FC_CACHE_MAX_LEVEL];
262 static int              fcCacheMaxLevel;
263
264
265 static FcMutex *cache_lock;
266
267 static void
268 lock_cache (void)
269 {
270   FcMutex *lock;
271 retry:
272   lock = fc_atomic_ptr_get (&cache_lock);
273   if (!lock) {
274     lock = (FcMutex *) malloc (sizeof (FcMutex));
275     FcMutexInit (lock);
276     if (!fc_atomic_ptr_cmpexch (&cache_lock, NULL, lock)) {
277       FcMutexFinish (lock);
278       goto retry;
279     }
280
281     FcMutexLock (lock);
282     /* Initialize random state */
283     FcRandom ();
284     return;
285   }
286   FcMutexLock (lock);
287 }
288
289 static void
290 unlock_cache (void)
291 {
292   FcMutexUnlock (cache_lock);
293 }
294
295 static void
296 free_lock (void)
297 {
298   FcMutex *lock;
299   lock = fc_atomic_ptr_get (&cache_lock);
300   if (lock && fc_atomic_ptr_cmpexch (&cache_lock, lock, NULL)) {
301     FcMutexFinish (lock);
302     free (lock);
303   }
304 }
305
306
307
308 /*
309  * Generate a random level number, distributed
310  * so that each level is 1/4 as likely as the one before
311  *
312  * Note that level numbers run 1 <= level <= MAX_LEVEL
313  */
314 static int
315 random_level (void)
316 {
317     /* tricky bit -- each bit is '1' 75% of the time */
318     long int    bits = FcRandom () | FcRandom ();
319     int level = 0;
320
321     while (++level < FC_CACHE_MAX_LEVEL)
322     {
323         if (bits & 1)
324             break;
325         bits >>= 1;
326     }
327     return level;
328 }
329
330 /*
331  * Insert cache into the list
332  */
333 static FcBool
334 FcCacheInsert (FcCache *cache, struct stat *cache_stat)
335 {
336     FcCacheSkip    **update[FC_CACHE_MAX_LEVEL];
337     FcCacheSkip    *s, **next;
338     int             i, level;
339
340     lock_cache ();
341
342     /*
343      * Find links along each chain
344      */
345     next = fcCacheChains;
346     for (i = fcCacheMaxLevel; --i >= 0; )
347     {
348         for (; (s = next[i]); next = s->next)
349             if (s->cache > cache)
350                 break;
351         update[i] = &next[i];
352     }
353
354     /*
355      * Create new list element
356      */
357     level = random_level ();
358     if (level > fcCacheMaxLevel)
359     {
360         level = fcCacheMaxLevel + 1;
361         update[fcCacheMaxLevel] = &fcCacheChains[fcCacheMaxLevel];
362         fcCacheMaxLevel = level;
363     }
364
365     s = malloc (sizeof (FcCacheSkip) + (level - 1) * sizeof (FcCacheSkip *));
366     if (!s)
367         return FcFalse;
368
369     s->cache = cache;
370     s->size = cache->size;
371     FcRefInit (&s->ref, 1);
372     if (cache_stat)
373     {
374         s->cache_dev = cache_stat->st_dev;
375         s->cache_ino = cache_stat->st_ino;
376         s->cache_mtime = cache_stat->st_mtime;
377     }
378     else
379     {
380         s->cache_dev = 0;
381         s->cache_ino = 0;
382         s->cache_mtime = 0;
383     }
384
385     /*
386      * Insert into all fcCacheChains
387      */
388     for (i = 0; i < level; i++)
389     {
390         s->next[i] = *update[i];
391         *update[i] = s;
392     }
393
394     unlock_cache ();
395     return FcTrue;
396 }
397
398 static FcCacheSkip *
399 FcCacheFindByAddrUnlocked (void *object)
400 {
401     int     i;
402     FcCacheSkip    **next = fcCacheChains;
403     FcCacheSkip    *s;
404
405     if (!object)
406         return NULL;
407
408     /*
409      * Walk chain pointers one level at a time
410      */
411     for (i = fcCacheMaxLevel; --i >= 0;)
412         while (next[i] && (char *) object >= ((char *) next[i]->cache + next[i]->size))
413             next = next[i]->next;
414     /*
415      * Here we are
416      */
417     s = next[0];
418     if (s && (char *) object < ((char *) s->cache + s->size))
419         return s;
420     return NULL;
421 }
422
423 static FcCacheSkip *
424 FcCacheFindByAddr (void *object)
425 {
426     FcCacheSkip *ret;
427     lock_cache ();
428     ret = FcCacheFindByAddrUnlocked (object);
429     unlock_cache ();
430     return ret;
431 }
432
433 static void
434 FcCacheRemoveUnlocked (FcCache *cache)
435 {
436     FcCacheSkip     **update[FC_CACHE_MAX_LEVEL];
437     FcCacheSkip     *s, **next;
438     int             i;
439
440     /*
441      * Find links along each chain
442      */
443     next = fcCacheChains;
444     for (i = fcCacheMaxLevel; --i >= 0; )
445     {
446         for (; (s = next[i]); next = s->next)
447             if (s->cache >= cache)
448                 break;
449         update[i] = &next[i];
450     }
451     s = next[0];
452     for (i = 0; i < fcCacheMaxLevel && *update[i] == s; i++)
453         *update[i] = s->next[i];
454     while (fcCacheMaxLevel > 0 && fcCacheChains[fcCacheMaxLevel - 1] == NULL)
455         fcCacheMaxLevel--;
456     free (s);
457 }
458
459 static FcCache *
460 FcCacheFindByStat (struct stat *cache_stat)
461 {
462     FcCacheSkip     *s;
463
464     lock_cache ();
465     for (s = fcCacheChains[0]; s; s = s->next[0])
466         if (s->cache_dev == cache_stat->st_dev &&
467             s->cache_ino == cache_stat->st_ino &&
468             s->cache_mtime == cache_stat->st_mtime)
469         {
470             FcRefInc (&s->ref);
471             unlock_cache ();
472             return s->cache;
473         }
474     unlock_cache ();
475     return NULL;
476 }
477
478 static void
479 FcDirCacheDisposeUnlocked (FcCache *cache)
480 {
481     FcCacheRemoveUnlocked (cache);
482
483     switch (cache->magic) {
484     case FC_CACHE_MAGIC_ALLOC:
485         free (cache);
486         break;
487     case FC_CACHE_MAGIC_MMAP:
488 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
489         munmap (cache, cache->size);
490 #elif defined(_WIN32)
491         UnmapViewOfFile (cache);
492 #endif
493         break;
494     }
495 }
496
497 void
498 FcCacheObjectReference (void *object)
499 {
500     FcCacheSkip *skip = FcCacheFindByAddr (object);
501
502     if (skip)
503         FcRefInc (&skip->ref);
504 }
505
506 void
507 FcCacheObjectDereference (void *object)
508 {
509     FcCacheSkip *skip;
510
511     lock_cache ();
512     skip = FcCacheFindByAddrUnlocked (object);
513     if (skip)
514     {
515         if (FcRefDec (&skip->ref) == 1)
516             FcDirCacheDisposeUnlocked (skip->cache);
517     }
518     unlock_cache ();
519 }
520
521 void
522 FcCacheFini (void)
523 {
524     int             i;
525
526     for (i = 0; i < FC_CACHE_MAX_LEVEL; i++)
527         assert (fcCacheChains[i] == NULL);
528     assert (fcCacheMaxLevel == 0);
529
530     free_lock ();
531 }
532
533 static FcBool
534 FcCacheTimeValid (FcCache *cache, struct stat *dir_stat)
535 {
536     struct stat dir_static;
537
538     if (!dir_stat)
539     {
540         if (FcStatChecksum (FcCacheDir (cache), &dir_static) < 0)
541             return FcFalse;
542         dir_stat = &dir_static;
543     }
544     if (FcDebug () & FC_DBG_CACHE)
545         printf ("FcCacheTimeValid dir \"%s\" cache checksum %d dir checksum %d\n",
546                 FcCacheDir (cache), cache->checksum, (int) dir_stat->st_mtime);
547     return cache->checksum == (int) dir_stat->st_mtime;
548 }
549
550 /*
551  * Map a cache file into memory
552  */
553 static FcCache *
554 FcDirCacheMapFd (int fd, struct stat *fd_stat, struct stat *dir_stat)
555 {
556     FcCache     *cache;
557     FcBool      allocated = FcFalse;
558
559     if (fd_stat->st_size < (int) sizeof (FcCache))
560         return NULL;
561     cache = FcCacheFindByStat (fd_stat);
562     if (cache)
563     {
564         if (FcCacheTimeValid (cache, dir_stat))
565             return cache;
566         FcDirCacheUnload (cache);
567         cache = NULL;
568     }
569
570     /*
571      * Large cache files are mmap'ed, smaller cache files are read. This
572      * balances the system cost of mmap against per-process memory usage.
573      */
574     if (FcCacheIsMmapSafe (fd) && fd_stat->st_size >= FC_CACHE_MIN_MMAP)
575     {
576 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
577         cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
578 #ifdef HAVE_POSIX_FADVISE
579         posix_fadvise (fd, 0, fd_stat->st_size, POSIX_FADV_WILLNEED);
580 #endif
581         if (cache == MAP_FAILED)
582             cache = NULL;
583 #elif defined(_WIN32)
584         {
585             HANDLE hFileMap;
586
587             cache = NULL;
588             hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
589                                          PAGE_READONLY, 0, 0, NULL);
590             if (hFileMap != NULL)
591             {
592                 cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0,
593                                        fd_stat->st_size);
594                 CloseHandle (hFileMap);
595             }
596         }
597 #endif
598     }
599     if (!cache)
600     {
601         cache = malloc (fd_stat->st_size);
602         if (!cache)
603             return NULL;
604
605         if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
606         {
607             free (cache);
608             return NULL;
609         }
610         allocated = FcTrue;
611     }
612     if (cache->magic != FC_CACHE_MAGIC_MMAP ||
613         cache->version < FC_CACHE_CONTENT_VERSION ||
614         cache->size != (intptr_t) fd_stat->st_size ||
615         !FcCacheTimeValid (cache, dir_stat) ||
616         !FcCacheInsert (cache, fd_stat))
617     {
618         if (allocated)
619             free (cache);
620         else
621         {
622 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
623             munmap (cache, fd_stat->st_size);
624 #elif defined(_WIN32)
625             UnmapViewOfFile (cache);
626 #endif
627         }
628         return NULL;
629     }
630
631     /* Mark allocated caches so they're freed rather than unmapped */
632     if (allocated)
633         cache->magic = FC_CACHE_MAGIC_ALLOC;
634         
635     return cache;
636 }
637
638 void
639 FcDirCacheReference (FcCache *cache, int nref)
640 {
641     FcCacheSkip *skip = FcCacheFindByAddr (cache);
642
643     if (skip)
644         FcRefAdd (&skip->ref, nref);
645 }
646
647 void
648 FcDirCacheUnload (FcCache *cache)
649 {
650     FcCacheObjectDereference (cache);
651 }
652
653 static FcBool
654 FcDirCacheMapHelper (int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure)
655 {
656     FcCache *cache = FcDirCacheMapFd (fd, fd_stat, dir_stat);
657
658     if (!cache)
659         return FcFalse;
660     *((FcCache **) closure) = cache;
661     return FcTrue;
662 }
663
664 FcCache *
665 FcDirCacheLoad (const FcChar8 *dir, FcConfig *config, FcChar8 **cache_file)
666 {
667     FcCache *cache = NULL;
668
669     if (!FcDirCacheProcess (config, dir,
670                             FcDirCacheMapHelper,
671                             &cache, cache_file))
672         return NULL;
673     return cache;
674 }
675
676 FcCache *
677 FcDirCacheLoadFile (const FcChar8 *cache_file, struct stat *file_stat)
678 {
679     int fd;
680     FcCache *cache;
681     struct stat my_file_stat;
682
683     if (!file_stat)
684         file_stat = &my_file_stat;
685     fd = FcDirCacheOpenFile (cache_file, file_stat);
686     if (fd < 0)
687         return NULL;
688     cache = FcDirCacheMapFd (fd, file_stat, NULL);
689     close (fd);
690     return cache;
691 }
692
693 /*
694  * Validate a cache file by reading the header and checking
695  * the magic number and the size field
696  */
697 static FcBool
698 FcDirCacheValidateHelper (int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure FC_UNUSED)
699 {
700     FcBool  ret = FcTrue;
701     FcCache     c;
702
703     if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
704         ret = FcFalse;
705     else if (c.magic != FC_CACHE_MAGIC_MMAP)
706         ret = FcFalse;
707     else if (c.version < FC_CACHE_CONTENT_VERSION)
708         ret = FcFalse;
709     else if (fd_stat->st_size != c.size)
710         ret = FcFalse;
711     else if (c.checksum != (int) dir_stat->st_mtime)
712         ret = FcFalse;
713     return ret;
714 }
715
716 static FcBool
717 FcDirCacheValidConfig (const FcChar8 *dir, FcConfig *config)
718 {
719     return FcDirCacheProcess (config, dir,
720                               FcDirCacheValidateHelper,
721                               NULL, NULL);
722 }
723
724 FcBool
725 FcDirCacheValid (const FcChar8 *dir)
726 {
727     FcConfig    *config;
728
729     config = FcConfigGetCurrent ();
730     if (!config)
731         return FcFalse;
732
733     return FcDirCacheValidConfig (dir, config);
734 }
735
736 /*
737  * Build a cache structure from the given contents
738  */
739 FcCache *
740 FcDirCacheBuild (FcFontSet *set, const FcChar8 *dir, struct stat *dir_stat, FcStrSet *dirs)
741 {
742     FcSerialize *serialize = FcSerializeCreate ();
743     FcCache *cache;
744     int i;
745     FcChar8     *dir_serialize;
746     intptr_t    *dirs_serialize;
747     FcFontSet   *set_serialize;
748
749     if (!serialize)
750         return NULL;
751     /*
752      * Space for cache structure
753      */
754     FcSerializeReserve (serialize, sizeof (FcCache));
755     /*
756      * Directory name
757      */
758     if (!FcStrSerializeAlloc (serialize, dir))
759         goto bail1;
760     /*
761      * Subdirs
762      */
763     FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
764     for (i = 0; i < dirs->num; i++)
765         if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
766             goto bail1;
767
768     /*
769      * Patterns
770      */
771     if (!FcFontSetSerializeAlloc (serialize, set))
772         goto bail1;
773
774     /* Serialize layout complete. Now allocate space and fill it */
775     cache = malloc (serialize->size);
776     if (!cache)
777         goto bail1;
778     /* shut up valgrind */
779     memset (cache, 0, serialize->size);
780
781     serialize->linear = cache;
782
783     cache->magic = FC_CACHE_MAGIC_ALLOC;
784     cache->version = FC_CACHE_CONTENT_VERSION;
785     cache->size = serialize->size;
786     cache->checksum = (int) dir_stat->st_mtime;
787
788     /*
789      * Serialize directory name
790      */
791     dir_serialize = FcStrSerialize (serialize, dir);
792     if (!dir_serialize)
793         goto bail2;
794     cache->dir = FcPtrToOffset (cache, dir_serialize);
795
796     /*
797      * Serialize sub dirs
798      */
799     dirs_serialize = FcSerializePtr (serialize, dirs);
800     if (!dirs_serialize)
801         goto bail2;
802     cache->dirs = FcPtrToOffset (cache, dirs_serialize);
803     cache->dirs_count = dirs->num;
804     for (i = 0; i < dirs->num; i++)
805     {
806         FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
807         if (!d_serialize)
808             goto bail2;
809         dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
810     }
811
812     /*
813      * Serialize font set
814      */
815     set_serialize = FcFontSetSerialize (serialize, set);
816     if (!set_serialize)
817         goto bail2;
818     cache->set = FcPtrToOffset (cache, set_serialize);
819
820     FcSerializeDestroy (serialize);
821
822     FcCacheInsert (cache, NULL);
823
824     return cache;
825
826 bail2:
827     free (cache);
828 bail1:
829     FcSerializeDestroy (serialize);
830     return NULL;
831 }
832
833
834 #ifdef _WIN32
835 #include <direct.h>
836 #define mkdir(path,mode) _mkdir(path)
837 #endif
838
839 static FcBool
840 FcMakeDirectory (const FcChar8 *dir)
841 {
842     FcChar8 *parent;
843     FcBool  ret;
844
845     if (strlen ((char *) dir) == 0)
846         return FcFalse;
847
848     parent = FcStrDirname (dir);
849     if (!parent)
850         return FcFalse;
851     if (access ((char *) parent, F_OK) == 0)
852         ret = mkdir ((char *) dir, 0755) == 0 && chmod ((char *) dir, 0755) == 0;
853     else if (access ((char *) parent, F_OK) == -1)
854         ret = FcMakeDirectory (parent) && (mkdir ((char *) dir, 0755) == 0) && chmod ((char *) dir, 0755) == 0;
855     else
856         ret = FcFalse;
857     FcStrFree (parent);
858     return ret;
859 }
860
861 /* write serialized state to the cache file */
862 FcBool
863 FcDirCacheWrite (FcCache *cache, FcConfig *config)
864 {
865     FcChar8         *dir = FcCacheDir (cache);
866     FcChar8         cache_base[CACHEBASE_LEN];
867     FcChar8         *cache_hashed;
868     int             fd;
869     FcAtomic        *atomic;
870     FcStrList       *list;
871     FcChar8         *cache_dir = NULL;
872     FcChar8         *test_dir, *d = NULL;
873     FcCacheSkip     *skip;
874     struct stat     cache_stat;
875     unsigned int    magic;
876     int             written;
877     const FcChar8   *sysroot = FcConfigGetSysRoot (config);
878
879     /*
880      * Write it to the first directory in the list which is writable
881      */
882
883     list = FcStrListCreate (config->cacheDirs);
884     if (!list)
885         return FcFalse;
886     while ((test_dir = FcStrListNext (list)))
887     {
888         if (d)
889             FcStrFree (d);
890         if (sysroot)
891             d = FcStrBuildFilename (sysroot, test_dir, NULL);
892         else
893             d = FcStrCopyFilename (test_dir);
894
895         if (access ((char *) d, W_OK) == 0)
896         {
897             cache_dir = FcStrCopyFilename (d);
898             break;
899         }
900         else
901         {
902             /*
903              * If the directory doesn't exist, try to create it
904              */
905             if (access ((char *) d, F_OK) == -1) {
906                 if (FcMakeDirectory (d))
907                 {
908                     cache_dir = FcStrCopyFilename (d);
909                     /* Create CACHEDIR.TAG */
910                     FcDirCacheCreateTagFile (d);
911                     break;
912                 }
913             }
914             /*
915              * Otherwise, try making it writable
916              */
917             else if (chmod ((char *) d, 0755) == 0)
918             {
919                 cache_dir = FcStrCopyFilename (d);
920                 /* Try to create CACHEDIR.TAG too */
921                 FcDirCacheCreateTagFile (d);
922                 break;
923             }
924         }
925     }
926     if (d)
927         FcStrFree (d);
928     FcStrListDone (list);
929     if (!cache_dir)
930         return FcFalse;
931
932     FcDirCacheBasename (dir, cache_base);
933     cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
934     if (!cache_hashed)
935         return FcFalse;
936     FcStrFree (cache_dir);
937
938     if (FcDebug () & FC_DBG_CACHE)
939         printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
940                 dir, cache_hashed);
941
942     atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
943     if (!atomic)
944         goto bail1;
945
946     if (!FcAtomicLock (atomic))
947         goto bail3;
948
949     fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
950     if (fd == -1)
951         goto bail4;
952
953     /* Temporarily switch magic to MMAP while writing to file */
954     magic = cache->magic;
955     if (magic != FC_CACHE_MAGIC_MMAP)
956         cache->magic = FC_CACHE_MAGIC_MMAP;
957
958     /*
959      * Write cache contents to file
960      */
961     written = write (fd, cache, cache->size);
962
963     /* Switch magic back */
964     if (magic != FC_CACHE_MAGIC_MMAP)
965         cache->magic = magic;
966
967     if (written != cache->size)
968     {
969         perror ("write cache");
970         goto bail5;
971     }
972
973     close(fd);
974     if (!FcAtomicReplaceOrig(atomic))
975         goto bail4;
976
977     /* If the file is small, update the cache chain entry such that the
978      * new cache file is not read again.  If it's large, we don't do that
979      * such that we reload it, using mmap, which is shared across processes.
980      */
981     if (cache->size < FC_CACHE_MIN_MMAP && FcStat (cache_hashed, &cache_stat))
982     {
983         lock_cache ();
984         if ((skip = FcCacheFindByAddrUnlocked (cache)))
985         {
986             skip->cache_dev = cache_stat.st_dev;
987             skip->cache_ino = cache_stat.st_ino;
988             skip->cache_mtime = cache_stat.st_mtime;
989         }
990         unlock_cache ();
991     }
992
993     FcStrFree (cache_hashed);
994     FcAtomicUnlock (atomic);
995     FcAtomicDestroy (atomic);
996     return FcTrue;
997
998  bail5:
999     close (fd);
1000  bail4:
1001     FcAtomicUnlock (atomic);
1002  bail3:
1003     FcAtomicDestroy (atomic);
1004  bail1:
1005     FcStrFree (cache_hashed);
1006     return FcFalse;
1007 }
1008
1009 FcBool
1010 FcDirCacheClean (const FcChar8 *cache_dir, FcBool verbose)
1011 {
1012     DIR         *d;
1013     struct dirent *ent;
1014     FcChar8     *dir;
1015     FcBool      ret = FcTrue;
1016     FcBool      remove;
1017     FcCache     *cache;
1018     struct stat target_stat;
1019     const FcChar8 *sysroot;
1020
1021     /* FIXME: this API needs to support non-current FcConfig */
1022     sysroot = FcConfigGetSysRoot (NULL);
1023     if (sysroot)
1024         dir = FcStrBuildFilename (sysroot, cache_dir, NULL);
1025     else
1026         dir = FcStrCopyFilename (cache_dir);
1027     if (!dir)
1028     {
1029         fprintf (stderr, "Fontconfig error: %s: out of memory\n", cache_dir);
1030         return FcFalse;
1031     }
1032     if (access ((char *) dir, W_OK) != 0)
1033     {
1034         if (verbose || FcDebug () & FC_DBG_CACHE)
1035             printf ("%s: not cleaning %s cache directory\n", dir,
1036                     access ((char *) dir, F_OK) == 0 ? "unwritable" : "non-existent");
1037         goto bail0;
1038     }
1039     if (verbose || FcDebug () & FC_DBG_CACHE)
1040         printf ("%s: cleaning cache directory\n", dir);
1041     d = opendir ((char *) dir);
1042     if (!d)
1043     {
1044         perror ((char *) dir);
1045         ret = FcFalse;
1046         goto bail0;
1047     }
1048     while ((ent = readdir (d)))
1049     {
1050         FcChar8 *file_name;
1051         const FcChar8   *target_dir;
1052
1053         if (ent->d_name[0] == '.')
1054             continue;
1055         /* skip cache files for different architectures and */
1056         /* files which are not cache files at all */
1057         if (strlen(ent->d_name) != 32 + strlen ("-" FC_ARCHITECTURE FC_CACHE_SUFFIX) ||
1058             strcmp(ent->d_name + 32, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX))
1059             continue;
1060
1061         file_name = FcStrBuildFilename (dir, (FcChar8 *)ent->d_name, NULL);
1062         if (!file_name)
1063         {
1064             fprintf (stderr, "Fontconfig error: %s: allocation failure\n", dir);
1065             ret = FcFalse;
1066             break;
1067         }
1068         remove = FcFalse;
1069         cache = FcDirCacheLoadFile (file_name, NULL);
1070         if (!cache)
1071         {
1072             if (verbose || FcDebug () & FC_DBG_CACHE)
1073                 printf ("%s: invalid cache file: %s\n", dir, ent->d_name);
1074             remove = FcTrue;
1075         }
1076         else
1077         {
1078             target_dir = FcCacheDir (cache);
1079             if (stat ((char *) target_dir, &target_stat) < 0)
1080             {
1081                 if (verbose || FcDebug () & FC_DBG_CACHE)
1082                     printf ("%s: %s: missing directory: %s \n",
1083                             dir, ent->d_name, target_dir);
1084                 remove = FcTrue;
1085             }
1086             FcDirCacheUnload (cache);
1087         }
1088         if (remove)
1089         {
1090             if (unlink ((char *) file_name) < 0)
1091             {
1092                 perror ((char *) file_name);
1093                 ret = FcFalse;
1094             }
1095         }
1096         FcStrFree (file_name);
1097     }
1098
1099     closedir (d);
1100   bail0:
1101     FcStrFree (dir);
1102
1103     return ret;
1104 }
1105
1106 /*
1107  * Hokey little macro trick to permit the definitions of C functions
1108  * with the same name as CPP macros
1109  */
1110 #define args1(x)            (x)
1111 #define args2(x,y)          (x,y)
1112
1113 const FcChar8 *
1114 FcCacheDir args1(const FcCache *c)
1115 {
1116     return FcCacheDir (c);
1117 }
1118
1119 FcFontSet *
1120 FcCacheCopySet args1(const FcCache *c)
1121 {
1122     FcFontSet   *old = FcCacheSet (c);
1123     FcFontSet   *new = FcFontSetCreate ();
1124     int         i;
1125
1126     if (!new)
1127         return NULL;
1128     for (i = 0; i < old->nfont; i++)
1129     {
1130         FcPattern   *font = FcFontSetFont (old, i);
1131         
1132         FcPatternReference (font);
1133         if (!FcFontSetAdd (new, font))
1134         {
1135             FcFontSetDestroy (new);
1136             return NULL;
1137         }
1138     }
1139     return new;
1140 }
1141
1142 const FcChar8 *
1143 FcCacheSubdir args2(const FcCache *c, int i)
1144 {
1145     return FcCacheSubdir (c, i);
1146 }
1147
1148 int
1149 FcCacheNumSubdir args1(const FcCache *c)
1150 {
1151     return c->dirs_count;
1152 }
1153
1154 int
1155 FcCacheNumFont args1(const FcCache *c)
1156 {
1157     return FcCacheSet(c)->nfont;
1158 }
1159
1160 /*
1161  * This code implements the MD5 message-digest algorithm.
1162  * The algorithm is due to Ron Rivest.  This code was
1163  * written by Colin Plumb in 1993, no copyright is claimed.
1164  * This code is in the public domain; do with it what you wish.
1165  *
1166  * Equivalent code is available from RSA Data Security, Inc.
1167  * This code has been tested against that, and is equivalent,
1168  * except that you don't need to include two pages of legalese
1169  * with every copy.
1170  *
1171  * To compute the message digest of a chunk of bytes, declare an
1172  * MD5Context structure, pass it to MD5Init, call MD5Update as
1173  * needed on buffers full of bytes, and then call MD5Final, which
1174  * will fill a supplied 16-byte array with the digest.
1175  */
1176
1177 #ifndef HIGHFIRST
1178 #define byteReverse(buf, len)   /* Nothing */
1179 #else
1180 /*
1181  * Note: this code is harmless on little-endian machines.
1182  */
1183 void byteReverse(unsigned char *buf, unsigned longs)
1184 {
1185     FcChar32 t;
1186     do {
1187         t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1188             ((unsigned) buf[1] << 8 | buf[0]);
1189         *(FcChar32 *) buf = t;
1190         buf += 4;
1191     } while (--longs);
1192 }
1193 #endif
1194
1195 /*
1196  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
1197  * initialization constants.
1198  */
1199 static void MD5Init(struct MD5Context *ctx)
1200 {
1201     ctx->buf[0] = 0x67452301;
1202     ctx->buf[1] = 0xefcdab89;
1203     ctx->buf[2] = 0x98badcfe;
1204     ctx->buf[3] = 0x10325476;
1205
1206     ctx->bits[0] = 0;
1207     ctx->bits[1] = 0;
1208 }
1209
1210 /*
1211  * Update context to reflect the concatenation of another buffer full
1212  * of bytes.
1213  */
1214 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len)
1215 {
1216     FcChar32 t;
1217
1218     /* Update bitcount */
1219
1220     t = ctx->bits[0];
1221     if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
1222         ctx->bits[1]++;         /* Carry from low to high */
1223     ctx->bits[1] += len >> 29;
1224
1225     t = (t >> 3) & 0x3f;        /* Bytes already in shsInfo->data */
1226
1227     /* Handle any leading odd-sized chunks */
1228
1229     if (t) {
1230         unsigned char *p = (unsigned char *) ctx->in + t;
1231
1232         t = 64 - t;
1233         if (len < t) {
1234             memcpy(p, buf, len);
1235             return;
1236         }
1237         memcpy(p, buf, t);
1238         byteReverse(ctx->in, 16);
1239         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1240         buf += t;
1241         len -= t;
1242     }
1243     /* Process data in 64-byte chunks */
1244
1245     while (len >= 64) {
1246         memcpy(ctx->in, buf, 64);
1247         byteReverse(ctx->in, 16);
1248         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1249         buf += 64;
1250         len -= 64;
1251     }
1252
1253     /* Handle any remaining bytes of data. */
1254
1255     memcpy(ctx->in, buf, len);
1256 }
1257
1258 /*
1259  * Final wrapup - pad to 64-byte boundary with the bit pattern
1260  * 1 0* (64-bit count of bits processed, MSB-first)
1261  */
1262 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
1263 {
1264     unsigned count;
1265     unsigned char *p;
1266
1267     /* Compute number of bytes mod 64 */
1268     count = (ctx->bits[0] >> 3) & 0x3F;
1269
1270     /* Set the first char of padding to 0x80.  This is safe since there is
1271        always at least one byte free */
1272     p = ctx->in + count;
1273     *p++ = 0x80;
1274
1275     /* Bytes of padding needed to make 64 bytes */
1276     count = 64 - 1 - count;
1277
1278     /* Pad out to 56 mod 64 */
1279     if (count < 8) {
1280         /* Two lots of padding:  Pad the first block to 64 bytes */
1281         memset(p, 0, count);
1282         byteReverse(ctx->in, 16);
1283         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1284
1285         /* Now fill the next block with 56 bytes */
1286         memset(ctx->in, 0, 56);
1287     } else {
1288         /* Pad block to 56 bytes */
1289         memset(p, 0, count - 8);
1290     }
1291     byteReverse(ctx->in, 14);
1292
1293     /* Append length in bits and transform */
1294     ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
1295     ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
1296
1297     MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1298     byteReverse((unsigned char *) ctx->buf, 4);
1299     memcpy(digest, ctx->buf, 16);
1300     memset(ctx, 0, sizeof(*ctx));        /* In case it's sensitive */
1301 }
1302
1303
1304 /* The four core functions - F1 is optimized somewhat */
1305
1306 /* #define F1(x, y, z) (x & y | ~x & z) */
1307 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1308 #define F2(x, y, z) F1(z, x, y)
1309 #define F3(x, y, z) (x ^ y ^ z)
1310 #define F4(x, y, z) (y ^ (x | ~z))
1311
1312 /* This is the central step in the MD5 algorithm. */
1313 #define MD5STEP(f, w, x, y, z, data, s) \
1314         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
1315
1316 /*
1317  * The core of the MD5 algorithm, this alters an existing MD5 hash to
1318  * reflect the addition of 16 longwords of new data.  MD5Update blocks
1319  * the data and converts bytes into longwords for this routine.
1320  */
1321 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
1322 {
1323     register FcChar32 a, b, c, d;
1324
1325     a = buf[0];
1326     b = buf[1];
1327     c = buf[2];
1328     d = buf[3];
1329
1330     MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1331     MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1332     MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1333     MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1334     MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1335     MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1336     MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1337     MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1338     MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1339     MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1340     MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1341     MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1342     MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1343     MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1344     MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1345     MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1346
1347     MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1348     MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1349     MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1350     MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1351     MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1352     MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1353     MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1354     MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1355     MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1356     MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1357     MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1358     MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1359     MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1360     MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1361     MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1362     MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1363
1364     MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1365     MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1366     MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1367     MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1368     MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1369     MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1370     MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1371     MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1372     MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1373     MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1374     MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1375     MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1376     MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1377     MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1378     MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1379     MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1380
1381     MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1382     MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1383     MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1384     MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1385     MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1386     MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1387     MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1388     MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1389     MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1390     MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1391     MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1392     MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1393     MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1394     MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1395     MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1396     MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1397
1398     buf[0] += a;
1399     buf[1] += b;
1400     buf[2] += c;
1401     buf[3] += d;
1402 }
1403
1404 FcBool
1405 FcDirCacheCreateTagFile (const FcChar8 *cache_dir)
1406 {
1407     FcChar8             *cache_tag;
1408     int                  fd;
1409     FILE                *fp;
1410     FcAtomic            *atomic;
1411     static const FcChar8 cache_tag_contents[] =
1412         "Signature: 8a477f597d28d172789f06886806bc55\n"
1413         "# This file is a cache directory tag created by fontconfig.\n"
1414         "# For information about cache directory tags, see:\n"
1415         "#       http://www.brynosaurus.com/cachedir/\n";
1416     static size_t        cache_tag_contents_size = sizeof (cache_tag_contents) - 1;
1417     FcBool               ret = FcFalse;
1418
1419     if (!cache_dir)
1420         return FcFalse;
1421
1422     if (access ((char *) cache_dir, W_OK) == 0)
1423     {
1424         /* Create CACHEDIR.TAG */
1425         cache_tag = FcStrBuildFilename (cache_dir, "CACHEDIR.TAG", NULL);
1426         if (!cache_tag)
1427             return FcFalse;
1428         atomic = FcAtomicCreate ((FcChar8 *)cache_tag);
1429         if (!atomic)
1430             goto bail1;
1431         if (!FcAtomicLock (atomic))
1432             goto bail2;
1433         fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0644);
1434         if (fd == -1)
1435             goto bail3;
1436         fp = fdopen(fd, "wb");
1437         if (fp == NULL)
1438             goto bail3;
1439
1440         fwrite(cache_tag_contents, cache_tag_contents_size, sizeof (FcChar8), fp);
1441         fclose(fp);
1442
1443         if (!FcAtomicReplaceOrig(atomic))
1444             goto bail3;
1445
1446         ret = FcTrue;
1447       bail3:
1448         FcAtomicUnlock (atomic);
1449       bail2:
1450         FcAtomicDestroy (atomic);
1451       bail1:
1452         FcStrFree (cache_tag);
1453     }
1454
1455     if (FcDebug () & FC_DBG_CACHE)
1456     {
1457         if (ret)
1458             printf ("Created CACHEDIR.TAG at %s\n", cache_dir);
1459         else
1460             printf ("Unable to create CACHEDIR.TAG at %s\n", cache_dir);
1461     }
1462
1463     return ret;
1464 }
1465
1466 void
1467 FcCacheCreateTagFile (const FcConfig *config)
1468 {
1469     FcChar8   *cache_dir = NULL, *d = NULL;
1470     FcStrList *list;
1471     const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1472
1473     list = FcConfigGetCacheDirs (config);
1474     if (!list)
1475         return;
1476
1477     while ((cache_dir = FcStrListNext (list)))
1478     {
1479         if (d)
1480             FcStrFree (d);
1481         if (sysroot)
1482             d = FcStrBuildFilename (sysroot, cache_dir, NULL);
1483         else
1484             d = FcStrCopyFilename (cache_dir);
1485         if (FcDirCacheCreateTagFile (d))
1486             break;
1487     }
1488     if (d)
1489         FcStrFree (d);
1490     FcStrListDone (list);
1491 }
1492
1493 #define __fccache__
1494 #include "fcaliastail.h"
1495 #undef __fccache__