]> git.wh0rd.org Git - fontconfig.git/blob - src/fccache.c
5cb49bd17fe52e8dea5b3cca1a26cc21e6279dca
[fontconfig.git] / src / fccache.c
1 /*
2  * $RCSId: xc/lib/fontconfig/src/fccache.c,v 1.12 2002/08/22 07:36:44 keithp Exp $
3  *
4  * Copyright © 2000 Keith Packard
5  * Copyright © 2005 Patrick Lam
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and its
8  * documentation for any purpose is hereby granted without fee, provided that
9  * the above copyright notice appear in all copies and that both that
10  * copyright notice and this permission notice appear in supporting
11  * documentation, and that the name of Keith Packard not be used in
12  * advertising or publicity pertaining to distribution of the software without
13  * specific, written prior permission.  Keith Packard makes no
14  * representations about the suitability of this software for any purpose.  It
15  * is provided "as is" without express or implied warranty.
16  *
17  * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
18  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
19  * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
20  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
21  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
22  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23  * PERFORMANCE OF THIS SOFTWARE.
24  */
25
26 #include "fcint.h"
27 #include <fcntl.h>
28 #include <dirent.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
32 #  include <unistd.h>
33 #  include <sys/mman.h>
34 #elif defined(_WIN32)
35 #  include <windows.h>
36 #endif
37
38 #define ENDIAN_TEST 0x12345678
39 #define MACHINE_SIGNATURE_SIZE (9 + 5*20 + 1)
40 /* for when we don't have sysconf: */
41 #define FC_HARDCODED_PAGESIZE 8192 
42
43 #ifndef O_BINARY
44 #define O_BINARY 0
45 #endif
46
47 static int
48 FcDirCacheOpen (const FcChar8 * dir);
49
50 static char *
51 FcDirCacheHashName (const FcChar8 * dir, int collisions);
52
53 static off_t
54 FcCacheSkipToArch (int fd, const char * arch);
55
56 static FcBool 
57 FcCacheCopyOld (int fd, int fd_orig, off_t start);
58
59 static void *
60 FcDirCacheProduce (FcFontSet *set, FcCache * metadata);
61
62 static FcBool
63 FcDirCacheConsume (int fd, const char * dir, FcFontSet *set, FcConfig *config);
64
65 static int
66 FcCacheNextOffset(off_t w);
67
68 static char *
69 FcCacheMachineSignature (void);
70
71 static FcBool
72 FcCacheHaveBank (int bank);
73
74 static void
75 FcCacheAddBankDir (int bank, const char * dir);
76
77 struct MD5Context {
78         FcChar32 buf[4];
79         FcChar32 bits[2];
80         unsigned char in[64];
81 };
82
83 static void MD5Init(struct MD5Context *ctx);
84 static void MD5Update(struct MD5Context *ctx, unsigned char *buf, unsigned len);
85 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx);
86 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16]);
87
88 #define FC_DBG_CACHE_REF    1024
89
90 static char *
91 FcCacheReadString (int fd, char *dest, int len)
92 {
93     int    size;
94     int    slen;
95
96     if (len == 0)
97         return 0;
98
99     size = read (fd, dest, len-1);
100
101     if (size > 0)
102     {
103         dest[size] = '\0';
104         slen = strlen (dest);
105
106         lseek (fd, slen - size + 1, SEEK_CUR);
107         return slen < len ? dest : 0;
108     }
109
110     return 0;
111 }
112
113 static void
114 FcCacheSkipString (int fd)
115 {
116     char buf[256];
117     int  size;
118     int  slen;
119
120     while ( (size = read (fd, buf, sizeof (buf)-1)) > 0) 
121     {
122         buf [size] = '\0';
123         slen = strlen (buf);
124         if (slen < size) 
125         {
126             lseek (fd, slen - size + 1, SEEK_CUR);
127             return;
128         }
129     }
130 }
131
132 static FcBool
133 FcCacheWriteString (int fd, const char *chars)
134 {
135     if (write (fd, chars, strlen(chars)+1) != strlen(chars)+1)
136         return FcFalse;
137     return FcTrue;
138 }
139
140 static void
141 FcGlobalCacheDirDestroy (FcGlobalCacheDir *d)
142 {
143     FcStrSetDestroy (d->subdirs);
144     FcMemFree (FC_MEM_STRING, strlen (d->name)+1);
145     free (d->name);
146     FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCacheDir));
147     free (d);
148 }
149
150 FcGlobalCache *
151 FcGlobalCacheCreate (void)
152 {
153     FcGlobalCache   *cache;
154
155     cache = malloc (sizeof (FcGlobalCache));
156     if (!cache)
157         return 0;
158     FcMemAlloc (FC_MEM_CACHE, sizeof (FcGlobalCache));
159     cache->dirs = 0;
160     cache->updated = FcFalse;
161     cache->fd = -1;
162     return cache;
163 }
164
165 void
166 FcGlobalCacheDestroy (FcGlobalCache *cache)
167 {
168     FcGlobalCacheDir    *d, *next;
169
170     for (d = cache->dirs; d; d = next)
171     {
172         next = d->next;
173         FcGlobalCacheDirDestroy (d);
174     }
175     FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCache));
176     free (cache);
177 }
178
179 void
180 FcGlobalCacheLoad (FcGlobalCache    *cache,
181                    FcStrSet         *staleDirs,
182                    const FcChar8    *cache_file,
183                    FcConfig         *config)
184 {
185     char                name_buf[FC_MAX_FILE_LEN];
186     FcGlobalCacheDir    *d, *next;
187     FcFileTime          config_time = FcConfigModifiedTime (config);
188     char                * current_arch_machine_name;
189     char                candidate_arch_machine_name[MACHINE_SIGNATURE_SIZE + 9];
190     off_t               current_arch_start;
191
192     struct stat         cache_stat, dir_stat;
193     char                subdirName[FC_MAX_FILE_LEN + 1 + 12 + 1];
194
195     if (stat ((char *) cache_file, &cache_stat) < 0)
196         return;
197
198     cache->fd = open ((char *) cache_file, O_RDONLY | O_BINARY);
199     if (cache->fd == -1)
200         return;
201
202     cache->updated = FcFalse;
203
204     if (!FcCacheReadString (cache->fd, name_buf, sizeof (name_buf)))
205         goto bail_and_destroy;
206     if (strcmp (name_buf, FC_GLOBAL_MAGIC_COOKIE) != 0)
207         goto bail_and_destroy;
208
209     current_arch_machine_name = FcCacheMachineSignature ();
210     current_arch_start = FcCacheSkipToArch(cache->fd, 
211                                            current_arch_machine_name);
212     if (current_arch_start < 0)
213         goto bail1;
214
215     lseek (cache->fd, current_arch_start, SEEK_SET);
216     if (!FcCacheReadString (cache->fd, candidate_arch_machine_name, 
217                             sizeof (candidate_arch_machine_name)))
218         goto bail_and_destroy;
219     if (strlen(candidate_arch_machine_name) == 0)
220         goto bail_and_destroy;
221
222     while (1) 
223     {
224         off_t targ;
225
226         if (!FcCacheReadString (cache->fd, name_buf, sizeof (name_buf)) || 
227             !strlen(name_buf))
228             break;
229
230         /* Directory must be older than the global cache file; also
231            cache must be newer than the config file. */
232         if (stat ((char *) name_buf, &dir_stat) < 0 || 
233             dir_stat.st_mtime > cache_stat.st_mtime ||
234             (config_time.set && cache_stat.st_mtime < config_time.time))
235         {
236             FcCache md;
237             off_t off;
238
239             FcStrSetAdd (staleDirs, (FcChar8 *)name_buf);
240
241             /* skip subdirs */
242             while (FcCacheReadString (cache->fd, subdirName, 
243                                       sizeof (subdirName)) &&
244                    strlen (subdirName))
245                 ;
246
247             if (read (cache->fd, &md, sizeof (FcCache)) != sizeof(FcCache)) 
248             {
249                 perror ("read metadata");
250                 goto bail1;
251             }
252             off = FcCacheNextOffset (lseek(cache->fd, 0, SEEK_CUR)) + md.count;
253             if (lseek (cache->fd, off, SEEK_SET) != off) 
254             {
255                 perror ("lseek");
256                 goto bail1;
257             }
258             continue;
259         }
260
261         d = malloc (sizeof (FcGlobalCacheDir));
262         if (!d)
263             goto bail1;
264
265         d->next = cache->dirs;
266         cache->dirs = d;
267
268         d->name = (char *)FcStrCopy ((FcChar8 *)name_buf);
269         d->ent = 0;
270         d->state = FcGCDirFileRead;
271
272         d->subdirs = FcStrSetCreate();
273         do
274         {
275             if (!FcCacheReadString (cache->fd, subdirName, 
276                                     sizeof (subdirName)) ||
277                 !strlen (subdirName))
278                 break;
279             FcStrSetAdd (d->subdirs, (FcChar8 *)subdirName);
280         } while (1);
281
282         d->offset = lseek (cache->fd, 0, SEEK_CUR);
283         if (read (cache->fd, &d->metadata, sizeof (FcCache)) != sizeof (FcCache))
284             goto bail1;
285         targ = FcCacheNextOffset (lseek(cache->fd, 0, SEEK_CUR)) + d->metadata.count;
286         if (lseek (cache->fd, targ, SEEK_SET) != targ)
287             goto bail1;
288     }
289     return;
290
291  bail1:
292     for (d = cache->dirs; d; d = next)
293     {
294         next = d->next;
295         free (d);
296     }
297     cache->dirs = 0;
298
299     close (cache->fd);
300     cache->fd = -1;
301     return;
302
303  bail_and_destroy:
304     close (cache->fd);
305     cache->fd = -1;
306
307     if (stat ((char *) cache_file, &cache_stat) == 0)
308         unlink ((char *)cache_file);
309
310     return;
311
312 }
313
314 FcBool
315 FcGlobalCacheReadDir (FcFontSet *set, FcStrSet *dirs, FcGlobalCache * cache, const char *dir, FcConfig *config)
316 {
317     FcGlobalCacheDir    *d;
318     int                 i;
319
320     if (cache->fd == -1)
321         return FcFalse;
322
323     if (config)
324         if (!(dir = (char *)FcConfigNormalizeFontDir (config, (FcChar8 *)dir)))
325             return FcFalse; /* non-existing directory */
326
327     for (d = cache->dirs; d; d = d->next)
328     {
329         if (strcmp (d->name, dir) == 0)
330         {
331             if (d->state == FcGCDirDisabled)
332                 return FcFalse;
333
334             if (d->state == FcGCDirFileRead) 
335             {
336                 lseek (cache->fd, d->offset, SEEK_SET);
337                 if (!FcDirCacheConsume (cache->fd, d->name, set, config))
338                     return FcFalse;
339
340                 for (i = 0; i < d->subdirs->num; i++)
341                     FcStrSetAdd (dirs, (FcChar8 *)d->subdirs->strs[i]);
342
343                 d->state = FcGCDirConsumed;
344             }
345             return FcTrue;
346         }
347     }
348
349     return FcFalse;
350 }
351
352 static FcGlobalCacheDir *
353 FcGlobalCacheDirFind (FcGlobalCache *cache, const char *name)
354 {
355     FcGlobalCacheDir * d;
356
357     if (!cache || !name)
358         return NULL;
359
360     for (d = cache->dirs; d; d = d->next)
361         if (strcmp((const char *)d->name, (const char *)name) == 0)
362             return d;
363
364     return NULL;
365  }
366
367 FcBool
368 FcGlobalCacheUpdate (FcGlobalCache  *cache,
369                      FcStrSet       *dirs,
370                      const char     *orig_name,
371                      FcFontSet      *set,
372                      FcConfig       *config)
373 {
374     FcGlobalCacheDir    *d;
375     int                 i;
376     const char *name;
377
378     name = (char *)FcConfigNormalizeFontDir (config, (FcChar8 *)orig_name);
379     if (!name) 
380     {
381         fprintf(stderr, "Invalid directory name %s\n", orig_name);
382         return FcFalse;
383     }
384
385     d = FcGlobalCacheDirFind (cache, name);
386
387     if (!d)
388     {
389         d = malloc (sizeof (FcGlobalCacheDir));
390         if (!d)
391             return FcFalse;
392         d->next = cache->dirs;
393         cache->dirs = d;
394     } else {
395         /* free old resources */
396         FcStrFree ((FcChar8 *)d->name);
397         free (d->ent);
398         FcStrSetDestroy (d->subdirs);
399     }
400
401     cache->updated = FcTrue;
402
403     d->name = (char *)FcStrCopy ((FcChar8 *)name);
404     d->ent = FcDirCacheProduce (set, &d->metadata);
405     d->offset = 0;
406     d->subdirs = FcStrSetCreate();
407     d->state = FcGCDirUpdated;
408     for (i = 0; i < dirs->num; i++)
409         FcStrSetAdd (d->subdirs, dirs->strs[i]);
410     return FcTrue;
411 }
412
413 FcBool
414 FcGlobalCacheSave (FcGlobalCache    *cache,
415                    const FcChar8    *cache_file,
416                    FcConfig         *config)
417 {
418     int                 fd, fd_orig;
419     FcGlobalCacheDir    *dir;
420     FcAtomic            *atomic;
421     off_t               current_arch_start = 0, truncate_to;
422     char                * current_arch_machine_name, * header;
423
424     if (!cache->updated)
425         return FcTrue;
426     
427 #if defined (HAVE_GETUID) && defined (HAVE_GETEUID)
428     /* Set-UID programs can't safely update the cache */
429     if (getuid () != geteuid ())
430         return FcFalse;
431 #endif
432     
433     atomic = FcAtomicCreate (cache_file);
434     if (!atomic)
435         return FcFalse;
436
437     if (!FcAtomicLock (atomic))
438         goto bail1;
439     fd = open ((char *) FcAtomicNewFile(atomic), O_RDWR | O_CREAT | O_BINARY, 
440                S_IRUSR | S_IWUSR);
441     if (fd == -1)
442         goto bail2;
443     FcCacheWriteString (fd, FC_GLOBAL_MAGIC_COOKIE);
444
445     fd_orig = open ((char *) FcAtomicOrigFile(atomic), O_RDONLY | O_BINARY);
446
447     current_arch_machine_name = FcCacheMachineSignature ();
448     if (fd_orig == -1)
449         current_arch_start = 0;
450     else
451         current_arch_start = FcCacheSkipToArch (fd_orig, 
452                                                 current_arch_machine_name);
453
454     if (current_arch_start < 0)
455     {
456         off_t i = lseek(fd_orig, 0, SEEK_END);
457         if (i < strlen (FC_GLOBAL_MAGIC_COOKIE)+1)
458             i = strlen (FC_GLOBAL_MAGIC_COOKIE)+1;
459         current_arch_start = FcCacheNextOffset (i);
460     }
461
462     if (!FcCacheCopyOld(fd, fd_orig, current_arch_start))
463         goto bail3;
464
465     current_arch_start = lseek(fd, 0, SEEK_CUR);
466 #if defined (HAVE_FTRUNCATE)
467     if (ftruncate (fd, current_arch_start) == -1)
468         goto bail3;
469 #else
470 #if defined (HAVE_CHSIZE)
471     if (chsize (fd, current_arch_start) == -1)
472         goto bail3;
473 #else
474     goto bail3;
475 #endif
476 #endif
477
478     header = malloc (10 + strlen (current_arch_machine_name));
479     if (!header)
480         goto bail3;
481
482     truncate_to = current_arch_start + strlen(current_arch_machine_name) + 11;
483     for (dir = cache->dirs; dir; dir = dir->next)
484     {
485         int i;
486
487         if (dir->state == FcGCDirDisabled)
488             continue;
489         truncate_to += strlen(dir->name) + 1;
490         truncate_to += sizeof (FcCache);
491         truncate_to = FcCacheNextOffset (truncate_to);
492         truncate_to += dir->metadata.count;
493
494         for (i = 0; i < dir->subdirs->size; i++)
495             truncate_to += strlen((char *)dir->subdirs->strs[i]) + 1;
496         truncate_to ++;
497     }
498     truncate_to -= current_arch_start;
499
500     sprintf (header, "%8x ", (int)truncate_to);
501     strcat (header, current_arch_machine_name);
502     if (!FcCacheWriteString (fd, header))
503         goto bail4;
504
505     free (header);
506
507     for (dir = cache->dirs; dir; dir = dir->next)
508     {
509         int i;
510         const char * d;
511         off_t off;
512
513         if (!dir->name || dir->state == FcGCDirDisabled)
514             continue;
515         d = (const char *)FcConfigNormalizeFontDir (config, (const FcChar8 *)dir->name);
516         if (!d) 
517             continue;
518             
519         if (dir->metadata.count && !dir->ent) 
520         {
521             if (dir->state == FcGCDirUpdated || fd_orig < 0) 
522             {
523                 fprintf(stderr, "Invalid metadata entry for %s, skipping...\n", d);
524                 continue;
525             }
526             /* copy the old content */
527             dir->ent = malloc (dir->metadata.count);
528             if (!dir->ent) 
529             {
530                 perror("malloc error");
531                 continue;
532             }
533             off = FcCacheNextOffset (dir->offset + sizeof(FcCache));
534             if (lseek (fd_orig, off, SEEK_SET) != off) 
535             {
536                 perror("lseek");
537                 free(dir->ent);
538                 continue;
539             }
540             if (read (fd_orig, dir->ent, dir->metadata.count)
541                 != dir->metadata.count) 
542             {
543                 perror("read");
544                 free(dir->ent);
545                 continue;
546             }
547         }
548         
549         FcCacheWriteString (fd, d);
550
551         for (i = 0; i < dir->subdirs->size; i++)
552             FcCacheWriteString (fd, (char *)dir->subdirs->strs[i]);
553         FcCacheWriteString (fd, "");
554         
555         if (write (fd, &dir->metadata, sizeof(FcCache)) != sizeof(FcCache))
556         {
557             perror ("write metadata");
558             free (dir->ent);
559             continue;
560         }
561         off = FcCacheNextOffset (lseek(fd, 0, SEEK_CUR));
562         if (lseek (fd, off, SEEK_SET) != off)
563         {
564             perror ("lseek");
565             free (dir->ent);
566             continue;
567         }
568         if (dir->metadata.count)
569         {
570             if (write (fd, dir->ent, dir->metadata.count) != dir->metadata.count)
571             {
572                 perror ("write dirent");
573                 free (dir->ent);
574                 continue;
575             }
576         }
577         free (dir->ent);
578     }
579     FcCacheWriteString (fd, "");
580
581     if (close (fd) == -1)
582         goto bail25;
583
584     close (fd_orig);
585     fd_orig = -1;
586     
587     if (!FcAtomicReplaceOrig (atomic))
588         goto bail25;
589     
590     FcAtomicUnlock (atomic);
591     FcAtomicDestroy (atomic);
592
593     cache->updated = FcFalse;
594     return FcTrue;
595
596  bail4:
597     free (header);
598  bail3:
599     if (fd_orig != -1)
600         close (fd_orig);
601
602     close (fd);
603  bail25:
604     FcAtomicDeleteNew (atomic);
605  bail2:
606     FcAtomicUnlock (atomic);
607  bail1:
608     FcAtomicDestroy (atomic);
609     return FcFalse;
610 }
611
612 /* 
613  * Find the next presumably-mmapable offset after the supplied file
614  * position.
615  */
616 static int
617 FcCacheNextOffset(off_t w)
618 {
619     static long pagesize = -1;
620
621     if (w == -1)
622         return w;
623
624     if (pagesize == -1)
625 #if defined (HAVE_SYSCONF)
626         pagesize = sysconf(_SC_PAGESIZE);
627 #else
628         pagesize = FC_HARDCODED_PAGESIZE;
629 #endif
630     if (w % pagesize == 0) 
631         return w;
632     else
633         return ((w / pagesize)+1)*pagesize;
634 }
635
636 /* return the address of the segment for the provided arch,
637  * or -1 if arch not found */
638 static off_t
639 FcCacheSkipToArch (int fd, const char * arch)
640 {
641     char candidate_arch_machine_name_count[MACHINE_SIGNATURE_SIZE + 9];
642     char * candidate_arch;
643     off_t current_arch_start = 0;
644
645     lseek (fd, 0, SEEK_SET);
646     FcCacheSkipString (fd);
647     current_arch_start = lseek (fd, 0, SEEK_CUR);
648
649     /* skip arches that are not the current arch */
650     while (1)
651     {
652         long bs;
653
654         if (lseek (fd, current_arch_start, SEEK_SET) != current_arch_start)
655             return -1;
656
657         if (FcCacheReadString (fd, candidate_arch_machine_name_count, 
658                                 sizeof (candidate_arch_machine_name_count)) == 0)
659             return -1;
660         if (!strlen(candidate_arch_machine_name_count))
661             return -1;
662         bs = strtol(candidate_arch_machine_name_count, &candidate_arch, 16);
663
664         /* count = 0 should probably be distinguished from the !bs condition */
665         if (!bs || bs < strlen (candidate_arch_machine_name_count))
666             return -1;
667
668         candidate_arch++; /* skip leading space */
669
670         if (strcmp (candidate_arch, arch)==0)
671             return current_arch_start;
672         current_arch_start += bs;
673         current_arch_start = FcCacheNextOffset (current_arch_start);
674     }
675 }
676
677 /* Cuts out the segment at the file pointer (moves everything else
678  * down to cover it), and leaves the file pointer at the end of the
679  * file. */
680 static FcBool 
681 FcCacheCopyOld (int fd, int fd_orig, off_t start)
682 {
683     char * buf = malloc (8192);
684     char candidate_arch_machine_name[MACHINE_SIGNATURE_SIZE + 9];
685     long bs;
686     int c, bytes_skipped;
687     off_t loc;
688
689     if (!buf)
690         return FcFalse;
691
692     loc = 0;
693     lseek (fd, 0, SEEK_SET); lseek (fd_orig, 0, SEEK_SET);
694     FcCacheSkipString (fd); FcCacheSkipString (fd_orig);
695     do
696     {
697         int b = 8192;
698         if (loc + b > start)
699             b = start - loc;
700
701         if ((c = read (fd_orig, buf, b)) <= 0)
702             break;
703         if (write (fd, buf, c) < 0)
704             goto bail;
705
706         loc += c;
707     }
708     while (c > 0);
709
710     lseek (fd, start, SEEK_SET);
711     if (FcCacheReadString (fd, candidate_arch_machine_name, 
712                            sizeof (candidate_arch_machine_name)) == 0)
713         goto done;
714     if (!strlen(candidate_arch_machine_name))
715         goto done;
716
717     bs = strtol(candidate_arch_machine_name, 0, 16);
718     if (bs == 0)
719         goto done;
720
721     bytes_skipped = 0;
722     do
723     {
724         lseek (fd, start+bs+bytes_skipped, SEEK_SET);
725         if ((c = read (fd, buf, 8192)) <= 0)
726             break;
727         lseek (fd, start+bytes_skipped, SEEK_SET);
728         if (write (fd, buf, c) < 0)
729             goto bail;
730         bytes_skipped += c;
731     }
732     while (c > 0);
733     lseek (fd, start+bytes_skipped, SEEK_SET);
734
735  done:
736     free (buf);
737     return FcTrue;
738
739  bail:
740     free (buf);
741     return FcFalse;
742 }
743
744 /* Does not check that the cache has the appropriate arch section. */
745 /* Also, this can be fooled if the original location has a stale
746  * cache, and the hashed location has an up-to-date cache.  Oh well,
747  * sucks to be you in that case! */
748 FcBool
749 FcDirCacheValid (const FcChar8 *dir)
750 {
751     struct stat file_stat, dir_stat;
752     int         fd;
753
754     if (stat ((char *) dir, &dir_stat) < 0)
755         return FcFalse;
756
757     fd = FcDirCacheOpen (dir);
758
759     if (fd < 0)
760         return FcFalse;
761     if (fstat (fd, &file_stat) < 0)
762         goto bail;
763
764     close (fd);
765
766     /*
767      * If the directory has been modified more recently than
768      * the cache file, the cache is not valid
769      */
770     if (dir_stat.st_mtime > file_stat.st_mtime)
771         return FcFalse;
772
773     return FcTrue;
774
775  bail:
776     close (fd);
777     return FcFalse;
778 }
779
780 /* Assumes that the cache file in 'dir' exists.
781  * Checks that the cache has the appropriate arch section. */
782 FcBool
783 FcDirCacheHasCurrentArch (const FcChar8 *dir)
784 {
785     int         fd;
786     off_t       current_arch_start;
787     char        *current_arch_machine_name;
788     FcCache     metadata;
789     char        subdirName[FC_MAX_FILE_LEN + 1 + 12 + 1];
790
791     fd = FcDirCacheOpen (dir);
792     if (fd < 0)
793         goto bail;
794
795     current_arch_machine_name = FcCacheMachineSignature();
796     current_arch_start = FcCacheSkipToArch(fd, current_arch_machine_name);
797
798     if (current_arch_start >= 0)
799     {
800         if (lseek (fd, current_arch_start, SEEK_SET) != current_arch_start)
801             goto bail1;
802
803         FcCacheSkipString (fd);
804
805         while (FcCacheReadString (fd, subdirName, sizeof (subdirName)) && strlen (subdirName) > 0)
806             ;
807
808         if (read(fd, &metadata, sizeof(FcCache)) != sizeof(FcCache))
809             goto bail1;
810
811         if (metadata.magic != FC_CACHE_MAGIC)
812             goto bail1;
813     }
814
815     close (fd);
816
817     if (current_arch_start < 0)
818         return FcFalse;
819     
820     return FcTrue;
821
822  bail1:
823     close (fd);
824  bail:
825     return FcFalse;
826 }
827
828 FcBool
829 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
830 {
831     char        *cache_hashed = 0;
832     int         fd, collisions;
833     struct stat cache_stat;
834     char        dir_buf[FC_MAX_FILE_LEN];
835
836     dir = FcConfigNormalizeFontDir (config, dir);
837
838     /* Remove any applicable hashed files. */
839     fd = -1; collisions = 0;
840     do
841     {
842         if (cache_hashed)
843             FcStrFree ((FcChar8 *)cache_hashed);
844
845         cache_hashed = FcDirCacheHashName (dir, collisions++);
846         if (!cache_hashed)
847             goto bail;
848
849         if (fd > 0)
850             close (fd);
851         fd = open(cache_hashed, O_RDONLY | O_BINARY);
852         if (fd == -1)
853         {
854             FcStrFree ((FcChar8 *)cache_hashed);
855             return FcTrue;
856         }
857
858         if (!FcCacheReadString (fd, dir_buf, sizeof (dir_buf)) || !strlen(dir_buf))
859         {
860             FcStrFree ((FcChar8 *)cache_hashed);
861             goto bail;
862         }
863     } while (strcmp ((char *) dir_buf, (char *) dir) != 0);
864
865     close (fd);
866
867     if (stat ((char *) cache_hashed, &cache_stat) == 0 &&
868         unlink ((char *)cache_hashed) != 0)
869     {
870         FcStrFree ((FcChar8 *)cache_hashed);
871         goto bail;
872     }
873
874     FcStrFree ((FcChar8 *)cache_hashed);
875     return FcTrue;
876
877  bail:
878     return FcFalse;
879 }
880
881 static int
882 FcCacheReadDirs (FcConfig * config, FcGlobalCache * cache, 
883                  FcStrList *list, FcFontSet * set, FcStrSet *processed_dirs)
884 {
885     int                 ret = 0;
886     FcChar8             *dir;
887     FcStrSet            *subdirs;
888     FcStrList           *sublist;
889     struct stat         statb;
890     FcGlobalCacheDir   *d;
891
892     /*
893      * Read in the results from 'list'.
894      */
895     while ((dir = FcStrListNext (list)))
896     {
897         if (!FcConfigAcceptFilename (config, dir))
898             continue;
899
900         /* Skip this directory if already updated
901          * to avoid the looped directories via symlinks
902          * Clearly a dir not in fonts.conf shouldn't be globally cached.
903          */
904         dir = (FcChar8 *)FcConfigNormalizeFontDir (config, dir);
905         if (!dir)
906             continue;
907
908         if (FcStrSetMember (processed_dirs, dir))
909             continue;
910         if (!FcStrSetAdd (processed_dirs, dir))
911             continue;
912
913         subdirs = FcStrSetCreate ();
914         if (!subdirs)
915         {
916             fprintf (stderr, "Can't create directory set\n");
917             ret++;
918             continue;
919         }
920         
921         if (access ((char *) dir, X_OK) < 0)
922         {
923             switch (errno) {
924             case ENOENT:
925             case ENOTDIR:
926             case EACCES:
927                 break;
928             default:
929                 fprintf (stderr, "\"%s\": ", dir);
930                 perror ("");
931                 ret++;
932             }
933             FcStrSetDestroy (subdirs);
934             continue;
935         }
936         if (stat ((char *) dir, &statb) == -1)
937         {
938             fprintf (stderr, "\"%s\": ", dir);
939             perror ("");
940             FcStrSetDestroy (subdirs);
941             ret++;
942             continue;
943         }
944         if (!S_ISDIR (statb.st_mode))
945         {
946             fprintf (stderr, "\"%s\": not a directory, skipping\n", dir);
947             FcStrSetDestroy (subdirs);
948             continue;
949         }
950         if (FcDirCacheValid (dir) && 
951             FcDirCacheHasCurrentArch (dir) && 
952             FcDirCacheRead (set, subdirs, dir, config))
953         {
954             /* if an old entry is found in the global cache, disable it */
955             if ((d = FcGlobalCacheDirFind (cache, (const char *)dir)) != NULL)
956             {
957                 d->state = FcGCDirDisabled;
958                 /* save the updated config later without this entry */
959                 cache->updated = FcTrue;
960             }
961         }
962         else
963         {
964             if (FcDebug () & FC_DBG_FONTSET)
965                 printf ("cache scan dir %s\n", dir);
966
967             FcDirScanConfig (set, subdirs, cache, 
968                              config->blanks, dir, FcFalse, config);
969         }
970         sublist = FcStrListCreate (subdirs);
971         FcStrSetDestroy (subdirs);
972         if (!sublist)
973         {
974             fprintf (stderr, "Can't create subdir list in \"%s\"\n", dir);
975             ret++;
976             continue;
977         }
978         ret += FcCacheReadDirs (config, cache, sublist, set, processed_dirs);
979     }
980     FcStrListDone (list);
981     return ret;
982 }
983
984 FcFontSet *
985 FcCacheRead (FcConfig *config, FcGlobalCache * cache)
986 {
987     FcFontSet   *s = FcFontSetCreate();
988     FcStrSet    *processed_dirs;
989
990     if (!s) 
991         return 0;
992
993     processed_dirs = FcStrSetCreate();
994     if (!processed_dirs)
995         goto bail;
996
997     if (FcCacheReadDirs (config, cache, FcConfigGetConfigDirs (config), s, processed_dirs))
998         goto bail1;
999
1000     FcStrSetDestroy (processed_dirs);
1001     return s;
1002
1003  bail1:
1004     FcStrSetDestroy (processed_dirs);
1005  bail:
1006     FcFontSetDestroy (s);
1007     return 0;
1008 }
1009
1010 static const char bin2hex[] = { '0', '1', '2', '3',
1011                                 '4', '5', '6', '7',
1012                                 '8', '9', 'a', 'b',
1013                                 'c', 'd', 'e', 'f' };
1014
1015 static char *
1016 FcDirCacheHashName (const FcChar8 * dir, int collisions)
1017 {
1018     unsigned char       hash[16], hex_hash[33];
1019     char                *cache_hashed;
1020     unsigned char       uscore = '_';
1021     int                 cnt, i;
1022     FcChar8             *tmp;
1023     struct MD5Context   ctx;
1024
1025     MD5Init (&ctx);
1026     MD5Update (&ctx, (unsigned char *)dir, strlen ((char *) dir));
1027
1028     for (i = 0; i < collisions; i++)
1029         MD5Update (&ctx, &uscore, 1);
1030
1031     MD5Final (hash, &ctx);
1032
1033     for (cnt = 0; cnt < 16; ++cnt)
1034     {
1035         hex_hash[2*cnt] = bin2hex[hash[cnt] >> 4];
1036         hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
1037     }
1038     hex_hash[32] = 0;
1039
1040     tmp = FcStrPlus ((FcChar8 *)hex_hash, (FcChar8 *)FC_CACHE_SUFFIX);
1041     if (!tmp)
1042         return 0;
1043
1044     cache_hashed = (char *)FcStrPlus ((FcChar8 *)PKGCACHEDIR"/", tmp);
1045     free (tmp);
1046
1047     return cache_hashed;
1048 }
1049
1050 /* Opens the hashed name for cache_file.
1051  * This would fail in the unlikely event of a collision and subsequent
1052  * removal of the file which originally caused the collision. */
1053 static int
1054 FcDirCacheOpen (const FcChar8 *dir)
1055 {
1056     FcBool      found;
1057     int         fd = -1, collisions = 0;
1058     char        *cache_hashed;
1059     char        dir_buf[FC_MAX_FILE_LEN];
1060     struct stat dir_stat;
1061
1062     if (stat ((char *)dir, &dir_stat) == -1)
1063         return -1;
1064
1065     found = FcFalse;
1066     do
1067     {
1068         struct stat     c;
1069
1070         if (fd >= 0)
1071             close (fd);
1072
1073         cache_hashed = FcDirCacheHashName (dir, collisions++);
1074         if (!cache_hashed)
1075             return -1;
1076
1077         fd = open(cache_hashed, O_RDONLY | O_BINARY);
1078         FcStrFree ((FcChar8 *)cache_hashed);
1079
1080         if (fd == -1)
1081             break;
1082         if (!FcCacheReadString (fd, dir_buf, sizeof (dir_buf)) || 
1083             !strlen(dir_buf))
1084             break;
1085
1086         if (stat ((char *)dir_buf, &c) == -1)
1087             continue;
1088
1089         found = (c.st_ino == dir_stat.st_ino) && (c.st_dev == dir_stat.st_dev);
1090     } while (!found);
1091
1092     return fd;
1093 }
1094
1095 /* read serialized state from the cache file */
1096 FcBool
1097 FcDirCacheRead (FcFontSet * set, FcStrSet * dirs, const FcChar8 *dir, FcConfig *config)
1098 {
1099     int         fd;
1100     char        *current_arch_machine_name;
1101     char        candidate_arch_machine_name[9+MACHINE_SIGNATURE_SIZE];
1102     off_t       current_arch_start = 0;
1103     char        subdirName[FC_MAX_FILE_LEN + 1 + 12 + 1];
1104
1105     fd = FcDirCacheOpen (dir);
1106     if (fd < 0)
1107         goto bail;
1108
1109     current_arch_machine_name = FcCacheMachineSignature();
1110     current_arch_start = FcCacheSkipToArch(fd, 
1111                                            current_arch_machine_name);
1112     if (current_arch_start < 0)
1113         goto bail1;
1114
1115     lseek (fd, current_arch_start, SEEK_SET);
1116     if (FcCacheReadString (fd, candidate_arch_machine_name, 
1117                            sizeof (candidate_arch_machine_name)) == 0)
1118         goto bail1;
1119
1120     while (FcCacheReadString (fd, subdirName, sizeof (subdirName)) && strlen (subdirName) > 0)
1121         FcStrSetAdd (dirs, (FcChar8 *)subdirName);
1122
1123     if (!FcDirCacheConsume (fd, (const char *)dir, set, config))
1124         goto bail1;
1125         
1126     close(fd);
1127     return FcTrue;
1128
1129  bail1:
1130     close (fd);
1131  bail:
1132     return FcFalse;
1133 }
1134
1135 static FcBool
1136 FcDirCacheConsume (int fd, const char * dir, FcFontSet *set, FcConfig *config)
1137 {
1138     FcCache metadata;
1139     void * current_dir_block;
1140     off_t pos, endpos;
1141
1142     if (read(fd, &metadata, sizeof(FcCache)) != sizeof(FcCache))
1143         return FcFalse;
1144     if (metadata.magic != FC_CACHE_MAGIC)
1145         return FcFalse;
1146
1147     if (!metadata.count)
1148     {
1149         pos = FcCacheNextOffset (lseek(fd, 0, SEEK_CUR));
1150         lseek (fd, pos, SEEK_SET);
1151         if (config)
1152             FcConfigAddFontDir (config, (FcChar8 *)dir);
1153         return FcTrue;
1154     }
1155
1156     pos = FcCacheNextOffset (lseek(fd, 0, SEEK_CUR));
1157
1158     /* This is not failsafe (multi-arches can break it),
1159      * but fd has got to have at least as many bytes as
1160      * metadata.count, or something's going to go horribly wrong. */
1161     if (pos == (off_t)-1)
1162         return FcFalse;
1163
1164     endpos = lseek (fd, 0, SEEK_END);
1165     if (endpos == (off_t)-1 || endpos - pos < metadata.count)
1166         return FcFalse;
1167     if (lseek (fd, pos, SEEK_SET) == -1)
1168         return FcFalse;
1169
1170 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
1171     current_dir_block = mmap (0, metadata.count, 
1172                               PROT_READ, MAP_SHARED, fd, pos);
1173     if (current_dir_block == MAP_FAILED)
1174         return FcFalse;
1175 #elif defined(_WIN32)
1176         {
1177                 HANDLE hFileMap;
1178
1179                 hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL, PAGE_READONLY, 0, 0, NULL);
1180                 if (hFileMap == NULL)
1181                         return FcFalse;
1182
1183                 current_dir_block = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0, metadata.count + pos);
1184                 if (current_dir_block == NULL)
1185                 {
1186                         CloseHandle (hFileMap);
1187                         return FcFalse;
1188                 }
1189
1190                 current_dir_block = (void *)((char *)current_dir_block + pos);
1191         }
1192 #else
1193     current_dir_block = malloc (metadata.count);
1194     if (!current_dir_block)
1195         return FcFalse;
1196
1197     /* could also use CreateMappedViewOfFile under MinGW... */
1198     if (read (fd, current_dir_block, metadata.count) != metadata.count)
1199         goto bail;
1200 #endif
1201     lseek (fd, pos+metadata.count, SEEK_SET);
1202
1203     FcCacheAddBankDir (metadata.bank, dir);
1204     if (config)
1205         FcConfigAddFontDir (config, (FcChar8 *)dir);
1206
1207     if (!FcFontSetUnserialize (&metadata, set, current_dir_block))
1208         goto bail;
1209
1210     return FcTrue;
1211  bail:
1212 #if !(defined(HAVE_MMAP) || defined(__CYGWIN__))
1213     free (current_dir_block);
1214 #endif
1215     return FcFalse;
1216 }
1217
1218 static void *
1219 FcDirCacheProduce (FcFontSet *set, FcCache *metadata)
1220 {
1221     void * current_dir_block, * final_dir_block;
1222     static unsigned int rand_state = 0;
1223     int bank, needed_bytes_no_align;
1224
1225 #if defined (HAVE_RAND_R)
1226     if (!rand_state) 
1227         rand_state = time(0L);
1228     bank = rand_r(&rand_state);
1229
1230     while (FcCacheHaveBank(bank))
1231         bank = rand_r(&rand_state);
1232 #else
1233     if (!rand_state)
1234     {
1235         rand_state = 1;
1236         srand (time (0L));
1237     }
1238     bank = rand();
1239
1240     while (FcCacheHaveBank(bank))
1241         bank = rand();
1242 #endif
1243
1244     memset (metadata, 0, sizeof(FcCache));
1245     FcFontSetNewBank();
1246     needed_bytes_no_align = FcFontSetNeededBytes (set);
1247     metadata->count = needed_bytes_no_align + 
1248         FcFontSetNeededBytesAlign ();
1249     metadata->magic = FC_CACHE_MAGIC;
1250     metadata->bank = bank;
1251
1252     if (!needed_bytes_no_align) /* not a failure, no fonts to write */
1253     {
1254         /* no, you don't really need to write any bytes at all. */
1255         metadata->count = 0;
1256         return 0;
1257     }
1258
1259     current_dir_block = malloc (metadata->count);
1260     if (!current_dir_block)
1261         goto bail;
1262     /* shut up valgrind */
1263     memset (current_dir_block, 0, metadata->count);
1264     final_dir_block = FcFontSetDistributeBytes (metadata, current_dir_block);
1265
1266     if ((void *)((char *)current_dir_block+metadata->count) < final_dir_block)
1267         goto bail;
1268                               
1269     if (!FcFontSetSerialize (bank, set))
1270         goto bail;
1271
1272     return current_dir_block;
1273
1274  bail:
1275     free (current_dir_block);
1276     return 0;
1277 }
1278
1279 /* write serialized state to the cache file */
1280 FcBool
1281 FcDirCacheWrite (FcFontSet *set, FcStrSet *dirs, const FcChar8 *dir)
1282 {
1283     char            *cache_hashed;
1284     int             fd, fd_orig, i, dirs_count;
1285     FcAtomic        *atomic;
1286     FcCache         metadata;
1287     off_t           current_arch_start = 0, truncate_to;
1288     char            dir_buf[FC_MAX_FILE_LEN];
1289     int             collisions;
1290
1291     char            *current_arch_machine_name, * header;
1292     void            *current_dir_block = 0;
1293
1294     dir = FcConfigNormalizeFontDir (FcConfigGetCurrent(), dir);
1295     if (!dir)
1296         return FcFalse;
1297
1298     /* Ensure that we're not trampling a cache for some other dir. */
1299     /* This is slightly different from FcDirCacheOpen, since it 
1300      * needs the filename, not the file descriptor. */
1301     fd = -1; collisions = 0;
1302     do
1303     {
1304         cache_hashed = FcDirCacheHashName (dir, collisions++);
1305         if (!cache_hashed)
1306             goto bail0;
1307
1308         if (fd > 0)
1309             close (fd);
1310         fd = open(cache_hashed, O_RDONLY | O_BINARY);
1311         if (fd == -1)
1312             break;
1313         if(!FcCacheReadString (fd, dir_buf, sizeof (dir_buf)) || !strlen(dir_buf))
1314         {
1315             close (fd);
1316             FcStrFree ((FcChar8 *)cache_hashed);
1317             continue;
1318         }
1319         close (fd);
1320
1321         if (strcmp (dir_buf, (char *) dir) != 0) 
1322         {
1323             FcStrFree ((FcChar8 *)cache_hashed);
1324             continue;
1325         }
1326
1327         break;
1328     } while (1);
1329
1330     current_dir_block = FcDirCacheProduce (set, &metadata);
1331
1332     if (metadata.count && !current_dir_block)
1333         goto bail1;
1334
1335     if (FcDebug () & FC_DBG_CACHE)
1336         printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
1337                 dir, cache_hashed);
1338
1339     atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
1340     if (!atomic)
1341         goto bail1;
1342
1343     if (!FcAtomicLock (atomic))
1344         goto bail2;
1345
1346     /* open the original file to save relevant portions */
1347     fd_orig = open((char *)FcAtomicOrigFile (atomic), O_RDONLY | O_BINARY);
1348
1349     fd = open((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
1350     if (fd == -1)
1351         goto bail3;
1352
1353     FcCacheWriteString (fd, (char *) dir);
1354
1355     current_arch_machine_name = FcCacheMachineSignature ();
1356     current_arch_start = 0;
1357
1358     if (fd_orig != -1)
1359         current_arch_start = 
1360             FcCacheSkipToArch(fd_orig, current_arch_machine_name);
1361
1362     if (current_arch_start < 0)
1363     {
1364         off_t offset = lseek(fd_orig, 0, SEEK_END);
1365         current_arch_start = FcCacheNextOffset (offset);
1366     }
1367
1368     if (fd_orig != -1 && !FcCacheCopyOld(fd, fd_orig, current_arch_start))
1369         goto bail4;
1370
1371     if (fd_orig != -1)
1372         close (fd_orig);
1373
1374     current_arch_start = lseek(fd, 0, SEEK_CUR);
1375 #if defined (HAVE_FTRUNCATE)
1376     if (ftruncate (fd, current_arch_start) == -1)
1377         goto bail4;
1378 #else
1379 #if defined (HAVE_CHSIZE)
1380     if (chsize (fd, current_arch_start) == -1)
1381         goto bail4;
1382 #else
1383     goto bail4;
1384 #endif
1385 #endif
1386
1387     /* allocate space for subdir names in this block */
1388     dirs_count = 0;
1389     for (i = 0; i < dirs->size; i++)
1390         dirs_count += strlen((char *)dirs->strs[i]) + 1;
1391     dirs_count ++;
1392
1393     /* now write the address of the next offset */
1394     truncate_to = FcCacheNextOffset (FcCacheNextOffset (current_arch_start + sizeof (FcCache) + dirs_count) + metadata.count) - current_arch_start;
1395     header = malloc (10 + strlen (current_arch_machine_name));
1396     if (!header)
1397         goto bail4;
1398     sprintf (header, "%8x ", (int)truncate_to);
1399     strcat (header, current_arch_machine_name);
1400     if (!FcCacheWriteString (fd, header))
1401         goto bail5;
1402
1403     for (i = 0; i < dirs->size; i++)
1404         FcCacheWriteString (fd, (char *)dirs->strs[i]);
1405     FcCacheWriteString (fd, "");
1406
1407     if (write (fd, &metadata, sizeof(FcCache)) != sizeof(FcCache)) 
1408     {
1409         perror("write metadata");
1410         goto bail5;
1411     }
1412     if (metadata.count)
1413     {
1414         off_t off = FcCacheNextOffset (lseek(fd, 0, SEEK_END));
1415         if (lseek (fd, off, SEEK_SET) != off)
1416             perror("lseek");
1417         else if (write (fd, current_dir_block, metadata.count) !=
1418                  metadata.count)
1419             perror("write current_dir_block");
1420         free (current_dir_block);
1421         current_dir_block = 0;
1422     }
1423
1424     /* this actually serves to pad out the cache file, if needed */
1425 #if defined (HAVE_FTRUNCATE)
1426     if (ftruncate (fd, current_arch_start + truncate_to) == -1)
1427         goto bail5;
1428 #else
1429 #if defined (HAVE_CHSIZE)
1430     if (chsize (fd, current_arch_start + truncate_to) == -1)
1431         goto bail5;
1432 #else
1433     goto bail5;
1434 #endif
1435 #endif
1436
1437     free (header);
1438     close(fd);
1439     if (!FcAtomicReplaceOrig(atomic))
1440         goto bail3;
1441     FcStrFree ((FcChar8 *)cache_hashed);
1442     FcAtomicUnlock (atomic);
1443     FcAtomicDestroy (atomic);
1444     return FcTrue;
1445
1446  bail5:
1447     free (header);
1448  bail4:
1449     close (fd);
1450  bail3:
1451     FcAtomicUnlock (atomic);
1452  bail2:
1453     FcAtomicDestroy (atomic);
1454  bail1:
1455     FcStrFree ((FcChar8 *)cache_hashed);
1456  bail0:
1457     if (current_dir_block)
1458         free (current_dir_block);
1459     return FcFalse;
1460 }
1461
1462 static char *
1463 FcCacheMachineSignature ()
1464 {
1465     static char buf[MACHINE_SIGNATURE_SIZE];
1466     int32_t magic = ENDIAN_TEST;
1467     char * m = (char *)&magic;
1468
1469     sprintf (buf, "%2x%2x%2x%2x "
1470              "%4x %4x %4x %4x %4x %4x %4x %4x %4x %4x %4x %4x "
1471              "%4x %4x %4x %4x %4x %4x %4x %4x\n", 
1472              m[0], m[1], m[2], m[3],
1473              (unsigned int)sizeof (char),
1474              (unsigned int)sizeof (char *),
1475              (unsigned int)sizeof (int),
1476              (unsigned int)sizeof (FcPattern),
1477              (unsigned int)sizeof (FcPatternEltPtr),
1478              (unsigned int)sizeof (struct _FcPatternElt *),
1479              (unsigned int)sizeof (FcPatternElt),
1480              (unsigned int)sizeof (FcObjectPtr),
1481              (unsigned int)sizeof (FcValueListPtr),
1482              (unsigned int)sizeof (FcValue),
1483              (unsigned int)sizeof (FcValueBinding),
1484              (unsigned int)sizeof (struct _FcValueList *),
1485              (unsigned int)sizeof (FcCharSet),
1486              (unsigned int)sizeof (FcCharLeaf **),
1487              (unsigned int)sizeof (FcChar16 *),
1488              (unsigned int)sizeof (FcChar16),
1489              (unsigned int)sizeof (FcCharLeaf),
1490              (unsigned int)sizeof (FcChar32),
1491              (unsigned int)sizeof (FcCache),
1492 #if defined (HAVE_SYSCONF)
1493              (unsigned int)sysconf(_SC_PAGESIZE));
1494 #else
1495              (unsigned int)FC_HARDCODED_PAGESIZE);
1496 #endif
1497
1498     return buf;
1499 }
1500
1501 static int banks_ptr = 0, banks_alloc = 0;
1502 int * _fcBankId = 0, * _fcBankIdx = 0;
1503 static const char ** bankDirs = 0;
1504
1505 static FcBool
1506 FcCacheHaveBank (int bank)
1507 {
1508     int i;
1509
1510     if (bank < FC_BANK_FIRST)
1511         return FcTrue;
1512
1513     for (i = 0; i < banks_ptr; i++)
1514         if (_fcBankId[i] == bank)
1515             return FcTrue;
1516
1517     return FcFalse;
1518 }
1519
1520 int
1521 FcCacheBankToIndexMTF (int bank)
1522 {
1523     int i, j;
1524
1525     for (i = 0; i < banks_ptr; i++)
1526         if (_fcBankId[_fcBankIdx[i]] == bank)
1527         {
1528             int t = _fcBankIdx[i];
1529
1530             for (j = i; j > 0; j--)
1531                 _fcBankIdx[j] = _fcBankIdx[j-1];
1532             _fcBankIdx[0] = t;
1533             return t;
1534         }
1535
1536     if (banks_ptr >= banks_alloc)
1537     {
1538         int * b, * bidx;
1539         const char ** bds;
1540
1541         b = realloc (_fcBankId, (banks_alloc + 4) * sizeof(int));
1542         if (!b)
1543             return -1;
1544         _fcBankId = b;
1545
1546         bidx = realloc (_fcBankIdx, (banks_alloc + 4) * sizeof(int));
1547         if (!bidx)
1548             return -1;
1549         _fcBankIdx = bidx;
1550
1551         bds = realloc (bankDirs, (banks_alloc + 4) * sizeof (char *));
1552         if (!bds)
1553             return -1;
1554         bankDirs = bds;
1555
1556         banks_alloc += 4;
1557     }
1558
1559     i = banks_ptr++;
1560     _fcBankId[i] = bank;
1561     _fcBankIdx[i] = i;
1562     return i;
1563 }
1564
1565 static void
1566 FcCacheAddBankDir (int bank, const char * dir)
1567 {
1568     int bi = FcCacheBankToIndexMTF (bank);
1569
1570     if (bi < 0)
1571         return;
1572
1573     bankDirs[bi] = (const char *)FcStrCopy ((FcChar8 *)dir);
1574 }
1575
1576 const char *
1577 FcCacheFindBankDir (int bank)
1578 {
1579     int bi = FcCacheBankToIndex (bank);
1580     return bankDirs[bi];
1581 }
1582
1583 /*
1584  * This code implements the MD5 message-digest algorithm.
1585  * The algorithm is due to Ron Rivest.  This code was
1586  * written by Colin Plumb in 1993, no copyright is claimed.
1587  * This code is in the public domain; do with it what you wish.
1588  *
1589  * Equivalent code is available from RSA Data Security, Inc.
1590  * This code has been tested against that, and is equivalent,
1591  * except that you don't need to include two pages of legalese
1592  * with every copy.
1593  *
1594  * To compute the message digest of a chunk of bytes, declare an
1595  * MD5Context structure, pass it to MD5Init, call MD5Update as
1596  * needed on buffers full of bytes, and then call MD5Final, which
1597  * will fill a supplied 16-byte array with the digest.
1598  */
1599
1600 #ifndef HIGHFIRST
1601 #define byteReverse(buf, len)   /* Nothing */
1602 #else
1603 /*
1604  * Note: this code is harmless on little-endian machines.
1605  */
1606 void byteReverse(unsigned char *buf, unsigned longs)
1607 {
1608     FcChar32 t;
1609     do {
1610         t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1611             ((unsigned) buf[1] << 8 | buf[0]);
1612         *(FcChar32 *) buf = t;
1613         buf += 4;
1614     } while (--longs);
1615 }
1616 #endif
1617
1618 /*
1619  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
1620  * initialization constants.
1621  */
1622 static void MD5Init(struct MD5Context *ctx)
1623 {
1624     ctx->buf[0] = 0x67452301;
1625     ctx->buf[1] = 0xefcdab89;
1626     ctx->buf[2] = 0x98badcfe;
1627     ctx->buf[3] = 0x10325476;
1628
1629     ctx->bits[0] = 0;
1630     ctx->bits[1] = 0;
1631 }
1632
1633 /*
1634  * Update context to reflect the concatenation of another buffer full
1635  * of bytes.
1636  */
1637 static void MD5Update(struct MD5Context *ctx, unsigned char *buf, unsigned len)
1638 {
1639     FcChar32 t;
1640
1641     /* Update bitcount */
1642
1643     t = ctx->bits[0];
1644     if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
1645         ctx->bits[1]++;         /* Carry from low to high */
1646     ctx->bits[1] += len >> 29;
1647
1648     t = (t >> 3) & 0x3f;        /* Bytes already in shsInfo->data */
1649
1650     /* Handle any leading odd-sized chunks */
1651
1652     if (t) {
1653         unsigned char *p = (unsigned char *) ctx->in + t;
1654
1655         t = 64 - t;
1656         if (len < t) {
1657             memcpy(p, buf, len);
1658             return;
1659         }
1660         memcpy(p, buf, t);
1661         byteReverse(ctx->in, 16);
1662         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1663         buf += t;
1664         len -= t;
1665     }
1666     /* Process data in 64-byte chunks */
1667
1668     while (len >= 64) {
1669         memcpy(ctx->in, buf, 64);
1670         byteReverse(ctx->in, 16);
1671         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1672         buf += 64;
1673         len -= 64;
1674     }
1675
1676     /* Handle any remaining bytes of data. */
1677
1678     memcpy(ctx->in, buf, len);
1679 }
1680
1681 /*
1682  * Final wrapup - pad to 64-byte boundary with the bit pattern 
1683  * 1 0* (64-bit count of bits processed, MSB-first)
1684  */
1685 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
1686 {
1687     unsigned count;
1688     unsigned char *p;
1689
1690     /* Compute number of bytes mod 64 */
1691     count = (ctx->bits[0] >> 3) & 0x3F;
1692
1693     /* Set the first char of padding to 0x80.  This is safe since there is
1694        always at least one byte free */
1695     p = ctx->in + count;
1696     *p++ = 0x80;
1697
1698     /* Bytes of padding needed to make 64 bytes */
1699     count = 64 - 1 - count;
1700
1701     /* Pad out to 56 mod 64 */
1702     if (count < 8) {
1703         /* Two lots of padding:  Pad the first block to 64 bytes */
1704         memset(p, 0, count);
1705         byteReverse(ctx->in, 16);
1706         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1707
1708         /* Now fill the next block with 56 bytes */
1709         memset(ctx->in, 0, 56);
1710     } else {
1711         /* Pad block to 56 bytes */
1712         memset(p, 0, count - 8);
1713     }
1714     byteReverse(ctx->in, 14);
1715
1716     /* Append length in bits and transform */
1717     ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
1718     ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
1719
1720     MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1721     byteReverse((unsigned char *) ctx->buf, 4);
1722     memcpy(digest, ctx->buf, 16);
1723     memset(ctx, 0, sizeof(ctx));        /* In case it's sensitive */
1724 }
1725
1726
1727 /* The four core functions - F1 is optimized somewhat */
1728
1729 /* #define F1(x, y, z) (x & y | ~x & z) */
1730 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1731 #define F2(x, y, z) F1(z, x, y)
1732 #define F3(x, y, z) (x ^ y ^ z)
1733 #define F4(x, y, z) (y ^ (x | ~z))
1734
1735 /* This is the central step in the MD5 algorithm. */
1736 #define MD5STEP(f, w, x, y, z, data, s) \
1737         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
1738
1739 /*
1740  * The core of the MD5 algorithm, this alters an existing MD5 hash to
1741  * reflect the addition of 16 longwords of new data.  MD5Update blocks
1742  * the data and converts bytes into longwords for this routine.
1743  */
1744 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
1745 {
1746     register FcChar32 a, b, c, d;
1747
1748     a = buf[0];
1749     b = buf[1];
1750     c = buf[2];
1751     d = buf[3];
1752
1753     MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1754     MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1755     MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1756     MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1757     MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1758     MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1759     MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1760     MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1761     MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1762     MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1763     MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1764     MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1765     MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1766     MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1767     MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1768     MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1769
1770     MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1771     MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1772     MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1773     MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1774     MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1775     MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1776     MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1777     MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1778     MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1779     MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1780     MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1781     MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1782     MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1783     MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1784     MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1785     MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1786
1787     MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1788     MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1789     MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1790     MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1791     MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1792     MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1793     MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1794     MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1795     MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1796     MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1797     MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1798     MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1799     MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1800     MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1801     MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1802     MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1803
1804     MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1805     MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1806     MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1807     MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1808     MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1809     MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1810     MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1811     MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1812     MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1813     MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1814     MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1815     MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1816     MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1817     MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1818     MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1819     MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1820
1821     buf[0] += a;
1822     buf[1] += b;
1823     buf[2] += c;
1824     buf[3] += d;
1825 }