Imported Upstream version 2.13.1
[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 #include "fcint.h"
24 #include "fcarch.h"
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <fcntl.h>
28 #include <dirent.h>
29 #include <string.h>
30 #include <limits.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <sys/time.h>
34 #include <assert.h>
35 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
36 #  include <unistd.h>
37 #  include <sys/mman.h>
38 #endif
39 #if defined(_WIN32)
40 #include <sys/locking.h>
41 #else
42 #include <uuid/uuid.h>
43 #endif
44
45 #ifndef O_BINARY
46 #define O_BINARY 0
47 #endif
48
49 FcBool
50 FcDirCacheCreateUUID (FcChar8  *dir,
51                       FcBool    force,
52                       FcConfig *config)
53 {
54     const FcChar8 *sysroot = FcConfigGetSysRoot (config);
55     FcChar8 *target;
56     FcBool ret = FcTrue;
57 #ifndef _WIN32
58     FcChar8 *uuidname;
59
60     if (sysroot)
61         target = FcStrBuildFilename (sysroot, dir, NULL);
62     else
63         target = FcStrdup (dir);
64     uuidname = FcStrBuildFilename (target, ".uuid", NULL);
65
66     if (!uuidname)
67     {
68         FcStrFree (target);
69         return FcFalse;
70     }
71
72     if (force || access ((const char *) uuidname, F_OK) < 0)
73     {
74         FcAtomic *atomic;
75         int fd;
76         uuid_t uuid;
77         char out[37];
78         FcBool (* hash_add) (FcHashTable *, void*, void*);
79         struct stat statb;
80         struct timeval times[2];
81
82         if (FcStat (target, &statb) != 0)
83         {
84             ret = FcFalse;
85             goto bail1;
86         }
87         atomic = FcAtomicCreate (uuidname);
88         if (!atomic)
89         {
90             ret = FcFalse;
91             goto bail1;
92         }
93         if (!FcAtomicLock (atomic))
94         {
95             ret = FcFalse;
96             goto bail2;
97         }
98         fd = FcOpen ((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0644);
99         if (fd == -1)
100         {
101             ret = FcFalse;
102             goto bail3;
103         }
104         uuid_generate_random (uuid);
105         if (force)
106             hash_add = FcHashTableReplace;
107         else
108             hash_add = FcHashTableAdd;
109         if (!hash_add (config->uuid_table, target, uuid))
110         {
111             ret = FcFalse;
112             FcAtomicDeleteNew (atomic);
113             close (fd);
114             goto bail3;
115         }
116         uuid_unparse (uuid, out);
117         if (FcDebug () & FC_DBG_CACHE)
118             printf ("FcDirCacheCreateUUID %s: %s\n", uuidname, out);
119         write (fd, out, strlen (out));
120         close (fd);
121         FcAtomicReplaceOrig (atomic);
122     bail3:
123         FcAtomicUnlock (atomic);
124     bail2:
125         FcAtomicDestroy (atomic);
126
127         if (ret)
128         {
129             /* revert mtime of the directory */
130             times[0].tv_sec = statb.st_atime;
131             times[1].tv_sec = statb.st_mtime;
132 #ifdef HAVE_STRUCT_STAT_ST_MTIM
133             times[0].tv_usec = statb.st_atim.tv_nsec / 1000;
134             times[1].tv_usec = statb.st_mtim.tv_nsec / 1000;
135 #else
136             times[0].tv_usec = 0;
137             times[1].tv_usec = 0;
138 #endif
139             if (utimes ((const  char *) target, times) != 0)
140             {
141                 fprintf (stderr, "Unable to revert mtime: %s\n", target);
142             }
143         }
144     }
145 bail1:
146     FcStrFree (uuidname);
147     FcStrFree (target);
148 #endif
149
150     return ret;
151 }
152
153 FcBool
154 FcDirCacheDeleteUUID (const FcChar8  *dir,
155                       FcConfig       *config)
156 {
157     const FcChar8 *sysroot = FcConfigGetSysRoot (config);
158     FcChar8 *target;
159     FcBool ret = FcTrue;
160
161     if (sysroot)
162         target = FcStrBuildFilename (sysroot, dir, ".uuid", NULL);
163     else
164         target = FcStrBuildFilename (dir, ".uuid", NULL);
165
166     ret = unlink ((char *) target) == 0;
167     FcHashTableRemove (config->uuid_table, target);
168     FcStrFree(target);
169
170     return ret;
171 }
172
173 #ifndef _WIN32
174 static void
175 FcDirCacheReadUUID (FcChar8  *dir,
176                     FcConfig *config)
177 {
178     void *u;
179     uuid_t uuid;
180     const FcChar8 *sysroot = FcConfigGetSysRoot (config);
181     FcChar8 *target;
182
183     if (sysroot)
184         target = FcStrBuildFilename (sysroot, dir, NULL);
185     else
186         target = FcStrdup (dir);
187
188     if (!FcHashTableFind (config->uuid_table, target, &u))
189     {
190         FcChar8 *uuidname = FcStrBuildFilename (target, ".uuid", NULL);
191         int fd;
192
193         if ((fd = FcOpen ((char *) uuidname, O_RDONLY)) >= 0)
194         {
195             char suuid[37];
196             ssize_t len;
197
198             memset (suuid, 0, sizeof (suuid));
199             len = read (fd, suuid, 36);
200             if (len != -1)
201             {
202                 suuid[len] = 0;
203                 memset (uuid, 0, sizeof (uuid));
204                 if (uuid_parse (suuid, uuid) == 0)
205                 {
206                     if (FcDebug () & FC_DBG_CACHE)
207                         printf ("FcDirCacheReadUUID %s -> %s\n", uuidname, suuid);
208                     FcHashTableAdd (config->uuid_table, target, uuid);
209                 }
210             }
211             close (fd);
212         }
213         else
214         {
215             if (FcDebug () & FC_DBG_CACHE)
216                 printf ("FcDirCacheReadUUID Unable to read %s\n", uuidname);
217         }
218         FcStrFree (uuidname);
219     }
220     else
221         FcHashUuidFree (u);
222     FcStrFree (target);
223 }
224 #endif
225
226 struct MD5Context {
227         FcChar32 buf[4];
228         FcChar32 bits[2];
229         unsigned char in[64];
230 };
231
232 static void MD5Init(struct MD5Context *ctx);
233 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len);
234 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx);
235 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16]);
236
237 #define CACHEBASE_LEN (1 + 36 + 1 + sizeof (FC_ARCHITECTURE) + sizeof (FC_CACHE_SUFFIX))
238
239 static FcBool
240 FcCacheIsMmapSafe (int fd)
241 {
242     enum {
243       MMAP_NOT_INITIALIZED = 0,
244       MMAP_USE,
245       MMAP_DONT_USE,
246       MMAP_CHECK_FS,
247     } status;
248     static void *static_status;
249
250     status = (intptr_t) fc_atomic_ptr_get (&static_status);
251
252     if (status == MMAP_NOT_INITIALIZED)
253     {
254         const char *env = getenv ("FONTCONFIG_USE_MMAP");
255         FcBool use;
256         if (env && FcNameBool ((const FcChar8 *) env, &use))
257             status =  use ? MMAP_USE : MMAP_DONT_USE;
258         else
259             status = MMAP_CHECK_FS;
260         (void) fc_atomic_ptr_cmpexch (&static_status, NULL, (void *) status);
261     }
262
263     if (status == MMAP_CHECK_FS)
264         return FcIsFsMmapSafe (fd);
265     else
266         return status == MMAP_USE;
267
268 }
269
270 static const char bin2hex[] = { '0', '1', '2', '3',
271                                 '4', '5', '6', '7',
272                                 '8', '9', 'a', 'b',
273                                 'c', 'd', 'e', 'f' };
274
275 static FcChar8 *
276 FcDirCacheBasenameMD5 (const FcChar8 *dir, FcChar8 cache_base[CACHEBASE_LEN])
277 {
278     unsigned char       hash[16];
279     FcChar8             *hex_hash;
280     int                 cnt;
281     struct MD5Context   ctx;
282
283     MD5Init (&ctx);
284     MD5Update (&ctx, (const unsigned char *)dir, strlen ((const char *) dir));
285
286     MD5Final (hash, &ctx);
287
288     cache_base[0] = '/';
289     hex_hash = cache_base + 1;
290     for (cnt = 0; cnt < 16; ++cnt)
291     {
292         hex_hash[2*cnt  ] = bin2hex[hash[cnt] >> 4];
293         hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
294     }
295     hex_hash[2*cnt] = 0;
296     strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
297
298     return cache_base;
299 }
300
301 #ifndef _WIN32
302 static FcChar8 *
303 FcDirCacheBasenameUUID (const FcChar8 *dir, FcChar8 cache_base[CACHEBASE_LEN], FcConfig *config)
304 {
305     void *u;
306     FcChar8 *target;
307     const FcChar8 *sysroot = FcConfigGetSysRoot (config);
308
309     if (sysroot)
310         target = FcStrBuildFilename (sysroot, dir, NULL);
311     else
312         target = FcStrdup (dir);
313     if (FcHashTableFind (config->uuid_table, target, &u))
314     {
315         uuid_unparse (u, (char *) cache_base);
316         strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
317         FcHashUuidFree (u);
318         FcStrFree (target);
319         return cache_base;
320     }
321     FcStrFree (target);
322     return NULL;
323 }
324 #endif
325
326 FcBool
327 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
328 {
329     FcChar8     *cache_hashed = NULL;
330     FcChar8     cache_base[CACHEBASE_LEN];
331     FcStrList   *list;
332     FcChar8     *cache_dir;
333     const FcChar8 *sysroot = FcConfigGetSysRoot (config);
334
335 #ifndef _WIN32
336     if (!FcDirCacheBasenameUUID (dir, cache_base, config))
337 #endif
338         FcDirCacheBasenameMD5 (dir, cache_base);
339
340     list = FcStrListCreate (config->cacheDirs);
341     if (!list)
342         return FcFalse;
343         
344     while ((cache_dir = FcStrListNext (list)))
345     {
346         if (sysroot)
347             cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
348         else
349             cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
350         if (!cache_hashed)
351             break;
352         (void) unlink ((char *) cache_hashed);
353         FcDirCacheDeleteUUID (dir, config);
354         FcStrFree (cache_hashed);
355     }
356     FcStrListDone (list);
357     /* return FcFalse if something went wrong */
358     if (cache_dir)
359         return FcFalse;
360     return FcTrue;
361 }
362
363 static int
364 FcDirCacheOpenFile (const FcChar8 *cache_file, struct stat *file_stat)
365 {
366     int fd;
367
368 #ifdef _WIN32
369     if (FcStat (cache_file, file_stat) < 0)
370         return -1;
371 #endif
372     fd = FcOpen((char *) cache_file, O_RDONLY | O_BINARY);
373     if (fd < 0)
374         return fd;
375 #ifndef _WIN32
376     if (fstat (fd, file_stat) < 0)
377     {
378         close (fd);
379         return -1;
380     }
381 #endif
382     return fd;
383 }
384
385 /*
386  * Look for a cache file for the specified dir. Attempt
387  * to use each one we find, stopping when the callback
388  * indicates success
389  */
390 static FcBool
391 FcDirCacheProcess (FcConfig *config, const FcChar8 *dir,
392                    FcBool (*callback) (FcConfig *config, int fd, struct stat *fd_stat,
393                                        struct stat *dir_stat, void *closure),
394                    void *closure, FcChar8 **cache_file_ret)
395 {
396     int         fd = -1;
397     FcChar8     cache_base[CACHEBASE_LEN];
398     FcStrList   *list;
399     FcChar8     *cache_dir, *d;
400     struct stat file_stat, dir_stat;
401     FcBool      ret = FcFalse;
402     const FcChar8 *sysroot = FcConfigGetSysRoot (config);
403
404     if (sysroot)
405         d = FcStrBuildFilename (sysroot, dir, NULL);
406     else
407         d = FcStrdup (dir);
408     if (FcStatChecksum (d, &dir_stat) < 0)
409     {
410         FcStrFree (d);
411         return FcFalse;
412     }
413     FcStrFree (d);
414
415 #ifndef _WIN32
416     if (!FcDirCacheBasenameUUID (dir, cache_base, config))
417 #endif
418         FcDirCacheBasenameMD5 (dir, cache_base);
419
420     list = FcStrListCreate (config->cacheDirs);
421     if (!list)
422         return FcFalse;
423         
424     while ((cache_dir = FcStrListNext (list)))
425     {
426         FcChar8 *cache_hashed;
427
428         if (sysroot)
429             cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
430         else
431             cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
432         if (!cache_hashed)
433             break;
434         fd = FcDirCacheOpenFile (cache_hashed, &file_stat);
435         if (fd >= 0) {
436             ret = (*callback) (config, fd, &file_stat, &dir_stat, closure);
437             close (fd);
438             if (ret)
439             {
440                 if (cache_file_ret)
441                     *cache_file_ret = cache_hashed;
442                 else
443                     FcStrFree (cache_hashed);
444                 break;
445             }
446         }
447         FcStrFree (cache_hashed);
448     }
449     FcStrListDone (list);
450
451     return ret;
452 }
453
454 #define FC_CACHE_MIN_MMAP   1024
455
456 /*
457  * Skip list element, make sure the 'next' pointer is the last thing
458  * in the structure, it will be allocated large enough to hold all
459  * of the necessary pointers
460  */
461
462 typedef struct _FcCacheSkip FcCacheSkip;
463
464 struct _FcCacheSkip {
465     FcCache         *cache;
466     FcRef           ref;
467     intptr_t        size;
468     void           *allocated;
469     dev_t           cache_dev;
470     ino_t           cache_ino;
471     time_t          cache_mtime;
472     long            cache_mtime_nano;
473     FcCacheSkip     *next[1];
474 };
475
476 /*
477  * The head of the skip list; pointers for every possible level
478  * in the skip list, plus the largest level in the list
479  */
480
481 #define FC_CACHE_MAX_LEVEL  16
482
483 /* Protected by cache_lock below */
484 static FcCacheSkip      *fcCacheChains[FC_CACHE_MAX_LEVEL];
485 static int              fcCacheMaxLevel;
486
487
488 static FcMutex *cache_lock;
489
490 static void
491 lock_cache (void)
492 {
493   FcMutex *lock;
494 retry:
495   lock = fc_atomic_ptr_get (&cache_lock);
496   if (!lock) {
497     lock = (FcMutex *) malloc (sizeof (FcMutex));
498     FcMutexInit (lock);
499     if (!fc_atomic_ptr_cmpexch (&cache_lock, NULL, lock)) {
500       FcMutexFinish (lock);
501       goto retry;
502     }
503
504     FcMutexLock (lock);
505     /* Initialize random state */
506     FcRandom ();
507     return;
508   }
509   FcMutexLock (lock);
510 }
511
512 static void
513 unlock_cache (void)
514 {
515   FcMutexUnlock (cache_lock);
516 }
517
518 static void
519 free_lock (void)
520 {
521   FcMutex *lock;
522   lock = fc_atomic_ptr_get (&cache_lock);
523   if (lock && fc_atomic_ptr_cmpexch (&cache_lock, lock, NULL)) {
524     FcMutexFinish (lock);
525     free (lock);
526   }
527 }
528
529
530
531 /*
532  * Generate a random level number, distributed
533  * so that each level is 1/4 as likely as the one before
534  *
535  * Note that level numbers run 1 <= level <= MAX_LEVEL
536  */
537 static int
538 random_level (void)
539 {
540     /* tricky bit -- each bit is '1' 75% of the time */
541     long int    bits = FcRandom () | FcRandom ();
542     int level = 0;
543
544     while (++level < FC_CACHE_MAX_LEVEL)
545     {
546         if (bits & 1)
547             break;
548         bits >>= 1;
549     }
550     return level;
551 }
552
553 /*
554  * Insert cache into the list
555  */
556 static FcBool
557 FcCacheInsert (FcCache *cache, struct stat *cache_stat)
558 {
559     FcCacheSkip    **update[FC_CACHE_MAX_LEVEL];
560     FcCacheSkip    *s, **next;
561     int             i, level;
562
563     lock_cache ();
564
565     /*
566      * Find links along each chain
567      */
568     next = fcCacheChains;
569     for (i = fcCacheMaxLevel; --i >= 0; )
570     {
571         for (; (s = next[i]); next = s->next)
572             if (s->cache > cache)
573                 break;
574         update[i] = &next[i];
575     }
576
577     /*
578      * Create new list element
579      */
580     level = random_level ();
581     if (level > fcCacheMaxLevel)
582     {
583         level = fcCacheMaxLevel + 1;
584         update[fcCacheMaxLevel] = &fcCacheChains[fcCacheMaxLevel];
585         fcCacheMaxLevel = level;
586     }
587
588     s = malloc (sizeof (FcCacheSkip) + (level - 1) * sizeof (FcCacheSkip *));
589     if (!s)
590         return FcFalse;
591
592     s->cache = cache;
593     s->size = cache->size;
594     s->allocated = NULL;
595     FcRefInit (&s->ref, 1);
596     if (cache_stat)
597     {
598         s->cache_dev = cache_stat->st_dev;
599         s->cache_ino = cache_stat->st_ino;
600         s->cache_mtime = cache_stat->st_mtime;
601 #ifdef HAVE_STRUCT_STAT_ST_MTIM
602         s->cache_mtime_nano = cache_stat->st_mtim.tv_nsec;
603 #else
604         s->cache_mtime_nano = 0;
605 #endif
606     }
607     else
608     {
609         s->cache_dev = 0;
610         s->cache_ino = 0;
611         s->cache_mtime = 0;
612         s->cache_mtime_nano = 0;
613     }
614
615     /*
616      * Insert into all fcCacheChains
617      */
618     for (i = 0; i < level; i++)
619     {
620         s->next[i] = *update[i];
621         *update[i] = s;
622     }
623
624     unlock_cache ();
625     return FcTrue;
626 }
627
628 static FcCacheSkip *
629 FcCacheFindByAddrUnlocked (void *object)
630 {
631     int     i;
632     FcCacheSkip    **next = fcCacheChains;
633     FcCacheSkip    *s;
634
635     if (!object)
636         return NULL;
637
638     /*
639      * Walk chain pointers one level at a time
640      */
641     for (i = fcCacheMaxLevel; --i >= 0;)
642         while (next[i] && (char *) object >= ((char *) next[i]->cache + next[i]->size))
643             next = next[i]->next;
644     /*
645      * Here we are
646      */
647     s = next[0];
648     if (s && (char *) object < ((char *) s->cache + s->size))
649         return s;
650     return NULL;
651 }
652
653 static FcCacheSkip *
654 FcCacheFindByAddr (void *object)
655 {
656     FcCacheSkip *ret;
657     lock_cache ();
658     ret = FcCacheFindByAddrUnlocked (object);
659     unlock_cache ();
660     return ret;
661 }
662
663 static void
664 FcCacheRemoveUnlocked (FcCache *cache)
665 {
666     FcCacheSkip     **update[FC_CACHE_MAX_LEVEL];
667     FcCacheSkip     *s, **next;
668     int             i;
669     void            *allocated;
670
671     /*
672      * Find links along each chain
673      */
674     next = fcCacheChains;
675     for (i = fcCacheMaxLevel; --i >= 0; )
676     {
677         for (; (s = next[i]); next = s->next)
678             if (s->cache >= cache)
679                 break;
680         update[i] = &next[i];
681     }
682     s = next[0];
683     for (i = 0; i < fcCacheMaxLevel && *update[i] == s; i++)
684         *update[i] = s->next[i];
685     while (fcCacheMaxLevel > 0 && fcCacheChains[fcCacheMaxLevel - 1] == NULL)
686         fcCacheMaxLevel--;
687
688     allocated = s->allocated;
689     while (allocated)
690     {
691         /* First element in allocated chunk is the free list */
692         next = *(void **)allocated;
693         free (allocated);
694         allocated = next;
695     }
696     free (s);
697 }
698
699 static FcCache *
700 FcCacheFindByStat (struct stat *cache_stat)
701 {
702     FcCacheSkip     *s;
703
704     lock_cache ();
705     for (s = fcCacheChains[0]; s; s = s->next[0])
706         if (s->cache_dev == cache_stat->st_dev &&
707             s->cache_ino == cache_stat->st_ino &&
708             s->cache_mtime == cache_stat->st_mtime)
709         {
710 #ifdef HAVE_STRUCT_STAT_ST_MTIM
711             if (s->cache_mtime_nano != cache_stat->st_mtim.tv_nsec)
712                 continue;
713 #endif
714             FcRefInc (&s->ref);
715             unlock_cache ();
716             return s->cache;
717         }
718     unlock_cache ();
719     return NULL;
720 }
721
722 static void
723 FcDirCacheDisposeUnlocked (FcCache *cache)
724 {
725     FcCacheRemoveUnlocked (cache);
726
727     switch (cache->magic) {
728     case FC_CACHE_MAGIC_ALLOC:
729         free (cache);
730         break;
731     case FC_CACHE_MAGIC_MMAP:
732 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
733         munmap (cache, cache->size);
734 #elif defined(_WIN32)
735         UnmapViewOfFile (cache);
736 #endif
737         break;
738     }
739 }
740
741 void
742 FcCacheObjectReference (void *object)
743 {
744     FcCacheSkip *skip = FcCacheFindByAddr (object);
745
746     if (skip)
747         FcRefInc (&skip->ref);
748 }
749
750 void
751 FcCacheObjectDereference (void *object)
752 {
753     FcCacheSkip *skip;
754
755     lock_cache ();
756     skip = FcCacheFindByAddrUnlocked (object);
757     if (skip)
758     {
759         if (FcRefDec (&skip->ref) == 1)
760             FcDirCacheDisposeUnlocked (skip->cache);
761     }
762     unlock_cache ();
763 }
764
765 void *
766 FcCacheAllocate (FcCache *cache, size_t len)
767 {
768     FcCacheSkip *skip;
769     void *allocated = NULL;
770
771     lock_cache ();
772     skip = FcCacheFindByAddrUnlocked (cache);
773     if (skip)
774     {
775       void *chunk = malloc (sizeof (void *) + len);
776       if (chunk)
777       {
778           /* First element in allocated chunk is the free list */
779           *(void **)chunk = skip->allocated;
780           skip->allocated = chunk;
781           /* Return the rest */
782           allocated = ((FcChar8 *)chunk) + sizeof (void *);
783       }
784     }
785     unlock_cache ();
786     return allocated;
787 }
788
789 void
790 FcCacheFini (void)
791 {
792     int             i;
793
794     for (i = 0; i < FC_CACHE_MAX_LEVEL; i++)
795         assert (fcCacheChains[i] == NULL);
796     assert (fcCacheMaxLevel == 0);
797
798     free_lock ();
799 }
800
801 static FcBool
802 FcCacheTimeValid (FcConfig *config, FcCache *cache, struct stat *dir_stat)
803 {
804     struct stat dir_static;
805     FcBool fnano = FcTrue;
806
807     if (!dir_stat)
808     {
809         const FcChar8 *sysroot = FcConfigGetSysRoot (config);
810         FcChar8 *d;
811
812         if (sysroot)
813             d = FcStrBuildFilename (sysroot, FcCacheDir (cache), NULL);
814         else
815             d = FcStrdup (FcCacheDir (cache));
816         if (FcStatChecksum (d, &dir_static) < 0)
817         {
818             FcStrFree (d);
819             return FcFalse;
820         }
821         FcStrFree (d);
822         dir_stat = &dir_static;
823     }
824 #ifdef HAVE_STRUCT_STAT_ST_MTIM
825     fnano = (cache->checksum_nano == dir_stat->st_mtim.tv_nsec);
826     if (FcDebug () & FC_DBG_CACHE)
827         printf ("FcCacheTimeValid dir \"%s\" cache checksum %d.%ld dir checksum %d.%ld\n",
828                 FcCacheDir (cache), cache->checksum, (long)cache->checksum_nano, (int) dir_stat->st_mtime, dir_stat->st_mtim.tv_nsec);
829 #else
830     if (FcDebug () & FC_DBG_CACHE)
831         printf ("FcCacheTimeValid dir \"%s\" cache checksum %d dir checksum %d\n",
832                 FcCacheDir (cache), cache->checksum, (int) dir_stat->st_mtime);
833 #endif
834
835     return cache->checksum == (int) dir_stat->st_mtime && fnano;
836 }
837
838 static FcBool
839 FcCacheOffsetsValid (FcCache *cache)
840 {
841     char                *base = (char *)cache;
842     char                *end = base + cache->size;
843     intptr_t            *dirs;
844     FcFontSet           *fs;
845     int                  i, j;
846
847     if (cache->dir < 0 || cache->dir > cache->size - sizeof (intptr_t) ||
848         memchr (base + cache->dir, '\0', cache->size - cache->dir) == NULL)
849         return FcFalse;
850
851     if (cache->dirs < 0 || cache->dirs >= cache->size ||
852         cache->dirs_count < 0 ||
853         cache->dirs_count > (cache->size - cache->dirs) / sizeof (intptr_t))
854         return FcFalse;
855
856     dirs = FcCacheDirs (cache);
857     if (dirs)
858     {
859         for (i = 0; i < cache->dirs_count; i++)
860         {
861             FcChar8     *dir;
862
863             if (dirs[i] < 0 ||
864                 dirs[i] > end - (char *) dirs - sizeof (intptr_t))
865                 return FcFalse;
866
867             dir = FcOffsetToPtr (dirs, dirs[i], FcChar8);
868             if (memchr (dir, '\0', end - (char *) dir) == NULL)
869                 return FcFalse;
870          }
871     }
872
873     if (cache->set < 0 || cache->set > cache->size - sizeof (FcFontSet))
874         return FcFalse;
875
876     fs = FcCacheSet (cache);
877     if (fs)
878     {
879         if (fs->nfont > (end - (char *) fs) / sizeof (FcPattern))
880             return FcFalse;
881
882         if (!FcIsEncodedOffset(fs->fonts))
883             return FcFalse;
884
885         for (i = 0; i < fs->nfont; i++)
886         {
887             FcPattern           *font = FcFontSetFont (fs, i);
888             FcPatternElt        *e;
889             FcValueListPtr       l;
890             char                *last_offset;
891
892             if ((char *) font < base ||
893                 (char *) font > end - sizeof (FcFontSet) ||
894                 font->elts_offset < 0 ||
895                 font->elts_offset > end - (char *) font ||
896                 font->num > (end - (char *) font - font->elts_offset) / sizeof (FcPatternElt) ||
897                 !FcRefIsConst (&font->ref))
898                 return FcFalse;
899
900
901             e = FcPatternElts(font);
902             if (e->values != 0 && !FcIsEncodedOffset(e->values))
903                 return FcFalse;
904
905             for (j = 0; j < font->num; j++)
906             {
907                 last_offset = (char *) font + font->elts_offset;
908                 for (l = FcPatternEltValues(&e[j]); l; l = FcValueListNext(l))
909                 {
910                     if ((char *) l < last_offset || (char *) l > end - sizeof (*l) ||
911                         (l->next != NULL && !FcIsEncodedOffset(l->next)))
912                         return FcFalse;
913                     last_offset = (char *) l + 1;
914                 }
915             }
916         }
917     }
918
919     return FcTrue;
920 }
921
922 /*
923  * Map a cache file into memory
924  */
925 static FcCache *
926 FcDirCacheMapFd (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat)
927 {
928     FcCache     *cache;
929     FcBool      allocated = FcFalse;
930
931     if (fd_stat->st_size > INTPTR_MAX ||
932         fd_stat->st_size < (int) sizeof (FcCache))
933         return NULL;
934     cache = FcCacheFindByStat (fd_stat);
935     if (cache)
936     {
937         if (FcCacheTimeValid (config, cache, dir_stat))
938             return cache;
939         FcDirCacheUnload (cache);
940         cache = NULL;
941     }
942
943     /*
944      * Large cache files are mmap'ed, smaller cache files are read. This
945      * balances the system cost of mmap against per-process memory usage.
946      */
947     if (FcCacheIsMmapSafe (fd) && fd_stat->st_size >= FC_CACHE_MIN_MMAP)
948     {
949 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
950         cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
951 #if (HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
952         posix_fadvise (fd, 0, fd_stat->st_size, POSIX_FADV_WILLNEED);
953 #endif
954         if (cache == MAP_FAILED)
955             cache = NULL;
956 #elif defined(_WIN32)
957         {
958             HANDLE hFileMap;
959
960             cache = NULL;
961             hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
962                                          PAGE_READONLY, 0, 0, NULL);
963             if (hFileMap != NULL)
964             {
965                 cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0,
966                                        fd_stat->st_size);
967                 CloseHandle (hFileMap);
968             }
969         }
970 #endif
971     }
972     if (!cache)
973     {
974         cache = malloc (fd_stat->st_size);
975         if (!cache)
976             return NULL;
977
978         if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
979         {
980             free (cache);
981             return NULL;
982         }
983         allocated = FcTrue;
984     }
985     if (cache->magic != FC_CACHE_MAGIC_MMAP ||
986         cache->version < FC_CACHE_VERSION_NUMBER ||
987         cache->size != (intptr_t) fd_stat->st_size ||
988         !FcCacheOffsetsValid (cache) ||
989         !FcCacheTimeValid (config, cache, dir_stat) ||
990         !FcCacheInsert (cache, fd_stat))
991     {
992         if (allocated)
993             free (cache);
994         else
995         {
996 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
997             munmap (cache, fd_stat->st_size);
998 #elif defined(_WIN32)
999             UnmapViewOfFile (cache);
1000 #endif
1001         }
1002         return NULL;
1003     }
1004
1005     /* Mark allocated caches so they're freed rather than unmapped */
1006     if (allocated)
1007         cache->magic = FC_CACHE_MAGIC_ALLOC;
1008         
1009     return cache;
1010 }
1011
1012 void
1013 FcDirCacheReference (FcCache *cache, int nref)
1014 {
1015     FcCacheSkip *skip = FcCacheFindByAddr (cache);
1016
1017     if (skip)
1018         FcRefAdd (&skip->ref, nref);
1019 }
1020
1021 void
1022 FcDirCacheUnload (FcCache *cache)
1023 {
1024     FcCacheObjectDereference (cache);
1025 }
1026
1027 static FcBool
1028 FcDirCacheMapHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure)
1029 {
1030     FcCache *cache = FcDirCacheMapFd (config, fd, fd_stat, dir_stat);
1031
1032     if (!cache)
1033         return FcFalse;
1034     *((FcCache **) closure) = cache;
1035     return FcTrue;
1036 }
1037
1038 FcCache *
1039 FcDirCacheLoad (const FcChar8 *dir, FcConfig *config, FcChar8 **cache_file)
1040 {
1041     FcCache *cache = NULL;
1042
1043 #ifndef _WIN32
1044     FcDirCacheReadUUID ((FcChar8 *) dir, config);
1045 #endif
1046     if (!FcDirCacheProcess (config, dir,
1047                             FcDirCacheMapHelper,
1048                             &cache, cache_file))
1049         return NULL;
1050
1051     return cache;
1052 }
1053
1054 FcCache *
1055 FcDirCacheLoadFile (const FcChar8 *cache_file, struct stat *file_stat)
1056 {
1057     int fd;
1058     FcCache *cache;
1059     struct stat my_file_stat;
1060
1061     if (!file_stat)
1062         file_stat = &my_file_stat;
1063     fd = FcDirCacheOpenFile (cache_file, file_stat);
1064     if (fd < 0)
1065         return NULL;
1066     cache = FcDirCacheMapFd (FcConfigGetCurrent (), fd, file_stat, NULL);
1067     close (fd);
1068     return cache;
1069 }
1070
1071 static int
1072 FcDirChecksum (struct stat *statb)
1073 {
1074     int                 ret = (int) statb->st_mtime;
1075     char                *endptr;
1076     char                *source_date_epoch;
1077     unsigned long long  epoch;
1078
1079     source_date_epoch = getenv("SOURCE_DATE_EPOCH");
1080     if (source_date_epoch)
1081     {
1082         epoch = strtoull(source_date_epoch, &endptr, 10);
1083
1084         if (endptr == source_date_epoch)
1085             fprintf (stderr,
1086                      "Fontconfig: SOURCE_DATE_EPOCH invalid\n");
1087         else if ((errno == ERANGE && (epoch == ULLONG_MAX || epoch == 0))
1088                 || (errno != 0 && epoch == 0))
1089             fprintf (stderr,
1090                      "Fontconfig: SOURCE_DATE_EPOCH: strtoull: %s: %llu\n",
1091                      strerror(errno), epoch);
1092         else if (*endptr != '\0')
1093             fprintf (stderr,
1094                      "Fontconfig: SOURCE_DATE_EPOCH has trailing garbage\n");
1095         else if (epoch > ULONG_MAX)
1096             fprintf (stderr,
1097                      "Fontconfig: SOURCE_DATE_EPOCH must be <= %lu but saw: %llu\n",
1098                      ULONG_MAX, epoch);
1099         else if (epoch < ret)
1100             /* Only override if directory is newer */
1101             ret = (int) epoch;
1102     }
1103
1104     return ret;
1105 }
1106
1107 static int64_t
1108 FcDirChecksumNano (struct stat *statb)
1109 {
1110 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1111     /* No nanosecond component to parse */
1112     if (getenv("SOURCE_DATE_EPOCH"))
1113         return 0;
1114     return statb->st_mtim.tv_nsec;
1115 #else
1116     return 0;
1117 #endif
1118 }
1119
1120 /*
1121  * Validate a cache file by reading the header and checking
1122  * the magic number and the size field
1123  */
1124 static FcBool
1125 FcDirCacheValidateHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure FC_UNUSED)
1126 {
1127     FcBool  ret = FcTrue;
1128     FcCache     c;
1129
1130     if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
1131         ret = FcFalse;
1132     else if (c.magic != FC_CACHE_MAGIC_MMAP)
1133         ret = FcFalse;
1134     else if (c.version < FC_CACHE_VERSION_NUMBER)
1135         ret = FcFalse;
1136     else if (fd_stat->st_size != c.size)
1137         ret = FcFalse;
1138     else if (c.checksum != FcDirChecksum (dir_stat))
1139         ret = FcFalse;
1140 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1141     else if (c.checksum_nano != FcDirChecksumNano (dir_stat))
1142         ret = FcFalse;
1143 #endif
1144     return ret;
1145 }
1146
1147 static FcBool
1148 FcDirCacheValidConfig (const FcChar8 *dir, FcConfig *config)
1149 {
1150     return FcDirCacheProcess (config, dir,
1151                               FcDirCacheValidateHelper,
1152                               NULL, NULL);
1153 }
1154
1155 FcBool
1156 FcDirCacheValid (const FcChar8 *dir)
1157 {
1158     FcConfig    *config;
1159
1160     config = FcConfigGetCurrent ();
1161     if (!config)
1162         return FcFalse;
1163
1164     return FcDirCacheValidConfig (dir, config);
1165 }
1166
1167 /*
1168  * Build a cache structure from the given contents
1169  */
1170 FcCache *
1171 FcDirCacheBuild (FcFontSet *set, const FcChar8 *dir, struct stat *dir_stat, FcStrSet *dirs)
1172 {
1173     FcSerialize *serialize = FcSerializeCreate ();
1174     FcCache *cache;
1175     int i;
1176     FcChar8     *dir_serialize;
1177     intptr_t    *dirs_serialize;
1178     FcFontSet   *set_serialize;
1179
1180     if (!serialize)
1181         return NULL;
1182     /*
1183      * Space for cache structure
1184      */
1185     FcSerializeReserve (serialize, sizeof (FcCache));
1186     /*
1187      * Directory name
1188      */
1189     if (!FcStrSerializeAlloc (serialize, dir))
1190         goto bail1;
1191     /*
1192      * Subdirs
1193      */
1194     FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
1195     for (i = 0; i < dirs->num; i++)
1196         if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
1197             goto bail1;
1198
1199     /*
1200      * Patterns
1201      */
1202     if (!FcFontSetSerializeAlloc (serialize, set))
1203         goto bail1;
1204
1205     /* Serialize layout complete. Now allocate space and fill it */
1206     cache = malloc (serialize->size);
1207     if (!cache)
1208         goto bail1;
1209     /* shut up valgrind */
1210     memset (cache, 0, serialize->size);
1211
1212     serialize->linear = cache;
1213
1214     cache->magic = FC_CACHE_MAGIC_ALLOC;
1215     cache->version = FC_CACHE_VERSION_NUMBER;
1216     cache->size = serialize->size;
1217     cache->checksum = FcDirChecksum (dir_stat);
1218     cache->checksum_nano = FcDirChecksumNano (dir_stat);
1219
1220     /*
1221      * Serialize directory name
1222      */
1223     dir_serialize = FcStrSerialize (serialize, dir);
1224     if (!dir_serialize)
1225         goto bail2;
1226     cache->dir = FcPtrToOffset (cache, dir_serialize);
1227
1228     /*
1229      * Serialize sub dirs
1230      */
1231     dirs_serialize = FcSerializePtr (serialize, dirs);
1232     if (!dirs_serialize)
1233         goto bail2;
1234     cache->dirs = FcPtrToOffset (cache, dirs_serialize);
1235     cache->dirs_count = dirs->num;
1236     for (i = 0; i < dirs->num; i++)
1237     {
1238         FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
1239         if (!d_serialize)
1240             goto bail2;
1241         dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
1242     }
1243
1244     /*
1245      * Serialize font set
1246      */
1247     set_serialize = FcFontSetSerialize (serialize, set);
1248     if (!set_serialize)
1249         goto bail2;
1250     cache->set = FcPtrToOffset (cache, set_serialize);
1251
1252     FcSerializeDestroy (serialize);
1253
1254     FcCacheInsert (cache, NULL);
1255
1256     return cache;
1257
1258 bail2:
1259     free (cache);
1260 bail1:
1261     FcSerializeDestroy (serialize);
1262     return NULL;
1263 }
1264
1265 FcCache *
1266 FcDirCacheRebuild (FcCache *cache, struct stat *dir_stat, FcStrSet *dirs)
1267 {
1268     FcCache *new;
1269     FcFontSet *set = FcFontSetDeserialize (FcCacheSet (cache));
1270     const FcChar8 *dir = FcCacheDir (cache);
1271
1272     new = FcDirCacheBuild (set, dir, dir_stat, dirs);
1273     FcFontSetDestroy (set);
1274
1275     return new;
1276 }
1277
1278 /* write serialized state to the cache file */
1279 FcBool
1280 FcDirCacheWrite (FcCache *cache, FcConfig *config)
1281 {
1282     FcChar8         *dir = FcCacheDir (cache);
1283     FcChar8         cache_base[CACHEBASE_LEN];
1284     FcChar8         *cache_hashed;
1285     int             fd;
1286     FcAtomic        *atomic;
1287     FcStrList       *list;
1288     FcChar8         *cache_dir = NULL;
1289     FcChar8         *test_dir, *d = NULL;
1290     FcCacheSkip     *skip;
1291     struct stat     cache_stat;
1292     unsigned int    magic;
1293     int             written;
1294     const FcChar8   *sysroot = FcConfigGetSysRoot (config);
1295
1296     /*
1297      * Write it to the first directory in the list which is writable
1298      */
1299
1300     list = FcStrListCreate (config->cacheDirs);
1301     if (!list)
1302         return FcFalse;
1303     while ((test_dir = FcStrListNext (list)))
1304     {
1305         if (d)
1306             FcStrFree (d);
1307         if (sysroot)
1308             d = FcStrBuildFilename (sysroot, test_dir, NULL);
1309         else
1310             d = FcStrCopyFilename (test_dir);
1311
1312         if (access ((char *) d, W_OK) == 0)
1313         {
1314             cache_dir = FcStrCopyFilename (d);
1315             break;
1316         }
1317         else
1318         {
1319             /*
1320              * If the directory doesn't exist, try to create it
1321              */
1322             if (access ((char *) d, F_OK) == -1) {
1323                 if (FcMakeDirectory (d))
1324                 {
1325                     cache_dir = FcStrCopyFilename (d);
1326                     /* Create CACHEDIR.TAG */
1327                     FcDirCacheCreateTagFile (d);
1328                     break;
1329                 }
1330             }
1331             /*
1332              * Otherwise, try making it writable
1333              */
1334             else if (chmod ((char *) d, 0755) == 0)
1335             {
1336                 cache_dir = FcStrCopyFilename (d);
1337                 /* Try to create CACHEDIR.TAG too */
1338                 FcDirCacheCreateTagFile (d);
1339                 break;
1340             }
1341         }
1342     }
1343     if (d)
1344         FcStrFree (d);
1345     FcStrListDone (list);
1346     if (!cache_dir)
1347         return FcFalse;
1348
1349 #ifndef _WIN32
1350     if (!FcDirCacheBasenameUUID (dir, cache_base, config))
1351 #endif
1352         FcDirCacheBasenameMD5 (dir, cache_base);
1353     cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1354     FcStrFree (cache_dir);
1355     if (!cache_hashed)
1356         return FcFalse;
1357
1358     if (FcDebug () & FC_DBG_CACHE)
1359         printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
1360                 dir, cache_hashed);
1361
1362     atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
1363     if (!atomic)
1364         goto bail1;
1365
1366     if (!FcAtomicLock (atomic))
1367         goto bail3;
1368
1369     fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
1370     if (fd == -1)
1371         goto bail4;
1372
1373     /* Temporarily switch magic to MMAP while writing to file */
1374     magic = cache->magic;
1375     if (magic != FC_CACHE_MAGIC_MMAP)
1376         cache->magic = FC_CACHE_MAGIC_MMAP;
1377
1378     /*
1379      * Write cache contents to file
1380      */
1381     written = write (fd, cache, cache->size);
1382
1383     /* Switch magic back */
1384     if (magic != FC_CACHE_MAGIC_MMAP)
1385         cache->magic = magic;
1386
1387     if (written != cache->size)
1388     {
1389         perror ("write cache");
1390         goto bail5;
1391     }
1392
1393     close(fd);
1394     if (!FcAtomicReplaceOrig(atomic))
1395         goto bail4;
1396
1397     /* If the file is small, update the cache chain entry such that the
1398      * new cache file is not read again.  If it's large, we don't do that
1399      * such that we reload it, using mmap, which is shared across processes.
1400      */
1401     if (cache->size < FC_CACHE_MIN_MMAP && FcStat (cache_hashed, &cache_stat))
1402     {
1403         lock_cache ();
1404         if ((skip = FcCacheFindByAddrUnlocked (cache)))
1405         {
1406             skip->cache_dev = cache_stat.st_dev;
1407             skip->cache_ino = cache_stat.st_ino;
1408             skip->cache_mtime = cache_stat.st_mtime;
1409 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1410             skip->cache_mtime_nano = cache_stat.st_mtim.tv_nsec;
1411 #else
1412             skip->cache_mtime_nano = 0;
1413 #endif
1414         }
1415         unlock_cache ();
1416     }
1417
1418     FcStrFree (cache_hashed);
1419     FcAtomicUnlock (atomic);
1420     FcAtomicDestroy (atomic);
1421     return FcTrue;
1422
1423  bail5:
1424     close (fd);
1425  bail4:
1426     FcAtomicUnlock (atomic);
1427  bail3:
1428     FcAtomicDestroy (atomic);
1429  bail1:
1430     FcStrFree (cache_hashed);
1431     return FcFalse;
1432 }
1433
1434 FcBool
1435 FcDirCacheClean (const FcChar8 *cache_dir, FcBool verbose)
1436 {
1437     DIR         *d;
1438     struct dirent *ent;
1439     FcChar8     *dir;
1440     FcBool      ret = FcTrue;
1441     FcBool      remove;
1442     FcCache     *cache;
1443     struct stat target_stat;
1444     const FcChar8 *sysroot;
1445
1446     /* FIXME: this API needs to support non-current FcConfig */
1447     sysroot = FcConfigGetSysRoot (NULL);
1448     if (sysroot)
1449         dir = FcStrBuildFilename (sysroot, cache_dir, NULL);
1450     else
1451         dir = FcStrCopyFilename (cache_dir);
1452     if (!dir)
1453     {
1454         fprintf (stderr, "Fontconfig error: %s: out of memory\n", cache_dir);
1455         return FcFalse;
1456     }
1457     if (access ((char *) dir, W_OK) != 0)
1458     {
1459         if (verbose || FcDebug () & FC_DBG_CACHE)
1460             printf ("%s: not cleaning %s cache directory\n", dir,
1461                     access ((char *) dir, F_OK) == 0 ? "unwritable" : "non-existent");
1462         goto bail0;
1463     }
1464     if (verbose || FcDebug () & FC_DBG_CACHE)
1465         printf ("%s: cleaning cache directory\n", dir);
1466     d = opendir ((char *) dir);
1467     if (!d)
1468     {
1469         perror ((char *) dir);
1470         ret = FcFalse;
1471         goto bail0;
1472     }
1473     while ((ent = readdir (d)))
1474     {
1475         FcChar8 *file_name;
1476         const FcChar8   *target_dir;
1477
1478         if (ent->d_name[0] == '.')
1479             continue;
1480         /* skip cache files for different architectures and */
1481         /* files which are not cache files at all */
1482         if (strlen(ent->d_name) != 32 + strlen ("-" FC_ARCHITECTURE FC_CACHE_SUFFIX) ||
1483             strcmp(ent->d_name + 32, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX))
1484             continue;
1485
1486         file_name = FcStrBuildFilename (dir, (FcChar8 *)ent->d_name, NULL);
1487         if (!file_name)
1488         {
1489             fprintf (stderr, "Fontconfig error: %s: allocation failure\n", dir);
1490             ret = FcFalse;
1491             break;
1492         }
1493         remove = FcFalse;
1494         cache = FcDirCacheLoadFile (file_name, NULL);
1495         if (!cache)
1496         {
1497             if (verbose || FcDebug () & FC_DBG_CACHE)
1498                 printf ("%s: invalid cache file: %s\n", dir, ent->d_name);
1499             remove = FcTrue;
1500         }
1501         else
1502         {
1503             FcChar8 *s;
1504
1505             target_dir = FcCacheDir (cache);
1506             if (sysroot)
1507                 s = FcStrBuildFilename (sysroot, target_dir, NULL);
1508             else
1509                 s = FcStrdup (target_dir);
1510             if (stat ((char *) s, &target_stat) < 0)
1511             {
1512                 if (verbose || FcDebug () & FC_DBG_CACHE)
1513                     printf ("%s: %s: missing directory: %s \n",
1514                             dir, ent->d_name, s);
1515                 remove = FcTrue;
1516             }
1517             FcDirCacheUnload (cache);
1518             FcStrFree (s);
1519         }
1520         if (remove)
1521         {
1522             if (unlink ((char *) file_name) < 0)
1523             {
1524                 perror ((char *) file_name);
1525                 ret = FcFalse;
1526             }
1527         }
1528         FcStrFree (file_name);
1529     }
1530
1531     closedir (d);
1532   bail0:
1533     FcStrFree (dir);
1534
1535     return ret;
1536 }
1537
1538 int
1539 FcDirCacheLock (const FcChar8 *dir,
1540                 FcConfig      *config)
1541 {
1542     FcChar8 *cache_hashed = NULL;
1543     FcChar8 cache_base[CACHEBASE_LEN];
1544     FcStrList *list;
1545     FcChar8 *cache_dir;
1546     const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1547     int fd = -1;
1548
1549 #ifndef _WIN32
1550     if (!FcDirCacheBasenameUUID (dir, cache_base, config))
1551 #endif
1552         FcDirCacheBasenameMD5 (dir, cache_base);
1553     list = FcStrListCreate (config->cacheDirs);
1554     if (!list)
1555         return -1;
1556
1557     while ((cache_dir = FcStrListNext (list)))
1558     {
1559         if (sysroot)
1560             cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
1561         else
1562             cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1563         if (!cache_hashed)
1564             break;
1565         fd = FcOpen ((const char *)cache_hashed, O_RDWR);
1566         FcStrFree (cache_hashed);
1567         /* No caches in that directory. simply retry with another one */
1568         if (fd != -1)
1569         {
1570 #if defined(_WIN32)
1571             if (_locking (fd, _LK_LOCK, 1) == -1)
1572                 goto bail;
1573 #else
1574             struct flock fl;
1575
1576             fl.l_type = F_WRLCK;
1577             fl.l_whence = SEEK_SET;
1578             fl.l_start = 0;
1579             fl.l_len = 0;
1580             fl.l_pid = getpid ();
1581             if (fcntl (fd, F_SETLKW, &fl) == -1)
1582                 goto bail;
1583 #endif
1584             break;
1585         }
1586     }
1587     FcStrListDone (list);
1588     return fd;
1589 bail:
1590     FcStrListDone (list);
1591     if (fd != -1)
1592         close (fd);
1593     return -1;
1594 }
1595
1596 void
1597 FcDirCacheUnlock (int fd)
1598 {
1599     if (fd != -1)
1600     {
1601 #if defined(_WIN32)
1602         _locking (fd, _LK_UNLCK, 1);
1603 #else
1604         struct flock fl;
1605
1606         fl.l_type = F_UNLCK;
1607         fl.l_whence = SEEK_SET;
1608         fl.l_start = 0;
1609         fl.l_len = 0;
1610         fl.l_pid = getpid ();
1611         fcntl (fd, F_SETLK, &fl);
1612 #endif
1613         close (fd);
1614     }
1615 }
1616
1617 /*
1618  * Hokey little macro trick to permit the definitions of C functions
1619  * with the same name as CPP macros
1620  */
1621 #define args1(x)            (x)
1622 #define args2(x,y)          (x,y)
1623
1624 const FcChar8 *
1625 FcCacheDir args1(const FcCache *c)
1626 {
1627     return FcCacheDir (c);
1628 }
1629
1630 FcFontSet *
1631 FcCacheCopySet args1(const FcCache *c)
1632 {
1633     FcFontSet   *old = FcCacheSet (c);
1634     FcFontSet   *new = FcFontSetCreate ();
1635     int         i;
1636
1637     if (!new)
1638         return NULL;
1639     for (i = 0; i < old->nfont; i++)
1640     {
1641         FcPattern   *font = FcFontSetFont (old, i);
1642         
1643         FcPatternReference (font);
1644         if (!FcFontSetAdd (new, font))
1645         {
1646             FcFontSetDestroy (new);
1647             return NULL;
1648         }
1649     }
1650     return new;
1651 }
1652
1653 const FcChar8 *
1654 FcCacheSubdir args2(const FcCache *c, int i)
1655 {
1656     return FcCacheSubdir (c, i);
1657 }
1658
1659 int
1660 FcCacheNumSubdir args1(const FcCache *c)
1661 {
1662     return c->dirs_count;
1663 }
1664
1665 int
1666 FcCacheNumFont args1(const FcCache *c)
1667 {
1668     return FcCacheSet(c)->nfont;
1669 }
1670
1671 /*
1672  * This code implements the MD5 message-digest algorithm.
1673  * The algorithm is due to Ron Rivest.  This code was
1674  * written by Colin Plumb in 1993, no copyright is claimed.
1675  * This code is in the public domain; do with it what you wish.
1676  *
1677  * Equivalent code is available from RSA Data Security, Inc.
1678  * This code has been tested against that, and is equivalent,
1679  * except that you don't need to include two pages of legalese
1680  * with every copy.
1681  *
1682  * To compute the message digest of a chunk of bytes, declare an
1683  * MD5Context structure, pass it to MD5Init, call MD5Update as
1684  * needed on buffers full of bytes, and then call MD5Final, which
1685  * will fill a supplied 16-byte array with the digest.
1686  */
1687
1688 #ifndef HIGHFIRST
1689 #define byteReverse(buf, len)   /* Nothing */
1690 #else
1691 /*
1692  * Note: this code is harmless on little-endian machines.
1693  */
1694 void byteReverse(unsigned char *buf, unsigned longs)
1695 {
1696     FcChar32 t;
1697     do {
1698         t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1699             ((unsigned) buf[1] << 8 | buf[0]);
1700         *(FcChar32 *) buf = t;
1701         buf += 4;
1702     } while (--longs);
1703 }
1704 #endif
1705
1706 /*
1707  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
1708  * initialization constants.
1709  */
1710 static void MD5Init(struct MD5Context *ctx)
1711 {
1712     ctx->buf[0] = 0x67452301;
1713     ctx->buf[1] = 0xefcdab89;
1714     ctx->buf[2] = 0x98badcfe;
1715     ctx->buf[3] = 0x10325476;
1716
1717     ctx->bits[0] = 0;
1718     ctx->bits[1] = 0;
1719 }
1720
1721 /*
1722  * Update context to reflect the concatenation of another buffer full
1723  * of bytes.
1724  */
1725 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len)
1726 {
1727     FcChar32 t;
1728
1729     /* Update bitcount */
1730
1731     t = ctx->bits[0];
1732     if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
1733         ctx->bits[1]++;         /* Carry from low to high */
1734     ctx->bits[1] += len >> 29;
1735
1736     t = (t >> 3) & 0x3f;        /* Bytes already in shsInfo->data */
1737
1738     /* Handle any leading odd-sized chunks */
1739
1740     if (t) {
1741         unsigned char *p = (unsigned char *) ctx->in + t;
1742
1743         t = 64 - t;
1744         if (len < t) {
1745             memcpy(p, buf, len);
1746             return;
1747         }
1748         memcpy(p, buf, t);
1749         byteReverse(ctx->in, 16);
1750         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1751         buf += t;
1752         len -= t;
1753     }
1754     /* Process data in 64-byte chunks */
1755
1756     while (len >= 64) {
1757         memcpy(ctx->in, buf, 64);
1758         byteReverse(ctx->in, 16);
1759         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1760         buf += 64;
1761         len -= 64;
1762     }
1763
1764     /* Handle any remaining bytes of data. */
1765
1766     memcpy(ctx->in, buf, len);
1767 }
1768
1769 /*
1770  * Final wrapup - pad to 64-byte boundary with the bit pattern
1771  * 1 0* (64-bit count of bits processed, MSB-first)
1772  */
1773 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
1774 {
1775     unsigned count;
1776     unsigned char *p;
1777
1778     /* Compute number of bytes mod 64 */
1779     count = (ctx->bits[0] >> 3) & 0x3F;
1780
1781     /* Set the first char of padding to 0x80.  This is safe since there is
1782        always at least one byte free */
1783     p = ctx->in + count;
1784     *p++ = 0x80;
1785
1786     /* Bytes of padding needed to make 64 bytes */
1787     count = 64 - 1 - count;
1788
1789     /* Pad out to 56 mod 64 */
1790     if (count < 8) {
1791         /* Two lots of padding:  Pad the first block to 64 bytes */
1792         memset(p, 0, count);
1793         byteReverse(ctx->in, 16);
1794         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1795
1796         /* Now fill the next block with 56 bytes */
1797         memset(ctx->in, 0, 56);
1798     } else {
1799         /* Pad block to 56 bytes */
1800         memset(p, 0, count - 8);
1801     }
1802     byteReverse(ctx->in, 14);
1803
1804     /* Append length in bits and transform */
1805     ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
1806     ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
1807
1808     MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1809     byteReverse((unsigned char *) ctx->buf, 4);
1810     memcpy(digest, ctx->buf, 16);
1811     memset(ctx, 0, sizeof(*ctx));        /* In case it's sensitive */
1812 }
1813
1814
1815 /* The four core functions - F1 is optimized somewhat */
1816
1817 /* #define F1(x, y, z) (x & y | ~x & z) */
1818 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1819 #define F2(x, y, z) F1(z, x, y)
1820 #define F3(x, y, z) (x ^ y ^ z)
1821 #define F4(x, y, z) (y ^ (x | ~z))
1822
1823 /* This is the central step in the MD5 algorithm. */
1824 #define MD5STEP(f, w, x, y, z, data, s) \
1825         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
1826
1827 /*
1828  * The core of the MD5 algorithm, this alters an existing MD5 hash to
1829  * reflect the addition of 16 longwords of new data.  MD5Update blocks
1830  * the data and converts bytes into longwords for this routine.
1831  */
1832 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
1833 {
1834     register FcChar32 a, b, c, d;
1835
1836     a = buf[0];
1837     b = buf[1];
1838     c = buf[2];
1839     d = buf[3];
1840
1841     MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1842     MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1843     MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1844     MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1845     MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1846     MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1847     MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1848     MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1849     MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1850     MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1851     MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1852     MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1853     MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1854     MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1855     MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1856     MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1857
1858     MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1859     MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1860     MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1861     MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1862     MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1863     MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1864     MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1865     MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1866     MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1867     MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1868     MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1869     MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1870     MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1871     MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1872     MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1873     MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1874
1875     MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1876     MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1877     MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1878     MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1879     MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1880     MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1881     MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1882     MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1883     MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1884     MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1885     MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1886     MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1887     MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1888     MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1889     MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1890     MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1891
1892     MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1893     MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1894     MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1895     MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1896     MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1897     MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1898     MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1899     MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1900     MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1901     MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1902     MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1903     MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1904     MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1905     MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1906     MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1907     MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1908
1909     buf[0] += a;
1910     buf[1] += b;
1911     buf[2] += c;
1912     buf[3] += d;
1913 }
1914
1915 FcBool
1916 FcDirCacheCreateTagFile (const FcChar8 *cache_dir)
1917 {
1918     FcChar8             *cache_tag;
1919     int                  fd;
1920     FILE                *fp;
1921     FcAtomic            *atomic;
1922     static const FcChar8 cache_tag_contents[] =
1923         "Signature: 8a477f597d28d172789f06886806bc55\n"
1924         "# This file is a cache directory tag created by fontconfig.\n"
1925         "# For information about cache directory tags, see:\n"
1926         "#       http://www.brynosaurus.com/cachedir/\n";
1927     static size_t        cache_tag_contents_size = sizeof (cache_tag_contents) - 1;
1928     FcBool               ret = FcFalse;
1929
1930     if (!cache_dir)
1931         return FcFalse;
1932
1933     if (access ((char *) cache_dir, W_OK) == 0)
1934     {
1935         /* Create CACHEDIR.TAG */
1936         cache_tag = FcStrBuildFilename (cache_dir, "CACHEDIR.TAG", NULL);
1937         if (!cache_tag)
1938             return FcFalse;
1939         atomic = FcAtomicCreate ((FcChar8 *)cache_tag);
1940         if (!atomic)
1941             goto bail1;
1942         if (!FcAtomicLock (atomic))
1943             goto bail2;
1944         fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0644);
1945         if (fd == -1)
1946             goto bail3;
1947         fp = fdopen(fd, "wb");
1948         if (fp == NULL)
1949             goto bail3;
1950
1951         fwrite(cache_tag_contents, cache_tag_contents_size, sizeof (FcChar8), fp);
1952         fclose(fp);
1953
1954         if (!FcAtomicReplaceOrig(atomic))
1955             goto bail3;
1956
1957         ret = FcTrue;
1958       bail3:
1959         FcAtomicUnlock (atomic);
1960       bail2:
1961         FcAtomicDestroy (atomic);
1962       bail1:
1963         FcStrFree (cache_tag);
1964     }
1965
1966     if (FcDebug () & FC_DBG_CACHE)
1967     {
1968         if (ret)
1969             printf ("Created CACHEDIR.TAG at %s\n", cache_dir);
1970         else
1971             printf ("Unable to create CACHEDIR.TAG at %s\n", cache_dir);
1972     }
1973
1974     return ret;
1975 }
1976
1977 void
1978 FcCacheCreateTagFile (const FcConfig *config)
1979 {
1980     FcChar8   *cache_dir = NULL, *d = NULL;
1981     FcStrList *list;
1982     const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1983
1984     list = FcConfigGetCacheDirs (config);
1985     if (!list)
1986         return;
1987
1988     while ((cache_dir = FcStrListNext (list)))
1989     {
1990         if (d)
1991             FcStrFree (d);
1992         if (sysroot)
1993             d = FcStrBuildFilename (sysroot, cache_dir, NULL);
1994         else
1995             d = FcStrCopyFilename (cache_dir);
1996         if (FcDirCacheCreateTagFile (d))
1997             break;
1998     }
1999     if (d)
2000         FcStrFree (d);
2001     FcStrListDone (list);
2002 }
2003
2004 #define __fccache__
2005 #include "fcaliastail.h"
2006 #undef __fccache__