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>
35 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
37 # include <sys/mman.h>
40 #include <sys/locking.h>
42 #include <uuid/uuid.h>
50 FcDirCacheCreateUUID (FcChar8 *dir,
58 uuidname = FcStrBuildFilename (dir, ".uuid", NULL);
62 if (force || access ((const char *) uuidname, F_OK) < 0)
68 FcBool (* hash_add) (FcHashTable *, void*, void*);
70 struct timeval times[2];
72 if (FcStat (dir, &statb) != 0)
77 atomic = FcAtomicCreate (uuidname);
83 if (!FcAtomicLock (atomic))
88 fd = FcOpen ((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0644);
94 uuid_generate_random (uuid);
96 hash_add = FcHashTableReplace;
98 hash_add = FcHashTableAdd;
99 if (!hash_add (config->uuid_table, dir, uuid))
104 uuid_unparse (uuid, out);
105 if (FcDebug () & FC_DBG_CACHE)
106 printf ("FcDirCacheCreateUUID %s: %s\n", uuidname, out);
107 write (fd, out, strlen (out));
109 FcAtomicReplaceOrig (atomic);
111 FcAtomicUnlock (atomic);
113 FcAtomicDestroy (atomic);
117 /* revert mtime of the directory */
118 times[0].tv_sec = statb.st_atime;
119 times[1].tv_sec = statb.st_mtime;
120 #ifdef HAVE_STRUCT_STAT_ST_MTIM
121 times[0].tv_usec = statb.st_atim.tv_nsec / 1000;
122 times[1].tv_usec = statb.st_mtim.tv_nsec / 1000;
124 times[0].tv_usec = 0;
125 times[1].tv_usec = 0;
127 if (utimes ((const char *) dir, times) != 0)
129 fprintf (stderr, "Unable to revert mtime: %s\n", dir);
134 FcStrFree (uuidname);
142 FcDirCacheReadUUID (FcChar8 *dir,
148 if (!FcHashTableFind (config->uuid_table, dir, &u))
150 FcChar8 *uuidname = FcStrBuildFilename (dir, ".uuid", NULL);
153 if ((fd = FcOpen ((char *) uuidname, O_RDONLY)) >= 0)
157 memset (suuid, 0, sizeof (suuid));
158 if (read (fd, suuid, 36) > 0)
160 memset (uuid, 0, sizeof (uuid));
161 if (uuid_parse (suuid, uuid) == 0)
163 if (FcDebug () & FC_DBG_CACHE)
164 printf ("FcDirCacheReadUUID %s -> %s\n", uuidname, suuid);
165 FcHashTableAdd (config->uuid_table, dir, uuid);
172 if (FcDebug () & FC_DBG_CACHE)
173 printf ("FcDirCacheReadUUID Unable to read %s\n", uuidname);
175 FcStrFree (uuidname);
185 unsigned char in[64];
188 static void MD5Init(struct MD5Context *ctx);
189 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len);
190 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx);
191 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16]);
193 #define CACHEBASE_LEN (1 + 36 + 1 + sizeof (FC_ARCHITECTURE) + sizeof (FC_CACHE_SUFFIX))
196 FcCacheIsMmapSafe (int fd)
199 MMAP_NOT_INITIALIZED = 0,
204 static void *static_status;
206 status = (intptr_t) fc_atomic_ptr_get (&static_status);
208 if (status == MMAP_NOT_INITIALIZED)
210 const char *env = getenv ("FONTCONFIG_USE_MMAP");
212 if (env && FcNameBool ((const FcChar8 *) env, &use))
213 status = use ? MMAP_USE : MMAP_DONT_USE;
215 status = MMAP_CHECK_FS;
216 (void) fc_atomic_ptr_cmpexch (&static_status, NULL, (void *) status);
219 if (status == MMAP_CHECK_FS)
220 return FcIsFsMmapSafe (fd);
222 return status == MMAP_USE;
226 static const char bin2hex[] = { '0', '1', '2', '3',
229 'c', 'd', 'e', 'f' };
232 FcDirCacheBasenameMD5 (const FcChar8 *dir, FcChar8 cache_base[CACHEBASE_LEN])
234 unsigned char hash[16];
237 struct MD5Context ctx;
240 MD5Update (&ctx, (const unsigned char *)dir, strlen ((const char *) dir));
242 MD5Final (hash, &ctx);
245 hex_hash = cache_base + 1;
246 for (cnt = 0; cnt < 16; ++cnt)
248 hex_hash[2*cnt ] = bin2hex[hash[cnt] >> 4];
249 hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
252 strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
259 FcDirCacheBasenameUUID (const FcChar8 *dir, FcChar8 cache_base[CACHEBASE_LEN], FcConfig *config)
264 if (!FcHashTableFind (config->alias_table, dir, (void **)&alias))
265 alias = FcStrdup (dir);
266 if (FcHashTableFind (config->uuid_table, alias, &u))
268 uuid_unparse (u, (char *) cache_base);
269 strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
280 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
282 FcChar8 *cache_hashed = NULL;
283 FcChar8 cache_base[CACHEBASE_LEN];
286 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
289 if (!FcDirCacheBasenameUUID (dir, cache_base, config))
291 FcDirCacheBasenameMD5 (dir, cache_base);
293 list = FcStrListCreate (config->cacheDirs);
297 while ((cache_dir = FcStrListNext (list)))
300 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
302 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
305 (void) unlink ((char *) cache_hashed);
306 FcStrFree (cache_hashed);
308 FcStrListDone (list);
309 /* return FcFalse if something went wrong */
316 FcDirCacheOpenFile (const FcChar8 *cache_file, struct stat *file_stat)
321 if (FcStat (cache_file, file_stat) < 0)
324 fd = FcOpen((char *) cache_file, O_RDONLY | O_BINARY);
328 if (fstat (fd, file_stat) < 0)
338 * Look for a cache file for the specified dir. Attempt
339 * to use each one we find, stopping when the callback
343 FcDirCacheProcess (FcConfig *config, const FcChar8 *dir,
344 FcBool (*callback) (FcConfig *config, int fd, struct stat *fd_stat,
345 struct stat *dir_stat, void *closure),
346 void *closure, FcChar8 **cache_file_ret)
349 FcChar8 cache_base[CACHEBASE_LEN];
351 FcChar8 *cache_dir, *d;
352 struct stat file_stat, dir_stat;
353 FcBool ret = FcFalse;
354 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
357 d = FcStrBuildFilename (sysroot, dir, NULL);
360 if (FcStatChecksum (d, &dir_stat) < 0)
368 if (!FcDirCacheBasenameUUID (dir, cache_base, config))
370 FcDirCacheBasenameMD5 (dir, cache_base);
372 list = FcStrListCreate (config->cacheDirs);
376 while ((cache_dir = FcStrListNext (list)))
378 FcChar8 *cache_hashed;
381 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
383 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
386 fd = FcDirCacheOpenFile (cache_hashed, &file_stat);
388 ret = (*callback) (config, fd, &file_stat, &dir_stat, closure);
393 *cache_file_ret = cache_hashed;
395 FcStrFree (cache_hashed);
399 FcStrFree (cache_hashed);
401 FcStrListDone (list);
406 #define FC_CACHE_MIN_MMAP 1024
409 * Skip list element, make sure the 'next' pointer is the last thing
410 * in the structure, it will be allocated large enough to hold all
411 * of the necessary pointers
414 typedef struct _FcCacheSkip FcCacheSkip;
416 struct _FcCacheSkip {
423 long cache_mtime_nano;
424 FcCacheSkip *next[1];
428 * The head of the skip list; pointers for every possible level
429 * in the skip list, plus the largest level in the list
432 #define FC_CACHE_MAX_LEVEL 16
434 /* Protected by cache_lock below */
435 static FcCacheSkip *fcCacheChains[FC_CACHE_MAX_LEVEL];
436 static int fcCacheMaxLevel;
439 static FcMutex *cache_lock;
446 lock = fc_atomic_ptr_get (&cache_lock);
448 lock = (FcMutex *) malloc (sizeof (FcMutex));
450 if (!fc_atomic_ptr_cmpexch (&cache_lock, NULL, lock)) {
451 FcMutexFinish (lock);
456 /* Initialize random state */
466 FcMutexUnlock (cache_lock);
473 lock = fc_atomic_ptr_get (&cache_lock);
474 if (lock && fc_atomic_ptr_cmpexch (&cache_lock, lock, NULL)) {
475 FcMutexFinish (lock);
483 * Generate a random level number, distributed
484 * so that each level is 1/4 as likely as the one before
486 * Note that level numbers run 1 <= level <= MAX_LEVEL
491 /* tricky bit -- each bit is '1' 75% of the time */
492 long int bits = FcRandom () | FcRandom ();
495 while (++level < FC_CACHE_MAX_LEVEL)
505 * Insert cache into the list
508 FcCacheInsert (FcCache *cache, struct stat *cache_stat)
510 FcCacheSkip **update[FC_CACHE_MAX_LEVEL];
511 FcCacheSkip *s, **next;
517 * Find links along each chain
519 next = fcCacheChains;
520 for (i = fcCacheMaxLevel; --i >= 0; )
522 for (; (s = next[i]); next = s->next)
523 if (s->cache > cache)
525 update[i] = &next[i];
529 * Create new list element
531 level = random_level ();
532 if (level > fcCacheMaxLevel)
534 level = fcCacheMaxLevel + 1;
535 update[fcCacheMaxLevel] = &fcCacheChains[fcCacheMaxLevel];
536 fcCacheMaxLevel = level;
539 s = malloc (sizeof (FcCacheSkip) + (level - 1) * sizeof (FcCacheSkip *));
544 s->size = cache->size;
545 FcRefInit (&s->ref, 1);
548 s->cache_dev = cache_stat->st_dev;
549 s->cache_ino = cache_stat->st_ino;
550 s->cache_mtime = cache_stat->st_mtime;
551 #ifdef HAVE_STRUCT_STAT_ST_MTIM
552 s->cache_mtime_nano = cache_stat->st_mtim.tv_nsec;
554 s->cache_mtime_nano = 0;
562 s->cache_mtime_nano = 0;
566 * Insert into all fcCacheChains
568 for (i = 0; i < level; i++)
570 s->next[i] = *update[i];
579 FcCacheFindByAddrUnlocked (void *object)
582 FcCacheSkip **next = fcCacheChains;
589 * Walk chain pointers one level at a time
591 for (i = fcCacheMaxLevel; --i >= 0;)
592 while (next[i] && (char *) object >= ((char *) next[i]->cache + next[i]->size))
593 next = next[i]->next;
598 if (s && (char *) object < ((char *) s->cache + s->size))
604 FcCacheFindByAddr (void *object)
608 ret = FcCacheFindByAddrUnlocked (object);
614 FcCacheRemoveUnlocked (FcCache *cache)
616 FcCacheSkip **update[FC_CACHE_MAX_LEVEL];
617 FcCacheSkip *s, **next;
621 * Find links along each chain
623 next = fcCacheChains;
624 for (i = fcCacheMaxLevel; --i >= 0; )
626 for (; (s = next[i]); next = s->next)
627 if (s->cache >= cache)
629 update[i] = &next[i];
632 for (i = 0; i < fcCacheMaxLevel && *update[i] == s; i++)
633 *update[i] = s->next[i];
634 while (fcCacheMaxLevel > 0 && fcCacheChains[fcCacheMaxLevel - 1] == NULL)
640 FcCacheFindByStat (struct stat *cache_stat)
645 for (s = fcCacheChains[0]; s; s = s->next[0])
646 if (s->cache_dev == cache_stat->st_dev &&
647 s->cache_ino == cache_stat->st_ino &&
648 s->cache_mtime == cache_stat->st_mtime)
650 #ifdef HAVE_STRUCT_STAT_ST_MTIM
651 if (s->cache_mtime != cache_stat->st_mtim.tv_nsec)
663 FcDirCacheDisposeUnlocked (FcCache *cache)
665 FcCacheRemoveUnlocked (cache);
667 switch (cache->magic) {
668 case FC_CACHE_MAGIC_ALLOC:
671 case FC_CACHE_MAGIC_MMAP:
672 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
673 munmap (cache, cache->size);
674 #elif defined(_WIN32)
675 UnmapViewOfFile (cache);
682 FcCacheObjectReference (void *object)
684 FcCacheSkip *skip = FcCacheFindByAddr (object);
687 FcRefInc (&skip->ref);
691 FcCacheObjectDereference (void *object)
696 skip = FcCacheFindByAddrUnlocked (object);
699 if (FcRefDec (&skip->ref) == 1)
700 FcDirCacheDisposeUnlocked (skip->cache);
710 for (i = 0; i < FC_CACHE_MAX_LEVEL; i++)
711 assert (fcCacheChains[i] == NULL);
712 assert (fcCacheMaxLevel == 0);
718 FcCacheTimeValid (FcConfig *config, FcCache *cache, struct stat *dir_stat)
720 struct stat dir_static;
721 FcBool fnano = FcTrue;
725 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
729 d = FcStrBuildFilename (sysroot, FcCacheDir (cache), NULL);
731 d = FcStrdup (FcCacheDir (cache));
732 if (FcStatChecksum (d, &dir_static) < 0)
738 dir_stat = &dir_static;
740 #ifdef HAVE_STRUCT_STAT_ST_MTIM
741 fnano = (cache->checksum_nano == dir_stat->st_mtim.tv_nsec);
742 if (FcDebug () & FC_DBG_CACHE)
743 printf ("FcCacheTimeValid dir \"%s\" cache checksum %d.%ld dir checksum %d.%ld\n",
744 FcCacheDir (cache), cache->checksum, (long)cache->checksum_nano, (int) dir_stat->st_mtime, dir_stat->st_mtim.tv_nsec);
746 if (FcDebug () & FC_DBG_CACHE)
747 printf ("FcCacheTimeValid dir \"%s\" cache checksum %d dir checksum %d\n",
748 FcCacheDir (cache), cache->checksum, (int) dir_stat->st_mtime);
751 return cache->checksum == (int) dir_stat->st_mtime && fnano;
755 FcCacheOffsetsValid (FcCache *cache)
757 char *base = (char *)cache;
758 char *end = base + cache->size;
763 if (cache->dir < 0 || cache->dir > cache->size - sizeof (intptr_t) ||
764 memchr (base + cache->dir, '\0', cache->size - cache->dir) == NULL)
767 if (cache->dirs < 0 || cache->dirs >= cache->size ||
768 cache->dirs_count < 0 ||
769 cache->dirs_count > (cache->size - cache->dirs) / sizeof (intptr_t))
772 dirs = FcCacheDirs (cache);
775 for (i = 0; i < cache->dirs_count; i++)
780 dirs[i] > end - (char *) dirs - sizeof (intptr_t))
783 dir = FcOffsetToPtr (dirs, dirs[i], FcChar8);
784 if (memchr (dir, '\0', end - (char *) dir) == NULL)
789 if (cache->set < 0 || cache->set > cache->size - sizeof (FcFontSet))
792 fs = FcCacheSet (cache);
795 if (fs->nfont > (end - (char *) fs) / sizeof (FcPattern))
798 if (fs->fonts != 0 && !FcIsEncodedOffset(fs->fonts))
801 for (i = 0; i < fs->nfont; i++)
803 FcPattern *font = FcFontSetFont (fs, i);
808 if ((char *) font < base ||
809 (char *) font > end - sizeof (FcFontSet) ||
810 font->elts_offset < 0 ||
811 font->elts_offset > end - (char *) font ||
812 font->num > (end - (char *) font - font->elts_offset) / sizeof (FcPatternElt) ||
813 !FcRefIsConst (&font->ref))
817 e = FcPatternElts(font);
818 if (e->values != 0 && !FcIsEncodedOffset(e->values))
821 for (j = 0; j < font->num; j++)
823 last_offset = (char *) font + font->elts_offset;
824 for (l = FcPatternEltValues(&e[j]); l; l = FcValueListNext(l))
826 if ((char *) l < last_offset || (char *) l > end - sizeof (*l) ||
827 (l->next != NULL && !FcIsEncodedOffset(l->next)))
829 last_offset = (char *) l + 1;
839 * Map a cache file into memory
842 FcDirCacheMapFd (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat)
845 FcBool allocated = FcFalse;
847 if (fd_stat->st_size > INTPTR_MAX ||
848 fd_stat->st_size < (int) sizeof (FcCache))
850 cache = FcCacheFindByStat (fd_stat);
853 if (FcCacheTimeValid (config, cache, dir_stat))
855 FcDirCacheUnload (cache);
860 * Large cache files are mmap'ed, smaller cache files are read. This
861 * balances the system cost of mmap against per-process memory usage.
863 if (FcCacheIsMmapSafe (fd) && fd_stat->st_size >= FC_CACHE_MIN_MMAP)
865 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
866 cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
867 #if (HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
868 posix_fadvise (fd, 0, fd_stat->st_size, POSIX_FADV_WILLNEED);
870 if (cache == MAP_FAILED)
872 #elif defined(_WIN32)
877 hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
878 PAGE_READONLY, 0, 0, NULL);
879 if (hFileMap != NULL)
881 cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0,
883 CloseHandle (hFileMap);
890 cache = malloc (fd_stat->st_size);
894 if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
901 if (cache->magic != FC_CACHE_MAGIC_MMAP ||
902 cache->version < FC_CACHE_VERSION_NUMBER ||
903 cache->size != (intptr_t) fd_stat->st_size ||
904 !FcCacheOffsetsValid (cache) ||
905 !FcCacheTimeValid (config, cache, dir_stat) ||
906 !FcCacheInsert (cache, fd_stat))
912 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
913 munmap (cache, fd_stat->st_size);
914 #elif defined(_WIN32)
915 UnmapViewOfFile (cache);
921 /* Mark allocated caches so they're freed rather than unmapped */
923 cache->magic = FC_CACHE_MAGIC_ALLOC;
929 FcDirCacheReference (FcCache *cache, int nref)
931 FcCacheSkip *skip = FcCacheFindByAddr (cache);
934 FcRefAdd (&skip->ref, nref);
938 FcDirCacheUnload (FcCache *cache)
940 FcCacheObjectDereference (cache);
944 FcDirCacheMapHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure)
946 FcCache *cache = FcDirCacheMapFd (config, fd, fd_stat, dir_stat);
950 *((FcCache **) closure) = cache;
955 FcDirCacheLoad (const FcChar8 *dir, FcConfig *config, FcChar8 **cache_file)
957 FcCache *cache = NULL;
961 FcDirCacheReadUUID ((FcChar8 *) dir, config);
963 if (!FcDirCacheProcess (config, dir,
968 d = FcCacheDir (cache);
969 if (FcStrCmp (dir, d))
970 FcHashTableAdd (config->alias_table, (FcChar8 *) d, (FcChar8 *) dir);
976 FcDirCacheLoadFile (const FcChar8 *cache_file, struct stat *file_stat)
980 struct stat my_file_stat;
983 file_stat = &my_file_stat;
984 fd = FcDirCacheOpenFile (cache_file, file_stat);
987 cache = FcDirCacheMapFd (FcConfigGetCurrent (), fd, file_stat, NULL);
993 * Validate a cache file by reading the header and checking
994 * the magic number and the size field
997 FcDirCacheValidateHelper (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure FC_UNUSED)
1002 if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
1004 else if (c.magic != FC_CACHE_MAGIC_MMAP)
1006 else if (c.version < FC_CACHE_VERSION_NUMBER)
1008 else if (fd_stat->st_size != c.size)
1010 else if (c.checksum != (int) dir_stat->st_mtime)
1012 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1013 else if (c.checksum_nano != dir_stat->st_mtim.tv_nsec)
1020 FcDirCacheValidConfig (const FcChar8 *dir, FcConfig *config)
1022 return FcDirCacheProcess (config, dir,
1023 FcDirCacheValidateHelper,
1028 FcDirCacheValid (const FcChar8 *dir)
1032 config = FcConfigGetCurrent ();
1036 return FcDirCacheValidConfig (dir, config);
1040 * Build a cache structure from the given contents
1043 FcDirCacheBuild (FcFontSet *set, const FcChar8 *dir, struct stat *dir_stat, FcStrSet *dirs)
1045 FcSerialize *serialize = FcSerializeCreate ();
1048 FcChar8 *dir_serialize;
1049 intptr_t *dirs_serialize;
1050 FcFontSet *set_serialize;
1055 * Space for cache structure
1057 FcSerializeReserve (serialize, sizeof (FcCache));
1061 if (!FcStrSerializeAlloc (serialize, dir))
1066 FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
1067 for (i = 0; i < dirs->num; i++)
1068 if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
1074 if (!FcFontSetSerializeAlloc (serialize, set))
1077 /* Serialize layout complete. Now allocate space and fill it */
1078 cache = malloc (serialize->size);
1081 /* shut up valgrind */
1082 memset (cache, 0, serialize->size);
1084 serialize->linear = cache;
1086 cache->magic = FC_CACHE_MAGIC_ALLOC;
1087 cache->version = FC_CACHE_VERSION_NUMBER;
1088 cache->size = serialize->size;
1089 cache->checksum = (int) dir_stat->st_mtime;
1090 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1091 cache->checksum_nano = dir_stat->st_mtim.tv_nsec;
1095 * Serialize directory name
1097 dir_serialize = FcStrSerialize (serialize, dir);
1100 cache->dir = FcPtrToOffset (cache, dir_serialize);
1103 * Serialize sub dirs
1105 dirs_serialize = FcSerializePtr (serialize, dirs);
1106 if (!dirs_serialize)
1108 cache->dirs = FcPtrToOffset (cache, dirs_serialize);
1109 cache->dirs_count = dirs->num;
1110 for (i = 0; i < dirs->num; i++)
1112 FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
1115 dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
1119 * Serialize font set
1121 set_serialize = FcFontSetSerialize (serialize, set);
1124 cache->set = FcPtrToOffset (cache, set_serialize);
1126 FcSerializeDestroy (serialize);
1128 FcCacheInsert (cache, NULL);
1135 FcSerializeDestroy (serialize);
1140 FcDirCacheRebuild (FcCache *cache, struct stat *dir_stat, FcStrSet *dirs)
1143 FcFontSet *set = FcFontSetDeserialize (FcCacheSet (cache));
1144 const FcChar8 *dir = FcCacheDir (cache);
1146 new = FcDirCacheBuild (set, dir, dir_stat, dirs);
1147 FcFontSetDestroy (set);
1152 /* write serialized state to the cache file */
1154 FcDirCacheWrite (FcCache *cache, FcConfig *config)
1156 FcChar8 *dir = FcCacheDir (cache);
1157 FcChar8 cache_base[CACHEBASE_LEN];
1158 FcChar8 *cache_hashed;
1162 FcChar8 *cache_dir = NULL;
1163 FcChar8 *test_dir, *d = NULL;
1165 struct stat cache_stat;
1168 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1171 * Write it to the first directory in the list which is writable
1174 list = FcStrListCreate (config->cacheDirs);
1177 while ((test_dir = FcStrListNext (list)))
1182 d = FcStrBuildFilename (sysroot, test_dir, NULL);
1184 d = FcStrCopyFilename (test_dir);
1186 if (access ((char *) d, W_OK) == 0)
1188 cache_dir = FcStrCopyFilename (d);
1194 * If the directory doesn't exist, try to create it
1196 if (access ((char *) d, F_OK) == -1) {
1197 if (FcMakeDirectory (d))
1199 cache_dir = FcStrCopyFilename (d);
1200 /* Create CACHEDIR.TAG */
1201 FcDirCacheCreateTagFile (d);
1206 * Otherwise, try making it writable
1208 else if (chmod ((char *) d, 0755) == 0)
1210 cache_dir = FcStrCopyFilename (d);
1211 /* Try to create CACHEDIR.TAG too */
1212 FcDirCacheCreateTagFile (d);
1219 FcStrListDone (list);
1224 if (!FcDirCacheBasenameUUID (dir, cache_base, config))
1226 FcDirCacheBasenameMD5 (dir, cache_base);
1227 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1230 FcStrFree (cache_dir);
1232 if (FcDebug () & FC_DBG_CACHE)
1233 printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
1236 atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
1240 if (!FcAtomicLock (atomic))
1243 fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
1247 /* Temporarily switch magic to MMAP while writing to file */
1248 magic = cache->magic;
1249 if (magic != FC_CACHE_MAGIC_MMAP)
1250 cache->magic = FC_CACHE_MAGIC_MMAP;
1253 * Write cache contents to file
1255 written = write (fd, cache, cache->size);
1257 /* Switch magic back */
1258 if (magic != FC_CACHE_MAGIC_MMAP)
1259 cache->magic = magic;
1261 if (written != cache->size)
1263 perror ("write cache");
1268 if (!FcAtomicReplaceOrig(atomic))
1271 /* If the file is small, update the cache chain entry such that the
1272 * new cache file is not read again. If it's large, we don't do that
1273 * such that we reload it, using mmap, which is shared across processes.
1275 if (cache->size < FC_CACHE_MIN_MMAP && FcStat (cache_hashed, &cache_stat))
1278 if ((skip = FcCacheFindByAddrUnlocked (cache)))
1280 skip->cache_dev = cache_stat.st_dev;
1281 skip->cache_ino = cache_stat.st_ino;
1282 skip->cache_mtime = cache_stat.st_mtime;
1283 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1284 skip->cache_mtime_nano = cache_stat.st_mtim.tv_nsec;
1286 skip->cache_mtime_nano = 0;
1292 FcStrFree (cache_hashed);
1293 FcAtomicUnlock (atomic);
1294 FcAtomicDestroy (atomic);
1300 FcAtomicUnlock (atomic);
1302 FcAtomicDestroy (atomic);
1304 FcStrFree (cache_hashed);
1309 FcDirCacheClean (const FcChar8 *cache_dir, FcBool verbose)
1314 FcBool ret = FcTrue;
1317 struct stat target_stat;
1318 const FcChar8 *sysroot;
1320 /* FIXME: this API needs to support non-current FcConfig */
1321 sysroot = FcConfigGetSysRoot (NULL);
1323 dir = FcStrBuildFilename (sysroot, cache_dir, NULL);
1325 dir = FcStrCopyFilename (cache_dir);
1328 fprintf (stderr, "Fontconfig error: %s: out of memory\n", cache_dir);
1331 if (access ((char *) dir, W_OK) != 0)
1333 if (verbose || FcDebug () & FC_DBG_CACHE)
1334 printf ("%s: not cleaning %s cache directory\n", dir,
1335 access ((char *) dir, F_OK) == 0 ? "unwritable" : "non-existent");
1338 if (verbose || FcDebug () & FC_DBG_CACHE)
1339 printf ("%s: cleaning cache directory\n", dir);
1340 d = opendir ((char *) dir);
1343 perror ((char *) dir);
1347 while ((ent = readdir (d)))
1350 const FcChar8 *target_dir;
1352 if (ent->d_name[0] == '.')
1354 /* skip cache files for different architectures and */
1355 /* files which are not cache files at all */
1356 if (strlen(ent->d_name) != 32 + strlen ("-" FC_ARCHITECTURE FC_CACHE_SUFFIX) ||
1357 strcmp(ent->d_name + 32, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX))
1360 file_name = FcStrBuildFilename (dir, (FcChar8 *)ent->d_name, NULL);
1363 fprintf (stderr, "Fontconfig error: %s: allocation failure\n", dir);
1368 cache = FcDirCacheLoadFile (file_name, NULL);
1371 if (verbose || FcDebug () & FC_DBG_CACHE)
1372 printf ("%s: invalid cache file: %s\n", dir, ent->d_name);
1379 target_dir = FcCacheDir (cache);
1381 s = FcStrBuildFilename (sysroot, target_dir, NULL);
1383 s = FcStrdup (target_dir);
1384 if (stat ((char *) s, &target_stat) < 0)
1386 if (verbose || FcDebug () & FC_DBG_CACHE)
1387 printf ("%s: %s: missing directory: %s \n",
1388 dir, ent->d_name, s);
1391 FcDirCacheUnload (cache);
1396 if (unlink ((char *) file_name) < 0)
1398 perror ((char *) file_name);
1402 FcStrFree (file_name);
1413 FcDirCacheLock (const FcChar8 *dir,
1416 FcChar8 *cache_hashed = NULL;
1417 FcChar8 cache_base[CACHEBASE_LEN];
1420 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1424 if (!FcDirCacheBasenameUUID (dir, cache_base, config))
1426 FcDirCacheBasenameMD5 (dir, cache_base);
1427 list = FcStrListCreate (config->cacheDirs);
1431 while ((cache_dir = FcStrListNext (list)))
1434 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
1436 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
1439 fd = FcOpen ((const char *)cache_hashed, O_RDWR);
1440 FcStrFree (cache_hashed);
1441 /* No caches in that directory. simply retry with another one */
1445 if (_locking (fd, _LK_LOCK, 1) == -1)
1450 fl.l_type = F_WRLCK;
1451 fl.l_whence = SEEK_SET;
1454 fl.l_pid = getpid ();
1455 if (fcntl (fd, F_SETLKW, &fl) == -1)
1461 FcStrListDone (list);
1464 FcStrListDone (list);
1471 FcDirCacheUnlock (int fd)
1476 _locking (fd, _LK_UNLCK, 1);
1480 fl.l_type = F_UNLCK;
1481 fl.l_whence = SEEK_SET;
1484 fl.l_pid = getpid ();
1485 fcntl (fd, F_SETLK, &fl);
1492 * Hokey little macro trick to permit the definitions of C functions
1493 * with the same name as CPP macros
1495 #define args1(x) (x)
1496 #define args2(x,y) (x,y)
1499 FcCacheDir args1(const FcCache *c)
1501 return FcCacheDir (c);
1505 FcCacheCopySet args1(const FcCache *c)
1507 FcFontSet *old = FcCacheSet (c);
1508 FcFontSet *new = FcFontSetCreate ();
1513 for (i = 0; i < old->nfont; i++)
1515 FcPattern *font = FcFontSetFont (old, i);
1517 FcPatternReference (font);
1518 if (!FcFontSetAdd (new, font))
1520 FcFontSetDestroy (new);
1528 FcCacheSubdir args2(const FcCache *c, int i)
1530 return FcCacheSubdir (c, i);
1534 FcCacheNumSubdir args1(const FcCache *c)
1536 return c->dirs_count;
1540 FcCacheNumFont args1(const FcCache *c)
1542 return FcCacheSet(c)->nfont;
1546 * This code implements the MD5 message-digest algorithm.
1547 * The algorithm is due to Ron Rivest. This code was
1548 * written by Colin Plumb in 1993, no copyright is claimed.
1549 * This code is in the public domain; do with it what you wish.
1551 * Equivalent code is available from RSA Data Security, Inc.
1552 * This code has been tested against that, and is equivalent,
1553 * except that you don't need to include two pages of legalese
1556 * To compute the message digest of a chunk of bytes, declare an
1557 * MD5Context structure, pass it to MD5Init, call MD5Update as
1558 * needed on buffers full of bytes, and then call MD5Final, which
1559 * will fill a supplied 16-byte array with the digest.
1563 #define byteReverse(buf, len) /* Nothing */
1566 * Note: this code is harmless on little-endian machines.
1568 void byteReverse(unsigned char *buf, unsigned longs)
1572 t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1573 ((unsigned) buf[1] << 8 | buf[0]);
1574 *(FcChar32 *) buf = t;
1581 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
1582 * initialization constants.
1584 static void MD5Init(struct MD5Context *ctx)
1586 ctx->buf[0] = 0x67452301;
1587 ctx->buf[1] = 0xefcdab89;
1588 ctx->buf[2] = 0x98badcfe;
1589 ctx->buf[3] = 0x10325476;
1596 * Update context to reflect the concatenation of another buffer full
1599 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len)
1603 /* Update bitcount */
1606 if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
1607 ctx->bits[1]++; /* Carry from low to high */
1608 ctx->bits[1] += len >> 29;
1610 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
1612 /* Handle any leading odd-sized chunks */
1615 unsigned char *p = (unsigned char *) ctx->in + t;
1619 memcpy(p, buf, len);
1623 byteReverse(ctx->in, 16);
1624 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1628 /* Process data in 64-byte chunks */
1631 memcpy(ctx->in, buf, 64);
1632 byteReverse(ctx->in, 16);
1633 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1638 /* Handle any remaining bytes of data. */
1640 memcpy(ctx->in, buf, len);
1644 * Final wrapup - pad to 64-byte boundary with the bit pattern
1645 * 1 0* (64-bit count of bits processed, MSB-first)
1647 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
1652 /* Compute number of bytes mod 64 */
1653 count = (ctx->bits[0] >> 3) & 0x3F;
1655 /* Set the first char of padding to 0x80. This is safe since there is
1656 always at least one byte free */
1657 p = ctx->in + count;
1660 /* Bytes of padding needed to make 64 bytes */
1661 count = 64 - 1 - count;
1663 /* Pad out to 56 mod 64 */
1665 /* Two lots of padding: Pad the first block to 64 bytes */
1666 memset(p, 0, count);
1667 byteReverse(ctx->in, 16);
1668 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1670 /* Now fill the next block with 56 bytes */
1671 memset(ctx->in, 0, 56);
1673 /* Pad block to 56 bytes */
1674 memset(p, 0, count - 8);
1676 byteReverse(ctx->in, 14);
1678 /* Append length in bits and transform */
1679 ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
1680 ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
1682 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1683 byteReverse((unsigned char *) ctx->buf, 4);
1684 memcpy(digest, ctx->buf, 16);
1685 memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */
1689 /* The four core functions - F1 is optimized somewhat */
1691 /* #define F1(x, y, z) (x & y | ~x & z) */
1692 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1693 #define F2(x, y, z) F1(z, x, y)
1694 #define F3(x, y, z) (x ^ y ^ z)
1695 #define F4(x, y, z) (y ^ (x | ~z))
1697 /* This is the central step in the MD5 algorithm. */
1698 #define MD5STEP(f, w, x, y, z, data, s) \
1699 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
1702 * The core of the MD5 algorithm, this alters an existing MD5 hash to
1703 * reflect the addition of 16 longwords of new data. MD5Update blocks
1704 * the data and converts bytes into longwords for this routine.
1706 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
1708 register FcChar32 a, b, c, d;
1715 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1716 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1717 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1718 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1719 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1720 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1721 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1722 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1723 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1724 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1725 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1726 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1727 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1728 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1729 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1730 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1732 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1733 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1734 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1735 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1736 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1737 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1738 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1739 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1740 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1741 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1742 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1743 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1744 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1745 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1746 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1747 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1749 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1750 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1751 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1752 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1753 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1754 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1755 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1756 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1757 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1758 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1759 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1760 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1761 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1762 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1763 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1764 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1766 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1767 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1768 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1769 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1770 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1771 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1772 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1773 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1774 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1775 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1776 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1777 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1778 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1779 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1780 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1781 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1790 FcDirCacheCreateTagFile (const FcChar8 *cache_dir)
1796 static const FcChar8 cache_tag_contents[] =
1797 "Signature: 8a477f597d28d172789f06886806bc55\n"
1798 "# This file is a cache directory tag created by fontconfig.\n"
1799 "# For information about cache directory tags, see:\n"
1800 "# http://www.brynosaurus.com/cachedir/\n";
1801 static size_t cache_tag_contents_size = sizeof (cache_tag_contents) - 1;
1802 FcBool ret = FcFalse;
1807 if (access ((char *) cache_dir, W_OK) == 0)
1809 /* Create CACHEDIR.TAG */
1810 cache_tag = FcStrBuildFilename (cache_dir, "CACHEDIR.TAG", NULL);
1813 atomic = FcAtomicCreate ((FcChar8 *)cache_tag);
1816 if (!FcAtomicLock (atomic))
1818 fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0644);
1821 fp = fdopen(fd, "wb");
1825 fwrite(cache_tag_contents, cache_tag_contents_size, sizeof (FcChar8), fp);
1828 if (!FcAtomicReplaceOrig(atomic))
1833 FcAtomicUnlock (atomic);
1835 FcAtomicDestroy (atomic);
1837 FcStrFree (cache_tag);
1840 if (FcDebug () & FC_DBG_CACHE)
1843 printf ("Created CACHEDIR.TAG at %s\n", cache_dir);
1845 printf ("Unable to create CACHEDIR.TAG at %s\n", cache_dir);
1852 FcCacheCreateTagFile (const FcConfig *config)
1854 FcChar8 *cache_dir = NULL, *d = NULL;
1856 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1858 list = FcConfigGetCacheDirs (config);
1862 while ((cache_dir = FcStrListNext (list)))
1867 d = FcStrBuildFilename (sysroot, cache_dir, NULL);
1869 d = FcStrCopyFilename (cache_dir);
1870 if (FcDirCacheCreateTagFile (d))
1875 FcStrListDone (list);
1879 #include "fcaliastail.h"