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 /* TIZEN_ONLY(20171013): Add a condition to FcCacheOffsetsValid() for detecting empty data of cache
646 if ((char *) font < base ||
647 (char *) font > end - sizeof (FcFontSet) ||
648 font->elts_offset < 0 ||
649 font->elts_offset > end - (char *) font ||
650 font->num > (end - (char *) font - font->elts_offset) / sizeof (FcPatternElt))
653 if ((char *) font < base ||
654 (char *) font > end - sizeof (FcFontSet) ||
655 font->elts_offset < 0 ||
656 font->elts_offset > end - (char *) font ||
657 font->num > (end - (char *) font - font->elts_offset) / sizeof (FcPatternElt) ||
658 !FcRefIsConst (&font->ref))
663 e = FcPatternElts(font);
664 if (e->values != 0 && !FcIsEncodedOffset(e->values))
667 for (j = 0; j < font->num; j++)
669 last_offset = (char *) font + font->elts_offset;
670 for (l = FcPatternEltValues(&e[j]); l; l = FcValueListNext(l))
672 if ((char *) l < last_offset || (char *) l > end - sizeof (*l) ||
673 (l->next != NULL && !FcIsEncodedOffset(l->next)))
675 last_offset = (char *) l + 1;
685 * Map a cache file into memory
688 FcDirCacheMapFd (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat)
691 FcBool allocated = FcFalse;
693 if (fd_stat->st_size > INTPTR_MAX ||
694 fd_stat->st_size < (int) sizeof (FcCache))
696 cache = FcCacheFindByStat (fd_stat);
699 if (FcCacheTimeValid (config, cache, dir_stat))
701 FcDirCacheUnload (cache);
706 * Large cache files are mmap'ed, smaller cache files are read. This
707 * balances the system cost of mmap against per-process memory usage.
709 if (FcCacheIsMmapSafe (fd) && fd_stat->st_size >= FC_CACHE_MIN_MMAP)
711 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
712 cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
713 #if (HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
714 posix_fadvise (fd, 0, fd_stat->st_size, POSIX_FADV_WILLNEED);
716 if (cache == MAP_FAILED)
718 #elif defined(_WIN32)
723 hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
724 PAGE_READONLY, 0, 0, NULL);
725 if (hFileMap != NULL)
727 cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0,
729 CloseHandle (hFileMap);
736 cache = malloc (fd_stat->st_size);
740 if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
747 if (cache->magic != FC_CACHE_MAGIC_MMAP ||
748 cache->version < FC_CACHE_VERSION_NUMBER ||
749 cache->size != (intptr_t) fd_stat->st_size ||
750 !FcCacheOffsetsValid (cache) ||
751 !FcCacheTimeValid (config, cache, dir_stat) ||
752 !FcCacheInsert (cache, fd_stat))
758 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
759 munmap (cache, fd_stat->st_size);
760 #elif defined(_WIN32)
761 UnmapViewOfFile (cache);
767 /* Mark allocated caches so they're freed rather than unmapped */
769 cache->magic = FC_CACHE_MAGIC_ALLOC;
775 FcDirCacheReference (FcCache *cache, int nref)
777 FcCacheSkip *skip = FcCacheFindByAddr (cache);
780 FcRefAdd (&skip->ref, nref);
784 FcDirCacheUnload (FcCache *cache)
786 FcCacheObjectDereference (cache);
790 FcDirCacheMapHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure)
792 FcCache *cache = FcDirCacheMapFd (config, fd, fd_stat, dir_stat);
796 *((FcCache **) closure) = cache;
801 FcDirCacheLoad (const FcChar8 *dir, FcConfig *config, FcChar8 **cache_file)
803 FcCache *cache = NULL;
805 if (!FcDirCacheProcess (config, dir,
814 FcDirCacheLoadFile (const FcChar8 *cache_file, struct stat *file_stat)
818 struct stat my_file_stat;
821 file_stat = &my_file_stat;
822 fd = FcDirCacheOpenFile (cache_file, file_stat);
825 cache = FcDirCacheMapFd (FcConfigGetCurrent (), fd, file_stat, NULL);
831 * Validate a cache file by reading the header and checking
832 * the magic number and the size field
835 FcDirCacheValidateHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure FC_UNUSED)
840 if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
842 else if (c.magic != FC_CACHE_MAGIC_MMAP)
844 else if (c.version < FC_CACHE_VERSION_NUMBER)
846 else if (fd_stat->st_size != c.size)
848 else if (c.checksum != (int) dir_stat->st_mtime)
850 #ifdef HAVE_STRUCT_STAT_ST_MTIM
851 else if (c.checksum_nano != dir_stat->st_mtim.tv_nsec)
858 FcDirCacheValidConfig (const FcChar8 *dir, FcConfig *config)
860 return FcDirCacheProcess (config, dir,
861 FcDirCacheValidateHelper,
866 FcDirCacheValid (const FcChar8 *dir)
870 config = FcConfigGetCurrent ();
874 return FcDirCacheValidConfig (dir, config);
878 * Build a cache structure from the given contents
881 FcDirCacheBuild (FcFontSet *set, const FcChar8 *dir, struct stat *dir_stat, FcStrSet *dirs)
883 FcSerialize *serialize = FcSerializeCreate ();
886 FcChar8 *dir_serialize;
887 intptr_t *dirs_serialize;
888 FcFontSet *set_serialize;
893 * Space for cache structure
895 FcSerializeReserve (serialize, sizeof (FcCache));
899 if (!FcStrSerializeAlloc (serialize, dir))
904 FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
905 for (i = 0; i < dirs->num; i++)
906 if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
912 if (!FcFontSetSerializeAlloc (serialize, set))
915 /* Serialize layout complete. Now allocate space and fill it */
916 cache = malloc (serialize->size);
919 /* shut up valgrind */
920 memset (cache, 0, serialize->size);
922 serialize->linear = cache;
924 cache->magic = FC_CACHE_MAGIC_ALLOC;
925 cache->version = FC_CACHE_VERSION_NUMBER;
926 cache->size = serialize->size;
927 cache->checksum = (int) dir_stat->st_mtime;
928 #ifdef HAVE_STRUCT_STAT_ST_MTIM
929 cache->checksum_nano = dir_stat->st_mtim.tv_nsec;
933 * Serialize directory name
935 dir_serialize = FcStrSerialize (serialize, dir);
938 cache->dir = FcPtrToOffset (cache, dir_serialize);
943 dirs_serialize = FcSerializePtr (serialize, dirs);
946 cache->dirs = FcPtrToOffset (cache, dirs_serialize);
947 cache->dirs_count = dirs->num;
948 for (i = 0; i < dirs->num; i++)
950 FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
953 dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
959 set_serialize = FcFontSetSerialize (serialize, set);
962 cache->set = FcPtrToOffset (cache, set_serialize);
964 FcSerializeDestroy (serialize);
966 FcCacheInsert (cache, NULL);
973 FcSerializeDestroy (serialize);
978 FcDirCacheRebuild (FcCache *cache, struct stat *dir_stat, FcStrSet *dirs)
981 FcFontSet *set = FcFontSetDeserialize (FcCacheSet (cache));
982 const FcChar8 *dir = FcCacheDir (cache);
984 new = FcDirCacheBuild (set, dir, dir_stat, dirs);
985 FcFontSetDestroy (set);
990 /* write serialized state to the cache file */
992 FcDirCacheWrite (FcCache *cache, FcConfig *config)
994 FcChar8 *dir = FcCacheDir (cache);
995 FcChar8 cache_base[CACHEBASE_LEN];
996 FcChar8 *cache_hashed;
1000 FcChar8 *cache_dir = NULL;
1001 FcChar8 *test_dir, *d = NULL;
1003 struct stat cache_stat;
1006 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1009 * Write it to the first directory in the list which is writable
1012 list = FcStrListCreate (config->cacheDirs);
1015 while ((test_dir = FcStrListNext (list)))
1020 d = FcStrBuildFilename (sysroot, test_dir, NULL);
1022 d = FcStrCopyFilename (test_dir);
1024 if (access ((char *) d, W_OK) == 0)
1026 cache_dir = FcStrCopyFilename (d);
1032 * If the directory doesn't exist, try to create it
1034 if (access ((char *) d, F_OK) == -1) {
1035 if (FcMakeDirectory (d))
1037 cache_dir = FcStrCopyFilename (d);
1038 /* Create CACHEDIR.TAG */
1039 FcDirCacheCreateTagFile (d);
1044 * Otherwise, try making it writable
1046 else if (chmod ((char *) d, 0755) == 0)
1048 cache_dir = FcStrCopyFilename (d);
1049 /* Try to create CACHEDIR.TAG too */
1050 FcDirCacheCreateTagFile (d);
1057 FcStrListDone (list);
1061 FcDirCacheBasename (dir, cache_base);
1062 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1065 FcStrFree (cache_dir);
1067 if (FcDebug () & FC_DBG_CACHE)
1068 printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
1071 atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
1075 if (!FcAtomicLock (atomic))
1078 fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
1082 /* Temporarily switch magic to MMAP while writing to file */
1083 magic = cache->magic;
1084 if (magic != FC_CACHE_MAGIC_MMAP)
1085 cache->magic = FC_CACHE_MAGIC_MMAP;
1088 * Write cache contents to file
1090 written = write (fd, cache, cache->size);
1092 /* Switch magic back */
1093 if (magic != FC_CACHE_MAGIC_MMAP)
1094 cache->magic = magic;
1096 if (written != cache->size)
1098 perror ("write cache");
1103 if (!FcAtomicReplaceOrig(atomic))
1106 /* If the file is small, update the cache chain entry such that the
1107 * new cache file is not read again. If it's large, we don't do that
1108 * such that we reload it, using mmap, which is shared across processes.
1110 if (cache->size < FC_CACHE_MIN_MMAP && FcStat (cache_hashed, &cache_stat))
1113 if ((skip = FcCacheFindByAddrUnlocked (cache)))
1115 skip->cache_dev = cache_stat.st_dev;
1116 skip->cache_ino = cache_stat.st_ino;
1117 skip->cache_mtime = cache_stat.st_mtime;
1118 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1119 skip->cache_mtime_nano = cache_stat.st_mtim.tv_nsec;
1121 skip->cache_mtime_nano = 0;
1127 FcStrFree (cache_hashed);
1128 FcAtomicUnlock (atomic);
1129 FcAtomicDestroy (atomic);
1135 FcAtomicUnlock (atomic);
1137 FcAtomicDestroy (atomic);
1139 FcStrFree (cache_hashed);
1144 FcDirCacheClean (const FcChar8 *cache_dir, FcBool verbose)
1149 FcBool ret = FcTrue;
1152 struct stat target_stat;
1153 const FcChar8 *sysroot;
1155 /* FIXME: this API needs to support non-current FcConfig */
1156 sysroot = FcConfigGetSysRoot (NULL);
1158 dir = FcStrBuildFilename (sysroot, cache_dir, NULL);
1160 dir = FcStrCopyFilename (cache_dir);
1163 fprintf (stderr, "Fontconfig error: %s: out of memory\n", cache_dir);
1166 if (access ((char *) dir, W_OK) != 0)
1168 if (verbose || FcDebug () & FC_DBG_CACHE)
1169 printf ("%s: not cleaning %s cache directory\n", dir,
1170 access ((char *) dir, F_OK) == 0 ? "unwritable" : "non-existent");
1173 if (verbose || FcDebug () & FC_DBG_CACHE)
1174 printf ("%s: cleaning cache directory\n", dir);
1175 d = opendir ((char *) dir);
1178 perror ((char *) dir);
1182 while ((ent = readdir (d)))
1185 const FcChar8 *target_dir;
1187 if (ent->d_name[0] == '.')
1189 /* skip cache files for different architectures and */
1190 /* files which are not cache files at all */
1191 if (strlen(ent->d_name) != 32 + strlen ("-" FC_ARCHITECTURE FC_CACHE_SUFFIX) ||
1192 strcmp(ent->d_name + 32, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX))
1195 file_name = FcStrBuildFilename (dir, (FcChar8 *)ent->d_name, NULL);
1198 fprintf (stderr, "Fontconfig error: %s: allocation failure\n", dir);
1203 cache = FcDirCacheLoadFile (file_name, NULL);
1206 if (verbose || FcDebug () & FC_DBG_CACHE)
1207 printf ("%s: invalid cache file: %s\n", dir, ent->d_name);
1214 target_dir = FcCacheDir (cache);
1216 s = FcStrBuildFilename (sysroot, target_dir, NULL);
1218 s = FcStrdup (target_dir);
1219 if (stat ((char *) s, &target_stat) < 0)
1221 if (verbose || FcDebug () & FC_DBG_CACHE)
1222 printf ("%s: %s: missing directory: %s \n",
1223 dir, ent->d_name, s);
1226 FcDirCacheUnload (cache);
1231 if (unlink ((char *) file_name) < 0)
1233 perror ((char *) file_name);
1237 FcStrFree (file_name);
1248 FcDirCacheLock (const FcChar8 *dir,
1251 FcChar8 *cache_hashed = NULL;
1252 FcChar8 cache_base[CACHEBASE_LEN];
1255 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1258 FcDirCacheBasename (dir, cache_base);
1259 list = FcStrListCreate (config->cacheDirs);
1263 while ((cache_dir = FcStrListNext (list)))
1266 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
1268 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1271 fd = FcOpen ((const char *)cache_hashed, O_RDWR);
1272 FcStrFree (cache_hashed);
1273 /* No caches in that directory. simply retry with another one */
1277 if (_locking (fd, _LK_LOCK, 1) == -1)
1282 fl.l_type = F_WRLCK;
1283 fl.l_whence = SEEK_SET;
1286 fl.l_pid = getpid ();
1287 if (fcntl (fd, F_SETLKW, &fl) == -1)
1293 FcStrListDone (list);
1296 FcStrListDone (list);
1303 FcDirCacheUnlock (int fd)
1308 _locking (fd, _LK_UNLCK, 1);
1312 fl.l_type = F_UNLCK;
1313 fl.l_whence = SEEK_SET;
1316 fl.l_pid = getpid ();
1317 fcntl (fd, F_SETLK, &fl);
1324 * Hokey little macro trick to permit the definitions of C functions
1325 * with the same name as CPP macros
1327 #define args1(x) (x)
1328 #define args2(x,y) (x,y)
1331 FcCacheDir args1(const FcCache *c)
1333 return FcCacheDir (c);
1337 FcCacheCopySet args1(const FcCache *c)
1339 FcFontSet *old = FcCacheSet (c);
1340 FcFontSet *new = FcFontSetCreate ();
1345 for (i = 0; i < old->nfont; i++)
1347 FcPattern *font = FcFontSetFont (old, i);
1349 FcPatternReference (font);
1350 if (!FcFontSetAdd (new, font))
1352 FcFontSetDestroy (new);
1360 FcCacheSubdir args2(const FcCache *c, int i)
1362 return FcCacheSubdir (c, i);
1366 FcCacheNumSubdir args1(const FcCache *c)
1368 return c->dirs_count;
1372 FcCacheNumFont args1(const FcCache *c)
1374 return FcCacheSet(c)->nfont;
1378 * This code implements the MD5 message-digest algorithm.
1379 * The algorithm is due to Ron Rivest. This code was
1380 * written by Colin Plumb in 1993, no copyright is claimed.
1381 * This code is in the public domain; do with it what you wish.
1383 * Equivalent code is available from RSA Data Security, Inc.
1384 * This code has been tested against that, and is equivalent,
1385 * except that you don't need to include two pages of legalese
1388 * To compute the message digest of a chunk of bytes, declare an
1389 * MD5Context structure, pass it to MD5Init, call MD5Update as
1390 * needed on buffers full of bytes, and then call MD5Final, which
1391 * will fill a supplied 16-byte array with the digest.
1395 #define byteReverse(buf, len) /* Nothing */
1398 * Note: this code is harmless on little-endian machines.
1400 void byteReverse(unsigned char *buf, unsigned longs)
1404 t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1405 ((unsigned) buf[1] << 8 | buf[0]);
1406 *(FcChar32 *) buf = t;
1413 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
1414 * initialization constants.
1416 static void MD5Init(struct MD5Context *ctx)
1418 ctx->buf[0] = 0x67452301;
1419 ctx->buf[1] = 0xefcdab89;
1420 ctx->buf[2] = 0x98badcfe;
1421 ctx->buf[3] = 0x10325476;
1428 * Update context to reflect the concatenation of another buffer full
1431 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len)
1435 /* Update bitcount */
1438 if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
1439 ctx->bits[1]++; /* Carry from low to high */
1440 ctx->bits[1] += len >> 29;
1442 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
1444 /* Handle any leading odd-sized chunks */
1447 unsigned char *p = (unsigned char *) ctx->in + t;
1451 memcpy(p, buf, len);
1455 byteReverse(ctx->in, 16);
1456 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1460 /* Process data in 64-byte chunks */
1463 memcpy(ctx->in, buf, 64);
1464 byteReverse(ctx->in, 16);
1465 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1470 /* Handle any remaining bytes of data. */
1472 memcpy(ctx->in, buf, len);
1476 * Final wrapup - pad to 64-byte boundary with the bit pattern
1477 * 1 0* (64-bit count of bits processed, MSB-first)
1479 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
1484 /* Compute number of bytes mod 64 */
1485 count = (ctx->bits[0] >> 3) & 0x3F;
1487 /* Set the first char of padding to 0x80. This is safe since there is
1488 always at least one byte free */
1489 p = ctx->in + count;
1492 /* Bytes of padding needed to make 64 bytes */
1493 count = 64 - 1 - count;
1495 /* Pad out to 56 mod 64 */
1497 /* Two lots of padding: Pad the first block to 64 bytes */
1498 memset(p, 0, count);
1499 byteReverse(ctx->in, 16);
1500 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1502 /* Now fill the next block with 56 bytes */
1503 memset(ctx->in, 0, 56);
1505 /* Pad block to 56 bytes */
1506 memset(p, 0, count - 8);
1508 byteReverse(ctx->in, 14);
1510 /* Append length in bits and transform */
1511 ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
1512 ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
1514 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1515 byteReverse((unsigned char *) ctx->buf, 4);
1516 memcpy(digest, ctx->buf, 16);
1517 memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */
1521 /* The four core functions - F1 is optimized somewhat */
1523 /* #define F1(x, y, z) (x & y | ~x & z) */
1524 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1525 #define F2(x, y, z) F1(z, x, y)
1526 #define F3(x, y, z) (x ^ y ^ z)
1527 #define F4(x, y, z) (y ^ (x | ~z))
1529 /* This is the central step in the MD5 algorithm. */
1530 #define MD5STEP(f, w, x, y, z, data, s) \
1531 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
1534 * The core of the MD5 algorithm, this alters an existing MD5 hash to
1535 * reflect the addition of 16 longwords of new data. MD5Update blocks
1536 * the data and converts bytes into longwords for this routine.
1538 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
1540 register FcChar32 a, b, c, d;
1547 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1548 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1549 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1550 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1551 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1552 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1553 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1554 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1555 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1556 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1557 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1558 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1559 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1560 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1561 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1562 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1564 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1565 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1566 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1567 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1568 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1569 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1570 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1571 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1572 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1573 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1574 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1575 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1576 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1577 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1578 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1579 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1581 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1582 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1583 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1584 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1585 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1586 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1587 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1588 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1589 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1590 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1591 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1592 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1593 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1594 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1595 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1596 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1598 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1599 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1600 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1601 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1602 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1603 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1604 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1605 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1606 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1607 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1608 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1609 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1610 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1611 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1612 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1613 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1622 FcDirCacheCreateTagFile (const FcChar8 *cache_dir)
1628 static const FcChar8 cache_tag_contents[] =
1629 "Signature: 8a477f597d28d172789f06886806bc55\n"
1630 "# This file is a cache directory tag created by fontconfig.\n"
1631 "# For information about cache directory tags, see:\n"
1632 "# http://www.brynosaurus.com/cachedir/\n";
1633 static size_t cache_tag_contents_size = sizeof (cache_tag_contents) - 1;
1634 FcBool ret = FcFalse;
1639 if (access ((char *) cache_dir, W_OK) == 0)
1641 /* Create CACHEDIR.TAG */
1642 cache_tag = FcStrBuildFilename (cache_dir, "CACHEDIR.TAG", NULL);
1645 atomic = FcAtomicCreate ((FcChar8 *)cache_tag);
1648 if (!FcAtomicLock (atomic))
1650 fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0644);
1653 fp = fdopen(fd, "wb");
1657 fwrite(cache_tag_contents, cache_tag_contents_size, sizeof (FcChar8), fp);
1660 if (!FcAtomicReplaceOrig(atomic))
1665 FcAtomicUnlock (atomic);
1667 FcAtomicDestroy (atomic);
1669 FcStrFree (cache_tag);
1672 if (FcDebug () & FC_DBG_CACHE)
1675 printf ("Created CACHEDIR.TAG at %s\n", cache_dir);
1677 printf ("Unable to create CACHEDIR.TAG at %s\n", cache_dir);
1684 FcCacheCreateTagFile (const FcConfig *config)
1686 FcChar8 *cache_dir = NULL, *d = NULL;
1688 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1690 list = FcConfigGetCacheDirs (config);
1694 while ((cache_dir = FcStrListNext (list)))
1699 d = FcStrBuildFilename (sysroot, cache_dir, NULL);
1701 d = FcStrCopyFilename (cache_dir);
1702 if (FcDirCacheCreateTagFile (d))
1707 FcStrListDone (list);
1711 #include "fcaliastail.h"