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.
31 #include <sys/types.h>
34 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
36 # include <sys/mman.h>
39 #include <sys/locking.h>
53 static void MD5Init(struct MD5Context *ctx);
54 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len);
55 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx);
56 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16]);
58 #define CACHEBASE_LEN (1 + 32 + 1 + sizeof (FC_ARCHITECTURE) + sizeof (FC_CACHE_SUFFIX))
61 FcCacheIsMmapSafe (int fd)
64 MMAP_NOT_INITIALIZED = 0,
69 static void *static_status;
71 status = (intptr_t) fc_atomic_ptr_get (&static_status);
73 if (status == MMAP_NOT_INITIALIZED)
75 const char *env = getenv ("FONTCONFIG_USE_MMAP");
77 if (env && FcNameBool ((const FcChar8 *) env, &use))
78 status = use ? MMAP_USE : MMAP_DONT_USE;
80 status = MMAP_CHECK_FS;
81 (void) fc_atomic_ptr_cmpexch (&static_status, NULL, (void *) status);
84 if (status == MMAP_CHECK_FS)
85 return FcIsFsMmapSafe (fd);
87 return status == MMAP_USE;
91 static const char bin2hex[] = { '0', '1', '2', '3',
97 FcDirCacheBasename (const FcChar8 * dir, FcChar8 cache_base[CACHEBASE_LEN])
99 unsigned char hash[16];
102 struct MD5Context ctx;
105 MD5Update (&ctx, (const unsigned char *)dir, strlen ((const char *) dir));
107 MD5Final (hash, &ctx);
110 hex_hash = cache_base + 1;
111 for (cnt = 0; cnt < 16; ++cnt)
113 hex_hash[2*cnt ] = bin2hex[hash[cnt] >> 4];
114 hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
117 strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
123 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
125 FcChar8 *cache_hashed = NULL;
126 FcChar8 cache_base[CACHEBASE_LEN];
129 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
131 FcDirCacheBasename (dir, cache_base);
133 list = FcStrListCreate (config->cacheDirs);
137 while ((cache_dir = FcStrListNext (list)))
140 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
142 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
145 (void) unlink ((char *) cache_hashed);
146 FcStrFree (cache_hashed);
148 FcStrListDone (list);
149 /* return FcFalse if something went wrong */
156 FcDirCacheOpenFile (const FcChar8 *cache_file, struct stat *file_stat)
161 if (FcStat (cache_file, file_stat) < 0)
164 fd = FcOpen((char *) cache_file, O_RDONLY | O_BINARY);
168 if (fstat (fd, file_stat) < 0)
178 * Look for a cache file for the specified dir. Attempt
179 * to use each one we find, stopping when the callback
183 FcDirCacheProcess (FcConfig *config, const FcChar8 *dir,
184 FcBool (*callback) (FcConfig *config, int fd, struct stat *fd_stat,
185 struct stat *dir_stat, void *closure),
186 void *closure, FcChar8 **cache_file_ret)
189 FcChar8 cache_base[CACHEBASE_LEN];
191 FcChar8 *cache_dir, *d;
192 struct stat file_stat, dir_stat;
193 FcBool ret = FcFalse;
194 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
197 d = FcStrBuildFilename (sysroot, dir, NULL);
200 if (FcStatChecksum (d, &dir_stat) < 0)
207 FcDirCacheBasename (dir, cache_base);
209 list = FcStrListCreate (config->cacheDirs);
213 while ((cache_dir = FcStrListNext (list)))
215 FcChar8 *cache_hashed;
218 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
220 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
223 fd = FcDirCacheOpenFile (cache_hashed, &file_stat);
225 ret = (*callback) (config, fd, &file_stat, &dir_stat, closure);
230 *cache_file_ret = cache_hashed;
232 FcStrFree (cache_hashed);
236 FcStrFree (cache_hashed);
238 FcStrListDone (list);
243 #define FC_CACHE_MIN_MMAP 1024
246 * Skip list element, make sure the 'next' pointer is the last thing
247 * in the structure, it will be allocated large enough to hold all
248 * of the necessary pointers
251 typedef struct _FcCacheSkip FcCacheSkip;
253 struct _FcCacheSkip {
260 long cache_mtime_nano;
261 FcCacheSkip *next[1];
265 * The head of the skip list; pointers for every possible level
266 * in the skip list, plus the largest level in the list
269 #define FC_CACHE_MAX_LEVEL 16
271 /* Protected by cache_lock below */
272 static FcCacheSkip *fcCacheChains[FC_CACHE_MAX_LEVEL];
273 static int fcCacheMaxLevel;
276 static FcMutex *cache_lock;
283 lock = fc_atomic_ptr_get (&cache_lock);
285 lock = (FcMutex *) malloc (sizeof (FcMutex));
287 if (!fc_atomic_ptr_cmpexch (&cache_lock, NULL, lock)) {
288 FcMutexFinish (lock);
293 /* Initialize random state */
303 FcMutexUnlock (cache_lock);
310 lock = fc_atomic_ptr_get (&cache_lock);
311 if (lock && fc_atomic_ptr_cmpexch (&cache_lock, lock, NULL)) {
312 FcMutexFinish (lock);
320 * Generate a random level number, distributed
321 * so that each level is 1/4 as likely as the one before
323 * Note that level numbers run 1 <= level <= MAX_LEVEL
328 /* tricky bit -- each bit is '1' 75% of the time */
329 long int bits = FcRandom () | FcRandom ();
332 while (++level < FC_CACHE_MAX_LEVEL)
342 * Insert cache into the list
345 FcCacheInsert (FcCache *cache, struct stat *cache_stat)
347 FcCacheSkip **update[FC_CACHE_MAX_LEVEL];
348 FcCacheSkip *s, **next;
354 * Find links along each chain
356 next = fcCacheChains;
357 for (i = fcCacheMaxLevel; --i >= 0; )
359 for (; (s = next[i]); next = s->next)
360 if (s->cache > cache)
362 update[i] = &next[i];
366 * Create new list element
368 level = random_level ();
369 if (level > fcCacheMaxLevel)
371 level = fcCacheMaxLevel + 1;
372 update[fcCacheMaxLevel] = &fcCacheChains[fcCacheMaxLevel];
373 fcCacheMaxLevel = level;
376 s = malloc (sizeof (FcCacheSkip) + (level - 1) * sizeof (FcCacheSkip *));
381 s->size = cache->size;
382 FcRefInit (&s->ref, 1);
385 s->cache_dev = cache_stat->st_dev;
386 s->cache_ino = cache_stat->st_ino;
387 s->cache_mtime = cache_stat->st_mtime;
388 #ifdef HAVE_STRUCT_STAT_ST_MTIM
389 s->cache_mtime_nano = cache_stat->st_mtim.tv_nsec;
391 s->cache_mtime_nano = 0;
399 s->cache_mtime_nano = 0;
403 * Insert into all fcCacheChains
405 for (i = 0; i < level; i++)
407 s->next[i] = *update[i];
416 FcCacheFindByAddrUnlocked (void *object)
419 FcCacheSkip **next = fcCacheChains;
426 * Walk chain pointers one level at a time
428 for (i = fcCacheMaxLevel; --i >= 0;)
429 while (next[i] && (char *) object >= ((char *) next[i]->cache + next[i]->size))
430 next = next[i]->next;
435 if (s && (char *) object < ((char *) s->cache + s->size))
441 FcCacheFindByAddr (void *object)
445 ret = FcCacheFindByAddrUnlocked (object);
451 FcCacheRemoveUnlocked (FcCache *cache)
453 FcCacheSkip **update[FC_CACHE_MAX_LEVEL];
454 FcCacheSkip *s, **next;
458 * Find links along each chain
460 next = fcCacheChains;
461 for (i = fcCacheMaxLevel; --i >= 0; )
463 for (; (s = next[i]); next = s->next)
464 if (s->cache >= cache)
466 update[i] = &next[i];
469 for (i = 0; i < fcCacheMaxLevel && *update[i] == s; i++)
470 *update[i] = s->next[i];
471 while (fcCacheMaxLevel > 0 && fcCacheChains[fcCacheMaxLevel - 1] == NULL)
477 FcCacheFindByStat (struct stat *cache_stat)
482 for (s = fcCacheChains[0]; s; s = s->next[0])
483 if (s->cache_dev == cache_stat->st_dev &&
484 s->cache_ino == cache_stat->st_ino &&
485 s->cache_mtime == cache_stat->st_mtime)
487 #ifdef HAVE_STRUCT_STAT_ST_MTIM
488 if (s->cache_mtime != cache_stat->st_mtim.tv_nsec)
500 FcDirCacheDisposeUnlocked (FcCache *cache)
502 FcCacheRemoveUnlocked (cache);
504 switch (cache->magic) {
505 case FC_CACHE_MAGIC_ALLOC:
508 case FC_CACHE_MAGIC_MMAP:
509 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
510 munmap (cache, cache->size);
511 #elif defined(_WIN32)
512 UnmapViewOfFile (cache);
519 FcCacheObjectReference (void *object)
521 FcCacheSkip *skip = FcCacheFindByAddr (object);
524 FcRefInc (&skip->ref);
528 FcCacheObjectDereference (void *object)
533 skip = FcCacheFindByAddrUnlocked (object);
536 if (FcRefDec (&skip->ref) == 1)
537 FcDirCacheDisposeUnlocked (skip->cache);
547 for (i = 0; i < FC_CACHE_MAX_LEVEL; i++)
548 assert (fcCacheChains[i] == NULL);
549 assert (fcCacheMaxLevel == 0);
555 FcCacheTimeValid (FcConfig *config, FcCache *cache, struct stat *dir_stat)
557 struct stat dir_static;
558 FcBool fnano = FcTrue;
562 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
566 d = FcStrBuildFilename (sysroot, FcCacheDir (cache), NULL);
568 d = FcStrdup (FcCacheDir (cache));
569 if (FcStatChecksum (d, &dir_static) < 0)
575 dir_stat = &dir_static;
577 #ifdef HAVE_STRUCT_STAT_ST_MTIM
578 fnano = (cache->checksum_nano == dir_stat->st_mtim.tv_nsec);
579 if (FcDebug () & FC_DBG_CACHE)
580 printf ("FcCacheTimeValid dir \"%s\" cache checksum %d.%ld dir checksum %d.%ld\n",
581 FcCacheDir (cache), cache->checksum, (long)cache->checksum_nano, (int) dir_stat->st_mtime, dir_stat->st_mtim.tv_nsec);
583 if (FcDebug () & FC_DBG_CACHE)
584 printf ("FcCacheTimeValid dir \"%s\" cache checksum %d dir checksum %d\n",
585 FcCacheDir (cache), cache->checksum, (int) dir_stat->st_mtime);
588 return cache->checksum == (int) dir_stat->st_mtime && fnano;
592 FcCacheOffsetsValid (FcCache *cache)
594 char *base = (char *)cache;
595 char *end = base + cache->size;
600 if (cache->dir < 0 || cache->dir > cache->size - sizeof (intptr_t) ||
601 memchr (base + cache->dir, '\0', cache->size - cache->dir) == NULL)
604 if (cache->dirs < 0 || cache->dirs >= cache->size ||
605 cache->dirs_count < 0 ||
606 cache->dirs_count > (cache->size - cache->dirs) / sizeof (intptr_t))
609 dirs = FcCacheDirs (cache);
612 for (i = 0; i < cache->dirs_count; i++)
617 dirs[i] > end - (char *) dirs - sizeof (intptr_t))
620 dir = FcOffsetToPtr (dirs, dirs[i], FcChar8);
621 if (memchr (dir, '\0', end - (char *) dir) == NULL)
626 if (cache->set < 0 || cache->set > cache->size - sizeof (FcFontSet))
629 fs = FcCacheSet (cache);
632 if (fs->nfont > (end - (char *) fs) / sizeof (FcPattern))
635 if (fs->fonts != 0 && !FcIsEncodedOffset(fs->fonts))
638 for (i = 0; i < fs->nfont; i++)
640 FcPattern *font = FcFontSetFont (fs, i);
645 if ((char *) font < base ||
646 (char *) font > end - sizeof (FcFontSet) ||
647 font->elts_offset < 0 ||
648 font->elts_offset > end - (char *) font ||
649 font->num > (end - (char *) font - font->elts_offset) / sizeof (FcPatternElt))
653 e = FcPatternElts(font);
654 if (e->values != 0 && !FcIsEncodedOffset(e->values))
657 for (j = 0; j < font->num; j++)
659 last_offset = (char *) font + font->elts_offset;
660 for (l = FcPatternEltValues(&e[j]); l; l = FcValueListNext(l))
662 if ((char *) l < last_offset || (char *) l > end - sizeof (*l) ||
663 (l->next != NULL && !FcIsEncodedOffset(l->next)))
665 last_offset = (char *) l + 1;
675 * Map a cache file into memory
678 FcDirCacheMapFd (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat)
681 FcBool allocated = FcFalse;
683 if (fd_stat->st_size > INTPTR_MAX ||
684 fd_stat->st_size < (int) sizeof (FcCache))
686 cache = FcCacheFindByStat (fd_stat);
689 if (FcCacheTimeValid (config, cache, dir_stat))
691 FcDirCacheUnload (cache);
696 * Large cache files are mmap'ed, smaller cache files are read. This
697 * balances the system cost of mmap against per-process memory usage.
699 if (FcCacheIsMmapSafe (fd) && fd_stat->st_size >= FC_CACHE_MIN_MMAP)
701 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
702 cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
703 #if (HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
704 posix_fadvise (fd, 0, fd_stat->st_size, POSIX_FADV_WILLNEED);
706 if (cache == MAP_FAILED)
708 #elif defined(_WIN32)
713 hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
714 PAGE_READONLY, 0, 0, NULL);
715 if (hFileMap != NULL)
717 cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0,
719 CloseHandle (hFileMap);
726 cache = malloc (fd_stat->st_size);
730 if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
737 if (cache->magic != FC_CACHE_MAGIC_MMAP ||
738 cache->version < FC_CACHE_VERSION_NUMBER ||
739 cache->size != (intptr_t) fd_stat->st_size ||
740 !FcCacheOffsetsValid (cache) ||
741 !FcCacheTimeValid (config, cache, dir_stat) ||
742 !FcCacheInsert (cache, fd_stat))
748 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
749 munmap (cache, fd_stat->st_size);
750 #elif defined(_WIN32)
751 UnmapViewOfFile (cache);
757 /* Mark allocated caches so they're freed rather than unmapped */
759 cache->magic = FC_CACHE_MAGIC_ALLOC;
765 FcDirCacheReference (FcCache *cache, int nref)
767 FcCacheSkip *skip = FcCacheFindByAddr (cache);
770 FcRefAdd (&skip->ref, nref);
774 FcDirCacheUnload (FcCache *cache)
776 FcCacheObjectDereference (cache);
780 FcDirCacheMapHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure)
782 FcCache *cache = FcDirCacheMapFd (config, fd, fd_stat, dir_stat);
786 *((FcCache **) closure) = cache;
791 FcDirCacheLoad (const FcChar8 *dir, FcConfig *config, FcChar8 **cache_file)
793 FcCache *cache = NULL;
795 if (!FcDirCacheProcess (config, dir,
804 FcDirCacheLoadFile (const FcChar8 *cache_file, struct stat *file_stat)
808 struct stat my_file_stat;
811 file_stat = &my_file_stat;
812 fd = FcDirCacheOpenFile (cache_file, file_stat);
815 cache = FcDirCacheMapFd (FcConfigGetCurrent (), fd, file_stat, NULL);
821 * Validate a cache file by reading the header and checking
822 * the magic number and the size field
825 FcDirCacheValidateHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure FC_UNUSED)
830 if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
832 else if (c.magic != FC_CACHE_MAGIC_MMAP)
834 else if (c.version < FC_CACHE_VERSION_NUMBER)
836 else if (fd_stat->st_size != c.size)
838 else if (c.checksum != (int) dir_stat->st_mtime)
840 #ifdef HAVE_STRUCT_STAT_ST_MTIM
841 else if (c.checksum_nano != dir_stat->st_mtim.tv_nsec)
848 FcDirCacheValidConfig (const FcChar8 *dir, FcConfig *config)
850 return FcDirCacheProcess (config, dir,
851 FcDirCacheValidateHelper,
856 FcDirCacheValid (const FcChar8 *dir)
860 config = FcConfigGetCurrent ();
864 return FcDirCacheValidConfig (dir, config);
868 * Build a cache structure from the given contents
871 FcDirCacheBuild (FcFontSet *set, const FcChar8 *dir, struct stat *dir_stat, FcStrSet *dirs)
873 FcSerialize *serialize = FcSerializeCreate ();
876 FcChar8 *dir_serialize;
877 intptr_t *dirs_serialize;
878 FcFontSet *set_serialize;
883 * Space for cache structure
885 FcSerializeReserve (serialize, sizeof (FcCache));
889 if (!FcStrSerializeAlloc (serialize, dir))
894 FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
895 for (i = 0; i < dirs->num; i++)
896 if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
902 if (!FcFontSetSerializeAlloc (serialize, set))
905 /* Serialize layout complete. Now allocate space and fill it */
906 cache = malloc (serialize->size);
909 /* shut up valgrind */
910 memset (cache, 0, serialize->size);
912 serialize->linear = cache;
914 cache->magic = FC_CACHE_MAGIC_ALLOC;
915 cache->version = FC_CACHE_VERSION_NUMBER;
916 cache->size = serialize->size;
917 cache->checksum = (int) dir_stat->st_mtime;
918 #ifdef HAVE_STRUCT_STAT_ST_MTIM
919 cache->checksum_nano = dir_stat->st_mtim.tv_nsec;
923 * Serialize directory name
925 dir_serialize = FcStrSerialize (serialize, dir);
928 cache->dir = FcPtrToOffset (cache, dir_serialize);
933 dirs_serialize = FcSerializePtr (serialize, dirs);
936 cache->dirs = FcPtrToOffset (cache, dirs_serialize);
937 cache->dirs_count = dirs->num;
938 for (i = 0; i < dirs->num; i++)
940 FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
943 dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
949 set_serialize = FcFontSetSerialize (serialize, set);
952 cache->set = FcPtrToOffset (cache, set_serialize);
954 FcSerializeDestroy (serialize);
956 FcCacheInsert (cache, NULL);
963 FcSerializeDestroy (serialize);
968 FcDirCacheRebuild (FcCache *cache, struct stat *dir_stat, FcStrSet *dirs)
971 FcFontSet *set = FcFontSetDeserialize (FcCacheSet (cache));
972 const FcChar8 *dir = FcCacheDir (cache);
974 new = FcDirCacheBuild (set, dir, dir_stat, dirs);
975 FcFontSetDestroy (set);
980 /* write serialized state to the cache file */
982 FcDirCacheWrite (FcCache *cache, FcConfig *config)
984 FcChar8 *dir = FcCacheDir (cache);
985 FcChar8 cache_base[CACHEBASE_LEN];
986 FcChar8 *cache_hashed;
990 FcChar8 *cache_dir = NULL;
991 FcChar8 *test_dir, *d = NULL;
993 struct stat cache_stat;
996 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
999 * Write it to the first directory in the list which is writable
1002 list = FcStrListCreate (config->cacheDirs);
1005 while ((test_dir = FcStrListNext (list)))
1010 d = FcStrBuildFilename (sysroot, test_dir, NULL);
1012 d = FcStrCopyFilename (test_dir);
1014 if (access ((char *) d, W_OK) == 0)
1016 cache_dir = FcStrCopyFilename (d);
1022 * If the directory doesn't exist, try to create it
1024 if (access ((char *) d, F_OK) == -1) {
1025 if (FcMakeDirectory (d))
1027 cache_dir = FcStrCopyFilename (d);
1028 /* Create CACHEDIR.TAG */
1029 FcDirCacheCreateTagFile (d);
1034 * Otherwise, try making it writable
1036 else if (chmod ((char *) d, 0755) == 0)
1038 cache_dir = FcStrCopyFilename (d);
1039 /* Try to create CACHEDIR.TAG too */
1040 FcDirCacheCreateTagFile (d);
1047 FcStrListDone (list);
1051 FcDirCacheBasename (dir, cache_base);
1052 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1055 FcStrFree (cache_dir);
1057 if (FcDebug () & FC_DBG_CACHE)
1058 printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
1061 atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
1065 if (!FcAtomicLock (atomic))
1068 fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
1072 /* Temporarily switch magic to MMAP while writing to file */
1073 magic = cache->magic;
1074 if (magic != FC_CACHE_MAGIC_MMAP)
1075 cache->magic = FC_CACHE_MAGIC_MMAP;
1078 * Write cache contents to file
1080 written = write (fd, cache, cache->size);
1082 /* Switch magic back */
1083 if (magic != FC_CACHE_MAGIC_MMAP)
1084 cache->magic = magic;
1086 if (written != cache->size)
1088 perror ("write cache");
1093 if (!FcAtomicReplaceOrig(atomic))
1096 /* If the file is small, update the cache chain entry such that the
1097 * new cache file is not read again. If it's large, we don't do that
1098 * such that we reload it, using mmap, which is shared across processes.
1100 if (cache->size < FC_CACHE_MIN_MMAP && FcStat (cache_hashed, &cache_stat))
1103 if ((skip = FcCacheFindByAddrUnlocked (cache)))
1105 skip->cache_dev = cache_stat.st_dev;
1106 skip->cache_ino = cache_stat.st_ino;
1107 skip->cache_mtime = cache_stat.st_mtime;
1108 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1109 skip->cache_mtime_nano = cache_stat.st_mtim.tv_nsec;
1111 skip->cache_mtime_nano = 0;
1117 FcStrFree (cache_hashed);
1118 FcAtomicUnlock (atomic);
1119 FcAtomicDestroy (atomic);
1125 FcAtomicUnlock (atomic);
1127 FcAtomicDestroy (atomic);
1129 FcStrFree (cache_hashed);
1134 FcDirCacheClean (const FcChar8 *cache_dir, FcBool verbose)
1139 FcBool ret = FcTrue;
1142 struct stat target_stat;
1143 const FcChar8 *sysroot;
1145 /* FIXME: this API needs to support non-current FcConfig */
1146 sysroot = FcConfigGetSysRoot (NULL);
1148 dir = FcStrBuildFilename (sysroot, cache_dir, NULL);
1150 dir = FcStrCopyFilename (cache_dir);
1153 fprintf (stderr, "Fontconfig error: %s: out of memory\n", cache_dir);
1156 if (access ((char *) dir, W_OK) != 0)
1158 if (verbose || FcDebug () & FC_DBG_CACHE)
1159 printf ("%s: not cleaning %s cache directory\n", dir,
1160 access ((char *) dir, F_OK) == 0 ? "unwritable" : "non-existent");
1163 if (verbose || FcDebug () & FC_DBG_CACHE)
1164 printf ("%s: cleaning cache directory\n", dir);
1165 d = opendir ((char *) dir);
1168 perror ((char *) dir);
1172 while ((ent = readdir (d)))
1175 const FcChar8 *target_dir;
1177 if (ent->d_name[0] == '.')
1179 /* skip cache files for different architectures and */
1180 /* files which are not cache files at all */
1181 if (strlen(ent->d_name) != 32 + strlen ("-" FC_ARCHITECTURE FC_CACHE_SUFFIX) ||
1182 strcmp(ent->d_name + 32, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX))
1185 file_name = FcStrBuildFilename (dir, (FcChar8 *)ent->d_name, NULL);
1188 fprintf (stderr, "Fontconfig error: %s: allocation failure\n", dir);
1193 cache = FcDirCacheLoadFile (file_name, NULL);
1196 if (verbose || FcDebug () & FC_DBG_CACHE)
1197 printf ("%s: invalid cache file: %s\n", dir, ent->d_name);
1204 target_dir = FcCacheDir (cache);
1206 s = FcStrBuildFilename (sysroot, target_dir, NULL);
1208 s = FcStrdup (target_dir);
1209 if (stat ((char *) s, &target_stat) < 0)
1211 if (verbose || FcDebug () & FC_DBG_CACHE)
1212 printf ("%s: %s: missing directory: %s \n",
1213 dir, ent->d_name, s);
1216 FcDirCacheUnload (cache);
1221 if (unlink ((char *) file_name) < 0)
1223 perror ((char *) file_name);
1227 FcStrFree (file_name);
1238 FcDirCacheLock (const FcChar8 *dir,
1241 FcChar8 *cache_hashed = NULL;
1242 FcChar8 cache_base[CACHEBASE_LEN];
1245 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1248 FcDirCacheBasename (dir, cache_base);
1249 list = FcStrListCreate (config->cacheDirs);
1253 while ((cache_dir = FcStrListNext (list)))
1256 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
1258 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1261 fd = FcOpen ((const char *)cache_hashed, O_RDWR);
1262 FcStrFree (cache_hashed);
1263 /* No caches in that directory. simply retry with another one */
1267 if (_locking (fd, _LK_LOCK, 1) == -1)
1272 fl.l_type = F_WRLCK;
1273 fl.l_whence = SEEK_SET;
1276 fl.l_pid = getpid ();
1277 if (fcntl (fd, F_SETLKW, &fl) == -1)
1283 FcStrListDone (list);
1286 FcStrListDone (list);
1293 FcDirCacheUnlock (int fd)
1298 _locking (fd, _LK_UNLCK, 1);
1302 fl.l_type = F_UNLCK;
1303 fl.l_whence = SEEK_SET;
1306 fl.l_pid = getpid ();
1307 fcntl (fd, F_SETLK, &fl);
1314 * Hokey little macro trick to permit the definitions of C functions
1315 * with the same name as CPP macros
1317 #define args1(x) (x)
1318 #define args2(x,y) (x,y)
1321 FcCacheDir args1(const FcCache *c)
1323 return FcCacheDir (c);
1327 FcCacheCopySet args1(const FcCache *c)
1329 FcFontSet *old = FcCacheSet (c);
1330 FcFontSet *new = FcFontSetCreate ();
1335 for (i = 0; i < old->nfont; i++)
1337 FcPattern *font = FcFontSetFont (old, i);
1339 FcPatternReference (font);
1340 if (!FcFontSetAdd (new, font))
1342 FcFontSetDestroy (new);
1350 FcCacheSubdir args2(const FcCache *c, int i)
1352 return FcCacheSubdir (c, i);
1356 FcCacheNumSubdir args1(const FcCache *c)
1358 return c->dirs_count;
1362 FcCacheNumFont args1(const FcCache *c)
1364 return FcCacheSet(c)->nfont;
1368 * This code implements the MD5 message-digest algorithm.
1369 * The algorithm is due to Ron Rivest. This code was
1370 * written by Colin Plumb in 1993, no copyright is claimed.
1371 * This code is in the public domain; do with it what you wish.
1373 * Equivalent code is available from RSA Data Security, Inc.
1374 * This code has been tested against that, and is equivalent,
1375 * except that you don't need to include two pages of legalese
1378 * To compute the message digest of a chunk of bytes, declare an
1379 * MD5Context structure, pass it to MD5Init, call MD5Update as
1380 * needed on buffers full of bytes, and then call MD5Final, which
1381 * will fill a supplied 16-byte array with the digest.
1385 #define byteReverse(buf, len) /* Nothing */
1388 * Note: this code is harmless on little-endian machines.
1390 void byteReverse(unsigned char *buf, unsigned longs)
1394 t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1395 ((unsigned) buf[1] << 8 | buf[0]);
1396 *(FcChar32 *) buf = t;
1403 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
1404 * initialization constants.
1406 static void MD5Init(struct MD5Context *ctx)
1408 ctx->buf[0] = 0x67452301;
1409 ctx->buf[1] = 0xefcdab89;
1410 ctx->buf[2] = 0x98badcfe;
1411 ctx->buf[3] = 0x10325476;
1418 * Update context to reflect the concatenation of another buffer full
1421 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len)
1425 /* Update bitcount */
1428 if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
1429 ctx->bits[1]++; /* Carry from low to high */
1430 ctx->bits[1] += len >> 29;
1432 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
1434 /* Handle any leading odd-sized chunks */
1437 unsigned char *p = (unsigned char *) ctx->in + t;
1441 memcpy(p, buf, len);
1445 byteReverse(ctx->in, 16);
1446 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1450 /* Process data in 64-byte chunks */
1453 memcpy(ctx->in, buf, 64);
1454 byteReverse(ctx->in, 16);
1455 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1460 /* Handle any remaining bytes of data. */
1462 memcpy(ctx->in, buf, len);
1466 * Final wrapup - pad to 64-byte boundary with the bit pattern
1467 * 1 0* (64-bit count of bits processed, MSB-first)
1469 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
1474 /* Compute number of bytes mod 64 */
1475 count = (ctx->bits[0] >> 3) & 0x3F;
1477 /* Set the first char of padding to 0x80. This is safe since there is
1478 always at least one byte free */
1479 p = ctx->in + count;
1482 /* Bytes of padding needed to make 64 bytes */
1483 count = 64 - 1 - count;
1485 /* Pad out to 56 mod 64 */
1487 /* Two lots of padding: Pad the first block to 64 bytes */
1488 memset(p, 0, count);
1489 byteReverse(ctx->in, 16);
1490 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1492 /* Now fill the next block with 56 bytes */
1493 memset(ctx->in, 0, 56);
1495 /* Pad block to 56 bytes */
1496 memset(p, 0, count - 8);
1498 byteReverse(ctx->in, 14);
1500 /* Append length in bits and transform */
1501 ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
1502 ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
1504 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1505 byteReverse((unsigned char *) ctx->buf, 4);
1506 memcpy(digest, ctx->buf, 16);
1507 memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */
1511 /* The four core functions - F1 is optimized somewhat */
1513 /* #define F1(x, y, z) (x & y | ~x & z) */
1514 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1515 #define F2(x, y, z) F1(z, x, y)
1516 #define F3(x, y, z) (x ^ y ^ z)
1517 #define F4(x, y, z) (y ^ (x | ~z))
1519 /* This is the central step in the MD5 algorithm. */
1520 #define MD5STEP(f, w, x, y, z, data, s) \
1521 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
1524 * The core of the MD5 algorithm, this alters an existing MD5 hash to
1525 * reflect the addition of 16 longwords of new data. MD5Update blocks
1526 * the data and converts bytes into longwords for this routine.
1528 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
1530 register FcChar32 a, b, c, d;
1537 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1538 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1539 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1540 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1541 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1542 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1543 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1544 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1545 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1546 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1547 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1548 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1549 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1550 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1551 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1552 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1554 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1555 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1556 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1557 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1558 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1559 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1560 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1561 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1562 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1563 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1564 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1565 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1566 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1567 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1568 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1569 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1571 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1572 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1573 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1574 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1575 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1576 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1577 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1578 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1579 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1580 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1581 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1582 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1583 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1584 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1585 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1586 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1588 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1589 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1590 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1591 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1592 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1593 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1594 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1595 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1596 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1597 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1598 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1599 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1600 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1601 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1602 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1603 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1612 FcDirCacheCreateTagFile (const FcChar8 *cache_dir)
1618 static const FcChar8 cache_tag_contents[] =
1619 "Signature: 8a477f597d28d172789f06886806bc55\n"
1620 "# This file is a cache directory tag created by fontconfig.\n"
1621 "# For information about cache directory tags, see:\n"
1622 "# http://www.brynosaurus.com/cachedir/\n";
1623 static size_t cache_tag_contents_size = sizeof (cache_tag_contents) - 1;
1624 FcBool ret = FcFalse;
1629 if (access ((char *) cache_dir, W_OK) == 0)
1631 /* Create CACHEDIR.TAG */
1632 cache_tag = FcStrBuildFilename (cache_dir, "CACHEDIR.TAG", NULL);
1635 atomic = FcAtomicCreate ((FcChar8 *)cache_tag);
1638 if (!FcAtomicLock (atomic))
1640 fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0644);
1643 fp = fdopen(fd, "wb");
1647 fwrite(cache_tag_contents, cache_tag_contents_size, sizeof (FcChar8), fp);
1650 if (!FcAtomicReplaceOrig(atomic))
1655 FcAtomicUnlock (atomic);
1657 FcAtomicDestroy (atomic);
1659 FcStrFree (cache_tag);
1662 if (FcDebug () & FC_DBG_CACHE)
1665 printf ("Created CACHEDIR.TAG at %s\n", cache_dir);
1667 printf ("Unable to create CACHEDIR.TAG at %s\n", cache_dir);
1674 FcCacheCreateTagFile (const FcConfig *config)
1676 FcChar8 *cache_dir = NULL, *d = NULL;
1678 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1680 list = FcConfigGetCacheDirs (config);
1684 while ((cache_dir = FcStrListNext (list)))
1689 d = FcStrBuildFilename (sysroot, cache_dir, NULL);
1691 d = FcStrCopyFilename (cache_dir);
1692 if (FcDirCacheCreateTagFile (d))
1697 FcStrListDone (list);
1701 #include "fcaliastail.h"