]> git.wh0rd.org Git - fontconfig.git/blob - src/fccache.c
Destroy the global cache file if it's terminally broken. (reported by Mike
[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 <sys/mman.h>
29 #include <sys/utsname.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32 #include "fcint.h"
33
34 #define ENDIAN_TEST 0x12345678
35 #define MACHINE_SIGNATURE_SIZE 9 + 5*19 + 1
36
37 static off_t
38 FcCacheSkipToArch (int fd, const char * arch);
39
40 static FcBool 
41 FcCacheCopyOld (int fd, int fd_orig, off_t start);
42
43 static void *
44 FcDirCacheProduce (FcFontSet *set, FcCache * metadata);
45
46 static FcBool
47 FcDirCacheConsume (int fd, FcFontSet *set);
48
49 FcBool
50 FcDirCacheRead (FcFontSet * set, FcStrSet * dirs, const FcChar8 *dir);
51
52 static int
53 FcCacheNextOffset(off_t w);
54
55 static char *
56 FcCacheMachineSignature (void);
57
58 static FcBool
59 FcCacheHaveBank (int bank);
60
61 #define FC_DBG_CACHE_REF    1024
62
63 static char *
64 FcCacheReadString (int fd, char *dest, int len)
65 {
66     FcChar8     c;
67     FcBool      escape;
68     int         size;
69     int         i;
70
71     if (len == 0)
72         return 0;
73     
74     size = len;
75     i = 0;
76     escape = FcFalse;
77     while (read (fd, &c, 1) == 1)
78     {
79         if (!escape)
80         {
81             switch (c) {
82             case '"':
83                 c = '\0';
84                 break;
85             case '\\':
86                 escape = FcTrue;
87                 continue;
88             }
89         }
90         if (i == size)
91         {
92             dest[i++] = 0;
93             return dest;
94         }
95         dest[i++] = c;
96         if (c == '\0')
97             return dest;
98         escape = FcFalse;
99     }
100     return 0;
101 }
102
103 static FcBool
104 FcCacheWriteString (int fd, const char *chars)
105 {
106     if (write (fd, chars, strlen(chars)+1) != strlen(chars)+1)
107         return FcFalse;
108     return FcTrue;
109 }
110
111 static void
112 FcGlobalCacheDirDestroy (FcGlobalCacheDir *d)
113 {
114     FcMemFree (FC_MEM_STRING, strlen (d->name)+1);
115     free (d->name);
116     FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCacheDir));
117     free (d);
118 }
119
120 FcGlobalCache *
121 FcGlobalCacheCreate (void)
122 {
123     FcGlobalCache   *cache;
124
125     cache = malloc (sizeof (FcGlobalCache));
126     if (!cache)
127         return 0;
128     FcMemAlloc (FC_MEM_CACHE, sizeof (FcGlobalCache));
129     cache->dirs = 0;
130     cache->updated = FcFalse;
131     cache->fd = -1;
132     return cache;
133 }
134
135 void
136 FcGlobalCacheDestroy (FcGlobalCache *cache)
137 {
138     FcGlobalCacheDir    *d, *next;
139
140     for (d = cache->dirs; d; d = next)
141     {
142         next = d->next;
143         FcGlobalCacheDirDestroy (d);
144     }
145     FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCache));
146     free (cache);
147 }
148
149 void
150 FcGlobalCacheLoad (FcGlobalCache    *cache,
151                    FcStrSet         *staleDirs,
152                    const FcChar8    *cache_file)
153 {
154     char                name_buf[8192];
155     FcGlobalCacheDir    *d, *next;
156     char                * current_arch_machine_name;
157     char                candidate_arch_machine_name[MACHINE_SIGNATURE_SIZE + 9];
158     off_t               current_arch_start;
159
160     struct stat         cache_stat, dir_stat;
161
162     if (stat ((char *) cache_file, &cache_stat) < 0)
163         return;
164
165     cache->fd = open ((char *) cache_file, O_RDONLY);
166     if (cache->fd == -1)
167         return;
168
169     cache->updated = FcFalse;
170
171     current_arch_machine_name = FcCacheMachineSignature ();
172     current_arch_start = FcCacheSkipToArch(cache->fd, 
173                                            current_arch_machine_name);
174     if (current_arch_start < 0)
175         goto bail_and_destroy;
176
177     lseek (cache->fd, current_arch_start, SEEK_SET);
178     FcCacheReadString (cache->fd, candidate_arch_machine_name, 
179                        sizeof (candidate_arch_machine_name));
180     if (strlen(candidate_arch_machine_name) == 0)
181         goto bail_and_destroy;
182
183     while (1) 
184     {
185         off_t targ;
186
187         FcCacheReadString (cache->fd, name_buf, sizeof (name_buf));
188         if (!strlen(name_buf))
189             break;
190
191         if (stat ((char *) name_buf, &dir_stat) < 0 || 
192             dir_stat.st_mtime > cache_stat.st_mtime)
193         {
194             FcCache md;
195
196             FcStrSetAdd (staleDirs, FcStrCopy ((FcChar8 *)name_buf));
197             read (cache->fd, &md, sizeof (FcCache));
198             lseek (cache->fd, FcCacheNextOffset (lseek(cache->fd, 0, SEEK_CUR)) + md.count, SEEK_SET);
199             continue;
200         }
201
202         d = malloc (sizeof (FcGlobalCacheDir));
203         if (!d)
204             goto bail1;
205
206         d->next = cache->dirs;
207         cache->dirs = d;
208
209         d->name = (char *)FcStrCopy ((FcChar8 *)name_buf);
210         d->ent = 0;
211         d->offset = lseek (cache->fd, 0, SEEK_CUR);
212         if (read (cache->fd, &d->metadata, sizeof (FcCache)) != sizeof (FcCache))
213             goto bail1;
214         targ = FcCacheNextOffset (lseek(cache->fd, 0, SEEK_CUR)) + d->metadata.count;
215         if (lseek (cache->fd, targ, SEEK_SET) != targ)
216             goto bail1;
217     }
218     return;
219
220  bail1:
221     for (d = cache->dirs; d; d = next)
222     {
223         next = d->next;
224         free (d);
225     }
226     cache->dirs = 0;
227
228     close (cache->fd);
229     cache->fd = -1;
230     return;
231
232  bail_and_destroy:
233     close (cache->fd);
234     cache->fd = -1;
235
236     if (stat ((char *) cache_file, &cache_stat) == 0)
237         unlink ((char *)cache_file);
238
239     return;
240
241 }
242
243 FcBool
244 FcGlobalCacheReadDir (FcFontSet *set, FcStrSet *dirs, FcGlobalCache * cache, const char *dir, FcConfig *config)
245 {
246     FcGlobalCacheDir *d;
247     FcBool ret = FcFalse;
248
249     if (cache->fd == -1)
250         return FcFalse;
251
252     for (d = cache->dirs; d; d = d->next)
253     {
254         if (strncmp (d->name, dir, strlen(dir)) == 0)
255         {
256             lseek (cache->fd, d->offset, SEEK_SET);
257             if (!FcDirCacheConsume (cache->fd, set))
258                 return FcFalse;
259             if (strcmp (d->name, dir) == 0)
260                 ret = FcTrue;
261         }
262     }
263
264     return ret;
265 }
266
267 FcBool
268 FcGlobalCacheUpdate (FcGlobalCache  *cache,
269                      const char     *name,
270                      FcFontSet      *set)
271 {
272     FcGlobalCacheDir * d;
273
274     if (!set->nfont)
275         return FcTrue;
276
277     for (d = cache->dirs; d; d = d->next)
278     {
279         if (strcmp(d->name, name) == 0)
280             break;
281     }
282
283     if (!d)
284     {
285         d = malloc (sizeof (FcGlobalCacheDir));
286         if (!d)
287             return FcFalse;
288         d->next = cache->dirs;
289         cache->dirs = d;
290     }
291
292     cache->updated = FcTrue;
293
294     d->name = (char *)FcStrCopy ((FcChar8 *)name);
295     d->ent = FcDirCacheProduce (set, &d->metadata);
296     d->offset = 0;
297     return FcTrue;
298 }
299
300 FcBool
301 FcGlobalCacheSave (FcGlobalCache    *cache,
302                    const FcChar8    *cache_file)
303 {
304     int                 fd, fd_orig;
305     FcGlobalCacheDir    *dir;
306     FcAtomic            *atomic;
307     off_t               current_arch_start = 0, truncate_to;
308     char                * current_arch_machine_name, * header;
309
310     if (!cache->updated)
311         return FcTrue;
312     
313 #if defined (HAVE_GETUID) && defined (HAVE_GETEUID)
314     /* Set-UID programs can't safely update the cache */
315     if (getuid () != geteuid ())
316         return FcFalse;
317 #endif
318     
319     atomic = FcAtomicCreate (cache_file);
320     if (!atomic)
321         return FcFalse;
322
323     if (!FcAtomicLock (atomic))
324         goto bail1;
325     fd = open ((char *) FcAtomicNewFile(atomic), O_RDWR | O_CREAT, 
326                S_IRUSR | S_IWUSR);
327     if (fd == -1)
328         goto bail2;
329
330     fd_orig = open ((char *) FcAtomicOrigFile(atomic), O_RDONLY);
331
332     current_arch_machine_name = FcCacheMachineSignature ();
333     if (fd_orig == -1)
334         current_arch_start = 0;
335     else
336         current_arch_start = FcCacheSkipToArch (fd_orig, 
337                                                 current_arch_machine_name);
338
339     if (current_arch_start < 0)
340         current_arch_start = FcCacheNextOffset (lseek(fd_orig, 0, SEEK_END));
341
342     if (!FcCacheCopyOld(fd, fd_orig, current_arch_start))
343         goto bail3;
344
345     close (fd_orig);
346     fd_orig = -1;
347
348     current_arch_start = lseek(fd, 0, SEEK_CUR);
349     if (ftruncate (fd, current_arch_start) == -1)
350         goto bail3;
351
352     header = malloc (10 + strlen (current_arch_machine_name));
353     if (!header)
354         goto bail3;
355
356     truncate_to = current_arch_start + strlen(current_arch_machine_name) + 11;
357     for (dir = cache->dirs; dir; dir = dir->next)
358     {
359         truncate_to += strlen(dir->name) + 1;
360         truncate_to += sizeof (FcCache);
361         truncate_to = FcCacheNextOffset (current_arch_start + truncate_to);
362         truncate_to += dir->metadata.count;
363     }
364     truncate_to -= current_arch_start;
365
366     sprintf (header, "%8x ", (int)truncate_to);
367     strcat (header, current_arch_machine_name);
368     if (!FcCacheWriteString (fd, header))
369         goto bail4;
370
371     for (dir = cache->dirs; dir; dir = dir->next)
372     {
373         if (dir->ent)
374         {
375             FcCacheWriteString (fd, dir->name);
376             write (fd, &dir->metadata, sizeof(FcCache));
377             lseek (fd, FcCacheNextOffset (lseek(fd, 0, SEEK_CUR)), SEEK_SET);
378             write (fd, dir->ent, dir->metadata.count);
379             free (dir->ent);
380         }
381     }
382     FcCacheWriteString (fd, "");
383
384     if (close (fd) == -1)
385         goto bail25;
386     
387     if (!FcAtomicReplaceOrig (atomic))
388         goto bail25;
389     
390     FcAtomicUnlock (atomic);
391     FcAtomicDestroy (atomic);
392
393     cache->updated = FcFalse;
394     return FcTrue;
395
396  bail4:
397     free (header);
398  bail3:
399     if (fd_orig != -1)
400         close (fd_orig);
401
402     close (fd);
403  bail25:
404     FcAtomicDeleteNew (atomic);
405  bail2:
406     FcAtomicUnlock (atomic);
407  bail1:
408     FcAtomicDestroy (atomic);
409     return FcFalse;
410 }
411
412 #define PAGESIZE 8192
413 /* 
414  * Find the next presumably-mmapable offset after the supplied file
415  * position.
416  */
417 static int
418 FcCacheNextOffset(off_t w)
419 {
420     if (w % PAGESIZE == 0) 
421         return w;
422     else
423         return ((w / PAGESIZE)+1)*PAGESIZE;
424 }
425
426 /* return the address of the segment for the provided arch,
427  * or -1 if arch not found */
428 static off_t
429 FcCacheSkipToArch (int fd, const char * arch)
430 {
431     char candidate_arch_machine_name_count[MACHINE_SIGNATURE_SIZE + 9];
432     char * candidate_arch;
433     off_t current_arch_start = 0;
434
435     /* skip arches that are not the current arch */
436     while (1)
437     {
438         long bs;
439
440         if (lseek (fd, current_arch_start, SEEK_SET) != current_arch_start)
441             return -1;
442
443         if (FcCacheReadString (fd, candidate_arch_machine_name_count, 
444                                 sizeof (candidate_arch_machine_name_count)) == 0)
445             return -1;
446         if (!strlen(candidate_arch_machine_name_count))
447             return -1;
448         bs = strtol(candidate_arch_machine_name_count, &candidate_arch, 16);
449
450         // count = 0 should probably be distinguished from the !bs condition
451         if (!bs || bs < strlen (candidate_arch_machine_name_count))
452             return -1;
453
454         candidate_arch++; /* skip leading space */
455
456         if (strcmp (candidate_arch, arch)==0)
457             return current_arch_start;
458         current_arch_start += bs;
459     }
460
461     return -1;
462 }
463
464 /* Cuts out the segment at the file pointer (moves everything else
465  * down to cover it), and leaves the file pointer at the end of the
466  * file. */
467 static FcBool 
468 FcCacheCopyOld (int fd, int fd_orig, off_t start)
469 {
470     char * buf = malloc (8192);
471     char candidate_arch_machine_name[MACHINE_SIGNATURE_SIZE + 9];
472     long bs;
473     int c, bytes_skipped;
474     off_t loc;
475
476     if (!buf)
477         return FcFalse;
478
479     loc = 0;
480     lseek (fd, 0, SEEK_SET); lseek (fd_orig, 0, SEEK_SET);
481     do
482     {
483         int b = 8192;
484         if (loc + b > start)
485             b = start - loc;
486
487         if ((c = read (fd_orig, buf, b)) <= 0)
488             break;
489         if (write (fd, buf, c) < 0)
490             goto bail;
491
492         loc += c;
493     }
494     while (c > 0);
495
496     lseek (fd, start, SEEK_SET);
497     if (FcCacheReadString (fd, candidate_arch_machine_name, 
498                            sizeof (candidate_arch_machine_name)) == 0)
499         goto done;
500     if (!strlen(candidate_arch_machine_name))
501         goto done;
502
503     bs = strtol(candidate_arch_machine_name, 0, 16);
504     if (bs == 0)
505         goto done;
506
507     bytes_skipped = 0;
508     do
509     {
510         lseek (fd, start+bs+bytes_skipped, SEEK_SET);
511         if ((c = read (fd, buf, 8192)) <= 0)
512             break;
513         lseek (fd, start+bytes_skipped, SEEK_SET);
514         if (write (fd, buf, c) < 0)
515             goto bail;
516         bytes_skipped += c;
517     }
518     while (c > 0);
519     lseek (fd, start+bytes_skipped, SEEK_SET);
520
521  done:
522     free (buf);
523     return FcTrue;
524
525  bail:
526     free (buf);
527     return FcFalse;
528 }
529
530 /* Does not check that the cache has the appropriate arch section. */
531 FcBool
532 FcDirCacheValid (const FcChar8 *dir)
533 {
534     FcChar8     *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
535     struct stat file_stat, dir_stat;
536
537     if (stat ((char *) dir, &dir_stat) < 0)
538     {
539         FcStrFree (cache_file);
540         return FcFalse;
541     }
542     if (stat ((char *) cache_file, &file_stat) < 0)
543     {
544         FcStrFree (cache_file);
545         return FcFalse;
546     }
547
548     FcStrFree (cache_file);
549     /*
550      * If the directory has been modified more recently than
551      * the cache file, the cache is not valid
552      */
553     if (dir_stat.st_mtime - file_stat.st_mtime > 0)
554         return FcFalse;
555     return FcTrue;
556 }
557
558 /* Assumes that the cache file in 'dir' exists.
559  * Checks that the cache has the appropriate arch section. */
560 FcBool
561 FcDirCacheHasCurrentArch (const FcChar8 *dir)
562 {
563     FcChar8     *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
564     int         fd;
565     off_t       current_arch_start;
566     char        *current_arch_machine_name;
567
568     current_arch_machine_name = FcCacheMachineSignature();
569     fd = open ((char *)cache_file, O_RDONLY);
570     if (fd == -1)
571         return FcFalse;
572
573     current_arch_start = FcCacheSkipToArch(fd, current_arch_machine_name);
574     close (fd);
575
576     if (current_arch_start < 0)
577         return FcFalse;
578     
579     return FcTrue;
580 }
581
582 FcBool
583 FcDirCacheUnlink (const FcChar8 *dir)
584 {
585     FcChar8     *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
586     struct stat cache_stat;
587
588     if (stat ((char *) cache_file, &cache_stat) == 0 &&
589         unlink ((char *)cache_file) != 0)
590     {
591         FcStrFree (cache_file);
592         return FcFalse;
593     }
594
595     FcStrFree (cache_file);
596     return FcTrue;
597 }
598
599 static int
600 FcCacheReadDirs (FcConfig * config, FcGlobalCache * cache, 
601                  FcStrList *list, FcFontSet * set)
602 {
603     int                 ret = 0;
604     FcChar8             *dir;
605     FcChar8             *file, *base;
606     FcStrSet            *subdirs;
607     FcStrList           *sublist;
608     struct stat         statb;
609
610     /*
611      * Read in the results from 'list'.
612      */
613     while ((dir = FcStrListNext (list)))
614     {
615         /* freed below */
616         file = (FcChar8 *) malloc (strlen ((char *) dir) + 1 + FC_MAX_FILE_LEN + 1);
617         if (!file)
618             return FcFalse;
619
620         strcpy ((char *) file, (char *) dir);
621         strcat ((char *) file, "/");
622         base = file + strlen ((char *) file);
623
624         subdirs = FcStrSetCreate ();
625         if (!subdirs)
626         {
627             fprintf (stderr, "Can't create directory set\n");
628             ret++;
629             free (file);
630             continue;
631         }
632         
633         if (access ((char *) dir, X_OK) < 0)
634         {
635             switch (errno) {
636             case ENOENT:
637             case ENOTDIR:
638             case EACCES:
639                 break;
640             default:
641                 fprintf (stderr, "\"%s\": ", dir);
642                 perror ("");
643                 ret++;
644             }
645             FcStrSetDestroy (subdirs);
646             free (file);
647             continue;
648         }
649         if (stat ((char *) dir, &statb) == -1)
650         {
651             fprintf (stderr, "\"%s\": ", dir);
652             perror ("");
653             FcStrSetDestroy (subdirs);
654             ret++;
655             free (file);
656             continue;
657         }
658         if (!S_ISDIR (statb.st_mode))
659         {
660             fprintf (stderr, "\"%s\": not a directory, skipping\n", dir);
661             FcStrSetDestroy (subdirs);
662             free (file);
663             continue;
664         }
665         if (!FcDirCacheValid (dir) || !FcDirCacheRead (set, subdirs, dir))
666         {
667             if (FcDebug () & FC_DBG_FONTSET)
668                 printf ("cache scan dir %s\n", dir);
669
670             FcDirScanConfig (set, subdirs, cache, 
671                              config->blanks, dir, FcFalse, config);
672         }
673         sublist = FcStrListCreate (subdirs);
674         FcStrSetDestroy (subdirs);
675         if (!sublist)
676         {
677             fprintf (stderr, "Can't create subdir list in \"%s\"\n", dir);
678             ret++;
679             free (file);
680             continue;
681         }
682         ret += FcCacheReadDirs (config, cache, sublist, set);
683         free (file);
684     }
685     FcStrListDone (list);
686     return ret;
687 }
688
689 FcFontSet *
690 FcCacheRead (FcConfig *config, FcGlobalCache * cache)
691 {
692     FcFontSet * s = FcFontSetCreate();
693     if (!s) 
694         return 0;
695
696     if (FcCacheReadDirs (config, cache, FcConfigGetConfigDirs (config), s))
697         goto bail;
698
699     return s;
700
701  bail:
702     FcFontSetDestroy (s);
703     return 0;
704 }
705
706 /* read serialized state from the cache file */
707 FcBool
708 FcDirCacheRead (FcFontSet * set, FcStrSet * dirs, const FcChar8 *dir)
709 {
710     char *cache_file = (char *)FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
711     int fd;
712     char * current_arch_machine_name;
713     char candidate_arch_machine_name[9+MACHINE_SIGNATURE_SIZE];
714     off_t current_arch_start = 0;
715     char subdirName[FC_MAX_FILE_LEN + 1 + 12 + 1];
716
717     if (!cache_file)
718         goto bail;
719
720     current_arch_machine_name = FcCacheMachineSignature();
721     fd = open(cache_file, O_RDONLY);
722     if (fd == -1)
723         goto bail;
724
725     current_arch_start = FcCacheSkipToArch(fd, current_arch_machine_name);
726     if (current_arch_start < 0)
727         goto bail1;
728
729     lseek (fd, current_arch_start, SEEK_SET);
730     if (FcCacheReadString (fd, candidate_arch_machine_name, 
731                            sizeof (candidate_arch_machine_name)) == 0)
732         goto bail1;
733
734     while (strlen(FcCacheReadString (fd, subdirName, sizeof (subdirName))) > 0)
735         FcStrSetAdd (dirs, (FcChar8 *)subdirName);
736
737     if (!FcDirCacheConsume (fd, set))
738         goto bail1;
739         
740     close(fd);
741     free (cache_file);
742     return FcTrue;
743
744  bail1:
745     close (fd);
746  bail:
747     free (cache_file);
748     return FcFalse;
749 }
750
751 static FcBool
752 FcDirCacheConsume (int fd, FcFontSet *set)
753 {
754     FcCache metadata;
755     void * current_dir_block;
756     off_t pos;
757
758     read(fd, &metadata, sizeof(FcCache));
759     if (metadata.magic != FC_CACHE_MAGIC)
760         return FcFalse;
761
762     if (!metadata.count)
763         return FcTrue;
764
765     pos = FcCacheNextOffset (lseek(fd, 0, SEEK_CUR));
766     current_dir_block = mmap (0, metadata.count, 
767                               PROT_READ, MAP_SHARED, fd, pos);
768     if (current_dir_block == MAP_FAILED)
769         return FcFalse;
770     
771     if (!FcFontSetUnserialize (metadata, set, current_dir_block))
772         return FcFalse;
773
774     return FcTrue;
775 }
776
777 static void *
778 FcDirCacheProduce (FcFontSet *set, FcCache *metadata)
779 {
780     void * current_dir_block, * final_dir_block;
781     static unsigned int rand_state = 0;
782     int bank;
783
784     if (!rand_state) 
785         rand_state = time(0L);
786     bank = rand_r(&rand_state);
787
788     while (FcCacheHaveBank(bank))
789         bank = rand_r(&rand_state);
790
791     memset (metadata, 0, sizeof(FcCache));
792     FcFontSetNewBank();
793     metadata->count = FcFontSetNeededBytes (set);
794     metadata->magic = FC_CACHE_MAGIC;
795     metadata->bank = bank;
796
797     if (!metadata->count) /* not a failure, no fonts to write */
798         return 0;
799
800     current_dir_block = malloc (metadata->count);
801     if (!current_dir_block)
802         goto bail;
803     final_dir_block = FcFontSetDistributeBytes (metadata, current_dir_block);
804
805     if ((char *)current_dir_block + metadata->count != final_dir_block)
806         goto bail;
807                               
808     if (!FcFontSetSerialize (bank, set))
809         goto bail;
810
811     return current_dir_block;
812
813  bail:
814     free (current_dir_block);
815     return 0;
816 }
817
818 /* write serialized state to the cache file */
819 FcBool
820 FcDirCacheWrite (FcFontSet *set, FcStrSet *dirs, const FcChar8 *dir)
821 {
822     FcChar8         *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
823     int             fd, fd_orig, i, dirs_count;
824     FcAtomic        *atomic;
825     FcCache         metadata;
826     off_t           current_arch_start = 0, truncate_to;
827
828     char            *current_arch_machine_name, * header;
829     void            *current_dir_block;
830
831     if (!cache_file)
832         goto bail;
833
834     current_dir_block = FcDirCacheProduce (set, &metadata);
835
836     if (metadata.count && !current_dir_block)
837         goto bail0;
838
839     if (FcDebug () & FC_DBG_CACHE)
840         printf ("FcDirCacheWriteDir cache_file \"%s\"\n", cache_file);
841
842     atomic = FcAtomicCreate (cache_file);
843     if (!atomic)
844         goto bail0;
845
846     if (!FcAtomicLock (atomic))
847         goto bail1;
848
849     fd_orig = open((char *)FcAtomicOrigFile (atomic), O_RDONLY, 0666);
850
851     fd = open((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0666);
852     if (fd == -1)
853         goto bail2;
854
855     current_arch_machine_name = FcCacheMachineSignature ();
856     current_arch_start = 0;
857
858     if (fd_orig != -1)
859         current_arch_start = 
860             FcCacheSkipToArch(fd_orig, current_arch_machine_name);
861
862     if (current_arch_start < 0)
863         current_arch_start = FcCacheNextOffset (lseek(fd_orig, 0, SEEK_END));
864
865     if (fd_orig != -1 && !FcCacheCopyOld(fd, fd_orig, current_arch_start))
866         goto bail3;
867
868     if (fd_orig != -1)
869         close (fd_orig);
870
871     current_arch_start = lseek(fd, 0, SEEK_CUR);
872     if (ftruncate (fd, current_arch_start) == -1)
873         goto bail3;
874
875     /* allocate space for subdir names in this block */
876     dirs_count = 0;
877     for (i = 0; i < dirs->size; i++)
878         dirs_count += strlen((char *)dirs->strs[i]) + 1;
879     dirs_count ++;
880
881     /* now write the address of the next offset */
882     truncate_to = FcCacheNextOffset (FcCacheNextOffset (current_arch_start + sizeof (FcCache) + dirs_count) + metadata.count) - current_arch_start;
883     header = malloc (10 + strlen (current_arch_machine_name));
884     if (!header)
885         goto bail3;
886     sprintf (header, "%8x ", (int)truncate_to);
887     strcat (header, current_arch_machine_name);
888     if (!FcCacheWriteString (fd, header))
889         goto bail4;
890
891     for (i = 0; i < dirs->size; i++)
892         FcCacheWriteString (fd, (char *)dirs->strs[i]);
893     FcCacheWriteString (fd, "");
894
895     write (fd, &metadata, sizeof(FcCache));
896     if (metadata.count)
897     {
898         lseek (fd, FcCacheNextOffset (lseek(fd, 0, SEEK_END)), SEEK_SET);
899         write (fd, current_dir_block, metadata.count);
900         free (current_dir_block);
901     }
902
903     /* this actually serves to pad out the cache file, if needed */
904     if (ftruncate (fd, current_arch_start + truncate_to) == -1)
905         goto bail4;
906
907     close(fd);
908     if (!FcAtomicReplaceOrig(atomic))
909         goto bail4;
910     FcAtomicUnlock (atomic);
911     FcAtomicDestroy (atomic);
912     return FcTrue;
913
914  bail4:
915     free (header);
916  bail3:
917     close (fd);
918  bail2:
919     FcAtomicUnlock (atomic);
920  bail1:
921     FcAtomicDestroy (atomic);
922  bail0:
923     unlink ((char *)cache_file);
924     free (cache_file);
925     if (current_dir_block)
926         free (current_dir_block);
927  bail:
928     return FcFalse;
929 }
930
931 static char *
932 FcCacheMachineSignature ()
933 {
934     static char buf[MACHINE_SIGNATURE_SIZE];
935     int magic = ENDIAN_TEST;
936     char * m = (char *)&magic;
937
938     sprintf (buf, "%2x%2x%2x%2x "
939              "%4x %4x %4x %4x %4x %4x %4x %4x %4x %4x %4x %4x "
940              "%4x %4x %4x %4x %4x %4x %4x\n", 
941              m[0], m[1], m[2], m[3],
942              (unsigned int)sizeof (char),
943              (unsigned int)sizeof (char *),
944              (unsigned int)sizeof (int),
945              (unsigned int)sizeof (FcPattern),
946              (unsigned int)sizeof (FcPatternEltPtr),
947              (unsigned int)sizeof (struct _FcPatternElt *),
948              (unsigned int)sizeof (FcPatternElt),
949              (unsigned int)sizeof (FcObjectPtr),
950              (unsigned int)sizeof (FcValueListPtr),
951              (unsigned int)sizeof (FcValue),
952              (unsigned int)sizeof (FcValueBinding),
953              (unsigned int)sizeof (struct _FcValueList *),
954              (unsigned int)sizeof (FcCharSet),
955              (unsigned int)sizeof (FcCharLeaf **),
956              (unsigned int)sizeof (FcChar16 *),
957              (unsigned int)sizeof (FcChar16),
958              (unsigned int)sizeof (FcCharLeaf),
959              (unsigned int)sizeof (FcChar32),
960              (unsigned int)sizeof (FcCache));
961
962     return buf;
963 }
964
965 static int banks_ptr = 0, banks_alloc = 0;
966 static int * bankId = 0, * bankIdx = 0;
967
968 static FcBool
969 FcCacheHaveBank (int bank)
970 {
971     int i;
972
973     if (bank < FC_BANK_FIRST)
974         return FcTrue;
975
976     for (i = 0; i < banks_ptr; i++)
977         if (bankId[i] == bank)
978             return FcTrue;
979
980     return FcFalse;
981 }
982
983 int
984 FcCacheBankToIndex (int bank)
985 {
986     int i, j;
987
988     for (i = 0; i < banks_ptr; i++)
989         if (bankId[bankIdx[i]] == bank)
990         {
991             int t = bankIdx[i];
992
993             for (j = i; j > 0; j--)
994                 bankIdx[j] = bankIdx[j-1];
995             bankIdx[0] = t;
996             return t;
997         }
998
999     if (banks_ptr >= banks_alloc)
1000     {
1001         int * b, * bidx;
1002         b = realloc (bankId, (banks_alloc + 4) * sizeof(int));
1003         if (!b)
1004             return -1;
1005         bankId = b;
1006
1007         bidx = realloc (bankIdx, (banks_alloc + 4) * sizeof(int));
1008         if (!bidx)
1009             return -1;
1010         bankIdx = bidx;
1011
1012         banks_alloc += 4;
1013     }
1014
1015     i = banks_ptr++;
1016     bankId[i] = bank;
1017     bankIdx[i] = i;
1018     return i;
1019 }