Explicitly chmod() directories (bug #18934)
[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 Keith Packard not be used in
10  * advertising or publicity pertaining to distribution of the software without
11  * specific, written prior permission.  Keith Packard makes 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  * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
16  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
17  * EVENT SHALL KEITH PACKARD 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
24 #include "fcint.h"
25 #include "../fc-arch/fcarch.h"
26 #include <stdio.h>
27 #include <fcntl.h>
28 #include <dirent.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <assert.h>
32 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
33 #  include <unistd.h>
34 #  include <sys/mman.h>
35 #elif defined(_WIN32)
36 #  define _WIN32_WINNT 0x0500
37 #  include <windows.h>
38 #endif
39
40 #ifndef O_BINARY
41 #define O_BINARY 0
42 #endif
43
44 struct MD5Context {
45         FcChar32 buf[4];
46         FcChar32 bits[2];
47         unsigned char in[64];
48 };
49
50 static void MD5Init(struct MD5Context *ctx);
51 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len);
52 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx);
53 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16]);
54
55 #define CACHEBASE_LEN (1 + 32 + 1 + sizeof (FC_ARCHITECTURE) + sizeof (FC_CACHE_SUFFIX))
56
57 #ifdef _WIN32
58
59 #include <windows.h>
60
61 #ifdef __GNUC__
62 typedef long long INT64;
63 #define EPOCH_OFFSET 11644473600ll
64 #else
65 #define EPOCH_OFFSET 11644473600i64
66 typedef __int64 INT64;
67 #endif
68
69 /* Workaround for problems in the stat() in the Microsoft C library:
70  *
71  * 1) stat() uses FindFirstFile() to get the file
72  * attributes. Unfortunately this API doesn't return correct values
73  * for modification time of a directory until some time after a file
74  * or subdirectory has been added to the directory. (This causes
75  * run-test.sh to fail, for instance.) GetFileAttributesEx() is
76  * better, it returns the updated timestamp right away.
77  *
78  * 2) stat() does some strange things related to backward
79  * compatibility with the local time timestamps on FAT volumes and
80  * daylight saving time. This causes problems after the switches
81  * to/from daylight saving time. See
82  * http://bugzilla.gnome.org/show_bug.cgi?id=154968 , especially
83  * comment #30, and http://www.codeproject.com/datetime/dstbugs.asp .
84  * We don't need any of that, FAT and Win9x are as good as dead. So
85  * just use the UTC timestamps from NTFS, converted to the Unix epoch.
86  */
87
88 int
89 FcStat (const char *file, struct stat *statb)
90 {
91     WIN32_FILE_ATTRIBUTE_DATA wfad;
92     char full_path_name[MAX_PATH];
93     char *basename;
94     DWORD rc;
95     
96     if (!GetFileAttributesEx (file, GetFileExInfoStandard, &wfad))
97         return -1;
98     
99     statb->st_dev = 0;
100
101     /* Calculate a pseudo inode number as a hash of the full path name.
102      * Call GetLongPathName() to get the spelling of the path name as it
103      * is on disk.
104      */
105     rc = GetFullPathName (file, sizeof (full_path_name), full_path_name, &basename);
106     if (rc == 0 || rc > sizeof (full_path_name))
107         return -1;
108
109     rc = GetLongPathName (full_path_name, full_path_name, sizeof (full_path_name));
110     statb->st_ino = FcStringHash (full_path_name);
111     
112     statb->st_mode = _S_IREAD | _S_IWRITE;
113     statb->st_mode |= (statb->st_mode >> 3) | (statb->st_mode >> 6);
114
115     if (wfad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
116         statb->st_mode |= _S_IFDIR;
117     else
118         statb->st_mode |= _S_IFREG;
119     
120     statb->st_nlink = 1;
121     statb->st_uid = statb->st_gid = 0;
122     statb->st_rdev = 0;
123     
124     if (wfad.nFileSizeHigh > 0)
125         return -1;
126     statb->st_size = wfad.nFileSizeLow;
127     
128     statb->st_atime = (*(INT64 *)&wfad.ftLastAccessTime)/10000000 - EPOCH_OFFSET;
129     statb->st_mtime = (*(INT64 *)&wfad.ftLastWriteTime)/10000000 - EPOCH_OFFSET;
130     statb->st_ctime = statb->st_mtime;
131     
132     return 0;
133 }
134 #endif
135
136 static const char bin2hex[] = { '0', '1', '2', '3',
137                                 '4', '5', '6', '7',
138                                 '8', '9', 'a', 'b',
139                                 'c', 'd', 'e', 'f' };
140
141 static FcChar8 *
142 FcDirCacheBasename (const FcChar8 * dir, FcChar8 cache_base[CACHEBASE_LEN])
143 {
144     unsigned char       hash[16];
145     FcChar8             *hex_hash;
146     int                 cnt;
147     struct MD5Context   ctx;
148
149     MD5Init (&ctx);
150     MD5Update (&ctx, (const unsigned char *)dir, strlen ((const char *) dir));
151
152     MD5Final (hash, &ctx);
153
154     cache_base[0] = '/';
155     hex_hash = cache_base + 1;
156     for (cnt = 0; cnt < 16; ++cnt)
157     {
158         hex_hash[2*cnt  ] = bin2hex[hash[cnt] >> 4];
159         hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
160     }
161     hex_hash[2*cnt] = 0;
162     strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
163
164     return cache_base;
165 }
166
167 FcBool
168 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
169 {
170     FcChar8     *cache_hashed = NULL;
171     FcChar8     cache_base[CACHEBASE_LEN];
172     FcStrList   *list;
173     FcChar8     *cache_dir;
174
175     FcDirCacheBasename (dir, cache_base);
176
177     list = FcStrListCreate (config->cacheDirs);
178     if (!list)
179         return FcFalse;
180         
181     while ((cache_dir = FcStrListNext (list)))
182     {
183         cache_hashed = FcStrPlus (cache_dir, cache_base);
184         if (!cache_hashed)
185             break;
186         (void) unlink ((char *) cache_hashed);
187         FcStrFree (cache_hashed);
188     }
189     FcStrListDone (list);
190     /* return FcFalse if something went wrong */
191     if (cache_dir)
192         return FcFalse;
193     return FcTrue;
194 }
195
196 static int
197 FcDirCacheOpenFile (const FcChar8 *cache_file, struct stat *file_stat)
198 {
199     int fd;
200
201 #ifdef _WIN32
202     if (FcStat (cache_file, file_stat) < 0)
203         return -1;
204 #endif
205     fd = open((char *) cache_file, O_RDONLY | O_BINARY);
206     if (fd < 0)
207         return fd;
208 #ifndef _WIN32
209     if (fstat (fd, file_stat) < 0)
210     {
211         close (fd);
212         return -1;
213     }
214 #endif
215     return fd;
216 }
217
218 /* 
219  * Look for a cache file for the specified dir. Attempt
220  * to use each one we find, stopping when the callback
221  * indicates success
222  */
223 static FcBool
224 FcDirCacheProcess (FcConfig *config, const FcChar8 *dir, 
225                    FcBool (*callback) (int fd, struct stat *fd_stat,
226                                        struct stat *dir_stat, void *closure),
227                    void *closure, FcChar8 **cache_file_ret)
228 {
229     int         fd = -1;
230     FcChar8     cache_base[CACHEBASE_LEN];
231     FcStrList   *list;
232     FcChar8     *cache_dir;
233     struct stat file_stat, dir_stat;
234     FcBool      ret = FcFalse;
235
236     if (FcStat ((char *) dir, &dir_stat) < 0)
237         return FcFalse;
238
239     FcDirCacheBasename (dir, cache_base);
240
241     list = FcStrListCreate (config->cacheDirs);
242     if (!list)
243         return FcFalse;
244         
245     while ((cache_dir = FcStrListNext (list)))
246     {
247         FcChar8 *cache_hashed = FcStrPlus (cache_dir, cache_base);
248         if (!cache_hashed)
249             break;
250         fd = FcDirCacheOpenFile (cache_hashed, &file_stat);
251         if (fd >= 0) {
252             ret = (*callback) (fd, &file_stat, &dir_stat, closure);
253             close (fd);
254             if (ret)
255             {
256                 if (cache_file_ret)
257                     *cache_file_ret = cache_hashed;
258                 else
259                     FcStrFree (cache_hashed);
260                 break;
261             }
262         }
263         FcStrFree (cache_hashed);
264     }
265     FcStrListDone (list);
266     
267     return ret;
268 }
269
270 #define FC_CACHE_MIN_MMAP   1024
271
272 /*
273  * Skip list element, make sure the 'next' pointer is the last thing
274  * in the structure, it will be allocated large enough to hold all
275  * of the necessary pointers
276  */
277
278 typedef struct _FcCacheSkip FcCacheSkip;
279
280 struct _FcCacheSkip {
281     FcCache         *cache;
282     int             ref;
283     intptr_t        size;
284     dev_t           cache_dev;
285     ino_t           cache_ino;
286     time_t          cache_mtime;
287     FcCacheSkip     *next[1];
288 };
289
290 /*
291  * The head of the skip list; pointers for every possible level
292  * in the skip list, plus the largest level in the list
293  */
294
295 #define FC_CACHE_MAX_LEVEL  16
296
297 static FcCacheSkip      *fcCacheChains[FC_CACHE_MAX_LEVEL];
298 static int              fcCacheMaxLevel;
299
300 #if HAVE_RANDOM
301 # define FcRandom()  random()
302 #else
303 # if HAVE_LRAND48
304 #  define FcRandom()  lrand48()
305 # else
306 #  if HAVE_RAND
307 #   define FcRandom()  rand()
308 #  endif
309 # endif
310 #endif
311 /*
312  * Generate a random level number, distributed
313  * so that each level is 1/4 as likely as the one before
314  *
315  * Note that level numbers run 1 <= level <= MAX_LEVEL
316  */
317 static int
318 random_level (void)
319 {
320     /* tricky bit -- each bit is '1' 75% of the time */
321     long int    bits = FcRandom () | FcRandom ();
322     int level = 0;
323
324     while (++level < FC_CACHE_MAX_LEVEL)
325     {
326         if (bits & 1)
327             break;
328         bits >>= 1;
329     }
330     return level;
331 }
332
333 /*
334  * Insert cache into the list
335  */
336 static FcBool
337 FcCacheInsert (FcCache *cache, struct stat *cache_stat)
338 {
339     FcCacheSkip    **update[FC_CACHE_MAX_LEVEL];
340     FcCacheSkip    *s, **next;
341     int             i, level;
342
343     /*
344      * Find links along each chain
345      */
346     next = fcCacheChains;
347     for (i = fcCacheMaxLevel; --i >= 0; )
348     {
349         for (; (s = next[i]); next = s->next)
350             if (s->cache > cache)
351                 break;
352         update[i] = &next[i];
353     }
354
355     /*
356      * Create new list element
357      */
358     level = random_level ();
359     if (level > fcCacheMaxLevel)
360     {
361         level = fcCacheMaxLevel + 1;
362         update[fcCacheMaxLevel] = &fcCacheChains[fcCacheMaxLevel];
363         fcCacheMaxLevel = level;
364     }
365     
366     s = malloc (sizeof (FcCacheSkip) + (level - 1) * sizeof (FcCacheSkip *));
367     if (!s)
368         return FcFalse;
369
370     s->cache = cache;
371     s->size = cache->size;
372     s->ref = 1;
373     if (cache_stat)
374     {
375         s->cache_dev = cache_stat->st_dev;
376         s->cache_ino = cache_stat->st_ino;
377         s->cache_mtime = cache_stat->st_mtime;
378     }
379     else
380     {
381         s->cache_dev = 0;
382         s->cache_ino = 0;
383         s->cache_mtime = 0;
384     }
385     
386     /*
387      * Insert into all fcCacheChains
388      */
389     for (i = 0; i < level; i++)
390     {
391         s->next[i] = *update[i];
392         *update[i] = s;
393     }
394     return FcTrue;
395 }
396
397 static FcCacheSkip *
398 FcCacheFindByAddr (void *object)
399 {
400     int     i;
401     FcCacheSkip    **next = fcCacheChains;
402     FcCacheSkip    *s;
403
404     /*
405      * Walk chain pointers one level at a time
406      */
407     for (i = fcCacheMaxLevel; --i >= 0;)
408         while (next[i] && (char *) object >= ((char *) next[i]->cache + next[i]->size))
409             next = next[i]->next;
410     /*
411      * Here we are
412      */
413     s = next[0];
414     if (s && (char *) object < ((char *) s->cache + s->size))
415         return s;
416     return NULL;
417 }
418
419 static void
420 FcCacheRemove (FcCache *cache)
421 {
422     FcCacheSkip     **update[FC_CACHE_MAX_LEVEL];
423     FcCacheSkip     *s, **next;
424     int             i;
425
426     /*
427      * Find links along each chain
428      */
429     next = fcCacheChains;
430     for (i = fcCacheMaxLevel; --i >= 0; )
431     {
432         for (; (s = next[i]); next = s->next)
433             if (s->cache >= cache)
434                 break;
435         update[i] = &next[i];
436     }
437     s = next[0];
438     for (i = 0; i < fcCacheMaxLevel && *update[i] == s; i++)
439         *update[i] = s->next[i];
440     while (fcCacheMaxLevel > 0 && fcCacheChains[fcCacheMaxLevel - 1] == NULL)
441         fcCacheMaxLevel--;
442     free (s);
443 }
444
445 static FcCache *
446 FcCacheFindByStat (struct stat *cache_stat)
447 {
448     FcCacheSkip     *s;
449
450     for (s = fcCacheChains[0]; s; s = s->next[0])
451         if (s->cache_dev == cache_stat->st_dev &&
452             s->cache_ino == cache_stat->st_ino &&
453             s->cache_mtime == cache_stat->st_mtime)
454         {
455             s->ref++;
456             return s->cache;
457         }
458     return NULL;
459 }
460
461 static void
462 FcDirCacheDispose (FcCache *cache)
463 {
464     switch (cache->magic) {
465     case FC_CACHE_MAGIC_ALLOC:
466         free (cache);
467         break;
468     case FC_CACHE_MAGIC_MMAP:
469 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
470         munmap (cache, cache->size);
471 #elif defined(_WIN32)
472         UnmapViewOfFile (cache);
473 #endif
474         break;
475     }
476     FcCacheRemove (cache);
477 }
478
479 void
480 FcCacheObjectReference (void *object)
481 {
482     FcCacheSkip *skip = FcCacheFindByAddr (object);
483
484     if (skip)
485         skip->ref++;
486 }
487
488 void
489 FcCacheObjectDereference (void *object)
490 {
491     FcCacheSkip *skip = FcCacheFindByAddr (object);
492
493     if (skip)
494     {
495         skip->ref--;
496         if (skip->ref <= 0)
497             FcDirCacheDispose (skip->cache);
498     }
499 }
500
501 void
502 FcCacheFini (void)
503 {
504     int             i;
505
506     for (i = 0; i < FC_CACHE_MAX_LEVEL; i++)
507         assert (fcCacheChains[i] == NULL);
508     assert (fcCacheMaxLevel == 0);
509 }
510
511 static FcBool
512 FcCacheTimeValid (FcCache *cache, struct stat *dir_stat)
513 {
514     struct stat dir_static;
515
516     if (!dir_stat)
517     {
518         if (FcStat ((const char *) FcCacheDir (cache), &dir_static) < 0)
519             return FcFalse;
520         dir_stat = &dir_static;
521     }
522     if (FcDebug () & FC_DBG_CACHE)
523         printf ("FcCacheTimeValid dir \"%s\" cache time %d dir time %d\n",
524                 FcCacheDir (cache), cache->mtime, (int) dir_stat->st_mtime);
525     return cache->mtime == (int) dir_stat->st_mtime;
526 }
527
528 /*
529  * Map a cache file into memory
530  */
531 static FcCache *
532 FcDirCacheMapFd (int fd, struct stat *fd_stat, struct stat *dir_stat)
533 {
534     FcCache     *cache;
535     FcBool      allocated = FcFalse;
536
537     if (fd_stat->st_size < sizeof (FcCache))
538         return NULL;
539     cache = FcCacheFindByStat (fd_stat);
540     if (cache)
541         return cache;
542     /*
543      * Lage cache files are mmap'ed, smaller cache files are read. This
544      * balances the system cost of mmap against per-process memory usage.
545      */
546     if (fd_stat->st_size >= FC_CACHE_MIN_MMAP)
547     {
548 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
549         cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
550 #elif defined(_WIN32)
551         {
552             HANDLE hFileMap;
553
554             cache = NULL;
555             hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
556                                          PAGE_READONLY, 0, 0, NULL);
557             if (hFileMap != NULL)
558             {
559                 cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0, 
560                                        fd_stat->st_size);
561                 CloseHandle (hFileMap);
562             }
563         }
564 #endif
565     }
566     if (!cache)
567     {
568         cache = malloc (fd_stat->st_size);
569         if (!cache)
570             return NULL;
571
572         if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
573         {
574             free (cache);
575             return NULL;
576         }
577         allocated = FcTrue;
578     } 
579     if (cache->magic != FC_CACHE_MAGIC_MMAP || 
580         cache->version < FC_CACHE_CONTENT_VERSION ||
581         cache->size != fd_stat->st_size ||
582         !FcCacheTimeValid (cache, dir_stat) ||
583         !FcCacheInsert (cache, fd_stat))
584     {
585         if (allocated)
586             free (cache);
587         else
588         {
589 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
590             munmap (cache, fd_stat->st_size);
591 #elif defined(_WIN32)
592             UnmapViewOfFile (cache);
593 #endif
594         }
595         return NULL;
596     }
597
598     /* Mark allocated caches so they're freed rather than unmapped */
599     if (allocated)
600         cache->magic = FC_CACHE_MAGIC_ALLOC;
601         
602     return cache;
603 }
604
605 void
606 FcDirCacheReference (FcCache *cache, int nref)
607 {
608     FcCacheSkip *skip = FcCacheFindByAddr (cache);
609
610     if (skip)
611         skip->ref += nref;
612 }
613
614 void
615 FcDirCacheUnload (FcCache *cache)
616 {
617     FcCacheObjectDereference (cache);
618 }
619
620 static FcBool
621 FcDirCacheMapHelper (int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure)
622 {
623     FcCache *cache = FcDirCacheMapFd (fd, fd_stat, dir_stat);
624
625     if (!cache)
626         return FcFalse;
627     *((FcCache **) closure) = cache;
628     return FcTrue;
629 }
630
631 FcCache *
632 FcDirCacheLoad (const FcChar8 *dir, FcConfig *config, FcChar8 **cache_file)
633 {
634     FcCache *cache = NULL;
635
636     if (!FcDirCacheProcess (config, dir,
637                             FcDirCacheMapHelper,
638                             &cache, cache_file))
639         return NULL;
640     return cache;
641 }
642
643 FcCache *
644 FcDirCacheLoadFile (const FcChar8 *cache_file, struct stat *file_stat)
645 {
646     int fd;
647     FcCache *cache;
648     struct stat my_file_stat;
649
650     if (!file_stat)
651         file_stat = &my_file_stat;
652     fd = FcDirCacheOpenFile (cache_file, file_stat);
653     if (fd < 0)
654         return NULL;
655     cache = FcDirCacheMapFd (fd, file_stat, NULL);
656     close (fd);
657     return cache;
658 }
659
660 /*
661  * Validate a cache file by reading the header and checking
662  * the magic number and the size field
663  */
664 static FcBool
665 FcDirCacheValidateHelper (int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure)
666 {
667     FcBool  ret = FcTrue;
668     FcCache     c;
669     
670     if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
671         ret = FcFalse;
672     else if (c.magic != FC_CACHE_MAGIC_MMAP)
673         ret = FcFalse;
674     else if (c.version < FC_CACHE_CONTENT_VERSION)
675         ret = FcFalse;
676     else if (fd_stat->st_size != c.size)
677         ret = FcFalse;
678     else if (c.mtime != (int) dir_stat->st_mtime)
679         ret = FcFalse;
680     return ret;
681 }
682
683 static FcBool
684 FcDirCacheValidConfig (const FcChar8 *dir, FcConfig *config)
685 {
686     return FcDirCacheProcess (config, dir, 
687                               FcDirCacheValidateHelper,
688                               NULL, NULL);
689 }
690
691 FcBool
692 FcDirCacheValid (const FcChar8 *dir)
693 {
694     FcConfig    *config;
695     
696     config = FcConfigGetCurrent ();
697     if (!config)
698         return FcFalse;
699
700     return FcDirCacheValidConfig (dir, config);
701 }
702
703 /*
704  * Build a cache structure from the given contents
705  */
706 FcCache *
707 FcDirCacheBuild (FcFontSet *set, const FcChar8 *dir, struct stat *dir_stat, FcStrSet *dirs)
708 {
709     FcSerialize *serialize = FcSerializeCreate ();
710     FcCache *cache;
711     int i;
712     intptr_t    cache_offset;
713     intptr_t    dirs_offset;
714     FcChar8     *dir_serialize;
715     intptr_t    *dirs_serialize;
716     FcFontSet   *set_serialize;
717     
718     if (!serialize)
719         return NULL;
720     /*
721      * Space for cache structure
722      */
723     cache_offset = FcSerializeReserve (serialize, sizeof (FcCache));
724     /*
725      * Directory name
726      */
727     if (!FcStrSerializeAlloc (serialize, dir))
728         goto bail1;
729     /*
730      * Subdirs
731      */
732     dirs_offset = FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
733     for (i = 0; i < dirs->num; i++)
734         if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
735             goto bail1;
736
737     /*
738      * Patterns
739      */
740     if (!FcFontSetSerializeAlloc (serialize, set))
741         goto bail1;
742     
743     /* Serialize layout complete. Now allocate space and fill it */
744     cache = malloc (serialize->size);
745     if (!cache)
746         goto bail1;
747     /* shut up valgrind */
748     memset (cache, 0, serialize->size);
749
750     serialize->linear = cache;
751
752     cache->magic = FC_CACHE_MAGIC_ALLOC;
753     cache->version = FC_CACHE_CONTENT_VERSION;
754     cache->size = serialize->size;
755     cache->mtime = (int) dir_stat->st_mtime;
756
757     /*
758      * Serialize directory name
759      */
760     dir_serialize = FcStrSerialize (serialize, dir);
761     if (!dir_serialize)
762         goto bail2;
763     cache->dir = FcPtrToOffset (cache, dir_serialize);
764     
765     /*
766      * Serialize sub dirs
767      */
768     dirs_serialize = FcSerializePtr (serialize, dirs);
769     if (!dirs_serialize)
770         goto bail2;
771     cache->dirs = FcPtrToOffset (cache, dirs_serialize);
772     cache->dirs_count = dirs->num;
773     for (i = 0; i < dirs->num; i++) 
774     {
775         FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
776         if (!d_serialize)
777             goto bail2;
778         dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
779     }
780     
781     /*
782      * Serialize font set
783      */
784     set_serialize = FcFontSetSerialize (serialize, set);
785     if (!set_serialize)
786         goto bail2;
787     cache->set = FcPtrToOffset (cache, set_serialize);
788
789     FcSerializeDestroy (serialize);
790     
791     FcCacheInsert (cache, NULL);
792
793     return cache;
794
795 bail2:
796     free (cache);
797 bail1:
798     FcSerializeDestroy (serialize);
799     return NULL;
800 }
801
802
803 #ifdef _WIN32
804 #define mkdir(path,mode) _mkdir(path)
805 #endif
806
807 static FcBool
808 FcMakeDirectory (const FcChar8 *dir)
809 {
810     FcChar8 *parent;
811     FcBool  ret;
812     
813     if (strlen ((char *) dir) == 0)
814         return FcFalse;
815     
816     parent = FcStrDirname (dir);
817     if (!parent)
818         return FcFalse;
819     if (access ((char *) parent, F_OK) == 0)
820         ret = mkdir ((char *) dir, 0755) == 0 && chmod ((char *) dir, 0755) == 0;
821     else if (access ((char *) parent, F_OK) == -1)
822         ret = FcMakeDirectory (parent) && (mkdir ((char *) dir, 0755) == 0) && chmod ((char *) dir, 0755) == 0;
823     else
824         ret = FcFalse;
825     FcStrFree (parent);
826     return ret;
827 }
828
829 /* write serialized state to the cache file */
830 FcBool
831 FcDirCacheWrite (FcCache *cache, FcConfig *config)
832 {
833     FcChar8         *dir = FcCacheDir (cache);
834     FcChar8         cache_base[CACHEBASE_LEN];
835     FcChar8         *cache_hashed;
836     int             fd;
837     FcAtomic        *atomic;
838     FcStrList       *list;
839     FcChar8         *cache_dir = NULL;
840     FcChar8         *test_dir;
841     int             magic;
842     int             written;
843
844     /*
845      * Write it to the first directory in the list which is writable
846      */
847     
848     list = FcStrListCreate (config->cacheDirs);
849     if (!list)
850         return FcFalse;
851     while ((test_dir = FcStrListNext (list))) {
852         if (access ((char *) test_dir, W_OK|X_OK) == 0)
853         {
854             cache_dir = test_dir;
855             break;
856         }
857         else
858         {
859             /*
860              * If the directory doesn't exist, try to create it
861              */
862             if (access ((char *) test_dir, F_OK) == -1) {
863                 if (FcMakeDirectory (test_dir))
864                 {
865                     cache_dir = test_dir;
866                     break;
867                 }
868             }
869             /*
870              * Otherwise, try making it writable
871              */
872             else if (chmod ((char *) test_dir, 0755) == 0)
873             {
874                 cache_dir = test_dir;
875                 break;
876             }
877         }
878     }
879     FcStrListDone (list);
880     if (!cache_dir)
881         return FcFalse;
882
883     FcDirCacheBasename (dir, cache_base);
884     cache_hashed = FcStrPlus (cache_dir, cache_base);
885     if (!cache_hashed)
886         return FcFalse;
887
888     if (FcDebug () & FC_DBG_CACHE)
889         printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
890                 dir, cache_hashed);
891
892     atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
893     if (!atomic)
894         goto bail1;
895
896     if (!FcAtomicLock (atomic))
897         goto bail3;
898
899     fd = open((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
900     if (fd == -1)
901         goto bail4;
902     
903     /* Temporarily switch magic to MMAP while writing to file */
904     magic = cache->magic;
905     if (magic != FC_CACHE_MAGIC_MMAP)
906         cache->magic = FC_CACHE_MAGIC_MMAP;
907     
908     /*
909      * Write cache contents to file
910      */
911     written = write (fd, cache, cache->size);
912     
913     /* Switch magic back */
914     if (magic != FC_CACHE_MAGIC_MMAP)
915         cache->magic = magic;
916     
917     if (written != cache->size)
918     {
919         perror ("write cache");
920         goto bail5;
921     }
922
923     close(fd);
924     if (!FcAtomicReplaceOrig(atomic))
925         goto bail4;
926     FcStrFree (cache_hashed);
927     FcAtomicUnlock (atomic);
928     FcAtomicDestroy (atomic);
929     return FcTrue;
930
931  bail5:
932     close (fd);
933  bail4:
934     FcAtomicUnlock (atomic);
935  bail3:
936     FcAtomicDestroy (atomic);
937  bail1:
938     FcStrFree (cache_hashed);
939     return FcFalse;
940 }
941
942 /*
943  * Hokey little macro trick to permit the definitions of C functions
944  * with the same name as CPP macros
945  */
946 #define args1(x)            (x)
947 #define args2(x,y)          (x,y)
948
949 const FcChar8 *
950 FcCacheDir args1(const FcCache *c)
951 {
952     return FcCacheDir (c);
953 }
954
955 FcFontSet *
956 FcCacheCopySet args1(const FcCache *c)
957 {
958     FcFontSet   *old = FcCacheSet (c);
959     FcFontSet   *new = FcFontSetCreate ();
960     int         i;
961     
962     if (!new)
963         return NULL;
964     for (i = 0; i < old->nfont; i++)
965     {
966         FcPattern   *font = FcFontSetFont (old, i);
967         
968         FcPatternReference (font);
969         if (!FcFontSetAdd (new, font))
970         {
971             FcFontSetDestroy (new);
972             return NULL;
973         }
974     }
975     return new;
976 }
977
978 const FcChar8 *
979 FcCacheSubdir args2(const FcCache *c, int i)
980 {
981     return FcCacheSubdir (c, i);
982 }
983
984 int
985 FcCacheNumSubdir args1(const FcCache *c)
986 {
987     return c->dirs_count;
988 }
989
990 int
991 FcCacheNumFont args1(const FcCache *c)
992 {
993     return FcCacheSet(c)->nfont;
994 }
995
996 /*
997  * This code implements the MD5 message-digest algorithm.
998  * The algorithm is due to Ron Rivest.  This code was
999  * written by Colin Plumb in 1993, no copyright is claimed.
1000  * This code is in the public domain; do with it what you wish.
1001  *
1002  * Equivalent code is available from RSA Data Security, Inc.
1003  * This code has been tested against that, and is equivalent,
1004  * except that you don't need to include two pages of legalese
1005  * with every copy.
1006  *
1007  * To compute the message digest of a chunk of bytes, declare an
1008  * MD5Context structure, pass it to MD5Init, call MD5Update as
1009  * needed on buffers full of bytes, and then call MD5Final, which
1010  * will fill a supplied 16-byte array with the digest.
1011  */
1012
1013 #ifndef HIGHFIRST
1014 #define byteReverse(buf, len)   /* Nothing */
1015 #else
1016 /*
1017  * Note: this code is harmless on little-endian machines.
1018  */
1019 void byteReverse(unsigned char *buf, unsigned longs)
1020 {
1021     FcChar32 t;
1022     do {
1023         t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1024             ((unsigned) buf[1] << 8 | buf[0]);
1025         *(FcChar32 *) buf = t;
1026         buf += 4;
1027     } while (--longs);
1028 }
1029 #endif
1030
1031 /*
1032  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
1033  * initialization constants.
1034  */
1035 static void MD5Init(struct MD5Context *ctx)
1036 {
1037     ctx->buf[0] = 0x67452301;
1038     ctx->buf[1] = 0xefcdab89;
1039     ctx->buf[2] = 0x98badcfe;
1040     ctx->buf[3] = 0x10325476;
1041
1042     ctx->bits[0] = 0;
1043     ctx->bits[1] = 0;
1044 }
1045
1046 /*
1047  * Update context to reflect the concatenation of another buffer full
1048  * of bytes.
1049  */
1050 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len)
1051 {
1052     FcChar32 t;
1053
1054     /* Update bitcount */
1055
1056     t = ctx->bits[0];
1057     if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
1058         ctx->bits[1]++;         /* Carry from low to high */
1059     ctx->bits[1] += len >> 29;
1060
1061     t = (t >> 3) & 0x3f;        /* Bytes already in shsInfo->data */
1062
1063     /* Handle any leading odd-sized chunks */
1064
1065     if (t) {
1066         unsigned char *p = (unsigned char *) ctx->in + t;
1067
1068         t = 64 - t;
1069         if (len < t) {
1070             memcpy(p, buf, len);
1071             return;
1072         }
1073         memcpy(p, buf, t);
1074         byteReverse(ctx->in, 16);
1075         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1076         buf += t;
1077         len -= t;
1078     }
1079     /* Process data in 64-byte chunks */
1080
1081     while (len >= 64) {
1082         memcpy(ctx->in, buf, 64);
1083         byteReverse(ctx->in, 16);
1084         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1085         buf += 64;
1086         len -= 64;
1087     }
1088
1089     /* Handle any remaining bytes of data. */
1090
1091     memcpy(ctx->in, buf, len);
1092 }
1093
1094 /*
1095  * Final wrapup - pad to 64-byte boundary with the bit pattern 
1096  * 1 0* (64-bit count of bits processed, MSB-first)
1097  */
1098 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
1099 {
1100     unsigned count;
1101     unsigned char *p;
1102
1103     /* Compute number of bytes mod 64 */
1104     count = (ctx->bits[0] >> 3) & 0x3F;
1105
1106     /* Set the first char of padding to 0x80.  This is safe since there is
1107        always at least one byte free */
1108     p = ctx->in + count;
1109     *p++ = 0x80;
1110
1111     /* Bytes of padding needed to make 64 bytes */
1112     count = 64 - 1 - count;
1113
1114     /* Pad out to 56 mod 64 */
1115     if (count < 8) {
1116         /* Two lots of padding:  Pad the first block to 64 bytes */
1117         memset(p, 0, count);
1118         byteReverse(ctx->in, 16);
1119         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1120
1121         /* Now fill the next block with 56 bytes */
1122         memset(ctx->in, 0, 56);
1123     } else {
1124         /* Pad block to 56 bytes */
1125         memset(p, 0, count - 8);
1126     }
1127     byteReverse(ctx->in, 14);
1128
1129     /* Append length in bits and transform */
1130     ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
1131     ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
1132
1133     MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1134     byteReverse((unsigned char *) ctx->buf, 4);
1135     memcpy(digest, ctx->buf, 16);
1136     memset(ctx, 0, sizeof(ctx));        /* In case it's sensitive */
1137 }
1138
1139
1140 /* The four core functions - F1 is optimized somewhat */
1141
1142 /* #define F1(x, y, z) (x & y | ~x & z) */
1143 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1144 #define F2(x, y, z) F1(z, x, y)
1145 #define F3(x, y, z) (x ^ y ^ z)
1146 #define F4(x, y, z) (y ^ (x | ~z))
1147
1148 /* This is the central step in the MD5 algorithm. */
1149 #define MD5STEP(f, w, x, y, z, data, s) \
1150         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
1151
1152 /*
1153  * The core of the MD5 algorithm, this alters an existing MD5 hash to
1154  * reflect the addition of 16 longwords of new data.  MD5Update blocks
1155  * the data and converts bytes into longwords for this routine.
1156  */
1157 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
1158 {
1159     register FcChar32 a, b, c, d;
1160
1161     a = buf[0];
1162     b = buf[1];
1163     c = buf[2];
1164     d = buf[3];
1165
1166     MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1167     MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1168     MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1169     MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1170     MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1171     MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1172     MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1173     MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1174     MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1175     MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1176     MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1177     MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1178     MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1179     MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1180     MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1181     MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1182
1183     MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1184     MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1185     MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1186     MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1187     MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1188     MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1189     MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1190     MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1191     MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1192     MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1193     MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1194     MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1195     MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1196     MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1197     MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1198     MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1199
1200     MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1201     MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1202     MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1203     MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1204     MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1205     MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1206     MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1207     MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1208     MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1209     MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1210     MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1211     MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1212     MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1213     MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1214     MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1215     MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1216
1217     MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1218     MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1219     MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1220     MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1221     MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1222     MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1223     MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1224     MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1225     MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1226     MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1227     MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1228     MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1229     MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1230     MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1231     MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1232     MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1233
1234     buf[0] += a;
1235     buf[1] += b;
1236     buf[2] += c;
1237     buf[3] += d;
1238 }
1239 #define __fccache__
1240 #include "fcaliastail.h"
1241 #undef __fccache__