Debian Codegraph @

src/fccache.c

raw
1 /*
2 * Copyright © 2000 Keith Packard
3 * Copyright © 2005 Patrick Lam
4 *
5 * Permission to use, copy, modify, distribute, and sell this software and its
6 * documentation for any purpose is hereby granted without fee, provided that
7 * the above copyright notice appear in all copies and that both that
8 * copyright notice and this permission notice appear in supporting
9 * documentation, and that the name of the author(s) not be used in
10 * advertising or publicity pertaining to distribution of the software without
11 * specific, written prior permission. The authors make no
12 * representations about the suitability of this software for any purpose. It
13 * is provided "as is" without express or implied warranty.
14 *
15 * THE AUTHOR(S) DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
16 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
17 * EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR
18 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
19 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
20 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21 * PERFORMANCE OF THIS SOFTWARE.
22 */
23 #include "fcint.h"
24
25 #include "fcarch.h"
26 #include "fcmd5.h"
27
28 #include <fcntl.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #ifdef HAVE_DIRENT_H
32 # include <dirent.h>
33 #endif
34 #include <limits.h>
35 #include <string.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38
39 #ifndef _WIN32
40 # include <sys/time.h>
41 #else
42 # include <winsock2.h> /* for struct timeval */
43 #endif
44
45 #include <assert.h>
46 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
47 # include <sys/mman.h>
48 # include <unistd.h>
49 #endif
50 #if defined(_WIN32)
51 # include <sys/locking.h>
52 #endif
53
54 #ifndef O_BINARY
55 # define O_BINARY 0
56 #endif
57
58 FcBool
59 FcDirCacheCreateUUID (FcChar8 *dir,
60 FcBool force,
61 FcConfig *config)
62 {
63 return FcTrue;
64 }
65
66 FcBool
67 FcDirCacheDeleteUUID (const FcChar8 *dir,
68 FcConfig *config)
69 {
70 FcBool ret = FcTrue;
71 #ifndef _WIN32
72 const FcChar8 *sysroot;
73 FcChar8 *target, *d;
74 struct stat statb;
75 struct timeval times[2];
76
77 config = FcConfigReference (config);
78 if (!config)
79 return FcFalse;
80 sysroot = FcConfigGetSysRoot (config);
81 if (sysroot)
82 d = FcStrBuildFilename (sysroot, dir, NULL);
83 else
84 d = FcStrBuildFilename (dir, NULL);
85 if (FcStat (d, &statb) != 0) {
86 ret = FcFalse;
87 goto bail;
88 }
89 target = FcStrBuildFilename (d, ".uuid", NULL);
90 ret = unlink ((char *)target) == 0;
91 if (ret) {
92 times[0].tv_sec = statb.st_atime;
93 times[1].tv_sec = statb.st_mtime;
94 # ifdef HAVE_STRUCT_STAT_ST_MTIM
95 times[0].tv_usec = statb.st_atim.tv_nsec / 1000;
96 times[1].tv_usec = statb.st_mtim.tv_nsec / 1000;
97 # else
98 times[0].tv_usec = 0;
99 times[1].tv_usec = 0;
100 # endif
101 if (utimes ((const char *)d, times) != 0) {
102 fprintf (stderr, "Unable to revert mtime: %s\n", d);
103 }
104 }
105 FcStrFree (target);
106 bail:
107 FcStrFree (d);
108 FcConfigDestroy (config);
109 #endif
110
111 return ret;
112 }
113
114 #define CACHEBASE_LEN (1 + 36 + 1 + sizeof (FC_ARCHITECTURE) + sizeof (FC_CACHE_SUFFIX))
115
116 static FcBool
117 FcCacheIsMmapSafe (int fd)
118 {
119 enum {
120 MMAP_NOT_INITIALIZED = 0,
121 MMAP_USE,
122 MMAP_DONT_USE,
123 MMAP_CHECK_FS,
124 } status;
125 static void *static_status;
126
127 status = (intptr_t)fc_atomic_ptr_get (&static_status);
128
129 if (status == MMAP_NOT_INITIALIZED) {
130 const char *env = getenv ("FONTCONFIG_USE_MMAP");
131 FcBool use;
132 if (env && FcNameBool ((const FcChar8 *)env, &use))
133 status = use ? MMAP_USE : MMAP_DONT_USE;
134 else
135 status = MMAP_CHECK_FS;
136 (void)fc_atomic_ptr_cmpexch (&static_status, NULL, (void *)(intptr_t)status);
137 }
138
139 if (status == MMAP_CHECK_FS)
140 return FcIsFsMmapSafe (fd);
141 else
142 return status == MMAP_USE;
143 }
144
145 static const char bin2hex[] = { '0', '1', '2', '3',
146 '4', '5', '6', '7',
147 '8', '9', 'a', 'b',
148 'c', 'd', 'e', 'f' };
149
150 static FcChar8 *
151 FcDirCacheBasenameMD5 (FcConfig *config, const FcChar8 *dir, FcChar8 cache_base[CACHEBASE_LEN])
152 {
153 FcChar8 *mapped_dir = NULL;
154 unsigned char hash[16];
155 FcChar8 *hex_hash, *key = NULL;
156 int cnt;
157 struct MD5Context ctx;
158 const FcChar8 *salt, *orig_dir = NULL;
159
160 salt = FcConfigMapSalt (config, dir);
161 /* Obtain a path where "dir" is mapped to.
162 * In case:
163 * <remap-dir as-path="/usr/share/fonts">/run/host/fonts</remap-dir>
164 *
165 * FcConfigMapFontPath (config, "/run/host/fonts") will returns "/usr/share/fonts".
166 */
167 mapped_dir = FcConfigMapFontPath (config, dir);
168 if (mapped_dir) {
169 orig_dir = dir;
170 dir = mapped_dir;
171 }
172 if (salt) {
173 size_t dl = strlen ((const char *)dir);
174 size_t sl = strlen ((const char *)salt);
175
176 key = (FcChar8 *)malloc (dl + sl + 1);
177 memcpy (key, dir, dl);
178 memcpy (key + dl, salt, sl + 1);
179 key[dl + sl] = 0;
180 if (!orig_dir)
181 orig_dir = dir;
182 dir = key;
183 }
184 MD5Init (&ctx);
185 MD5Update (&ctx, (const unsigned char *)dir, strlen ((const char *)dir));
186
187 MD5Final (hash, &ctx);
188
189 if (key)
190 FcStrFree (key);
191
192 hex_hash = cache_base;
193 for (cnt = 0; cnt < 16; ++cnt) {
194 hex_hash[2 * cnt] = bin2hex[hash[cnt] >> 4];
195 hex_hash[2 * cnt + 1] = bin2hex[hash[cnt] & 0xf];
196 }
197 hex_hash[2 * cnt] = 0;
198 strcat ((char *)cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
199 if (FcDebug() & FC_DBG_CACHE) {
200 printf ("cache: %s (dir: %s%s%s%s%s%s)\n", cache_base, orig_dir ? orig_dir : dir, mapped_dir ? " (mapped to " : "", mapped_dir ? (char *)mapped_dir : "", mapped_dir ? ")" : "", salt ? ", salt: " : "", salt ? (char *)salt : "");
201 }
202
203 if (mapped_dir)
204 FcStrFree (mapped_dir);
205
206 return cache_base;
207 }
208
209 #ifndef _WIN32
210 static FcChar8 *
211 FcDirCacheBasenameUUID (FcConfig *config, const FcChar8 *dir, FcChar8 cache_base[CACHEBASE_LEN])
212 {
213 FcChar8 *target, *fuuid;
214 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
215 int fd;
216
217 /* We don't need to apply remapping here. because .uuid was created at that very directory
218 * to determine the cache name no matter where it was mapped to.
219 */
220 cache_base[0] = 0;
221 if (sysroot)
222 target = FcStrBuildFilename (sysroot, dir, NULL);
223 else
224 target = FcStrdup (dir);
225 fuuid = FcStrBuildFilename (target, ".uuid", NULL);
226 if ((fd = FcOpen ((char *)fuuid, O_RDONLY)) != -1) {
227 char suuid[37];
228 ssize_t len;
229
230 memset (suuid, 0, sizeof (suuid));
231 len = read (fd, suuid, 36);
232 suuid[36] = 0;
233 close (fd);
234 if (len < 0)
235 goto bail;
236 cache_base[0] = '/';
237 strcpy ((char *)&cache_base[1], suuid);
238 strcat ((char *)cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
239 if (FcDebug() & FC_DBG_CACHE) {
240 printf ("cache fallbacks to: %s (dir: %s)\n", cache_base, dir);
241 }
242 }
243 bail:
244 FcStrFree (fuuid);
245 FcStrFree (target);
246
247 return cache_base;
248 }
249 #endif
250
251 FcBool
252 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
253 {
254 FcChar8 *cache_hashed = NULL;
255 FcChar8 cache_base[CACHEBASE_LEN];
256 #ifndef _WIN32
257 FcChar8 uuid_cache_base[CACHEBASE_LEN];
258 #endif
259 FcStrList *list;
260 FcChar8 *cache_dir;
261 const FcChar8 *sysroot;
262 FcBool ret = FcTrue;
263
264 config = FcConfigReference (config);
265 if (!config)
266 return FcFalse;
267 sysroot = FcConfigGetSysRoot (config);
268
269 FcDirCacheBasenameMD5 (config, dir, cache_base);
270 #ifndef _WIN32
271 FcDirCacheBasenameUUID (config, dir, uuid_cache_base);
272 #endif
273
274 list = FcStrListCreate (config->cacheDirs);
275 if (!list) {
276 ret = FcFalse;
277 goto bail;
278 }
279
280 while ((cache_dir = FcStrListNext (list))) {
281 if (sysroot)
282 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
283 else
284 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
285 if (!cache_hashed)
286 break;
287 (void)unlink ((char *)cache_hashed);
288 FcStrFree (cache_hashed);
289 #ifndef _WIN32
290 if (uuid_cache_base[0] != 0) {
291 if (sysroot)
292 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, uuid_cache_base, NULL);
293 else
294 cache_hashed = FcStrBuildFilename (cache_dir, uuid_cache_base, NULL);
295 if (!cache_hashed)
296 break;
297 (void)unlink ((char *)cache_hashed);
298 FcStrFree (cache_hashed);
299 }
300 #endif
301 }
302 FcStrListDone (list);
303 FcDirCacheDeleteUUID (dir, config);
304 /* return FcFalse if something went wrong */
305 if (cache_dir)
306 ret = FcFalse;
307 bail:
308 FcConfigDestroy (config);
309
310 return ret;
311 }
312
313 static int
314 FcDirCacheOpenFile (const FcChar8 *cache_file, struct stat *file_stat)
315 {
316 int fd;
317
318 #ifdef _WIN32
319 if (FcStat (cache_file, file_stat) < 0)
320 return -1;
321 #endif
322 fd = FcOpen ((char *)cache_file, O_RDONLY | O_BINARY);
323 if (fd < 0)
324 return fd;
325 #ifndef _WIN32
326 if (fstat (fd, file_stat) < 0) {
327 close (fd);
328 return -1;
329 }
330 #endif
331 return fd;
332 }
333
334 /*
335 * Look for a cache file for the specified dir. Attempt
336 * to use each one we find, stopping when the callback
337 * indicates success
338 */
339 static FcBool
340 FcDirCacheProcess (FcConfig *config, const FcChar8 *dir,
341 FcBool (*callback) (FcConfig *config, int fd, struct stat *fd_stat,
342 struct stat *dir_stat, struct timeval *cache_mtime, void *closure),
343 void *closure, FcChar8 **cache_file_ret)
344 {
345 int fd = -1;
346 FcChar8 cache_base[CACHEBASE_LEN];
347 FcStrList *list;
348 FcChar8 *cache_dir, *d;
349 struct stat file_stat, dir_stat;
350 FcBool ret = FcFalse;
351 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
352 struct timeval latest_mtime = (struct timeval){ 0 };
353
354 if (sysroot)
355 d = FcStrBuildFilename (sysroot, dir, NULL);
356 else
357 d = FcStrdup (dir);
358 if (FcStatChecksum (d, &dir_stat) < 0) {
359 FcStrFree (d);
360 return FcFalse;
361 }
362 FcStrFree (d);
363
364 FcDirCacheBasenameMD5 (config, dir, cache_base);
365
366 list = FcStrListCreate (config->cacheDirs);
367 if (!list)
368 return FcFalse;
369
370 while ((cache_dir = FcStrListNext (list))) {
371 FcChar8 *cache_hashed;
372 #ifndef _WIN32
373 FcBool retried = FcFalse;
374 #endif
375
376 if (sysroot)
377 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
378 else
379 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
380 if (!cache_hashed)
381 break;
382 #ifndef _WIN32
383 retry:
384 #endif
385 fd = FcDirCacheOpenFile (cache_hashed, &file_stat);
386 if (fd >= 0) {
387 ret = (*callback) (config, fd, &file_stat, &dir_stat, &latest_mtime, closure);
388 close (fd);
389 if (ret) {
390 if (cache_file_ret) {
391 if (*cache_file_ret)
392 FcStrFree (*cache_file_ret);
393 *cache_file_ret = cache_hashed;
394 } else
395 FcStrFree (cache_hashed);
396 } else
397 FcStrFree (cache_hashed);
398 }
399 #ifndef _WIN32
400 else if (!retried) {
401 FcChar8 uuid_cache_base[CACHEBASE_LEN];
402
403 retried = FcTrue;
404 FcDirCacheBasenameUUID (config, dir, uuid_cache_base);
405 if (uuid_cache_base[0] != 0) {
406 FcStrFree (cache_hashed);
407 if (sysroot)
408 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, uuid_cache_base, NULL);
409 else
410 cache_hashed = FcStrBuildFilename (cache_dir, uuid_cache_base, NULL);
411 if (!cache_hashed)
412 break;
413 goto retry;
414 } else
415 FcStrFree (cache_hashed);
416 }
417 #endif
418 else
419 FcStrFree (cache_hashed);
420 }
421 FcStrListDone (list);
422
423 if (closure)
424 return !!(*((FcCache **)closure) != NULL);
425 return ret;
426 }
427
428 #define FC_CACHE_MIN_MMAP 1024
429
430 /*
431 * Skip list element, make sure the 'next' pointer is the last thing
432 * in the structure, it will be allocated large enough to hold all
433 * of the necessary pointers
434 */
435
436 typedef struct _FcCacheSkip FcCacheSkip;
437
438 struct _FcCacheSkip {
439 FcCache *cache;
440 FcRef ref;
441 intptr_t size;
442 void *allocated;
443 dev_t cache_dev;
444 ino_t cache_ino;
445 time_t cache_mtime;
446 long cache_mtime_nano;
447 FcCacheSkip *next[1];
448 };
449
450 /*
451 * The head of the skip list; pointers for every possible level
452 * in the skip list, plus the largest level in the list
453 */
454
455 #define FC_CACHE_MAX_LEVEL 16
456
457 /* Protected by cache_lock below */
458 static FcCacheSkip *fcCacheChains[FC_CACHE_MAX_LEVEL];
459 static int fcCacheMaxLevel;
460
461 static FcMutex *cache_lock;
462
463 static void
464 lock_cache (void)
465 {
466 FcMutex *lock;
467 retry:
468 lock = fc_atomic_ptr_get (&cache_lock);
469 if (!lock) {
470 lock = (FcMutex *)malloc (sizeof (FcMutex));
471 FcMutexInit (lock);
472 if (!fc_atomic_ptr_cmpexch (&cache_lock, NULL, lock)) {
473 FcMutexFinish (lock);
474 free (lock);
475 goto retry;
476 }
477
478 FcMutexLock (lock);
479 /* Initialize random state */
480 FcRandom();
481 return;
482 }
483 FcMutexLock (lock);
484 }
485
486 static void
487 unlock_cache (void)
488 {
489 FcMutex *lock;
490 lock = fc_atomic_ptr_get (&cache_lock);
491 FcMutexUnlock (lock);
492 }
493
494 static void
495 free_lock (void)
496 {
497 FcMutex *lock;
498 lock = fc_atomic_ptr_get (&cache_lock);
499 if (lock && fc_atomic_ptr_cmpexch (&cache_lock, lock, NULL)) {
500 FcMutexFinish (lock);
501 free (lock);
502 }
503 }
504
505 /*
506 * Generate a random level number, distributed
507 * so that each level is 1/4 as likely as the one before
508 *
509 * Note that level numbers run 1 <= level <= MAX_LEVEL
510 */
511 static int
512 random_level (void)
513 {
514 /* tricky bit -- each bit is '1' 75% of the time */
515 long int bits = FcRandom() | FcRandom();
516 int level = 0;
517
518 while (++level < FC_CACHE_MAX_LEVEL) {
519 if (bits & 1)
520 break;
521 bits >>= 1;
522 }
523 return level;
524 }
525
526 /*
527 * Insert cache into the list
528 */
529 static FcBool
530 FcCacheInsert (FcCache *cache, struct stat *cache_stat)
531 {
532 FcCacheSkip **update[FC_CACHE_MAX_LEVEL];
533 FcCacheSkip *s, **next;
534 int i, level;
535
536 lock_cache();
537
538 /*
539 * Find links along each chain
540 */
541 next = fcCacheChains;
542 for (i = fcCacheMaxLevel; --i >= 0;) {
543 for (; (s = next[i]); next = s->next)
544 if (s->cache > cache)
545 break;
546 update[i] = &next[i];
547 }
548
549 /*
550 * Create new list element
551 */
552 level = random_level();
553 if (level > fcCacheMaxLevel) {
554 level = fcCacheMaxLevel + 1;
555 update[fcCacheMaxLevel] = &fcCacheChains[fcCacheMaxLevel];
556 fcCacheMaxLevel = level;
557 }
558
559 s = malloc (sizeof (FcCacheSkip) + (level - 1) * sizeof (FcCacheSkip *));
560 if (!s) {
561 unlock_cache();
562 return FcFalse;
563 }
564
565 s->cache = cache;
566 s->size = cache->size;
567 s->allocated = NULL;
568 FcRefInit (&s->ref, 1);
569 if (cache_stat) {
570 s->cache_dev = cache_stat->st_dev;
571 s->cache_ino = cache_stat->st_ino;
572 s->cache_mtime = cache_stat->st_mtime;
573 #ifdef HAVE_STRUCT_STAT_ST_MTIM
574 s->cache_mtime_nano = cache_stat->st_mtim.tv_nsec;
575 #else
576 s->cache_mtime_nano = 0;
577 #endif
578 } else {
579 s->cache_dev = 0;
580 s->cache_ino = 0;
581 s->cache_mtime = 0;
582 s->cache_mtime_nano = 0;
583 }
584
585 /*
586 * Insert into all fcCacheChains
587 */
588 for (i = 0; i < level; i++) {
589 s->next[i] = *update[i];
590 *update[i] = s;
591 }
592
593 unlock_cache();
594 return FcTrue;
595 }
596
597 static FcCacheSkip *
598 FcCacheFindByAddrUnlocked (void *object)
599 {
600 int i;
601 FcCacheSkip **next = fcCacheChains;
602 FcCacheSkip *s;
603
604 if (!object)
605 return NULL;
606
607 /*
608 * Walk chain pointers one level at a time
609 */
610 for (i = fcCacheMaxLevel; --i >= 0;)
611 while (next[i] && (char *)object >= ((char *)next[i]->cache + next[i]->size))
612 next = next[i]->next;
613 /*
614 * Here we are
615 */
616 s = next[0];
617 if (s && (char *)object < ((char *)s->cache + s->size))
618 return s;
619 return NULL;
620 }
621
622 static FcCacheSkip *
623 FcCacheFindByAddr (void *object)
624 {
625 FcCacheSkip *ret;
626 lock_cache();
627 ret = FcCacheFindByAddrUnlocked (object);
628 unlock_cache();
629 return ret;
630 }
631
632 static void
633 FcCacheRemoveUnlocked (FcCache *cache)
634 {
635 FcCacheSkip **update[FC_CACHE_MAX_LEVEL];
636 FcCacheSkip *s, **next;
637 int i;
638 void *allocated;
639
640 /*
641 * Find links along each chain
642 */
643 next = fcCacheChains;
644 for (i = fcCacheMaxLevel; --i >= 0;) {
645 for (; (s = next[i]); next = s->next)
646 if (s->cache >= cache)
647 break;
648 update[i] = &next[i];
649 }
650 s = next[0];
651 for (i = 0; i < fcCacheMaxLevel && *update[i] == s; i++)
652 *update[i] = s->next[i];
653 while (fcCacheMaxLevel > 0 && fcCacheChains[fcCacheMaxLevel - 1] == NULL)
654 fcCacheMaxLevel--;
655
656 if (s) {
657 allocated = s->allocated;
658 while (allocated) {
659 /* First element in allocated chunk is the free list */
660 next = *(void **)allocated;
661 free (allocated);
662 allocated = next;
663 }
664 free (s);
665 }
666 }
667
668 static FcCache *
669 FcCacheFindByStat (struct stat *cache_stat)
670 {
671 FcCacheSkip *s;
672
673 lock_cache();
674 for (s = fcCacheChains[0]; s; s = s->next[0])
675 if (s->cache_dev == cache_stat->st_dev &&
676 s->cache_ino == cache_stat->st_ino &&
677 s->cache_mtime == cache_stat->st_mtime) {
678 #ifdef HAVE_STRUCT_STAT_ST_MTIM
679 if (s->cache_mtime_nano != cache_stat->st_mtim.tv_nsec)
680 continue;
681 #endif
682 FcRefInc (&s->ref);
683 unlock_cache();
684 return s->cache;
685 }
686 unlock_cache();
687 return NULL;
688 }
689
690 static void
691 FcDirCacheDisposeUnlocked (FcCache *cache)
692 {
693 FcCacheRemoveUnlocked (cache);
694
695 switch (cache->magic) {
696 case FC_CACHE_MAGIC_ALLOC:
697 free (cache);
698 break;
699 case FC_CACHE_MAGIC_MMAP:
700 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
701 munmap (cache, cache->size);
702 #elif defined(_WIN32)
703 UnmapViewOfFile (cache);
704 #endif
705 break;
706 }
707 }
708
709 void
710 FcCacheObjectReference (void *object)
711 {
712 FcCacheSkip *skip = FcCacheFindByAddr (object);
713
714 if (skip)
715 FcRefInc (&skip->ref);
716 }
717
718 void
719 FcCacheObjectDereference (void *object)
720 {
721 FcCacheSkip *skip;
722
723 lock_cache();
724 skip = FcCacheFindByAddrUnlocked (object);
725 if (skip) {
726 if (FcRefDec (&skip->ref) == 1)
727 FcDirCacheDisposeUnlocked (skip->cache);
728 }
729 unlock_cache();
730 }
731
732 void *
733 FcCacheAllocate (FcCache *cache, size_t len)
734 {
735 FcCacheSkip *skip;
736 void *allocated = NULL;
737
738 lock_cache();
739 skip = FcCacheFindByAddrUnlocked (cache);
740 if (skip) {
741 void *chunk = malloc (sizeof (void *) + len);
742 if (chunk) {
743 /* First element in allocated chunk is the free list */
744 *(void **)chunk = skip->allocated;
745 skip->allocated = chunk;
746 /* Return the rest */
747 allocated = ((FcChar8 *)chunk) + sizeof (void *);
748 }
749 }
750 unlock_cache();
751 return allocated;
752 }
753
754 void
755 FcCacheFini (void)
756 {
757 int i;
758 FcBool res = FcTrue;
759
760 for (i = 0; i < FC_CACHE_MAX_LEVEL; i++) {
761 if (fcCacheChains[i] != NULL) {
762 res = FcFalse;
763 if (FcDebug() & FC_DBG_CACHE) {
764 FcCacheSkip *s = fcCacheChains[i];
765 fprintf (stderr, "Fontconfig error: not freed %p (dir: %s, refcount %" FC_ATOMIC_INT_FORMAT ")\n", s->cache, FcCacheDir (s->cache), s->ref.count);
766 }
767 }
768 }
769 if (res)
770 free_lock();
771 }
772
773 static FcBool
774 FcCacheTimeValid (FcConfig *config, FcCache *cache, struct stat *dir_stat)
775 {
776 struct stat dir_static;
777 FcBool fnano = FcTrue;
778
779 if (!dir_stat) {
780 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
781 FcChar8 *d;
782
783 if (sysroot)
784 d = FcStrBuildFilename (sysroot, FcCacheDir (cache), NULL);
785 else
786 d = FcStrdup (FcCacheDir (cache));
787 if (FcStatChecksum (d, &dir_static) < 0) {
788 FcStrFree (d);
789 return FcFalse;
790 }
791 FcStrFree (d);
792 dir_stat = &dir_static;
793 }
794 #ifdef HAVE_STRUCT_STAT_ST_MTIM
795 fnano = (cache->checksum_nano == dir_stat->st_mtim.tv_nsec);
796 if (FcDebug() & FC_DBG_CACHE)
797 printf ("FcCacheTimeValid dir \"%s\" cache checksum %d.%ld dir checksum %d.%ld\n",
798 FcCacheDir (cache), cache->checksum, (long)cache->checksum_nano, (int)dir_stat->st_mtime, dir_stat->st_mtim.tv_nsec);
799 #else
800 if (FcDebug() & FC_DBG_CACHE)
801 printf ("FcCacheTimeValid dir \"%s\" cache checksum %d dir checksum %d\n",
802 FcCacheDir (cache), cache->checksum, (int)dir_stat->st_mtime);
803 #endif
804
805 return dir_stat->st_mtime == 0 || (cache->checksum == (int)dir_stat->st_mtime && fnano);
806 }
807
808 static FcBool
809 FcCacheOffsetsValid (FcCache *cache)
810 {
811 char *base = (char *)cache;
812 char *end = base + cache->size;
813 intptr_t *dirs;
814 FcFontSet *fs;
815 int i, j;
816
817 if (cache->dir < 0 || cache->dir > cache->size - sizeof (intptr_t) ||
818 memchr (base + cache->dir, '\0', cache->size - cache->dir) == NULL)
819 return FcFalse;
820
821 if (cache->dirs < 0 || cache->dirs >= cache->size ||
822 cache->dirs_count < 0 ||
823 cache->dirs_count > (cache->size - cache->dirs) / sizeof (intptr_t))
824 return FcFalse;
825
826 dirs = FcCacheDirs (cache);
827 if (dirs) {
828 for (i = 0; i < cache->dirs_count; i++) {
829 FcChar8 *dir;
830
831 if (dirs[i] < 0 ||
832 dirs[i] > end - (char *)dirs - sizeof (intptr_t))
833 return FcFalse;
834
835 dir = FcOffsetToPtr (dirs, dirs[i], FcChar8);
836 if (memchr (dir, '\0', end - (char *)dir) == NULL)
837 return FcFalse;
838 }
839 }
840
841 if (cache->set < 0 || cache->set > cache->size - sizeof (FcFontSet))
842 return FcFalse;
843
844 fs = FcCacheSet (cache);
845 if (fs) {
846 if (fs->nfont > (end - (char *)fs) / sizeof (FcPattern))
847 return FcFalse;
848
849 if (!FcIsEncodedOffset (fs->fonts))
850 return FcFalse;
851
852 for (i = 0; i < fs->nfont; i++) {
853 FcPattern *font = FcFontSetFont (fs, i);
854 FcPatternElt *e;
855 FcValueListPtr l;
856 char *last_offset;
857 const FcLangSet *ls;
858 const FcRange *r;
859 const FcChar8 *s;
860
861 if ((char *)font < base ||
862 (char *)font > end - sizeof (FcFontSet) ||
863 font->elts_offset < 0 ||
864 font->elts_offset > end - (char *)font ||
865 font->num > (end - (char *)font - font->elts_offset) / sizeof (FcPatternElt) ||
866 !FcRefIsConst (&font->ref))
867 return FcFalse;
868
869 e = FcPatternElts (font);
870 if (e->values != 0 && !FcIsEncodedOffset (e->values))
871 return FcFalse;
872
873 for (j = 0; j < font->num; j++) {
874 last_offset = (char *)font + font->elts_offset;
875 for (l = FcPatternEltValues (&e[j]); l; l = FcValueListNext (l)) {
876 if ((char *)l < last_offset || (char *)l > end - sizeof (*l) ||
877 (l->next != NULL && !FcIsEncodedOffset (l->next)))
878 return FcFalse;
879 switch (l->value.type) {
880 case FcTypeVoid:
881 case FcTypeInteger:
882 case FcTypeDouble:
883 case FcTypeBool:
884 case FcTypeMatrix:
885 case FcTypeFTFace:
886 break; /* nop */
887 case FcTypeString:
888 s = FcValueString (&l->value);
889 if ((intptr_t)s < (intptr_t)&e[j] ||
890 (intptr_t)&l->value > (intptr_t)end - sizeof (*l) ||
891 !FcIsEncodedOffset (l->value.u.s)) {
892 if (FcDebug() & FC_DBG_CACHE) {
893 fprintf (stderr, "Fontconfig warning: invalid cache: broken string pointer\n");
894 }
895 return FcFalse;
896 }
897 break;
898 case FcTypeCharSet:
899 /* FcCharSet might be re-used by FcCharSetFindFrozen
900 * which would means a pointer might be out of Elts
901 */
902 if ((intptr_t)&l->value > (intptr_t)end - sizeof (*l) ||
903 !FcIsEncodedOffset (l->value.u.c)) {
904 if (FcDebug() & FC_DBG_CACHE) {
905 fprintf (stderr, "Fontconfig warning: invalid cache: broken charset\n");
906 }
907 return FcFalse;
908 }
909 break;
910 case FcTypeLangSet:
911 ls = FcValueLangSet (&l->value);
912 if ((intptr_t)ls < (intptr_t)&e[j] ||
913 (intptr_t)&l->value > (intptr_t)end - sizeof (*l) ||
914 !FcIsEncodedOffset (l->value.u.l)) {
915 if (FcDebug() & FC_DBG_CACHE) {
916 fprintf (stderr, "Fontconfig warning: invalid cache: broken langset\n");
917 }
918 return FcFalse;
919 }
920 /* ls->extra isn't serialized. it must be null */
921 if (ls->extra != NULL) {
922 if (FcDebug() & FC_DBG_CACHE) {
923 fprintf (stderr, "Fontconfig warning: invalid cache: broken langset\n");
924 }
925 return FcFalse;
926 }
927 break;
928 case FcTypeRange:
929 r = FcValueRange (&l->value);
930 if ((intptr_t)r < (intptr_t)&e[j] ||
931 (intptr_t)&l->value > (intptr_t)end - sizeof (*l) ||
932 !FcIsEncodedOffset (l->value.u.r)) {
933 if (FcDebug() & FC_DBG_CACHE) {
934 fprintf (stderr, "Fontconfig warning: invalid cache: broken range\n");
935 }
936 return FcFalse;
937 }
938 break;
939 default:
940 /* just ignore unknown object type for upper-compatible in the future */
941 if (FcDebug() & FC_DBG_CACHEV) {
942 fprintf (stderr, "Fontconfig warning: invalid cache: unknown object type in pattern: %d\n", l->value.type);
943 }
944 break;
945 }
946 last_offset = (char *)l + 1;
947 }
948 }
949 }
950 }
951
952 return FcTrue;
953 }
954
955 /*
956 * Map a cache file into memory
957 */
958 static FcCache *
959 FcDirCacheMapFd (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat)
960 {
961 FcCache *cache;
962 FcBool allocated = FcFalse;
963
964 if (fd_stat->st_size > INTPTR_MAX ||
965 fd_stat->st_size < (int)sizeof (FcCache))
966 return NULL;
967 cache = FcCacheFindByStat (fd_stat);
968 if (cache) {
969 if (FcCacheTimeValid (config, cache, dir_stat))
970 return cache;
971 FcDirCacheUnload (cache);
972 cache = NULL;
973 }
974
975 /*
976 * Large cache files are mmap'ed, smaller cache files are read. This
977 * balances the system cost of mmap against per-process memory usage.
978 */
979 if (FcCacheIsMmapSafe (fd) && fd_stat->st_size >= FC_CACHE_MIN_MMAP) {
980 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
981 cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
982 # if defined(HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
983 posix_fadvise (fd, 0, fd_stat->st_size, POSIX_FADV_WILLNEED);
984 # endif
985 if (cache == MAP_FAILED)
986 cache = NULL;
987 #elif defined(_WIN32)
988 {
989 HANDLE hFileMap;
990
991 cache = NULL;
992 hFileMap = CreateFileMapping ((HANDLE)_get_osfhandle (fd), NULL,
993 PAGE_READONLY, 0, 0, NULL);
994 if (hFileMap != NULL) {
995 cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0,
996 fd_stat->st_size);
997 CloseHandle (hFileMap);
998 }
999 }
1000 #endif
1001 }
1002 if (!cache) {
1003 cache = malloc (fd_stat->st_size);
1004 if (!cache)
1005 return NULL;
1006
1007 if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size) {
1008 free (cache);
1009 return NULL;
1010 }
1011 allocated = FcTrue;
1012 }
1013 if (cache->magic != FC_CACHE_MAGIC_MMAP ||
1014 cache->version < FC_CACHE_VERSION_NUMBER ||
1015 cache->size != (intptr_t)fd_stat->st_size ||
1016 !FcCacheOffsetsValid (cache) ||
1017 !FcCacheTimeValid (config, cache, dir_stat) ||
1018 !FcCacheInsert (cache, fd_stat)) {
1019 if (allocated)
1020 free (cache);
1021 else {
1022 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
1023 munmap (cache, fd_stat->st_size);
1024 #elif defined(_WIN32)
1025 UnmapViewOfFile (cache);
1026 #endif
1027 }
1028 return NULL;
1029 }
1030
1031 /* Mark allocated caches so they're freed rather than unmapped */
1032 if (allocated)
1033 cache->magic = FC_CACHE_MAGIC_ALLOC;
1034
1035 return cache;
1036 }
1037
1038 void
1039 FcDirCacheReference (FcCache *cache, int nref)
1040 {
1041 FcCacheSkip *skip = FcCacheFindByAddr (cache);
1042
1043 if (skip)
1044 FcRefAdd (&skip->ref, nref);
1045 }
1046
1047 void
1048 FcDirCacheUnload (FcCache *cache)
1049 {
1050 FcCacheObjectDereference (cache);
1051 }
1052
1053 static FcBool
1054 FcDirCacheMapHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, struct timeval *latest_cache_mtime, void *closure)
1055 {
1056 FcCache *cache = FcDirCacheMapFd (config, fd, fd_stat, dir_stat);
1057 struct timeval cache_mtime, zero_mtime = { 0, 0 }, dir_mtime;
1058
1059 if (!cache)
1060 return FcFalse;
1061 cache_mtime.tv_sec = fd_stat->st_mtime;
1062 dir_mtime.tv_sec = dir_stat->st_mtime;
1063 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1064 cache_mtime.tv_usec = fd_stat->st_mtim.tv_nsec / 1000;
1065 dir_mtime.tv_usec = dir_stat->st_mtim.tv_nsec / 1000;
1066 #else
1067 cache_mtime.tv_usec = 0;
1068 dir_mtime.tv_usec = 0;
1069 #endif
1070 /* special take care of OSTree */
1071 if (!timercmp (&zero_mtime, &dir_mtime, !=)) {
1072 if (!timercmp (&zero_mtime, &cache_mtime, !=)) {
1073 if (*((FcCache **)closure))
1074 FcDirCacheUnload (*((FcCache **)closure));
1075 } else if (*((FcCache **)closure) && !timercmp (&zero_mtime, latest_cache_mtime, !=)) {
1076 FcDirCacheUnload (cache);
1077 return FcFalse;
1078 } else if (timercmp (latest_cache_mtime, &cache_mtime, <)) {
1079 if (*((FcCache **)closure))
1080 FcDirCacheUnload (*((FcCache **)closure));
1081 }
1082 } else if (timercmp (latest_cache_mtime, &cache_mtime, <)) {
1083 if (*((FcCache **)closure))
1084 FcDirCacheUnload (*((FcCache **)closure));
1085 } else {
1086 FcDirCacheUnload (cache);
1087 return FcFalse;
1088 }
1089 latest_cache_mtime->tv_sec = cache_mtime.tv_sec;
1090 latest_cache_mtime->tv_usec = cache_mtime.tv_usec;
1091 *((FcCache **)closure) = cache;
1092 return FcTrue;
1093 }
1094
1095 FcCache *
1096 FcDirCacheLoad (const FcChar8 *dir, FcConfig *config, FcChar8 **cache_file)
1097 {
1098 FcCache *cache = NULL;
1099
1100 config = FcConfigReference (config);
1101 if (!config)
1102 return NULL;
1103 if (!FcDirCacheProcess (config, dir,
1104 FcDirCacheMapHelper,
1105 &cache, cache_file))
1106 cache = NULL;
1107
1108 FcConfigDestroy (config);
1109
1110 return cache;
1111 }
1112
1113 FcCache *
1114 FcDirCacheLoadFile (const FcChar8 *cache_file, struct stat *file_stat)
1115 {
1116 int fd;
1117 FcCache *cache = NULL;
1118 struct stat my_file_stat;
1119 FcConfig *config;
1120
1121 if (!file_stat)
1122 file_stat = &my_file_stat;
1123 config = FcConfigReference (NULL);
1124 if (!config)
1125 return NULL;
1126 fd = FcDirCacheOpenFile (cache_file, file_stat);
1127 if (fd >= 0) {
1128 cache = FcDirCacheMapFd (config, fd, file_stat, NULL);
1129 close (fd);
1130 }
1131 FcConfigDestroy (config);
1132
1133 return cache;
1134 }
1135
1136 static int
1137 FcDirChecksum (struct stat *statb)
1138 {
1139 int ret = (int)statb->st_mtime;
1140 char *endptr;
1141 char *source_date_epoch;
1142 unsigned long long epoch;
1143
1144 source_date_epoch = getenv ("SOURCE_DATE_EPOCH");
1145 if (source_date_epoch) {
1146 errno = 0;
1147 epoch = strtoull (source_date_epoch, &endptr, 10);
1148
1149 if (endptr == source_date_epoch)
1150 fprintf (stderr,
1151 "Fontconfig: SOURCE_DATE_EPOCH invalid\n");
1152 else if ((errno == ERANGE && (epoch == ULLONG_MAX || epoch == 0)) || (errno != 0 && epoch == 0))
1153 fprintf (stderr,
1154 "Fontconfig: SOURCE_DATE_EPOCH: strtoull: %s: %" FC_UINT64_FORMAT "\n",
1155 strerror (errno), epoch);
1156 else if (*endptr != '\0')
1157 fprintf (stderr,
1158 "Fontconfig: SOURCE_DATE_EPOCH has trailing garbage\n");
1159 else if (epoch > ULONG_MAX)
1160 fprintf (stderr,
1161 "Fontconfig: SOURCE_DATE_EPOCH must be <= %lu but saw: %" FC_UINT64_FORMAT "\n",
1162 ULONG_MAX, epoch);
1163 else if (epoch < ret)
1164 /* Only override if directory is newer */
1165 ret = (int)epoch;
1166 }
1167
1168 return ret;
1169 }
1170
1171 static int64_t
1172 FcDirChecksumNano (struct stat *statb)
1173 {
1174 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1175 /* No nanosecond component to parse */
1176 if (getenv ("SOURCE_DATE_EPOCH"))
1177 return 0;
1178 return statb->st_mtim.tv_nsec;
1179 #else
1180 return 0;
1181 #endif
1182 }
1183
1184 /*
1185 * Validate a cache file by reading the header and checking
1186 * the magic number and the size field
1187 */
1188 static FcBool
1189 FcDirCacheValidateHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, struct timeval *latest_cache_mtime, void *closure FC_UNUSED)
1190 {
1191 FcBool ret = FcTrue;
1192 FcCache c;
1193
1194 if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
1195 ret = FcFalse;
1196 else if (c.magic != FC_CACHE_MAGIC_MMAP)
1197 ret = FcFalse;
1198 else if (c.version < FC_CACHE_VERSION_NUMBER)
1199 ret = FcFalse;
1200 else if (fd_stat->st_size != c.size)
1201 ret = FcFalse;
1202 else if (c.checksum != FcDirChecksum (dir_stat))
1203 ret = FcFalse;
1204 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1205 else if (c.checksum_nano != FcDirChecksumNano (dir_stat))
1206 ret = FcFalse;
1207 #endif
1208 return ret;
1209 }
1210
1211 static FcBool
1212 FcDirCacheValidConfig (const FcChar8 *dir, FcConfig *config)
1213 {
1214 return FcDirCacheProcess (config, dir,
1215 FcDirCacheValidateHelper,
1216 NULL, NULL);
1217 }
1218
1219 FcBool
1220 FcDirCacheValid (const FcChar8 *dir)
1221 {
1222 FcConfig *config;
1223 FcBool ret;
1224
1225 config = FcConfigReference (NULL);
1226 if (!config)
1227 return FcFalse;
1228
1229 ret = FcDirCacheValidConfig (dir, config);
1230 FcConfigDestroy (config);
1231
1232 return ret;
1233 }
1234
1235 /*
1236 * Build a cache structure from the given contents
1237 */
1238 FcCache *
1239 FcDirCacheBuild (FcFontSet *set, const FcChar8 *dir, struct stat *dir_stat, FcStrSet *dirs)
1240 {
1241 FcSerialize *serialize = FcSerializeCreate();
1242 FcCache *cache;
1243 int i;
1244 FcChar8 *dir_serialize;
1245 intptr_t *dirs_serialize;
1246 FcFontSet *set_serialize;
1247
1248 if (!serialize)
1249 return NULL;
1250 /*
1251 * Space for cache structure
1252 */
1253 FcSerializeReserve (serialize, sizeof (FcCache));
1254 /*
1255 * Directory name
1256 */
1257 if (!FcStrSerializeAlloc (serialize, dir))
1258 goto bail1;
1259 /*
1260 * Subdirs
1261 */
1262 FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
1263 for (i = 0; i < dirs->num; i++)
1264 if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
1265 goto bail1;
1266
1267 /*
1268 * Patterns
1269 */
1270 if (!FcFontSetSerializeAlloc (serialize, set))
1271 goto bail1;
1272
1273 /* Serialize layout complete. Now allocate space and fill it */
1274 cache = malloc (serialize->size);
1275 if (!cache)
1276 goto bail1;
1277 /* shut up valgrind */
1278 memset (cache, 0, serialize->size);
1279
1280 serialize->linear = cache;
1281
1282 cache->magic = FC_CACHE_MAGIC_ALLOC;
1283 cache->version = FC_CACHE_VERSION_NUMBER;
1284 cache->size = serialize->size;
1285 cache->checksum = FcDirChecksum (dir_stat);
1286 cache->checksum_nano = FcDirChecksumNano (dir_stat);
1287
1288 /*
1289 * Serialize directory name
1290 */
1291 dir_serialize = FcStrSerialize (serialize, dir);
1292 if (!dir_serialize)
1293 goto bail2;
1294 cache->dir = FcPtrToOffset (cache, dir_serialize);
1295
1296 /*
1297 * Serialize sub dirs
1298 */
1299 dirs_serialize = FcSerializePtr (serialize, dirs);
1300 if (!dirs_serialize)
1301 goto bail2;
1302 cache->dirs = FcPtrToOffset (cache, dirs_serialize);
1303 cache->dirs_count = dirs->num;
1304 for (i = 0; i < dirs->num; i++) {
1305 FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
1306 if (!d_serialize)
1307 goto bail2;
1308 dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
1309 }
1310
1311 /*
1312 * Serialize font set
1313 */
1314 set_serialize = FcFontSetSerialize (serialize, set);
1315 if (!set_serialize)
1316 goto bail2;
1317 cache->set = FcPtrToOffset (cache, set_serialize);
1318
1319 FcSerializeDestroy (serialize);
1320
1321 FcCacheInsert (cache, NULL);
1322
1323 return cache;
1324
1325 bail2:
1326 free (cache);
1327 bail1:
1328 FcSerializeDestroy (serialize);
1329 return NULL;
1330 }
1331
1332 FcCache *
1333 FcDirCacheRebuild (FcCache *cache, struct stat *dir_stat, FcStrSet *dirs)
1334 {
1335 FcCache *newp;
1336 FcFontSet *set = FcFontSetDeserialize (FcCacheSet (cache));
1337 const FcChar8 *dir = FcCacheDir (cache);
1338
1339 newp = FcDirCacheBuild (set, dir, dir_stat, dirs);
1340 FcFontSetDestroy (set);
1341
1342 return newp;
1343 }
1344
1345 /* write serialized state to the cache file */
1346 FcBool
1347 FcDirCacheWrite (FcCache *cache, FcConfig *config)
1348 {
1349 FcChar8 *dir = FcCacheDir (cache);
1350 FcChar8 cache_base[CACHEBASE_LEN];
1351 FcChar8 *cache_hashed;
1352 int fd;
1353 FcAtomic *atomic;
1354 FcStrList *list;
1355 FcChar8 *cache_dir = NULL;
1356 FcChar8 *test_dir, *d = NULL;
1357 FcCacheSkip *skip;
1358 struct stat cache_stat;
1359 unsigned int magic;
1360 int written;
1361 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1362 FcStrSet *cpath;
1363
1364 /*
1365 * Write it to the first directory in the list which is writable
1366 */
1367
1368 cpath = FcStrSetCreateEx (FCSS_GROW_BY_64);
1369 if (!cpath)
1370 return FcFalse;
1371 list = FcStrListCreate (config->cacheDirs);
1372 if (!list) {
1373 FcStrSetDestroy (cpath);
1374 return FcFalse;
1375 }
1376 while ((test_dir = FcStrListNext (list))) {
1377 if (d)
1378 FcStrFree (d);
1379 if (sysroot)
1380 d = FcStrBuildFilename (sysroot, test_dir, NULL);
1381 else
1382 d = FcStrCopyFilename (test_dir);
1383
1384 if (access ((char *)d, W_OK) == 0) {
1385 cache_dir = FcStrCopyFilename (d);
1386 break;
1387 } else {
1388 /*
1389 * If the directory doesn't exist, try to create it
1390 */
1391 if (access ((char *)d, F_OK) == -1) {
1392 if (FcMakeDirectory (d)) {
1393 cache_dir = FcStrCopyFilename (d);
1394 /* Create CACHEDIR.TAG */
1395 FcDirCacheCreateTagFile (d);
1396 break;
1397 }
1398 }
1399 /*
1400 * Otherwise, try making it writable
1401 */
1402 else if (chmod ((char *)d, 0755) == 0) {
1403 cache_dir = FcStrCopyFilename (d);
1404 /* Try to create CACHEDIR.TAG too */
1405 FcDirCacheCreateTagFile (d);
1406 break;
1407 }
1408 /* Record a path that was supposed to be a cache directory */
1409 FcStrSetAdd (cpath, d);
1410 }
1411 }
1412 if (!test_dir) {
1413 FcStrList *l;
1414 FcChar8 *s;
1415
1416 l = FcStrListCreate (cpath);
1417 fprintf (stderr, "\nFontconfig error: No writable cache directories\n");
1418 while ((s = FcStrListNext (l))) {
1419 fprintf (stderr, "\t%s\n", s);
1420 }
1421 FcStrListDone (l);
1422 }
1423 if (d)
1424 FcStrFree (d);
1425 FcStrSetDestroy (cpath);
1426 FcStrListDone (list);
1427 if (!cache_dir)
1428 return FcFalse;
1429
1430 FcDirCacheBasenameMD5 (config, dir, cache_base);
1431 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1432 FcStrFree (cache_dir);
1433 if (!cache_hashed)
1434 return FcFalse;
1435
1436 if (FcDebug() & FC_DBG_CACHE)
1437 printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
1438 dir, cache_hashed);
1439
1440 atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
1441 if (!atomic)
1442 goto bail1;
1443
1444 if (!FcAtomicLock (atomic))
1445 goto bail3;
1446
1447 fd = FcOpen ((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
1448 if (fd == -1)
1449 goto bail4;
1450
1451 /* Temporarily switch magic to MMAP while writing to file */
1452 magic = cache->magic;
1453 if (magic != FC_CACHE_MAGIC_MMAP)
1454 cache->magic = FC_CACHE_MAGIC_MMAP;
1455
1456 /*
1457 * Write cache contents to file
1458 */
1459 written = write (fd, cache, cache->size);
1460
1461 /* Switch magic back */
1462 if (magic != FC_CACHE_MAGIC_MMAP)
1463 cache->magic = magic;
1464
1465 if (written != cache->size) {
1466 perror ("write cache");
1467 goto bail5;
1468 }
1469
1470 close (fd);
1471 if (!FcAtomicReplaceOrig (atomic))
1472 goto bail4;
1473
1474 /* If the file is small, update the cache chain entry such that the
1475 * new cache file is not read again. If it's large, we don't do that
1476 * such that we reload it, using mmap, which is shared across processes.
1477 */
1478 if (cache->size < FC_CACHE_MIN_MMAP && FcStat (cache_hashed, &cache_stat)) {
1479 lock_cache();
1480 if ((skip = FcCacheFindByAddrUnlocked (cache))) {
1481 skip->cache_dev = cache_stat.st_dev;
1482 skip->cache_ino = cache_stat.st_ino;
1483 skip->cache_mtime = cache_stat.st_mtime;
1484 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1485 skip->cache_mtime_nano = cache_stat.st_mtim.tv_nsec;
1486 #else
1487 skip->cache_mtime_nano = 0;
1488 #endif
1489 }
1490 unlock_cache();
1491 }
1492
1493 FcStrFree (cache_hashed);
1494 FcAtomicUnlock (atomic);
1495 FcAtomicDestroy (atomic);
1496 return FcTrue;
1497
1498 bail5:
1499 close (fd);
1500 bail4:
1501 FcAtomicUnlock (atomic);
1502 bail3:
1503 FcAtomicDestroy (atomic);
1504 bail1:
1505 FcStrFree (cache_hashed);
1506 return FcFalse;
1507 }
1508
1509 FcBool
1510 FcDirCacheClean (const FcChar8 *cache_dir, FcBool verbose)
1511 {
1512 DIR *d;
1513 struct dirent *ent;
1514 FcChar8 *dir;
1515 FcBool ret = FcTrue;
1516 FcBool remove;
1517 FcCache *cache;
1518 struct stat target_stat;
1519 const FcChar8 *sysroot;
1520 FcConfig *config;
1521
1522 config = FcConfigReference (NULL);
1523 if (!config)
1524 return FcFalse;
1525 /* FIXME: this API needs to support non-current FcConfig */
1526 sysroot = FcConfigGetSysRoot (config);
1527 if (sysroot)
1528 dir = FcStrBuildFilename (sysroot, cache_dir, NULL);
1529 else
1530 dir = FcStrCopyFilename (cache_dir);
1531 if (!dir) {
1532 fprintf (stderr, "Fontconfig error: %s: out of memory\n", cache_dir);
1533 ret = FcFalse;
1534 goto bail;
1535 }
1536 if (access ((char *)dir, W_OK) != 0) {
1537 if (verbose || FcDebug() & FC_DBG_CACHE)
1538 printf ("%s: not cleaning %s cache directory\n", dir,
1539 access ((char *)dir, F_OK) == 0 ? "unwritable" : "non-existent");
1540 goto bail0;
1541 }
1542 if (verbose || FcDebug() & FC_DBG_CACHE)
1543 printf ("%s: cleaning cache directory\n", dir);
1544 d = opendir ((char *)dir);
1545 if (!d) {
1546 perror ((char *)dir);
1547 ret = FcFalse;
1548 goto bail0;
1549 }
1550 while ((ent = readdir (d))) {
1551 FcChar8 *file_name;
1552 const FcChar8 *target_dir;
1553
1554 if (ent->d_name[0] == '.')
1555 continue;
1556 /* skip cache files for different architectures and */
1557 /* files which are not cache files at all */
1558 if (strlen (ent->d_name) != 32 + strlen ("-" FC_ARCHITECTURE FC_CACHE_SUFFIX) ||
1559 strcmp (ent->d_name + 32, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX))
1560 continue;
1561
1562 file_name = FcStrBuildFilename (dir, (FcChar8 *)ent->d_name, NULL);
1563 if (!file_name) {
1564 fprintf (stderr, "Fontconfig error: %s: allocation failure\n", dir);
1565 ret = FcFalse;
1566 break;
1567 }
1568 remove = FcFalse;
1569 cache = FcDirCacheLoadFile (file_name, NULL);
1570 if (!cache) {
1571 if (verbose || FcDebug() & FC_DBG_CACHE)
1572 printf ("%s: invalid cache file: %s\n", dir, ent->d_name);
1573 remove = FcTrue;
1574 } else {
1575 FcChar8 *s;
1576
1577 target_dir = FcCacheDir (cache);
1578 if (sysroot)
1579 s = FcStrBuildFilename (sysroot, target_dir, NULL);
1580 else
1581 s = FcStrdup (target_dir);
1582 if (stat ((char *)s, &target_stat) < 0) {
1583 if (verbose || FcDebug() & FC_DBG_CACHE)
1584 printf ("%s: %s: missing directory: %s \n",
1585 dir, ent->d_name, s);
1586 remove = FcTrue;
1587 }
1588 FcDirCacheUnload (cache);
1589 FcStrFree (s);
1590 }
1591 if (remove) {
1592 if (unlink ((char *)file_name) < 0) {
1593 perror ((char *)file_name);
1594 ret = FcFalse;
1595 }
1596 }
1597 FcStrFree (file_name);
1598 }
1599
1600 closedir (d);
1601 bail0:
1602 FcStrFree (dir);
1603 bail:
1604 FcConfigDestroy (config);
1605
1606 return ret;
1607 }
1608
1609 int
1610 FcDirCacheLock (const FcChar8 *dir,
1611 FcConfig *config)
1612 {
1613 FcChar8 *cache_hashed = NULL;
1614 FcChar8 cache_base[CACHEBASE_LEN];
1615 FcStrList *list;
1616 FcChar8 *cache_dir;
1617 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1618 int fd = -1;
1619
1620 FcDirCacheBasenameMD5 (config, dir, cache_base);
1621 list = FcStrListCreate (config->cacheDirs);
1622 if (!list)
1623 return -1;
1624
1625 while ((cache_dir = FcStrListNext (list))) {
1626 if (sysroot)
1627 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
1628 else
1629 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1630 if (!cache_hashed)
1631 break;
1632 fd = FcOpen ((const char *)cache_hashed, O_RDWR);
1633 FcStrFree (cache_hashed);
1634 /* No caches in that directory. simply retry with another one */
1635 if (fd != -1) {
1636 #if defined(_WIN32)
1637 if (_locking (fd, _LK_LOCK, 1) == -1)
1638 goto bail;
1639 #else
1640 struct flock fl;
1641
1642 fl.l_type = F_WRLCK;
1643 fl.l_whence = SEEK_SET;
1644 fl.l_start = 0;
1645 fl.l_len = 0;
1646 fl.l_pid = getpid();
1647 if (fcntl (fd, F_SETLKW, &fl) == -1)
1648 goto bail;
1649 #endif
1650 break;
1651 }
1652 }
1653 FcStrListDone (list);
1654 return fd;
1655 bail:
1656 FcStrListDone (list);
1657 if (fd != -1)
1658 close (fd);
1659 return -1;
1660 }
1661
1662 void
1663 FcDirCacheUnlock (int fd)
1664 {
1665 if (fd != -1) {
1666 #if defined(_WIN32)
1667 _locking (fd, _LK_UNLCK, 1);
1668 #else
1669 struct flock fl;
1670
1671 fl.l_type = F_UNLCK;
1672 fl.l_whence = SEEK_SET;
1673 fl.l_start = 0;
1674 fl.l_len = 0;
1675 fl.l_pid = getpid();
1676 fcntl (fd, F_SETLK, &fl);
1677 #endif
1678 close (fd);
1679 }
1680 }
1681
1682 /*
1683 * Hokey little macro trick to permit the definitions of C functions
1684 * with the same name as CPP macros
1685 */
1686 #define args1(x) (x)
1687 #define args2(x, y) (x, y)
1688
1689 const FcChar8 *
1690 FcCacheDir args1 (const FcCache *c)
1691 {
1692 return FcCacheDir (c);
1693 }
1694
1695 FcFontSet *
1696 FcCacheCopySet args1 (const FcCache *c)
1697 {
1698 FcFontSet *old = FcCacheSet (c);
1699 FcFontSet *newp = FcFontSetCreate();
1700 int i;
1701
1702 if (!newp)
1703 return NULL;
1704 for (i = 0; i < old->nfont; i++) {
1705 FcPattern *font = FcFontSetFont (old, i);
1706
1707 FcPatternReference (font);
1708 if (!FcFontSetAdd (newp, font)) {
1709 FcFontSetDestroy (newp);
1710 return NULL;
1711 }
1712 }
1713 return newp;
1714 }
1715
1716 const FcChar8 *
1717 FcCacheSubdir args2 (const FcCache *c, int i)
1718 {
1719 return FcCacheSubdir (c, i);
1720 }
1721
1722 int
1723 FcCacheNumSubdir args1 (const FcCache *c)
1724 {
1725 return c->dirs_count;
1726 }
1727
1728 int
1729 FcCacheNumFont args1 (const FcCache *c)
1730 {
1731 return FcCacheSet (c)->nfont;
1732 }
1733
1734 FcBool
1735 FcDirCacheCreateTagFile (const FcChar8 *cache_dir)
1736 {
1737 FcChar8 *cache_tag;
1738 int fd;
1739 FILE *fp;
1740 FcAtomic *atomic;
1741 static const FcChar8 cache_tag_contents[] =
1742 "Signature: 8a477f597d28d172789f06886806bc55\n"
1743 "# This file is a cache directory tag created by fontconfig.\n"
1744 "# For information about cache directory tags, see:\n"
1745 "# http://www.brynosaurus.com/cachedir/\n";
1746 static size_t cache_tag_contents_size = sizeof (cache_tag_contents) - 1;
1747 FcBool ret = FcFalse;
1748
1749 if (!cache_dir)
1750 return FcFalse;
1751
1752 if (access ((char *)cache_dir, W_OK) == 0) {
1753 /* Create CACHEDIR.TAG */
1754 cache_tag = FcStrBuildFilename (cache_dir, "CACHEDIR.TAG", NULL);
1755 if (!cache_tag)
1756 return FcFalse;
1757 atomic = FcAtomicCreate ((FcChar8 *)cache_tag);
1758 if (!atomic)
1759 goto bail1;
1760 if (!FcAtomicLock (atomic))
1761 goto bail2;
1762 fd = FcOpen ((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0644);
1763 if (fd == -1)
1764 goto bail3;
1765 fp = fdopen (fd, "wb");
1766 if (fp == NULL)
1767 goto bail3;
1768
1769 fwrite (cache_tag_contents, cache_tag_contents_size, sizeof (FcChar8), fp);
1770 fclose (fp);
1771
1772 if (!FcAtomicReplaceOrig (atomic))
1773 goto bail3;
1774
1775 ret = FcTrue;
1776 bail3:
1777 FcAtomicUnlock (atomic);
1778 bail2:
1779 FcAtomicDestroy (atomic);
1780 bail1:
1781 FcStrFree (cache_tag);
1782 }
1783
1784 if (FcDebug() & FC_DBG_CACHE) {
1785 if (ret)
1786 printf ("Created CACHEDIR.TAG at %s\n", cache_dir);
1787 else
1788 printf ("Unable to create CACHEDIR.TAG at %s\n", cache_dir);
1789 }
1790
1791 return ret;
1792 }
1793
1794 void
1795 FcCacheCreateTagFile (FcConfig *config)
1796 {
1797 FcChar8 *cache_dir = NULL, *d = NULL;
1798 FcStrList *list;
1799 const FcChar8 *sysroot;
1800
1801 config = FcConfigReference (config);
1802 if (!config)
1803 return;
1804 sysroot = FcConfigGetSysRoot (config);
1805
1806 list = FcConfigGetCacheDirs (config);
1807 if (!list)
1808 goto bail;
1809
1810 while ((cache_dir = FcStrListNext (list))) {
1811 if (d)
1812 FcStrFree (d);
1813 if (sysroot)
1814 d = FcStrBuildFilename (sysroot, cache_dir, NULL);
1815 else
1816 d = FcStrCopyFilename (cache_dir);
1817 if (FcDirCacheCreateTagFile (d))
1818 break;
1819 }
1820 if (d)
1821 FcStrFree (d);
1822 FcStrListDone (list);
1823 bail:
1824 FcConfigDestroy (config);
1825 }
1826
1827 #define __fccache__
1828 #include "fcaliastail.h"
1829 #undef __fccache__