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