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