58f925db8db6ef5de91802b50f55c2bd09e31fe1
[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 <fcntl.h>
27 #include <dirent.h>
28 #include <string.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31 #include "fcint.h"
32 #include <unistd.h>
33 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
34 #  include <sys/mman.h>
35 #  include <sys/utsname.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 (char * cache_file, 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     if (pagesize == -1)
621 #if defined (HAVE_SYSCONF)
622         pagesize = sysconf(_SC_PAGESIZE);
623 #else
624         pagesize = FC_HARDCODED_PAGESIZE;
625 #endif
626     if (w % pagesize == 0) 
627         return w;
628     else
629         return ((w / pagesize)+1)*pagesize;
630 }
631
632 /* return the address of the segment for the provided arch,
633  * or -1 if arch not found */
634 static off_t
635 FcCacheSkipToArch (int fd, const char * arch)
636 {
637     char candidate_arch_machine_name_count[MACHINE_SIGNATURE_SIZE + 9];
638     char * candidate_arch;
639     off_t current_arch_start = 0;
640
641     lseek (fd, 0, SEEK_SET);
642     FcCacheSkipString (fd);
643     current_arch_start = lseek (fd, 0, SEEK_CUR);
644
645     /* skip arches that are not the current arch */
646     while (1)
647     {
648         long bs;
649
650         if (lseek (fd, current_arch_start, SEEK_SET) != current_arch_start)
651             return -1;
652
653         if (FcCacheReadString (fd, candidate_arch_machine_name_count, 
654                                 sizeof (candidate_arch_machine_name_count)) == 0)
655             return -1;
656         if (!strlen(candidate_arch_machine_name_count))
657             return -1;
658         bs = strtol(candidate_arch_machine_name_count, &candidate_arch, 16);
659
660         /* count = 0 should probably be distinguished from the !bs condition */
661         if (!bs || bs < strlen (candidate_arch_machine_name_count))
662             return -1;
663
664         candidate_arch++; /* skip leading space */
665
666         if (strcmp (candidate_arch, arch)==0)
667             return current_arch_start;
668         current_arch_start += bs;
669         current_arch_start = FcCacheNextOffset (current_arch_start);
670     }
671 }
672
673 /* Cuts out the segment at the file pointer (moves everything else
674  * down to cover it), and leaves the file pointer at the end of the
675  * file. */
676 static FcBool 
677 FcCacheCopyOld (int fd, int fd_orig, off_t start)
678 {
679     char * buf = malloc (8192);
680     char candidate_arch_machine_name[MACHINE_SIGNATURE_SIZE + 9];
681     long bs;
682     int c, bytes_skipped;
683     off_t loc;
684
685     if (!buf)
686         return FcFalse;
687
688     loc = 0;
689     lseek (fd, 0, SEEK_SET); lseek (fd_orig, 0, SEEK_SET);
690     FcCacheSkipString (fd); FcCacheSkipString (fd_orig);
691     do
692     {
693         int b = 8192;
694         if (loc + b > start)
695             b = start - loc;
696
697         if ((c = read (fd_orig, buf, b)) <= 0)
698             break;
699         if (write (fd, buf, c) < 0)
700             goto bail;
701
702         loc += c;
703     }
704     while (c > 0);
705
706     lseek (fd, start, SEEK_SET);
707     if (FcCacheReadString (fd, candidate_arch_machine_name, 
708                            sizeof (candidate_arch_machine_name)) == 0)
709         goto done;
710     if (!strlen(candidate_arch_machine_name))
711         goto done;
712
713     bs = strtol(candidate_arch_machine_name, 0, 16);
714     if (bs == 0)
715         goto done;
716
717     bytes_skipped = 0;
718     do
719     {
720         lseek (fd, start+bs+bytes_skipped, SEEK_SET);
721         if ((c = read (fd, buf, 8192)) <= 0)
722             break;
723         lseek (fd, start+bytes_skipped, SEEK_SET);
724         if (write (fd, buf, c) < 0)
725             goto bail;
726         bytes_skipped += c;
727     }
728     while (c > 0);
729     lseek (fd, start+bytes_skipped, SEEK_SET);
730
731  done:
732     free (buf);
733     return FcTrue;
734
735  bail:
736     free (buf);
737     return FcFalse;
738 }
739
740 /* Does not check that the cache has the appropriate arch section. */
741 /* Also, this can be fooled if the original location has a stale
742  * cache, and the hashed location has an up-to-date cache.  Oh well,
743  * sucks to be you in that case! */
744 FcBool
745 FcDirCacheValid (const FcChar8 *dir)
746 {
747     struct stat file_stat, dir_stat;
748     int         fd;
749
750     if (stat ((char *) dir, &dir_stat) < 0)
751         return FcFalse;
752
753     fd = FcDirCacheOpen (dir);
754
755     if (fd < 0)
756         return FcFalse;
757     if (fstat (fd, &file_stat) < 0)
758         goto bail;
759
760     close (fd);
761
762     /*
763      * If the directory has been modified more recently than
764      * the cache file, the cache is not valid
765      */
766     if (dir_stat.st_mtime > file_stat.st_mtime)
767         return FcFalse;
768
769     return FcTrue;
770
771  bail:
772     close (fd);
773     return FcFalse;
774 }
775
776 /* Assumes that the cache file in 'dir' exists.
777  * Checks that the cache has the appropriate arch section. */
778 FcBool
779 FcDirCacheHasCurrentArch (const FcChar8 *dir)
780 {
781     int         fd;
782     off_t       current_arch_start;
783     char        *current_arch_machine_name;
784     FcCache     metadata;
785     char        subdirName[FC_MAX_FILE_LEN + 1 + 12 + 1];
786
787     fd = FcDirCacheOpen (dir);
788     if (fd < 0)
789         goto bail;
790
791     current_arch_machine_name = FcCacheMachineSignature();
792     current_arch_start = FcCacheSkipToArch(fd, current_arch_machine_name);
793
794     if (current_arch_start >= 0)
795     {
796         if (lseek (fd, current_arch_start, SEEK_SET) != current_arch_start)
797             goto bail1;
798
799         FcCacheSkipString (fd);
800
801         while (FcCacheReadString (fd, subdirName, sizeof (subdirName)) && strlen (subdirName) > 0)
802             ;
803
804         if (read(fd, &metadata, sizeof(FcCache)) != sizeof(FcCache))
805             goto bail1;
806
807         if (metadata.magic != FC_CACHE_MAGIC)
808             goto bail1;
809     }
810
811     close (fd);
812
813     if (current_arch_start < 0)
814         return FcFalse;
815     
816     return FcTrue;
817
818  bail1:
819     close (fd);
820  bail:
821     return FcFalse;
822 }
823
824 FcBool
825 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
826 {
827     char        *cache_file;
828     char        *cache_hashed = 0;
829     int         fd, collisions;
830     struct stat cache_stat;
831     char        name_buf[FC_MAX_FILE_LEN];
832
833     dir = FcConfigNormalizeFontDir (config, dir);
834     cache_file = (char *)FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
835     if (!cache_file)
836         return FcFalse;
837
838     /* First remove normal cache file. */
839     if (stat ((char *) cache_file, &cache_stat) == 0)
840         unlink ((char *)cache_file);
841
842     /* Next remove any applicable hashed files. */
843     fd = -1; collisions = 0;
844     do
845     {
846         if (cache_hashed)
847             FcStrFree ((FcChar8 *)cache_hashed);
848
849         cache_hashed = FcDirCacheHashName (cache_file, collisions++);
850         if (!cache_hashed)
851             goto bail;
852
853         if (fd > 0)
854             close (fd);
855         fd = open(cache_hashed, O_RDONLY | O_BINARY);
856         if (fd == -1)
857         {
858             FcStrFree ((FcChar8 *)cache_hashed);
859             FcStrFree ((FcChar8 *)cache_file);
860             return FcTrue;
861         }
862
863         if (!FcCacheReadString (fd, name_buf, sizeof (name_buf)) || !strlen(name_buf))
864         {
865             FcStrFree ((FcChar8 *)cache_hashed);
866             goto bail;
867         }
868     } while (strcmp (name_buf, cache_file) != 0);
869
870     close (fd);
871
872     if (stat ((char *) cache_hashed, &cache_stat) == 0 &&
873         unlink ((char *)cache_hashed) != 0)
874     {
875         FcStrFree ((FcChar8 *)cache_hashed);
876         goto bail;
877     }
878
879     FcStrFree ((FcChar8 *)cache_file);
880     FcStrFree ((FcChar8 *)cache_hashed);
881     return FcTrue;
882
883  bail:
884     FcStrFree ((FcChar8 *)cache_file);
885     return FcFalse;
886 }
887
888 static int
889 FcCacheReadDirs (FcConfig * config, FcGlobalCache * cache, 
890                  FcStrList *list, FcFontSet * set, FcStrSet *processed_dirs)
891 {
892     int                 ret = 0;
893     FcChar8             *dir;
894     FcStrSet            *subdirs;
895     FcStrList           *sublist;
896     struct stat         statb;
897     FcGlobalCacheDir   *d;
898
899     /*
900      * Read in the results from 'list'.
901      */
902     while ((dir = FcStrListNext (list)))
903     {
904         if (!FcConfigAcceptFilename (config, dir))
905             continue;
906
907         /* Skip this directory if already updated
908          * to avoid the looped directories via symlinks
909          * Clearly a dir not in fonts.conf shouldn't be globally cached.
910          */
911         dir = (FcChar8 *)FcConfigNormalizeFontDir (config, dir);
912         if (!dir)
913             continue;
914
915         if (FcStrSetMember (processed_dirs, dir))
916             continue;
917         if (!FcStrSetAdd (processed_dirs, dir))
918             continue;
919
920         subdirs = FcStrSetCreate ();
921         if (!subdirs)
922         {
923             fprintf (stderr, "Can't create directory set\n");
924             ret++;
925             continue;
926         }
927         
928         if (access ((char *) dir, X_OK) < 0)
929         {
930             switch (errno) {
931             case ENOENT:
932             case ENOTDIR:
933             case EACCES:
934                 break;
935             default:
936                 fprintf (stderr, "\"%s\": ", dir);
937                 perror ("");
938                 ret++;
939             }
940             FcStrSetDestroy (subdirs);
941             continue;
942         }
943         if (stat ((char *) dir, &statb) == -1)
944         {
945             fprintf (stderr, "\"%s\": ", dir);
946             perror ("");
947             FcStrSetDestroy (subdirs);
948             ret++;
949             continue;
950         }
951         if (!S_ISDIR (statb.st_mode))
952         {
953             fprintf (stderr, "\"%s\": not a directory, skipping\n", dir);
954             FcStrSetDestroy (subdirs);
955             continue;
956         }
957         if (FcDirCacheValid (dir) && 
958             FcDirCacheHasCurrentArch (dir) && 
959             FcDirCacheRead (set, subdirs, dir, config))
960         {
961             /* if an old entry is found in the global cache, disable it */
962             if ((d = FcGlobalCacheDirFind (cache, (const char *)dir)) != NULL)
963             {
964                 d->state = FcGCDirDisabled;
965                 /* save the updated config later without this entry */
966                 cache->updated = FcTrue;
967             }
968         }
969         else
970         {
971             if (FcDebug () & FC_DBG_FONTSET)
972                 printf ("cache scan dir %s\n", dir);
973
974             FcDirScanConfig (set, subdirs, cache, 
975                              config->blanks, dir, FcFalse, config);
976         }
977         sublist = FcStrListCreate (subdirs);
978         FcStrSetDestroy (subdirs);
979         if (!sublist)
980         {
981             fprintf (stderr, "Can't create subdir list in \"%s\"\n", dir);
982             ret++;
983             continue;
984         }
985         ret += FcCacheReadDirs (config, cache, sublist, set, processed_dirs);
986     }
987     FcStrListDone (list);
988     return ret;
989 }
990
991 FcFontSet *
992 FcCacheRead (FcConfig *config, FcGlobalCache * cache)
993 {
994     FcFontSet   *s = FcFontSetCreate();
995     FcStrSet    *processed_dirs;
996
997     if (!s) 
998         return 0;
999
1000     processed_dirs = FcStrSetCreate();
1001     if (!processed_dirs)
1002         goto bail;
1003
1004     if (FcCacheReadDirs (config, cache, FcConfigGetConfigDirs (config), s, processed_dirs))
1005         goto bail1;
1006
1007     FcStrSetDestroy (processed_dirs);
1008     return s;
1009
1010  bail1:
1011     FcStrSetDestroy (processed_dirs);
1012  bail:
1013     FcFontSetDestroy (s);
1014     return 0;
1015 }
1016
1017 static const char bin2hex[] = { '0', '1', '2', '3',
1018                                 '4', '5', '6', '7',
1019                                 '8', '9', 'a', 'b',
1020                                 'c', 'd', 'e', 'f' };
1021
1022 static char *
1023 FcDirCacheHashName (char * cache_file, int collisions)
1024 {
1025     unsigned char       hash[16], hex_hash[33];
1026     char                *cache_hashed;
1027     unsigned char       uscore = '_';
1028     int                 cnt, i;
1029     FcChar8             *tmp;
1030     struct MD5Context   ctx;
1031
1032     MD5Init (&ctx);
1033     MD5Update (&ctx, (unsigned char *)cache_file, strlen (cache_file));
1034
1035     for (i = 0; i < collisions; i++)
1036         MD5Update (&ctx, &uscore, 1);
1037
1038     MD5Final (hash, &ctx);
1039
1040     for (cnt = 0; cnt < 16; ++cnt)
1041     {
1042         hex_hash[2*cnt] = bin2hex[hash[cnt] >> 4];
1043         hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
1044     }
1045     hex_hash[32] = 0;
1046
1047     tmp = FcStrPlus ((FcChar8 *)hex_hash, (FcChar8 *)FC_CACHE_SUFFIX);
1048     if (!tmp)
1049         return 0;
1050
1051     cache_hashed = (char *)FcStrPlus ((FcChar8 *)PKGCACHEDIR"/", tmp);
1052     free (tmp);
1053
1054     return cache_hashed;
1055 }
1056
1057 /* Opens the hashed name for cache_file.
1058  * This would fail in the unlikely event of a collision and subsequent
1059  * removal of the file which originally caused the collision. */
1060 static int
1061 FcDirCacheOpen (const FcChar8 *dir)
1062 {
1063     FcBool      found;
1064     int         fd = -1, collisions = 0;
1065     char        *cache_file, *cache_hashed;
1066     char        name_buf[FC_MAX_FILE_LEN];
1067     struct stat dir_stat;
1068
1069     if (stat ((char *)dir, &dir_stat) == -1)
1070         return -1;
1071
1072     cache_file = (char *)FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
1073     if (!cache_file)
1074         return -1;
1075
1076     found = FcFalse;
1077     do
1078     {
1079         struct stat     c;
1080         FcChar8         *name_buf_dir;
1081
1082         if (fd >= 0)
1083             close (fd);
1084
1085         cache_hashed = FcDirCacheHashName (cache_file, collisions++);
1086         if (!cache_hashed)
1087         {
1088             FcStrFree ((FcChar8 *)cache_file);
1089             return -1;
1090         }
1091
1092         fd = open(cache_hashed, O_RDONLY | O_BINARY);
1093         FcStrFree ((FcChar8 *)cache_hashed);
1094
1095         if (fd == -1)
1096             break;
1097         if (!FcCacheReadString (fd, name_buf, sizeof (name_buf)) || 
1098             !strlen(name_buf))
1099             break;
1100
1101         name_buf_dir = FcStrDirname ((FcChar8 *)name_buf);
1102         if (stat ((char *)name_buf_dir, &c) == -1)
1103         {
1104             FcStrFree (name_buf_dir);
1105             continue;
1106         }
1107         FcStrFree (name_buf_dir);
1108         found = (c.st_ino == dir_stat.st_ino) && (c.st_dev == dir_stat.st_dev);
1109     } while (!found);
1110
1111     if (!found || fd < 0) 
1112     {
1113         if (fd >= 0)
1114             close (fd);
1115         fd = open(cache_file, O_RDONLY | O_BINARY);
1116     }
1117
1118     FcStrFree ((FcChar8 *)cache_file);
1119     return fd;
1120 }
1121
1122 /* read serialized state from the cache file */
1123 FcBool
1124 FcDirCacheRead (FcFontSet * set, FcStrSet * dirs, const FcChar8 *dir, FcConfig *config)
1125 {
1126     int         fd;
1127     char        *current_arch_machine_name;
1128     char        candidate_arch_machine_name[9+MACHINE_SIGNATURE_SIZE];
1129     off_t       current_arch_start = 0;
1130     char        subdirName[FC_MAX_FILE_LEN + 1 + 12 + 1];
1131
1132     fd = FcDirCacheOpen (dir);
1133     if (fd < 0)
1134         goto bail;
1135
1136     current_arch_machine_name = FcCacheMachineSignature();
1137     current_arch_start = FcCacheSkipToArch(fd, 
1138                                            current_arch_machine_name);
1139     if (current_arch_start < 0)
1140         goto bail1;
1141
1142     lseek (fd, current_arch_start, SEEK_SET);
1143     if (FcCacheReadString (fd, candidate_arch_machine_name, 
1144                            sizeof (candidate_arch_machine_name)) == 0)
1145         goto bail1;
1146
1147     while (FcCacheReadString (fd, subdirName, sizeof (subdirName)) && strlen (subdirName) > 0)
1148         FcStrSetAdd (dirs, (FcChar8 *)subdirName);
1149
1150     if (!FcDirCacheConsume (fd, (const char *)dir, set, config))
1151         goto bail1;
1152         
1153     close(fd);
1154     return FcTrue;
1155
1156  bail1:
1157     close (fd);
1158  bail:
1159     return FcFalse;
1160 }
1161
1162 static FcBool
1163 FcDirCacheConsume (int fd, const char * dir, FcFontSet *set, FcConfig *config)
1164 {
1165     FcCache metadata;
1166     void * current_dir_block;
1167     off_t pos;
1168
1169     if (read(fd, &metadata, sizeof(FcCache)) != sizeof(FcCache))
1170         return FcFalse;
1171     if (metadata.magic != FC_CACHE_MAGIC)
1172         return FcFalse;
1173
1174     if (!metadata.count)
1175     {
1176         pos = FcCacheNextOffset (lseek(fd, 0, SEEK_CUR));
1177         lseek (fd, pos, SEEK_SET);
1178         if (config)
1179             FcConfigAddFontDir (config, (FcChar8 *)dir);
1180         return FcTrue;
1181     }
1182
1183     pos = FcCacheNextOffset (lseek(fd, 0, SEEK_CUR));
1184 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
1185     current_dir_block = mmap (0, metadata.count, 
1186                               PROT_READ, MAP_SHARED, fd, pos);
1187     if (current_dir_block == MAP_FAILED)
1188         return FcFalse;
1189 #else
1190     current_dir_block = malloc (metadata.count);
1191     if (!current_dir_block)
1192         return FcFalse;
1193
1194     /* could also use CreateMappedViewOfFile under MinGW... */
1195     if (read (fd, current_dir_block, metadata.count) != metadata.count)
1196         goto bail;
1197 #endif
1198     lseek (fd, pos+metadata.count, SEEK_SET);
1199
1200     FcCacheAddBankDir (metadata.bank, dir);
1201     if (config)
1202         FcConfigAddFontDir (config, (FcChar8 *)dir);
1203
1204     if (!FcFontSetUnserialize (&metadata, set, current_dir_block))
1205         goto bail;
1206
1207     return FcTrue;
1208  bail:
1209 #if !(defined(HAVE_MMAP) || defined(__CYGWIN__))
1210     free (current_dir_block);
1211 #endif
1212     return FcFalse;
1213 }
1214
1215 static void *
1216 FcDirCacheProduce (FcFontSet *set, FcCache *metadata)
1217 {
1218     void * current_dir_block, * final_dir_block;
1219     static unsigned int rand_state = 0;
1220     int bank, needed_bytes_no_align;
1221
1222 #if defined (HAVE_RAND_R)
1223     if (!rand_state) 
1224         rand_state = time(0L);
1225     bank = rand_r(&rand_state);
1226
1227     while (FcCacheHaveBank(bank))
1228         bank = rand_r(&rand_state);
1229 #else
1230     if (!rand_state)
1231     {
1232         rand_state = 1;
1233         srand (time (0L));
1234     }
1235     bank = rand();
1236
1237     while (FcCacheHaveBank(bank))
1238         bank = rand();
1239 #endif
1240
1241     memset (metadata, 0, sizeof(FcCache));
1242     FcFontSetNewBank();
1243     needed_bytes_no_align = FcFontSetNeededBytes (set);
1244     metadata->count = needed_bytes_no_align + 
1245         FcFontSetNeededBytesAlign ();
1246     metadata->magic = FC_CACHE_MAGIC;
1247     metadata->bank = bank;
1248
1249     if (!needed_bytes_no_align) /* not a failure, no fonts to write */
1250     {
1251         /* no, you don't really need to write any bytes at all. */
1252         metadata->count = 0;
1253         return 0;
1254     }
1255
1256     current_dir_block = malloc (metadata->count);
1257     if (!current_dir_block)
1258         goto bail;
1259     /* shut up valgrind */
1260     memset (current_dir_block, 0, metadata->count);
1261     final_dir_block = FcFontSetDistributeBytes (metadata, current_dir_block);
1262
1263     if ((void *)((char *)current_dir_block+metadata->count) < final_dir_block)
1264         goto bail;
1265                               
1266     if (!FcFontSetSerialize (bank, set))
1267         goto bail;
1268
1269     return current_dir_block;
1270
1271  bail:
1272     free (current_dir_block);
1273     return 0;
1274 }
1275
1276 /* write serialized state to the cache file */
1277 FcBool
1278 FcDirCacheWrite (FcFontSet *set, FcStrSet *dirs, const FcChar8 *dir)
1279 {
1280     char            *cache_file;
1281     char            *cache_hashed;
1282     int             fd, fd_orig, i, dirs_count;
1283     FcAtomic        *atomic;
1284     FcCache         metadata;
1285     off_t           current_arch_start = 0, truncate_to;
1286     char            name_buf[FC_MAX_FILE_LEN];
1287     int             collisions;
1288
1289     char            *current_arch_machine_name, * header;
1290     void            *current_dir_block = 0;
1291
1292     dir = FcConfigNormalizeFontDir (FcConfigGetCurrent(), dir);
1293     if (!dir)
1294         return FcFalse;
1295
1296     cache_file = (char *)FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
1297     if (!cache_file)
1298         goto bail;
1299
1300     /* Ensure that we're not trampling a cache for some other dir. */
1301     /* This is slightly different from FcDirCacheOpen, since it 
1302      * needs the filename, not the file descriptor. */
1303     fd = -1; collisions = 0;
1304     do
1305     {
1306         cache_hashed = FcDirCacheHashName (cache_file, collisions++);
1307         if (!cache_hashed)
1308             goto bail0;
1309
1310         if (fd > 0)
1311             close (fd);
1312         fd = open(cache_hashed, O_RDONLY | O_BINARY);
1313         if (fd == -1)
1314             break;
1315         if(!FcCacheReadString (fd, name_buf, sizeof (name_buf)) || !strlen(name_buf))
1316         {
1317             close (fd);
1318             FcStrFree ((FcChar8 *)cache_hashed);
1319             continue;
1320         }
1321         close (fd);
1322
1323         if (strcmp (name_buf, cache_file) != 0) 
1324         {
1325             FcStrFree ((FcChar8 *)cache_hashed);
1326             continue;
1327         }
1328
1329         break;
1330     } while (1);
1331
1332     current_dir_block = FcDirCacheProduce (set, &metadata);
1333
1334     if (metadata.count && !current_dir_block)
1335         goto bail1;
1336
1337     if (FcDebug () & FC_DBG_CACHE)
1338         printf ("FcDirCacheWriteDir cache_file \"%s\"\n", cache_file);
1339
1340     atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
1341     if (!atomic)
1342         goto bail1;
1343
1344     if (!FcAtomicLock (atomic))
1345     {
1346         /* Now try rewriting the original version of the file. */
1347         FcAtomicDestroy (atomic);
1348
1349         atomic = FcAtomicCreate ((FcChar8 *)cache_file);
1350         fd_orig = open (cache_file, O_RDONLY | O_BINARY);
1351         if (fd_orig == -1)
1352             fd_orig = open((char *)FcAtomicOrigFile (atomic), O_RDONLY | O_BINARY);
1353
1354         fd = open((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
1355         if (fd == -1)
1356             goto bail2;
1357     }
1358
1359     /* In all cases, try opening the real location of the cache file first. */
1360     /* (even if that's not atomic.) */
1361     fd_orig = open (cache_file, O_RDONLY | O_BINARY);
1362     if (fd_orig == -1)
1363         fd_orig = open((char *)FcAtomicOrigFile (atomic), O_RDONLY | O_BINARY);
1364
1365     fd = open((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
1366     if (fd == -1)
1367         goto bail3;
1368
1369     FcCacheWriteString (fd, cache_file);
1370
1371     current_arch_machine_name = FcCacheMachineSignature ();
1372     current_arch_start = 0;
1373
1374     if (fd_orig != -1)
1375         current_arch_start = 
1376             FcCacheSkipToArch(fd_orig, current_arch_machine_name);
1377
1378     if (current_arch_start < 0)
1379     {
1380         off_t offset = lseek(fd_orig, 0, SEEK_END);
1381         current_arch_start = FcCacheNextOffset (offset);
1382     }
1383
1384     if (fd_orig != -1 && !FcCacheCopyOld(fd, fd_orig, current_arch_start))
1385         goto bail4;
1386
1387     if (fd_orig != -1)
1388         close (fd_orig);
1389
1390     current_arch_start = lseek(fd, 0, SEEK_CUR);
1391 #if defined (HAVE_FTRUNCATE)
1392     if (ftruncate (fd, current_arch_start) == -1)
1393         goto bail4;
1394 #else
1395 #if defined (HAVE_CHSIZE)
1396     if (chsize (fd, current_arch_start) == -1)
1397         goto bail4;
1398 #else
1399     goto bail4;
1400 #endif
1401 #endif
1402
1403     /* allocate space for subdir names in this block */
1404     dirs_count = 0;
1405     for (i = 0; i < dirs->size; i++)
1406         dirs_count += strlen((char *)dirs->strs[i]) + 1;
1407     dirs_count ++;
1408
1409     /* now write the address of the next offset */
1410     truncate_to = FcCacheNextOffset (FcCacheNextOffset (current_arch_start + sizeof (FcCache) + dirs_count) + metadata.count) - current_arch_start;
1411     header = malloc (10 + strlen (current_arch_machine_name));
1412     if (!header)
1413         goto bail4;
1414     sprintf (header, "%8x ", (int)truncate_to);
1415     strcat (header, current_arch_machine_name);
1416     if (!FcCacheWriteString (fd, header))
1417         goto bail5;
1418
1419     for (i = 0; i < dirs->size; i++)
1420         FcCacheWriteString (fd, (char *)dirs->strs[i]);
1421     FcCacheWriteString (fd, "");
1422
1423     if (write (fd, &metadata, sizeof(FcCache)) != sizeof(FcCache)) 
1424     {
1425         perror("write metadata");
1426         goto bail5;
1427     }
1428     if (metadata.count)
1429     {
1430         off_t off = FcCacheNextOffset (lseek(fd, 0, SEEK_END));
1431         if (lseek (fd, off, SEEK_SET) != off)
1432             perror("lseek");
1433         else if (write (fd, current_dir_block, metadata.count) !=
1434                  metadata.count)
1435             perror("write current_dir_block");
1436         free (current_dir_block);
1437         current_dir_block = 0;
1438     }
1439
1440     /* this actually serves to pad out the cache file, if needed */
1441 #if defined (HAVE_FTRUNCATE)
1442     if (ftruncate (fd, current_arch_start + truncate_to) == -1)
1443         goto bail5;
1444 #else
1445 #if defined (HAVE_CHSIZE)
1446     if (chsize (fd, current_arch_start + truncate_to) == -1)
1447         goto bail5;
1448 #else
1449     goto bail5;
1450 #endif
1451 #endif
1452
1453     free (header);
1454     close(fd);
1455     if (!FcAtomicReplaceOrig(atomic))
1456         goto bail3;
1457     FcStrFree ((FcChar8 *)cache_hashed);
1458     FcStrFree ((FcChar8 *)cache_file);
1459     FcAtomicUnlock (atomic);
1460     FcAtomicDestroy (atomic);
1461     return FcTrue;
1462
1463  bail5:
1464     free (header);
1465  bail4:
1466     close (fd);
1467  bail3:
1468     FcAtomicUnlock (atomic);
1469  bail2:
1470     FcAtomicDestroy (atomic);
1471  bail1:
1472     FcStrFree ((FcChar8 *)cache_hashed);
1473  bail0:
1474     unlink ((char *)cache_file);
1475     FcStrFree ((FcChar8 *)cache_file);
1476     if (current_dir_block)
1477         free (current_dir_block);
1478  bail:
1479     return FcFalse;
1480 }
1481
1482 static char *
1483 FcCacheMachineSignature ()
1484 {
1485     static char buf[MACHINE_SIGNATURE_SIZE];
1486     int32_t magic = ENDIAN_TEST;
1487     char * m = (char *)&magic;
1488
1489     sprintf (buf, "%2x%2x%2x%2x "
1490              "%4x %4x %4x %4x %4x %4x %4x %4x %4x %4x %4x %4x "
1491              "%4x %4x %4x %4x %4x %4x %4x %4x\n", 
1492              m[0], m[1], m[2], m[3],
1493              (unsigned int)sizeof (char),
1494              (unsigned int)sizeof (char *),
1495              (unsigned int)sizeof (int),
1496              (unsigned int)sizeof (FcPattern),
1497              (unsigned int)sizeof (FcPatternEltPtr),
1498              (unsigned int)sizeof (struct _FcPatternElt *),
1499              (unsigned int)sizeof (FcPatternElt),
1500              (unsigned int)sizeof (FcObjectPtr),
1501              (unsigned int)sizeof (FcValueListPtr),
1502              (unsigned int)sizeof (FcValue),
1503              (unsigned int)sizeof (FcValueBinding),
1504              (unsigned int)sizeof (struct _FcValueList *),
1505              (unsigned int)sizeof (FcCharSet),
1506              (unsigned int)sizeof (FcCharLeaf **),
1507              (unsigned int)sizeof (FcChar16 *),
1508              (unsigned int)sizeof (FcChar16),
1509              (unsigned int)sizeof (FcCharLeaf),
1510              (unsigned int)sizeof (FcChar32),
1511              (unsigned int)sizeof (FcCache),
1512 #if defined (HAVE_SYSCONF)
1513              (unsigned int)sysconf(_SC_PAGESIZE));
1514 #else
1515              (unsigned int)FC_HARDCODED_PAGESIZE);
1516 #endif
1517
1518     return buf;
1519 }
1520
1521 static int banks_ptr = 0, banks_alloc = 0;
1522 int * _fcBankId = 0, * _fcBankIdx = 0;
1523 static const char ** bankDirs = 0;
1524
1525 static FcBool
1526 FcCacheHaveBank (int bank)
1527 {
1528     int i;
1529
1530     if (bank < FC_BANK_FIRST)
1531         return FcTrue;
1532
1533     for (i = 0; i < banks_ptr; i++)
1534         if (_fcBankId[i] == bank)
1535             return FcTrue;
1536
1537     return FcFalse;
1538 }
1539
1540 int
1541 FcCacheBankToIndexMTF (int bank)
1542 {
1543     int i, j;
1544
1545     for (i = 0; i < banks_ptr; i++)
1546         if (_fcBankId[_fcBankIdx[i]] == bank)
1547         {
1548             int t = _fcBankIdx[i];
1549
1550             for (j = i; j > 0; j--)
1551                 _fcBankIdx[j] = _fcBankIdx[j-1];
1552             _fcBankIdx[0] = t;
1553             return t;
1554         }
1555
1556     if (banks_ptr >= banks_alloc)
1557     {
1558         int * b, * bidx;
1559         const char ** bds;
1560
1561         b = realloc (_fcBankId, (banks_alloc + 4) * sizeof(int));
1562         if (!b)
1563             return -1;
1564         _fcBankId = b;
1565
1566         bidx = realloc (_fcBankIdx, (banks_alloc + 4) * sizeof(int));
1567         if (!bidx)
1568             return -1;
1569         _fcBankIdx = bidx;
1570
1571         bds = realloc (bankDirs, (banks_alloc + 4) * sizeof (char *));
1572         if (!bds)
1573             return -1;
1574         bankDirs = bds;
1575
1576         banks_alloc += 4;
1577     }
1578
1579     i = banks_ptr++;
1580     _fcBankId[i] = bank;
1581     _fcBankIdx[i] = i;
1582     return i;
1583 }
1584
1585 static void
1586 FcCacheAddBankDir (int bank, const char * dir)
1587 {
1588     int bi = FcCacheBankToIndexMTF (bank);
1589
1590     if (bi < 0)
1591         return;
1592
1593     bankDirs[bi] = (const char *)FcStrCopy ((FcChar8 *)dir);
1594 }
1595
1596 const char *
1597 FcCacheFindBankDir (int bank)
1598 {
1599     int bi = FcCacheBankToIndex (bank);
1600     return bankDirs[bi];
1601 }
1602
1603 /*
1604  * This code implements the MD5 message-digest algorithm.
1605  * The algorithm is due to Ron Rivest.  This code was
1606  * written by Colin Plumb in 1993, no copyright is claimed.
1607  * This code is in the public domain; do with it what you wish.
1608  *
1609  * Equivalent code is available from RSA Data Security, Inc.
1610  * This code has been tested against that, and is equivalent,
1611  * except that you don't need to include two pages of legalese
1612  * with every copy.
1613  *
1614  * To compute the message digest of a chunk of bytes, declare an
1615  * MD5Context structure, pass it to MD5Init, call MD5Update as
1616  * needed on buffers full of bytes, and then call MD5Final, which
1617  * will fill a supplied 16-byte array with the digest.
1618  */
1619
1620 #ifndef HIGHFIRST
1621 #define byteReverse(buf, len)   /* Nothing */
1622 #else
1623 /*
1624  * Note: this code is harmless on little-endian machines.
1625  */
1626 void byteReverse(unsigned char *buf, unsigned longs)
1627 {
1628     FcChar32 t;
1629     do {
1630         t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1631             ((unsigned) buf[1] << 8 | buf[0]);
1632         *(FcChar32 *) buf = t;
1633         buf += 4;
1634     } while (--longs);
1635 }
1636 #endif
1637
1638 /*
1639  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
1640  * initialization constants.
1641  */
1642 static void MD5Init(struct MD5Context *ctx)
1643 {
1644     ctx->buf[0] = 0x67452301;
1645     ctx->buf[1] = 0xefcdab89;
1646     ctx->buf[2] = 0x98badcfe;
1647     ctx->buf[3] = 0x10325476;
1648
1649     ctx->bits[0] = 0;
1650     ctx->bits[1] = 0;
1651 }
1652
1653 /*
1654  * Update context to reflect the concatenation of another buffer full
1655  * of bytes.
1656  */
1657 static void MD5Update(struct MD5Context *ctx, unsigned char *buf, unsigned len)
1658 {
1659     FcChar32 t;
1660
1661     /* Update bitcount */
1662
1663     t = ctx->bits[0];
1664     if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
1665         ctx->bits[1]++;         /* Carry from low to high */
1666     ctx->bits[1] += len >> 29;
1667
1668     t = (t >> 3) & 0x3f;        /* Bytes already in shsInfo->data */
1669
1670     /* Handle any leading odd-sized chunks */
1671
1672     if (t) {
1673         unsigned char *p = (unsigned char *) ctx->in + t;
1674
1675         t = 64 - t;
1676         if (len < t) {
1677             memcpy(p, buf, len);
1678             return;
1679         }
1680         memcpy(p, buf, t);
1681         byteReverse(ctx->in, 16);
1682         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1683         buf += t;
1684         len -= t;
1685     }
1686     /* Process data in 64-byte chunks */
1687
1688     while (len >= 64) {
1689         memcpy(ctx->in, buf, 64);
1690         byteReverse(ctx->in, 16);
1691         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1692         buf += 64;
1693         len -= 64;
1694     }
1695
1696     /* Handle any remaining bytes of data. */
1697
1698     memcpy(ctx->in, buf, len);
1699 }
1700
1701 /*
1702  * Final wrapup - pad to 64-byte boundary with the bit pattern 
1703  * 1 0* (64-bit count of bits processed, MSB-first)
1704  */
1705 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
1706 {
1707     unsigned count;
1708     unsigned char *p;
1709
1710     /* Compute number of bytes mod 64 */
1711     count = (ctx->bits[0] >> 3) & 0x3F;
1712
1713     /* Set the first char of padding to 0x80.  This is safe since there is
1714        always at least one byte free */
1715     p = ctx->in + count;
1716     *p++ = 0x80;
1717
1718     /* Bytes of padding needed to make 64 bytes */
1719     count = 64 - 1 - count;
1720
1721     /* Pad out to 56 mod 64 */
1722     if (count < 8) {
1723         /* Two lots of padding:  Pad the first block to 64 bytes */
1724         memset(p, 0, count);
1725         byteReverse(ctx->in, 16);
1726         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1727
1728         /* Now fill the next block with 56 bytes */
1729         memset(ctx->in, 0, 56);
1730     } else {
1731         /* Pad block to 56 bytes */
1732         memset(p, 0, count - 8);
1733     }
1734     byteReverse(ctx->in, 14);
1735
1736     /* Append length in bits and transform */
1737     ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
1738     ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
1739
1740     MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1741     byteReverse((unsigned char *) ctx->buf, 4);
1742     memcpy(digest, ctx->buf, 16);
1743     memset(ctx, 0, sizeof(ctx));        /* In case it's sensitive */
1744 }
1745
1746
1747 /* The four core functions - F1 is optimized somewhat */
1748
1749 /* #define F1(x, y, z) (x & y | ~x & z) */
1750 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1751 #define F2(x, y, z) F1(z, x, y)
1752 #define F3(x, y, z) (x ^ y ^ z)
1753 #define F4(x, y, z) (y ^ (x | ~z))
1754
1755 /* This is the central step in the MD5 algorithm. */
1756 #define MD5STEP(f, w, x, y, z, data, s) \
1757         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
1758
1759 /*
1760  * The core of the MD5 algorithm, this alters an existing MD5 hash to
1761  * reflect the addition of 16 longwords of new data.  MD5Update blocks
1762  * the data and converts bytes into longwords for this routine.
1763  */
1764 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
1765 {
1766     register FcChar32 a, b, c, d;
1767
1768     a = buf[0];
1769     b = buf[1];
1770     c = buf[2];
1771     d = buf[3];
1772
1773     MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1774     MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1775     MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1776     MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1777     MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1778     MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1779     MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1780     MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1781     MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1782     MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1783     MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1784     MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1785     MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1786     MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1787     MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1788     MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1789
1790     MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1791     MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1792     MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1793     MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1794     MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1795     MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1796     MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1797     MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1798     MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1799     MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1800     MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1801     MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1802     MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1803     MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1804     MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1805     MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1806
1807     MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1808     MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1809     MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1810     MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1811     MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1812     MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1813     MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1814     MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1815     MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1816     MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1817     MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1818     MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1819     MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1820     MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1821     MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1822     MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1823
1824     MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1825     MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1826     MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1827     MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1828     MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1829     MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1830     MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1831     MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1832     MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1833     MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1834     MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1835     MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1836     MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1837     MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1838     MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1839     MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1840
1841     buf[0] += a;
1842     buf[1] += b;
1843     buf[2] += c;
1844     buf[3] += d;
1845 }