2 * Copyright © 2000 Keith Packard
3 * Copyright © 2005 Patrick Lam
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.
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.
34 #include <sys/types.h>
40 #include <winsock2.h> /* for struct timeval */
44 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
46 # include <sys/mman.h>
49 #include <sys/locking.h>
57 FcDirCacheCreateUUID (FcChar8 *dir,
65 FcDirCacheDeleteUUID (const FcChar8 *dir,
70 const FcChar8 *sysroot;
73 struct timeval times[2];
75 config = FcConfigReference (config);
78 sysroot = FcConfigGetSysRoot (config);
80 d = FcStrBuildFilename (sysroot, dir, NULL);
82 d = FcStrBuildFilename (dir, NULL);
83 if (FcStat (d, &statb) != 0)
88 target = FcStrBuildFilename (d, ".uuid", NULL);
89 ret = unlink ((char *) target) == 0;
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;
101 if (utimes ((const char *) d, times) != 0)
103 fprintf (stderr, "Unable to revert mtime: %s\n", d);
110 FcConfigDestroy (config);
115 #define CACHEBASE_LEN (1 + 36 + 1 + sizeof (FC_ARCHITECTURE) + sizeof (FC_CACHE_SUFFIX))
118 FcCacheIsMmapSafe (int fd)
121 MMAP_NOT_INITIALIZED = 0,
126 static void *static_status;
128 status = (intptr_t) fc_atomic_ptr_get (&static_status);
130 if (status == MMAP_NOT_INITIALIZED)
132 const char *env = getenv ("FONTCONFIG_USE_MMAP");
134 if (env && FcNameBool ((const FcChar8 *) env, &use))
135 status = use ? MMAP_USE : MMAP_DONT_USE;
137 status = MMAP_CHECK_FS;
138 (void) fc_atomic_ptr_cmpexch (&static_status, NULL, (void *) (intptr_t) status);
141 if (status == MMAP_CHECK_FS)
142 return FcIsFsMmapSafe (fd);
144 return status == MMAP_USE;
148 static const char bin2hex[] = { '0', '1', '2', '3',
151 'c', 'd', 'e', 'f' };
154 FcDirCacheBasenameMD5 (FcConfig *config, const FcChar8 *dir, FcChar8 cache_base[CACHEBASE_LEN])
156 FcChar8 *mapped_dir = NULL;
157 unsigned char hash[16];
158 FcChar8 *hex_hash, *key = NULL;
160 struct MD5Context ctx;
161 const FcChar8 *salt, *orig_dir = NULL;
163 salt = FcConfigMapSalt (config, dir);
164 /* Obtain a path where "dir" is mapped to.
166 * <remap-dir as-path="/usr/share/fonts">/run/host/fonts</remap-dir>
168 * FcConfigMapFontPath (config, "/run/host/fonts") will returns "/usr/share/fonts".
170 mapped_dir = FcConfigMapFontPath(config, dir);
178 size_t dl = strlen ((const char *) dir);
179 size_t sl = strlen ((const char *) salt);
181 key = (FcChar8 *) malloc (dl + sl + 1);
182 memcpy (key, dir, dl);
183 memcpy (key + dl, salt, sl + 1);
190 MD5Update (&ctx, (const unsigned char *)dir, strlen ((const char *) dir));
192 MD5Final (hash, &ctx);
198 hex_hash = cache_base + 1;
199 for (cnt = 0; cnt < 16; ++cnt)
201 hex_hash[2*cnt ] = bin2hex[hash[cnt] >> 4];
202 hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
205 strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
206 if (FcDebug() & FC_DBG_CACHE)
208 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 : "");
212 FcStrFree(mapped_dir);
219 FcDirCacheBasenameUUID (FcConfig *config, const FcChar8 *dir, FcChar8 cache_base[CACHEBASE_LEN])
221 FcChar8 *target, *fuuid;
222 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
225 /* We don't need to apply remapping here. because .uuid was created at that very directory
226 * to determine the cache name no matter where it was mapped to.
230 target = FcStrBuildFilename (sysroot, dir, NULL);
232 target = FcStrdup (dir);
233 fuuid = FcStrBuildFilename (target, ".uuid", NULL);
234 if ((fd = FcOpen ((char *) fuuid, O_RDONLY)) != -1)
239 memset (suuid, 0, sizeof (suuid));
240 len = read (fd, suuid, 36);
246 strcpy ((char *)&cache_base[1], suuid);
247 strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
248 if (FcDebug () & FC_DBG_CACHE)
250 printf ("cache fallbacks to: %s (dir: %s)\n", cache_base, dir);
262 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
264 FcChar8 *cache_hashed = NULL;
265 FcChar8 cache_base[CACHEBASE_LEN];
267 FcChar8 uuid_cache_base[CACHEBASE_LEN];
271 const FcChar8 *sysroot;
274 config = FcConfigReference (config);
277 sysroot = FcConfigGetSysRoot (config);
279 FcDirCacheBasenameMD5 (config, dir, cache_base);
281 FcDirCacheBasenameUUID (config, dir, uuid_cache_base);
284 list = FcStrListCreate (config->cacheDirs);
291 while ((cache_dir = FcStrListNext (list)))
294 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
296 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
299 (void) unlink ((char *) cache_hashed);
300 FcStrFree (cache_hashed);
302 if (uuid_cache_base[0] != 0)
305 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, uuid_cache_base, NULL);
307 cache_hashed = FcStrBuildFilename (cache_dir, uuid_cache_base, NULL);
310 (void) unlink ((char *) cache_hashed);
311 FcStrFree (cache_hashed);
315 FcStrListDone (list);
316 FcDirCacheDeleteUUID (dir, config);
317 /* return FcFalse if something went wrong */
321 FcConfigDestroy (config);
327 FcDirCacheOpenFile (const FcChar8 *cache_file, struct stat *file_stat)
332 if (FcStat (cache_file, file_stat) < 0)
335 fd = FcOpen((char *) cache_file, O_RDONLY | O_BINARY);
339 if (fstat (fd, file_stat) < 0)
349 * Look for a cache file for the specified dir. Attempt
350 * to use each one we find, stopping when the callback
354 FcDirCacheProcess (FcConfig *config, const FcChar8 *dir,
355 FcBool (*callback) (FcConfig *config, int fd, struct stat *fd_stat,
356 struct stat *dir_stat, struct timeval *cache_mtime, void *closure),
357 void *closure, FcChar8 **cache_file_ret)
360 FcChar8 cache_base[CACHEBASE_LEN];
362 FcChar8 *cache_dir, *d;
363 struct stat file_stat, dir_stat;
364 FcBool ret = FcFalse;
365 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
366 struct timeval latest_mtime = (struct timeval){ 0 };
369 d = FcStrBuildFilename (sysroot, dir, NULL);
372 if (FcStatChecksum (d, &dir_stat) < 0)
379 FcDirCacheBasenameMD5 (config, dir, cache_base);
381 list = FcStrListCreate (config->cacheDirs);
385 while ((cache_dir = FcStrListNext (list)))
387 FcChar8 *cache_hashed;
389 FcBool retried = FcFalse;
393 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
395 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
401 fd = FcDirCacheOpenFile (cache_hashed, &file_stat);
403 ret = (*callback) (config, fd, &file_stat, &dir_stat, &latest_mtime, closure);
410 FcStrFree (*cache_file_ret);
411 *cache_file_ret = cache_hashed;
414 FcStrFree (cache_hashed);
417 FcStrFree (cache_hashed);
422 FcChar8 uuid_cache_base[CACHEBASE_LEN];
425 FcDirCacheBasenameUUID (config, dir, uuid_cache_base);
426 if (uuid_cache_base[0] != 0)
428 FcStrFree (cache_hashed);
430 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, uuid_cache_base, NULL);
432 cache_hashed = FcStrBuildFilename (cache_dir, uuid_cache_base, NULL);
438 FcStrFree (cache_hashed);
442 FcStrFree (cache_hashed);
444 FcStrListDone (list);
447 return !!(*((FcCache **)closure) != NULL);
451 #define FC_CACHE_MIN_MMAP 1024
454 * Skip list element, make sure the 'next' pointer is the last thing
455 * in the structure, it will be allocated large enough to hold all
456 * of the necessary pointers
459 typedef struct _FcCacheSkip FcCacheSkip;
461 struct _FcCacheSkip {
469 long cache_mtime_nano;
470 FcCacheSkip *next[1];
474 * The head of the skip list; pointers for every possible level
475 * in the skip list, plus the largest level in the list
478 #define FC_CACHE_MAX_LEVEL 16
480 /* Protected by cache_lock below */
481 static FcCacheSkip *fcCacheChains[FC_CACHE_MAX_LEVEL];
482 static int fcCacheMaxLevel;
485 static FcMutex *cache_lock;
492 lock = fc_atomic_ptr_get (&cache_lock);
494 lock = (FcMutex *) malloc (sizeof (FcMutex));
496 if (!fc_atomic_ptr_cmpexch (&cache_lock, NULL, lock)) {
497 FcMutexFinish (lock);
503 /* Initialize random state */
514 lock = fc_atomic_ptr_get (&cache_lock);
515 FcMutexUnlock (lock);
522 lock = fc_atomic_ptr_get (&cache_lock);
523 if (lock && fc_atomic_ptr_cmpexch (&cache_lock, lock, NULL)) {
524 FcMutexFinish (lock);
532 * Generate a random level number, distributed
533 * so that each level is 1/4 as likely as the one before
535 * Note that level numbers run 1 <= level <= MAX_LEVEL
540 /* tricky bit -- each bit is '1' 75% of the time */
541 long int bits = FcRandom () | FcRandom ();
544 while (++level < FC_CACHE_MAX_LEVEL)
554 * Insert cache into the list
557 FcCacheInsert (FcCache *cache, struct stat *cache_stat)
559 FcCacheSkip **update[FC_CACHE_MAX_LEVEL];
560 FcCacheSkip *s, **next;
566 * Find links along each chain
568 next = fcCacheChains;
569 for (i = fcCacheMaxLevel; --i >= 0; )
571 for (; (s = next[i]); next = s->next)
572 if (s->cache > cache)
574 update[i] = &next[i];
578 * Create new list element
580 level = random_level ();
581 if (level > fcCacheMaxLevel)
583 level = fcCacheMaxLevel + 1;
584 update[fcCacheMaxLevel] = &fcCacheChains[fcCacheMaxLevel];
585 fcCacheMaxLevel = level;
588 s = malloc (sizeof (FcCacheSkip) + (level - 1) * sizeof (FcCacheSkip *));
593 s->size = cache->size;
595 FcRefInit (&s->ref, 1);
598 s->cache_dev = cache_stat->st_dev;
599 s->cache_ino = cache_stat->st_ino;
600 s->cache_mtime = cache_stat->st_mtime;
601 #ifdef HAVE_STRUCT_STAT_ST_MTIM
602 s->cache_mtime_nano = cache_stat->st_mtim.tv_nsec;
604 s->cache_mtime_nano = 0;
612 s->cache_mtime_nano = 0;
616 * Insert into all fcCacheChains
618 for (i = 0; i < level; i++)
620 s->next[i] = *update[i];
629 FcCacheFindByAddrUnlocked (void *object)
632 FcCacheSkip **next = fcCacheChains;
639 * Walk chain pointers one level at a time
641 for (i = fcCacheMaxLevel; --i >= 0;)
642 while (next[i] && (char *) object >= ((char *) next[i]->cache + next[i]->size))
643 next = next[i]->next;
648 if (s && (char *) object < ((char *) s->cache + s->size))
654 FcCacheFindByAddr (void *object)
658 ret = FcCacheFindByAddrUnlocked (object);
664 FcCacheRemoveUnlocked (FcCache *cache)
666 FcCacheSkip **update[FC_CACHE_MAX_LEVEL];
667 FcCacheSkip *s, **next;
672 * Find links along each chain
674 next = fcCacheChains;
675 for (i = fcCacheMaxLevel; --i >= 0; )
677 for (; (s = next[i]); next = s->next)
678 if (s->cache >= cache)
680 update[i] = &next[i];
683 for (i = 0; i < fcCacheMaxLevel && *update[i] == s; i++)
684 *update[i] = s->next[i];
685 while (fcCacheMaxLevel > 0 && fcCacheChains[fcCacheMaxLevel - 1] == NULL)
690 allocated = s->allocated;
693 /* First element in allocated chunk is the free list */
694 next = *(void **)allocated;
703 FcCacheFindByStat (struct stat *cache_stat)
708 for (s = fcCacheChains[0]; s; s = s->next[0])
709 if (s->cache_dev == cache_stat->st_dev &&
710 s->cache_ino == cache_stat->st_ino &&
711 s->cache_mtime == cache_stat->st_mtime)
713 #ifdef HAVE_STRUCT_STAT_ST_MTIM
714 if (s->cache_mtime_nano != cache_stat->st_mtim.tv_nsec)
726 FcDirCacheDisposeUnlocked (FcCache *cache)
728 FcCacheRemoveUnlocked (cache);
730 switch (cache->magic) {
731 case FC_CACHE_MAGIC_ALLOC:
734 case FC_CACHE_MAGIC_MMAP:
735 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
736 munmap (cache, cache->size);
737 #elif defined(_WIN32)
738 UnmapViewOfFile (cache);
745 FcCacheObjectReference (void *object)
747 FcCacheSkip *skip = FcCacheFindByAddr (object);
750 FcRefInc (&skip->ref);
754 FcCacheObjectDereference (void *object)
759 skip = FcCacheFindByAddrUnlocked (object);
762 if (FcRefDec (&skip->ref) == 1)
763 FcDirCacheDisposeUnlocked (skip->cache);
769 FcCacheAllocate (FcCache *cache, size_t len)
772 void *allocated = NULL;
775 skip = FcCacheFindByAddrUnlocked (cache);
778 void *chunk = malloc (sizeof (void *) + len);
781 /* First element in allocated chunk is the free list */
782 *(void **)chunk = skip->allocated;
783 skip->allocated = chunk;
784 /* Return the rest */
785 allocated = ((FcChar8 *)chunk) + sizeof (void *);
797 if (FcDebug() & FC_DBG_CACHE)
799 for (i = 0; i < FC_CACHE_MAX_LEVEL; i++)
801 if (fcCacheChains[i] != NULL)
803 FcCacheSkip *s = fcCacheChains[i];
804 fprintf(stderr, "Fontconfig error: not freed %p (dir: %s, refcount %" FC_ATOMIC_INT_FORMAT ")\n", s->cache, FcCacheDir(s->cache), s->ref.count);
813 FcCacheTimeValid (FcConfig *config, FcCache *cache, struct stat *dir_stat)
815 struct stat dir_static;
816 FcBool fnano = FcTrue;
820 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
824 d = FcStrBuildFilename (sysroot, FcCacheDir (cache), NULL);
826 d = FcStrdup (FcCacheDir (cache));
827 if (FcStatChecksum (d, &dir_static) < 0)
833 dir_stat = &dir_static;
835 #ifdef HAVE_STRUCT_STAT_ST_MTIM
836 fnano = (cache->checksum_nano == dir_stat->st_mtim.tv_nsec);
837 if (FcDebug () & FC_DBG_CACHE)
838 printf ("FcCacheTimeValid dir \"%s\" cache checksum %d.%ld dir checksum %d.%ld\n",
839 FcCacheDir (cache), cache->checksum, (long)cache->checksum_nano, (int) dir_stat->st_mtime, dir_stat->st_mtim.tv_nsec);
841 if (FcDebug () & FC_DBG_CACHE)
842 printf ("FcCacheTimeValid dir \"%s\" cache checksum %d dir checksum %d\n",
843 FcCacheDir (cache), cache->checksum, (int) dir_stat->st_mtime);
846 return dir_stat->st_mtime == 0 || (cache->checksum == (int) dir_stat->st_mtime && fnano);
850 FcCacheOffsetsValid (FcCache *cache)
852 char *base = (char *)cache;
853 char *end = base + cache->size;
858 if (cache->dir < 0 || cache->dir > cache->size - sizeof (intptr_t) ||
859 memchr (base + cache->dir, '\0', cache->size - cache->dir) == NULL)
862 if (cache->dirs < 0 || cache->dirs >= cache->size ||
863 cache->dirs_count < 0 ||
864 cache->dirs_count > (cache->size - cache->dirs) / sizeof (intptr_t))
867 dirs = FcCacheDirs (cache);
870 for (i = 0; i < cache->dirs_count; i++)
875 dirs[i] > end - (char *) dirs - sizeof (intptr_t))
878 dir = FcOffsetToPtr (dirs, dirs[i], FcChar8);
879 if (memchr (dir, '\0', end - (char *) dir) == NULL)
884 if (cache->set < 0 || cache->set > cache->size - sizeof (FcFontSet))
887 fs = FcCacheSet (cache);
890 if (fs->nfont > (end - (char *) fs) / sizeof (FcPattern))
893 if (!FcIsEncodedOffset(fs->fonts))
896 for (i = 0; i < fs->nfont; i++)
898 FcPattern *font = FcFontSetFont (fs, i);
903 if ((char *) font < base ||
904 (char *) font > end - sizeof (FcFontSet) ||
905 font->elts_offset < 0 ||
906 font->elts_offset > end - (char *) font ||
907 font->num > (end - (char *) font - font->elts_offset) / sizeof (FcPatternElt) ||
908 !FcRefIsConst (&font->ref))
912 e = FcPatternElts(font);
913 if (e->values != 0 && !FcIsEncodedOffset(e->values))
916 for (j = 0; j < font->num; j++)
918 last_offset = (char *) font + font->elts_offset;
919 for (l = FcPatternEltValues(&e[j]); l; l = FcValueListNext(l))
921 if ((char *) l < last_offset || (char *) l > end - sizeof (*l) ||
922 (l->next != NULL && !FcIsEncodedOffset(l->next)))
924 last_offset = (char *) l + 1;
934 * Map a cache file into memory
937 FcDirCacheMapFd (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat)
940 FcBool allocated = FcFalse;
942 if (fd_stat->st_size > INTPTR_MAX ||
943 fd_stat->st_size < (int) sizeof (FcCache))
945 cache = FcCacheFindByStat (fd_stat);
948 if (FcCacheTimeValid (config, cache, dir_stat))
950 FcDirCacheUnload (cache);
955 * Large cache files are mmap'ed, smaller cache files are read. This
956 * balances the system cost of mmap against per-process memory usage.
958 if (FcCacheIsMmapSafe (fd) && fd_stat->st_size >= FC_CACHE_MIN_MMAP)
960 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
961 cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
962 #if defined(HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
963 posix_fadvise (fd, 0, fd_stat->st_size, POSIX_FADV_WILLNEED);
965 if (cache == MAP_FAILED)
967 #elif defined(_WIN32)
972 hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
973 PAGE_READONLY, 0, 0, NULL);
974 if (hFileMap != NULL)
976 cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0,
978 CloseHandle (hFileMap);
985 cache = malloc (fd_stat->st_size);
989 if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
996 if (cache->magic != FC_CACHE_MAGIC_MMAP ||
997 cache->version < FC_CACHE_VERSION_NUMBER ||
998 cache->size != (intptr_t) fd_stat->st_size ||
999 !FcCacheOffsetsValid (cache) ||
1000 !FcCacheTimeValid (config, cache, dir_stat) ||
1001 !FcCacheInsert (cache, fd_stat))
1007 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
1008 munmap (cache, fd_stat->st_size);
1009 #elif defined(_WIN32)
1010 UnmapViewOfFile (cache);
1016 /* Mark allocated caches so they're freed rather than unmapped */
1018 cache->magic = FC_CACHE_MAGIC_ALLOC;
1024 FcDirCacheReference (FcCache *cache, int nref)
1026 FcCacheSkip *skip = FcCacheFindByAddr (cache);
1029 FcRefAdd (&skip->ref, nref);
1033 FcDirCacheUnload (FcCache *cache)
1035 FcCacheObjectDereference (cache);
1039 FcDirCacheMapHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, struct timeval *latest_cache_mtime, void *closure)
1041 FcCache *cache = FcDirCacheMapFd (config, fd, fd_stat, dir_stat);
1042 struct timeval cache_mtime, zero_mtime = { 0, 0}, dir_mtime;
1046 cache_mtime.tv_sec = fd_stat->st_mtime;
1047 dir_mtime.tv_sec = dir_stat->st_mtime;
1048 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1049 cache_mtime.tv_usec = fd_stat->st_mtim.tv_nsec / 1000;
1050 dir_mtime.tv_usec = dir_stat->st_mtim.tv_nsec / 1000;
1052 cache_mtime.tv_usec = 0;
1053 dir_mtime.tv_usec = 0;
1055 /* special take care of OSTree */
1056 if (!timercmp (&zero_mtime, &dir_mtime, !=))
1058 if (!timercmp (&zero_mtime, &cache_mtime, !=))
1060 if (*((FcCache **) closure))
1061 FcDirCacheUnload (*((FcCache **) closure));
1063 else if (*((FcCache **) closure) && !timercmp (&zero_mtime, latest_cache_mtime, !=))
1065 FcDirCacheUnload (cache);
1068 else if (timercmp (latest_cache_mtime, &cache_mtime, <))
1070 if (*((FcCache **) closure))
1071 FcDirCacheUnload (*((FcCache **) closure));
1074 else if (timercmp (latest_cache_mtime, &cache_mtime, <))
1076 if (*((FcCache **) closure))
1077 FcDirCacheUnload (*((FcCache **) closure));
1081 FcDirCacheUnload (cache);
1084 latest_cache_mtime->tv_sec = cache_mtime.tv_sec;
1085 latest_cache_mtime->tv_usec = cache_mtime.tv_usec;
1086 *((FcCache **) closure) = cache;
1091 FcDirCacheLoad (const FcChar8 *dir, FcConfig *config, FcChar8 **cache_file)
1093 FcCache *cache = NULL;
1095 config = FcConfigReference (config);
1098 if (!FcDirCacheProcess (config, dir,
1099 FcDirCacheMapHelper,
1100 &cache, cache_file))
1103 FcConfigDestroy (config);
1109 FcDirCacheLoadFile (const FcChar8 *cache_file, struct stat *file_stat)
1112 FcCache *cache = NULL;
1113 struct stat my_file_stat;
1117 file_stat = &my_file_stat;
1118 config = FcConfigReference (NULL);
1121 fd = FcDirCacheOpenFile (cache_file, file_stat);
1124 cache = FcDirCacheMapFd (config, fd, file_stat, NULL);
1127 FcConfigDestroy (config);
1133 FcDirChecksum (struct stat *statb)
1135 int ret = (int) statb->st_mtime;
1137 char *source_date_epoch;
1138 unsigned long long epoch;
1140 source_date_epoch = getenv("SOURCE_DATE_EPOCH");
1141 if (source_date_epoch)
1144 epoch = strtoull(source_date_epoch, &endptr, 10);
1146 if (endptr == source_date_epoch)
1148 "Fontconfig: SOURCE_DATE_EPOCH invalid\n");
1149 else if ((errno == ERANGE && (epoch == ULLONG_MAX || epoch == 0))
1150 || (errno != 0 && epoch == 0))
1152 "Fontconfig: SOURCE_DATE_EPOCH: strtoull: %s: %" FC_UINT64_FORMAT "\n",
1153 strerror(errno), epoch);
1154 else if (*endptr != '\0')
1156 "Fontconfig: SOURCE_DATE_EPOCH has trailing garbage\n");
1157 else if (epoch > ULONG_MAX)
1159 "Fontconfig: SOURCE_DATE_EPOCH must be <= %lu but saw: %" FC_UINT64_FORMAT "\n",
1161 else if (epoch < ret)
1162 /* Only override if directory is newer */
1170 FcDirChecksumNano (struct stat *statb)
1172 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1173 /* No nanosecond component to parse */
1174 if (getenv("SOURCE_DATE_EPOCH"))
1176 return statb->st_mtim.tv_nsec;
1183 * Validate a cache file by reading the header and checking
1184 * the magic number and the size field
1187 FcDirCacheValidateHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, struct timeval *latest_cache_mtime, void *closure FC_UNUSED)
1189 FcBool ret = FcTrue;
1192 if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
1194 else if (c.magic != FC_CACHE_MAGIC_MMAP)
1196 else if (c.version < FC_CACHE_VERSION_NUMBER)
1198 else if (fd_stat->st_size != c.size)
1200 else if (c.checksum != FcDirChecksum (dir_stat))
1202 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1203 else if (c.checksum_nano != FcDirChecksumNano (dir_stat))
1210 FcDirCacheValidConfig (const FcChar8 *dir, FcConfig *config)
1212 return FcDirCacheProcess (config, dir,
1213 FcDirCacheValidateHelper,
1218 FcDirCacheValid (const FcChar8 *dir)
1223 config = FcConfigReference (NULL);
1227 ret = FcDirCacheValidConfig (dir, config);
1228 FcConfigDestroy (config);
1234 * Build a cache structure from the given contents
1237 FcDirCacheBuild (FcFontSet *set, const FcChar8 *dir, struct stat *dir_stat, FcStrSet *dirs)
1239 FcSerialize *serialize = FcSerializeCreate ();
1242 FcChar8 *dir_serialize;
1243 intptr_t *dirs_serialize;
1244 FcFontSet *set_serialize;
1249 * Space for cache structure
1251 FcSerializeReserve (serialize, sizeof (FcCache));
1255 if (!FcStrSerializeAlloc (serialize, dir))
1260 FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
1261 for (i = 0; i < dirs->num; i++)
1262 if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
1268 if (!FcFontSetSerializeAlloc (serialize, set))
1271 /* Serialize layout complete. Now allocate space and fill it */
1272 cache = malloc (serialize->size);
1275 /* shut up valgrind */
1276 memset (cache, 0, serialize->size);
1278 serialize->linear = cache;
1280 cache->magic = FC_CACHE_MAGIC_ALLOC;
1281 cache->version = FC_CACHE_VERSION_NUMBER;
1282 cache->size = serialize->size;
1283 cache->checksum = FcDirChecksum (dir_stat);
1284 cache->checksum_nano = FcDirChecksumNano (dir_stat);
1287 * Serialize directory name
1289 dir_serialize = FcStrSerialize (serialize, dir);
1292 cache->dir = FcPtrToOffset (cache, dir_serialize);
1295 * Serialize sub dirs
1297 dirs_serialize = FcSerializePtr (serialize, dirs);
1298 if (!dirs_serialize)
1300 cache->dirs = FcPtrToOffset (cache, dirs_serialize);
1301 cache->dirs_count = dirs->num;
1302 for (i = 0; i < dirs->num; i++)
1304 FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
1307 dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
1311 * Serialize font set
1313 set_serialize = FcFontSetSerialize (serialize, set);
1316 cache->set = FcPtrToOffset (cache, set_serialize);
1318 FcSerializeDestroy (serialize);
1320 FcCacheInsert (cache, NULL);
1327 FcSerializeDestroy (serialize);
1332 FcDirCacheRebuild (FcCache *cache, struct stat *dir_stat, FcStrSet *dirs)
1335 FcFontSet *set = FcFontSetDeserialize (FcCacheSet (cache));
1336 const FcChar8 *dir = FcCacheDir (cache);
1338 new = FcDirCacheBuild (set, dir, dir_stat, dirs);
1339 FcFontSetDestroy (set);
1344 /* write serialized state to the cache file */
1346 FcDirCacheWrite (FcCache *cache, FcConfig *config)
1348 FcChar8 *dir = FcCacheDir (cache);
1349 FcChar8 cache_base[CACHEBASE_LEN];
1350 FcChar8 *cache_hashed;
1354 FcChar8 *cache_dir = NULL;
1355 FcChar8 *test_dir, *d = NULL;
1357 struct stat cache_stat;
1360 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1363 * Write it to the first directory in the list which is writable
1366 list = FcStrListCreate (config->cacheDirs);
1369 while ((test_dir = FcStrListNext (list)))
1374 d = FcStrBuildFilename (sysroot, test_dir, NULL);
1376 d = FcStrCopyFilename (test_dir);
1378 if (access ((char *) d, W_OK) == 0)
1380 cache_dir = FcStrCopyFilename (d);
1386 * If the directory doesn't exist, try to create it
1388 if (access ((char *) d, F_OK) == -1) {
1389 if (FcMakeDirectory (d))
1391 cache_dir = FcStrCopyFilename (d);
1392 /* Create CACHEDIR.TAG */
1393 FcDirCacheCreateTagFile (d);
1398 * Otherwise, try making it writable
1400 else if (chmod ((char *) d, 0755) == 0)
1402 cache_dir = FcStrCopyFilename (d);
1403 /* Try to create CACHEDIR.TAG too */
1404 FcDirCacheCreateTagFile (d);
1410 fprintf (stderr, "Fontconfig error: No writable cache directories\n");
1413 FcStrListDone (list);
1417 FcDirCacheBasenameMD5 (config, dir, cache_base);
1418 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1419 FcStrFree (cache_dir);
1423 if (FcDebug () & FC_DBG_CACHE)
1424 printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
1427 atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
1431 if (!FcAtomicLock (atomic))
1434 fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
1438 /* Temporarily switch magic to MMAP while writing to file */
1439 magic = cache->magic;
1440 if (magic != FC_CACHE_MAGIC_MMAP)
1441 cache->magic = FC_CACHE_MAGIC_MMAP;
1444 * Write cache contents to file
1446 written = write (fd, cache, cache->size);
1448 /* Switch magic back */
1449 if (magic != FC_CACHE_MAGIC_MMAP)
1450 cache->magic = magic;
1452 if (written != cache->size)
1454 perror ("write cache");
1459 if (!FcAtomicReplaceOrig(atomic))
1462 /* If the file is small, update the cache chain entry such that the
1463 * new cache file is not read again. If it's large, we don't do that
1464 * such that we reload it, using mmap, which is shared across processes.
1466 if (cache->size < FC_CACHE_MIN_MMAP && FcStat (cache_hashed, &cache_stat))
1469 if ((skip = FcCacheFindByAddrUnlocked (cache)))
1471 skip->cache_dev = cache_stat.st_dev;
1472 skip->cache_ino = cache_stat.st_ino;
1473 skip->cache_mtime = cache_stat.st_mtime;
1474 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1475 skip->cache_mtime_nano = cache_stat.st_mtim.tv_nsec;
1477 skip->cache_mtime_nano = 0;
1483 FcStrFree (cache_hashed);
1484 FcAtomicUnlock (atomic);
1485 FcAtomicDestroy (atomic);
1491 FcAtomicUnlock (atomic);
1493 FcAtomicDestroy (atomic);
1495 FcStrFree (cache_hashed);
1500 FcDirCacheClean (const FcChar8 *cache_dir, FcBool verbose)
1505 FcBool ret = FcTrue;
1508 struct stat target_stat;
1509 const FcChar8 *sysroot;
1512 config = FcConfigReference (NULL);
1515 /* FIXME: this API needs to support non-current FcConfig */
1516 sysroot = FcConfigGetSysRoot (config);
1518 dir = FcStrBuildFilename (sysroot, cache_dir, NULL);
1520 dir = FcStrCopyFilename (cache_dir);
1523 fprintf (stderr, "Fontconfig error: %s: out of memory\n", cache_dir);
1527 if (access ((char *) dir, W_OK) != 0)
1529 if (verbose || FcDebug () & FC_DBG_CACHE)
1530 printf ("%s: not cleaning %s cache directory\n", dir,
1531 access ((char *) dir, F_OK) == 0 ? "unwritable" : "non-existent");
1534 if (verbose || FcDebug () & FC_DBG_CACHE)
1535 printf ("%s: cleaning cache directory\n", dir);
1536 d = opendir ((char *) dir);
1539 perror ((char *) dir);
1543 while ((ent = readdir (d)))
1546 const FcChar8 *target_dir;
1548 if (ent->d_name[0] == '.')
1550 /* skip cache files for different architectures and */
1551 /* files which are not cache files at all */
1552 if (strlen(ent->d_name) != 32 + strlen ("-" FC_ARCHITECTURE FC_CACHE_SUFFIX) ||
1553 strcmp(ent->d_name + 32, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX))
1556 file_name = FcStrBuildFilename (dir, (FcChar8 *)ent->d_name, NULL);
1559 fprintf (stderr, "Fontconfig error: %s: allocation failure\n", dir);
1564 cache = FcDirCacheLoadFile (file_name, NULL);
1567 if (verbose || FcDebug () & FC_DBG_CACHE)
1568 printf ("%s: invalid cache file: %s\n", dir, ent->d_name);
1575 target_dir = FcCacheDir (cache);
1577 s = FcStrBuildFilename (sysroot, target_dir, NULL);
1579 s = FcStrdup (target_dir);
1580 if (stat ((char *) s, &target_stat) < 0)
1582 if (verbose || FcDebug () & FC_DBG_CACHE)
1583 printf ("%s: %s: missing directory: %s \n",
1584 dir, ent->d_name, s);
1587 FcDirCacheUnload (cache);
1592 if (unlink ((char *) file_name) < 0)
1594 perror ((char *) file_name);
1598 FcStrFree (file_name);
1605 FcConfigDestroy (config);
1611 FcDirCacheLock (const FcChar8 *dir,
1614 FcChar8 *cache_hashed = NULL;
1615 FcChar8 cache_base[CACHEBASE_LEN];
1618 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1621 FcDirCacheBasenameMD5 (config, dir, cache_base);
1622 list = FcStrListCreate (config->cacheDirs);
1626 while ((cache_dir = FcStrListNext (list)))
1629 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
1631 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1634 fd = FcOpen ((const char *)cache_hashed, O_RDWR);
1635 FcStrFree (cache_hashed);
1636 /* No caches in that directory. simply retry with another one */
1640 if (_locking (fd, _LK_LOCK, 1) == -1)
1645 fl.l_type = F_WRLCK;
1646 fl.l_whence = SEEK_SET;
1649 fl.l_pid = getpid ();
1650 if (fcntl (fd, F_SETLKW, &fl) == -1)
1656 FcStrListDone (list);
1659 FcStrListDone (list);
1666 FcDirCacheUnlock (int fd)
1671 _locking (fd, _LK_UNLCK, 1);
1675 fl.l_type = F_UNLCK;
1676 fl.l_whence = SEEK_SET;
1679 fl.l_pid = getpid ();
1680 fcntl (fd, F_SETLK, &fl);
1687 * Hokey little macro trick to permit the definitions of C functions
1688 * with the same name as CPP macros
1690 #define args1(x) (x)
1691 #define args2(x,y) (x,y)
1694 FcCacheDir args1(const FcCache *c)
1696 return FcCacheDir (c);
1700 FcCacheCopySet args1(const FcCache *c)
1702 FcFontSet *old = FcCacheSet (c);
1703 FcFontSet *new = FcFontSetCreate ();
1708 for (i = 0; i < old->nfont; i++)
1710 FcPattern *font = FcFontSetFont (old, i);
1712 FcPatternReference (font);
1713 if (!FcFontSetAdd (new, font))
1715 FcFontSetDestroy (new);
1723 FcCacheSubdir args2(const FcCache *c, int i)
1725 return FcCacheSubdir (c, i);
1729 FcCacheNumSubdir args1(const FcCache *c)
1731 return c->dirs_count;
1735 FcCacheNumFont args1(const FcCache *c)
1737 return FcCacheSet(c)->nfont;
1741 FcDirCacheCreateTagFile (const FcChar8 *cache_dir)
1747 static const FcChar8 cache_tag_contents[] =
1748 "Signature: 8a477f597d28d172789f06886806bc55\n"
1749 "# This file is a cache directory tag created by fontconfig.\n"
1750 "# For information about cache directory tags, see:\n"
1751 "# http://www.brynosaurus.com/cachedir/\n";
1752 static size_t cache_tag_contents_size = sizeof (cache_tag_contents) - 1;
1753 FcBool ret = FcFalse;
1758 if (access ((char *) cache_dir, W_OK) == 0)
1760 /* Create CACHEDIR.TAG */
1761 cache_tag = FcStrBuildFilename (cache_dir, "CACHEDIR.TAG", NULL);
1764 atomic = FcAtomicCreate ((FcChar8 *)cache_tag);
1767 if (!FcAtomicLock (atomic))
1769 fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0644);
1772 fp = fdopen(fd, "wb");
1776 fwrite(cache_tag_contents, cache_tag_contents_size, sizeof (FcChar8), fp);
1779 if (!FcAtomicReplaceOrig(atomic))
1784 FcAtomicUnlock (atomic);
1786 FcAtomicDestroy (atomic);
1788 FcStrFree (cache_tag);
1791 if (FcDebug () & FC_DBG_CACHE)
1794 printf ("Created CACHEDIR.TAG at %s\n", cache_dir);
1796 printf ("Unable to create CACHEDIR.TAG at %s\n", cache_dir);
1803 FcCacheCreateTagFile (FcConfig *config)
1805 FcChar8 *cache_dir = NULL, *d = NULL;
1807 const FcChar8 *sysroot;
1809 config = FcConfigReference (config);
1812 sysroot = FcConfigGetSysRoot (config);
1814 list = FcConfigGetCacheDirs (config);
1818 while ((cache_dir = FcStrListNext (list)))
1823 d = FcStrBuildFilename (sysroot, cache_dir, NULL);
1825 d = FcStrCopyFilename (cache_dir);
1826 if (FcDirCacheCreateTagFile (d))
1831 FcStrListDone (list);
1833 FcConfigDestroy (config);
1837 #include "fcaliastail.h"