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.
30 #include <sys/types.h>
33 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
35 # include <sys/mman.h>
49 static void MD5Init(struct MD5Context *ctx);
50 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len);
51 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx);
52 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16]);
54 #define CACHEBASE_LEN (1 + 32 + 1 + sizeof (FC_ARCHITECTURE) + sizeof (FC_CACHE_SUFFIX))
57 FcCacheIsMmapSafe (int fd)
60 MMAP_NOT_INITIALIZED = 0,
65 static void *static_status;
67 status = (intptr_t) fc_atomic_ptr_get (&static_status);
69 if (status == MMAP_NOT_INITIALIZED)
71 const char *env = getenv ("FONTCONFIG_USE_MMAP");
73 if (env && FcNameBool ((const FcChar8 *) env, &use))
74 status = use ? MMAP_USE : MMAP_DONT_USE;
76 status = MMAP_CHECK_FS;
77 (void) fc_atomic_ptr_cmpexch (&static_status, NULL, (void *) status);
80 if (status == MMAP_CHECK_FS)
81 return FcIsFsMmapSafe (fd);
83 return status == MMAP_USE;
87 static const char bin2hex[] = { '0', '1', '2', '3',
93 FcDirCacheBasename (const FcChar8 * dir, FcChar8 cache_base[CACHEBASE_LEN])
95 unsigned char hash[16];
98 struct MD5Context ctx;
101 MD5Update (&ctx, (const unsigned char *)dir, strlen ((const char *) dir));
103 MD5Final (hash, &ctx);
106 hex_hash = cache_base + 1;
107 for (cnt = 0; cnt < 16; ++cnt)
109 hex_hash[2*cnt ] = bin2hex[hash[cnt] >> 4];
110 hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
113 strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
119 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
121 FcChar8 *cache_hashed = NULL;
122 FcChar8 cache_base[CACHEBASE_LEN];
125 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
127 FcDirCacheBasename (dir, cache_base);
129 list = FcStrListCreate (config->cacheDirs);
133 while ((cache_dir = FcStrListNext (list)))
136 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
138 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
141 (void) unlink ((char *) cache_hashed);
142 FcStrFree (cache_hashed);
144 FcStrListDone (list);
145 /* return FcFalse if something went wrong */
152 FcDirCacheOpenFile (const FcChar8 *cache_file, struct stat *file_stat)
157 if (FcStat (cache_file, file_stat) < 0)
160 fd = FcOpen((char *) cache_file, O_RDONLY | O_BINARY);
164 if (fstat (fd, file_stat) < 0)
174 * Look for a cache file for the specified dir. Attempt
175 * to use each one we find, stopping when the callback
179 FcDirCacheProcess (FcConfig *config, const FcChar8 *dir,
180 FcBool (*callback) (int fd, struct stat *fd_stat,
181 struct stat *dir_stat, void *closure),
182 void *closure, FcChar8 **cache_file_ret)
185 FcChar8 cache_base[CACHEBASE_LEN];
188 struct stat file_stat, dir_stat;
189 FcBool ret = FcFalse;
191 if (FcStatChecksum (dir, &dir_stat) < 0)
194 FcDirCacheBasename (dir, cache_base);
196 list = FcStrListCreate (config->cacheDirs);
200 while ((cache_dir = FcStrListNext (list)))
202 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
203 FcChar8 *cache_hashed;
206 cache_hashed = FcStrBuildFilename (sysroot, cache_dir, cache_base, NULL);
208 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
211 fd = FcDirCacheOpenFile (cache_hashed, &file_stat);
213 ret = (*callback) (fd, &file_stat, &dir_stat, closure);
218 *cache_file_ret = cache_hashed;
220 FcStrFree (cache_hashed);
224 FcStrFree (cache_hashed);
226 FcStrListDone (list);
231 #define FC_CACHE_MIN_MMAP 1024
234 * Skip list element, make sure the 'next' pointer is the last thing
235 * in the structure, it will be allocated large enough to hold all
236 * of the necessary pointers
239 typedef struct _FcCacheSkip FcCacheSkip;
241 struct _FcCacheSkip {
248 FcCacheSkip *next[1];
252 * The head of the skip list; pointers for every possible level
253 * in the skip list, plus the largest level in the list
256 #define FC_CACHE_MAX_LEVEL 16
258 /* Protected by cache_lock below */
259 static FcCacheSkip *fcCacheChains[FC_CACHE_MAX_LEVEL];
260 static int fcCacheMaxLevel;
263 static FcMutex *cache_lock;
270 lock = fc_atomic_ptr_get (&cache_lock);
272 lock = (FcMutex *) malloc (sizeof (FcMutex));
274 if (!fc_atomic_ptr_cmpexch (&cache_lock, NULL, lock)) {
275 FcMutexFinish (lock);
280 /* Initialize random state */
290 FcMutexUnlock (cache_lock);
297 lock = fc_atomic_ptr_get (&cache_lock);
298 if (lock && fc_atomic_ptr_cmpexch (&cache_lock, lock, NULL)) {
299 FcMutexFinish (lock);
307 * Generate a random level number, distributed
308 * so that each level is 1/4 as likely as the one before
310 * Note that level numbers run 1 <= level <= MAX_LEVEL
315 /* tricky bit -- each bit is '1' 75% of the time */
316 long int bits = FcRandom () | FcRandom ();
319 while (++level < FC_CACHE_MAX_LEVEL)
329 * Insert cache into the list
332 FcCacheInsert (FcCache *cache, struct stat *cache_stat)
334 FcCacheSkip **update[FC_CACHE_MAX_LEVEL];
335 FcCacheSkip *s, **next;
341 * Find links along each chain
343 next = fcCacheChains;
344 for (i = fcCacheMaxLevel; --i >= 0; )
346 for (; (s = next[i]); next = s->next)
347 if (s->cache > cache)
349 update[i] = &next[i];
353 * Create new list element
355 level = random_level ();
356 if (level > fcCacheMaxLevel)
358 level = fcCacheMaxLevel + 1;
359 update[fcCacheMaxLevel] = &fcCacheChains[fcCacheMaxLevel];
360 fcCacheMaxLevel = level;
363 s = malloc (sizeof (FcCacheSkip) + (level - 1) * sizeof (FcCacheSkip *));
368 s->size = cache->size;
369 FcRefInit (&s->ref, 1);
372 s->cache_dev = cache_stat->st_dev;
373 s->cache_ino = cache_stat->st_ino;
374 s->cache_mtime = cache_stat->st_mtime;
384 * Insert into all fcCacheChains
386 for (i = 0; i < level; i++)
388 s->next[i] = *update[i];
397 FcCacheFindByAddrUnlocked (void *object)
400 FcCacheSkip **next = fcCacheChains;
407 * Walk chain pointers one level at a time
409 for (i = fcCacheMaxLevel; --i >= 0;)
410 while (next[i] && (char *) object >= ((char *) next[i]->cache + next[i]->size))
411 next = next[i]->next;
416 if (s && (char *) object < ((char *) s->cache + s->size))
422 FcCacheFindByAddr (void *object)
426 ret = FcCacheFindByAddrUnlocked (object);
432 FcCacheRemoveUnlocked (FcCache *cache)
434 FcCacheSkip **update[FC_CACHE_MAX_LEVEL];
435 FcCacheSkip *s, **next;
439 * Find links along each chain
441 next = fcCacheChains;
442 for (i = fcCacheMaxLevel; --i >= 0; )
444 for (; (s = next[i]); next = s->next)
445 if (s->cache >= cache)
447 update[i] = &next[i];
450 for (i = 0; i < fcCacheMaxLevel && *update[i] == s; i++)
451 *update[i] = s->next[i];
452 while (fcCacheMaxLevel > 0 && fcCacheChains[fcCacheMaxLevel - 1] == NULL)
458 FcCacheFindByStat (struct stat *cache_stat)
463 for (s = fcCacheChains[0]; s; s = s->next[0])
464 if (s->cache_dev == cache_stat->st_dev &&
465 s->cache_ino == cache_stat->st_ino &&
466 s->cache_mtime == cache_stat->st_mtime)
477 FcDirCacheDisposeUnlocked (FcCache *cache)
479 FcCacheRemoveUnlocked (cache);
481 switch (cache->magic) {
482 case FC_CACHE_MAGIC_ALLOC:
485 case FC_CACHE_MAGIC_MMAP:
486 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
487 munmap (cache, cache->size);
488 #elif defined(_WIN32)
489 UnmapViewOfFile (cache);
496 FcCacheObjectReference (void *object)
498 FcCacheSkip *skip = FcCacheFindByAddr (object);
501 FcRefInc (&skip->ref);
505 FcCacheObjectDereference (void *object)
510 skip = FcCacheFindByAddrUnlocked (object);
513 if (FcRefDec (&skip->ref) == 1)
514 FcDirCacheDisposeUnlocked (skip->cache);
524 for (i = 0; i < FC_CACHE_MAX_LEVEL; i++)
525 assert (fcCacheChains[i] == NULL);
526 assert (fcCacheMaxLevel == 0);
532 FcCacheTimeValid (FcCache *cache, struct stat *dir_stat)
534 struct stat dir_static;
538 if (FcStatChecksum (FcCacheDir (cache), &dir_static) < 0)
540 dir_stat = &dir_static;
542 if (FcDebug () & FC_DBG_CACHE)
543 printf ("FcCacheTimeValid dir \"%s\" cache checksum %d dir checksum %d\n",
544 FcCacheDir (cache), cache->checksum, (int) dir_stat->st_mtime);
545 return cache->checksum == (int) dir_stat->st_mtime;
549 * Map a cache file into memory
552 FcDirCacheMapFd (int fd, struct stat *fd_stat, struct stat *dir_stat)
555 FcBool allocated = FcFalse;
557 if (fd_stat->st_size < (int) sizeof (FcCache))
559 cache = FcCacheFindByStat (fd_stat);
562 if (FcCacheTimeValid (cache, dir_stat))
564 FcDirCacheUnload (cache);
569 * Large cache files are mmap'ed, smaller cache files are read. This
570 * balances the system cost of mmap against per-process memory usage.
572 if (FcCacheIsMmapSafe (fd) && fd_stat->st_size >= FC_CACHE_MIN_MMAP)
574 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
575 cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
576 #if (HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
577 posix_fadvise (fd, 0, fd_stat->st_size, POSIX_FADV_WILLNEED);
579 if (cache == MAP_FAILED)
581 #elif defined(_WIN32)
586 hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
587 PAGE_READONLY, 0, 0, NULL);
588 if (hFileMap != NULL)
590 cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0,
592 CloseHandle (hFileMap);
599 cache = malloc (fd_stat->st_size);
603 if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
610 if (cache->magic != FC_CACHE_MAGIC_MMAP ||
611 cache->version < FC_CACHE_CONTENT_VERSION ||
612 cache->size != (intptr_t) fd_stat->st_size ||
613 !FcCacheTimeValid (cache, dir_stat) ||
614 !FcCacheInsert (cache, fd_stat))
620 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
621 munmap (cache, fd_stat->st_size);
622 #elif defined(_WIN32)
623 UnmapViewOfFile (cache);
629 /* Mark allocated caches so they're freed rather than unmapped */
631 cache->magic = FC_CACHE_MAGIC_ALLOC;
637 FcDirCacheReference (FcCache *cache, int nref)
639 FcCacheSkip *skip = FcCacheFindByAddr (cache);
642 FcRefAdd (&skip->ref, nref);
646 FcDirCacheUnload (FcCache *cache)
648 FcCacheObjectDereference (cache);
652 FcDirCacheMapHelper (int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure)
654 FcCache *cache = FcDirCacheMapFd (fd, fd_stat, dir_stat);
658 *((FcCache **) closure) = cache;
663 FcDirCacheLoad (const FcChar8 *dir, FcConfig *config, FcChar8 **cache_file)
665 FcCache *cache = NULL;
667 if (!FcDirCacheProcess (config, dir,
675 FcDirCacheLoadFile (const FcChar8 *cache_file, struct stat *file_stat)
679 struct stat my_file_stat;
682 file_stat = &my_file_stat;
683 fd = FcDirCacheOpenFile (cache_file, file_stat);
686 cache = FcDirCacheMapFd (fd, file_stat, NULL);
692 * Validate a cache file by reading the header and checking
693 * the magic number and the size field
696 FcDirCacheValidateHelper (int fd, struct stat *fd_stat, struct stat *dir_stat, void *closure FC_UNUSED)
701 if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
703 else if (c.magic != FC_CACHE_MAGIC_MMAP)
705 else if (c.version < FC_CACHE_CONTENT_VERSION)
707 else if (fd_stat->st_size != c.size)
709 else if (c.checksum != (int) dir_stat->st_mtime)
715 FcDirCacheValidConfig (const FcChar8 *dir, FcConfig *config)
717 return FcDirCacheProcess (config, dir,
718 FcDirCacheValidateHelper,
723 FcDirCacheValid (const FcChar8 *dir)
727 config = FcConfigGetCurrent ();
731 return FcDirCacheValidConfig (dir, config);
735 * Build a cache structure from the given contents
738 FcDirCacheBuild (FcFontSet *set, const FcChar8 *dir, struct stat *dir_stat, FcStrSet *dirs)
740 FcSerialize *serialize = FcSerializeCreate ();
743 FcChar8 *dir_serialize;
744 intptr_t *dirs_serialize;
745 FcFontSet *set_serialize;
750 * Space for cache structure
752 FcSerializeReserve (serialize, sizeof (FcCache));
756 if (!FcStrSerializeAlloc (serialize, dir))
761 FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
762 for (i = 0; i < dirs->num; i++)
763 if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
769 if (!FcFontSetSerializeAlloc (serialize, set))
772 /* Serialize layout complete. Now allocate space and fill it */
773 cache = malloc (serialize->size);
776 /* shut up valgrind */
777 memset (cache, 0, serialize->size);
779 serialize->linear = cache;
781 cache->magic = FC_CACHE_MAGIC_ALLOC;
782 cache->version = FC_CACHE_CONTENT_VERSION;
783 cache->size = serialize->size;
784 cache->checksum = (int) dir_stat->st_mtime;
787 * Serialize directory name
789 dir_serialize = FcStrSerialize (serialize, dir);
792 cache->dir = FcPtrToOffset (cache, dir_serialize);
797 dirs_serialize = FcSerializePtr (serialize, dirs);
800 cache->dirs = FcPtrToOffset (cache, dirs_serialize);
801 cache->dirs_count = dirs->num;
802 for (i = 0; i < dirs->num; i++)
804 FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
807 dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
813 set_serialize = FcFontSetSerialize (serialize, set);
816 cache->set = FcPtrToOffset (cache, set_serialize);
818 FcSerializeDestroy (serialize);
820 FcCacheInsert (cache, NULL);
827 FcSerializeDestroy (serialize);
831 /* write serialized state to the cache file */
833 FcDirCacheWrite (FcCache *cache, FcConfig *config)
835 FcChar8 *dir = FcCacheDir (cache);
836 FcChar8 cache_base[CACHEBASE_LEN];
837 FcChar8 *cache_hashed;
841 FcChar8 *cache_dir = NULL;
842 FcChar8 *test_dir, *d = NULL;
844 struct stat cache_stat;
847 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
850 * Write it to the first directory in the list which is writable
853 list = FcStrListCreate (config->cacheDirs);
856 while ((test_dir = FcStrListNext (list)))
861 d = FcStrBuildFilename (sysroot, test_dir, NULL);
863 d = FcStrCopyFilename (test_dir);
865 if (access ((char *) d, W_OK) == 0)
867 cache_dir = FcStrCopyFilename (d);
873 * If the directory doesn't exist, try to create it
875 if (access ((char *) d, F_OK) == -1) {
876 if (FcMakeDirectory (d))
878 cache_dir = FcStrCopyFilename (d);
879 /* Create CACHEDIR.TAG */
880 FcDirCacheCreateTagFile (d);
885 * Otherwise, try making it writable
887 else if (chmod ((char *) d, 0755) == 0)
889 cache_dir = FcStrCopyFilename (d);
890 /* Try to create CACHEDIR.TAG too */
891 FcDirCacheCreateTagFile (d);
898 FcStrListDone (list);
902 FcDirCacheBasename (dir, cache_base);
903 cache_hashed = FcStrBuildFilename (cache_dir, cache_base, NULL);
906 FcStrFree (cache_dir);
908 if (FcDebug () & FC_DBG_CACHE)
909 printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
912 atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
916 if (!FcAtomicLock (atomic))
919 fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
923 /* Temporarily switch magic to MMAP while writing to file */
924 magic = cache->magic;
925 if (magic != FC_CACHE_MAGIC_MMAP)
926 cache->magic = FC_CACHE_MAGIC_MMAP;
929 * Write cache contents to file
931 written = write (fd, cache, cache->size);
933 /* Switch magic back */
934 if (magic != FC_CACHE_MAGIC_MMAP)
935 cache->magic = magic;
937 if (written != cache->size)
939 perror ("write cache");
944 if (!FcAtomicReplaceOrig(atomic))
947 /* If the file is small, update the cache chain entry such that the
948 * new cache file is not read again. If it's large, we don't do that
949 * such that we reload it, using mmap, which is shared across processes.
951 if (cache->size < FC_CACHE_MIN_MMAP && FcStat (cache_hashed, &cache_stat))
954 if ((skip = FcCacheFindByAddrUnlocked (cache)))
956 skip->cache_dev = cache_stat.st_dev;
957 skip->cache_ino = cache_stat.st_ino;
958 skip->cache_mtime = cache_stat.st_mtime;
963 FcStrFree (cache_hashed);
964 FcAtomicUnlock (atomic);
965 FcAtomicDestroy (atomic);
971 FcAtomicUnlock (atomic);
973 FcAtomicDestroy (atomic);
975 FcStrFree (cache_hashed);
980 FcDirCacheClean (const FcChar8 *cache_dir, FcBool verbose)
988 struct stat target_stat;
989 const FcChar8 *sysroot;
991 /* FIXME: this API needs to support non-current FcConfig */
992 sysroot = FcConfigGetSysRoot (NULL);
994 dir = FcStrBuildFilename (sysroot, cache_dir, NULL);
996 dir = FcStrCopyFilename (cache_dir);
999 fprintf (stderr, "Fontconfig error: %s: out of memory\n", cache_dir);
1002 if (access ((char *) dir, W_OK) != 0)
1004 if (verbose || FcDebug () & FC_DBG_CACHE)
1005 printf ("%s: not cleaning %s cache directory\n", dir,
1006 access ((char *) dir, F_OK) == 0 ? "unwritable" : "non-existent");
1009 if (verbose || FcDebug () & FC_DBG_CACHE)
1010 printf ("%s: cleaning cache directory\n", dir);
1011 d = opendir ((char *) dir);
1014 perror ((char *) dir);
1018 while ((ent = readdir (d)))
1021 const FcChar8 *target_dir;
1023 if (ent->d_name[0] == '.')
1025 /* skip cache files for different architectures and */
1026 /* files which are not cache files at all */
1027 if (strlen(ent->d_name) != 32 + strlen ("-" FC_ARCHITECTURE FC_CACHE_SUFFIX) ||
1028 strcmp(ent->d_name + 32, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX))
1031 file_name = FcStrBuildFilename (dir, (FcChar8 *)ent->d_name, NULL);
1034 fprintf (stderr, "Fontconfig error: %s: allocation failure\n", dir);
1039 cache = FcDirCacheLoadFile (file_name, NULL);
1042 if (verbose || FcDebug () & FC_DBG_CACHE)
1043 printf ("%s: invalid cache file: %s\n", dir, ent->d_name);
1048 target_dir = FcCacheDir (cache);
1049 if (stat ((char *) target_dir, &target_stat) < 0)
1051 if (verbose || FcDebug () & FC_DBG_CACHE)
1052 printf ("%s: %s: missing directory: %s \n",
1053 dir, ent->d_name, target_dir);
1056 FcDirCacheUnload (cache);
1060 if (unlink ((char *) file_name) < 0)
1062 perror ((char *) file_name);
1066 FcStrFree (file_name);
1077 * Hokey little macro trick to permit the definitions of C functions
1078 * with the same name as CPP macros
1080 #define args1(x) (x)
1081 #define args2(x,y) (x,y)
1084 FcCacheDir args1(const FcCache *c)
1086 return FcCacheDir (c);
1090 FcCacheCopySet args1(const FcCache *c)
1092 FcFontSet *old = FcCacheSet (c);
1093 FcFontSet *new = FcFontSetCreate ();
1098 for (i = 0; i < old->nfont; i++)
1100 FcPattern *font = FcFontSetFont (old, i);
1102 FcPatternReference (font);
1103 if (!FcFontSetAdd (new, font))
1105 FcFontSetDestroy (new);
1113 FcCacheSubdir args2(const FcCache *c, int i)
1115 return FcCacheSubdir (c, i);
1119 FcCacheNumSubdir args1(const FcCache *c)
1121 return c->dirs_count;
1125 FcCacheNumFont args1(const FcCache *c)
1127 return FcCacheSet(c)->nfont;
1131 * This code implements the MD5 message-digest algorithm.
1132 * The algorithm is due to Ron Rivest. This code was
1133 * written by Colin Plumb in 1993, no copyright is claimed.
1134 * This code is in the public domain; do with it what you wish.
1136 * Equivalent code is available from RSA Data Security, Inc.
1137 * This code has been tested against that, and is equivalent,
1138 * except that you don't need to include two pages of legalese
1141 * To compute the message digest of a chunk of bytes, declare an
1142 * MD5Context structure, pass it to MD5Init, call MD5Update as
1143 * needed on buffers full of bytes, and then call MD5Final, which
1144 * will fill a supplied 16-byte array with the digest.
1148 #define byteReverse(buf, len) /* Nothing */
1151 * Note: this code is harmless on little-endian machines.
1153 void byteReverse(unsigned char *buf, unsigned longs)
1157 t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1158 ((unsigned) buf[1] << 8 | buf[0]);
1159 *(FcChar32 *) buf = t;
1166 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
1167 * initialization constants.
1169 static void MD5Init(struct MD5Context *ctx)
1171 ctx->buf[0] = 0x67452301;
1172 ctx->buf[1] = 0xefcdab89;
1173 ctx->buf[2] = 0x98badcfe;
1174 ctx->buf[3] = 0x10325476;
1181 * Update context to reflect the concatenation of another buffer full
1184 static void MD5Update(struct MD5Context *ctx, const unsigned char *buf, unsigned len)
1188 /* Update bitcount */
1191 if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
1192 ctx->bits[1]++; /* Carry from low to high */
1193 ctx->bits[1] += len >> 29;
1195 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
1197 /* Handle any leading odd-sized chunks */
1200 unsigned char *p = (unsigned char *) ctx->in + t;
1204 memcpy(p, buf, len);
1208 byteReverse(ctx->in, 16);
1209 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1213 /* Process data in 64-byte chunks */
1216 memcpy(ctx->in, buf, 64);
1217 byteReverse(ctx->in, 16);
1218 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1223 /* Handle any remaining bytes of data. */
1225 memcpy(ctx->in, buf, len);
1229 * Final wrapup - pad to 64-byte boundary with the bit pattern
1230 * 1 0* (64-bit count of bits processed, MSB-first)
1232 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
1237 /* Compute number of bytes mod 64 */
1238 count = (ctx->bits[0] >> 3) & 0x3F;
1240 /* Set the first char of padding to 0x80. This is safe since there is
1241 always at least one byte free */
1242 p = ctx->in + count;
1245 /* Bytes of padding needed to make 64 bytes */
1246 count = 64 - 1 - count;
1248 /* Pad out to 56 mod 64 */
1250 /* Two lots of padding: Pad the first block to 64 bytes */
1251 memset(p, 0, count);
1252 byteReverse(ctx->in, 16);
1253 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1255 /* Now fill the next block with 56 bytes */
1256 memset(ctx->in, 0, 56);
1258 /* Pad block to 56 bytes */
1259 memset(p, 0, count - 8);
1261 byteReverse(ctx->in, 14);
1263 /* Append length in bits and transform */
1264 ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
1265 ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
1267 MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1268 byteReverse((unsigned char *) ctx->buf, 4);
1269 memcpy(digest, ctx->buf, 16);
1270 memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */
1274 /* The four core functions - F1 is optimized somewhat */
1276 /* #define F1(x, y, z) (x & y | ~x & z) */
1277 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1278 #define F2(x, y, z) F1(z, x, y)
1279 #define F3(x, y, z) (x ^ y ^ z)
1280 #define F4(x, y, z) (y ^ (x | ~z))
1282 /* This is the central step in the MD5 algorithm. */
1283 #define MD5STEP(f, w, x, y, z, data, s) \
1284 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
1287 * The core of the MD5 algorithm, this alters an existing MD5 hash to
1288 * reflect the addition of 16 longwords of new data. MD5Update blocks
1289 * the data and converts bytes into longwords for this routine.
1291 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
1293 register FcChar32 a, b, c, d;
1300 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1301 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1302 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1303 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1304 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1305 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1306 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1307 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1308 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1309 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1310 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1311 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1312 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1313 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1314 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1315 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1317 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1318 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1319 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1320 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1321 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1322 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1323 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1324 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1325 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1326 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1327 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1328 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1329 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1330 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1331 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1332 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1334 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1335 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1336 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1337 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1338 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1339 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1340 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1341 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1342 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1343 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1344 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1345 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1346 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1347 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1348 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1349 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1351 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1352 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1353 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1354 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1355 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1356 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1357 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1358 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1359 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1360 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1361 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1362 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1363 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1364 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1365 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1366 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1375 FcDirCacheCreateTagFile (const FcChar8 *cache_dir)
1381 static const FcChar8 cache_tag_contents[] =
1382 "Signature: 8a477f597d28d172789f06886806bc55\n"
1383 "# This file is a cache directory tag created by fontconfig.\n"
1384 "# For information about cache directory tags, see:\n"
1385 "# http://www.brynosaurus.com/cachedir/\n";
1386 static size_t cache_tag_contents_size = sizeof (cache_tag_contents) - 1;
1387 FcBool ret = FcFalse;
1392 if (access ((char *) cache_dir, W_OK) == 0)
1394 /* Create CACHEDIR.TAG */
1395 cache_tag = FcStrBuildFilename (cache_dir, "CACHEDIR.TAG", NULL);
1398 atomic = FcAtomicCreate ((FcChar8 *)cache_tag);
1401 if (!FcAtomicLock (atomic))
1403 fd = FcOpen((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0644);
1406 fp = fdopen(fd, "wb");
1410 fwrite(cache_tag_contents, cache_tag_contents_size, sizeof (FcChar8), fp);
1413 if (!FcAtomicReplaceOrig(atomic))
1418 FcAtomicUnlock (atomic);
1420 FcAtomicDestroy (atomic);
1422 FcStrFree (cache_tag);
1425 if (FcDebug () & FC_DBG_CACHE)
1428 printf ("Created CACHEDIR.TAG at %s\n", cache_dir);
1430 printf ("Unable to create CACHEDIR.TAG at %s\n", cache_dir);
1437 FcCacheCreateTagFile (const FcConfig *config)
1439 FcChar8 *cache_dir = NULL, *d = NULL;
1441 const FcChar8 *sysroot = FcConfigGetSysRoot (config);
1443 list = FcConfigGetCacheDirs (config);
1447 while ((cache_dir = FcStrListNext (list)))
1452 d = FcStrBuildFilename (sysroot, cache_dir, NULL);
1454 d = FcStrCopyFilename (cache_dir);
1455 if (FcDirCacheCreateTagFile (d))
1460 FcStrListDone (list);
1464 #include "fcaliastail.h"