Leave cache files mapped permanently.
[platform/upstream/fontconfig.git] / src / fccache.c
1 /*
2  * Copyright © 2000 Keith Packard
3  * Copyright © 2005 Patrick Lam
4  *
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 Keith Packard not be used in
10  * advertising or publicity pertaining to distribution of the software without
11  * specific, written prior permission.  Keith Packard makes no
12  * representations about the suitability of this software for any purpose.  It
13  * is provided "as is" without express or implied warranty.
14  *
15  * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
16  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
17  * EVENT SHALL KEITH PACKARD 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.
22  */
23
24 #include "fcint.h"
25 #include "../fc-arch/fcarch.h"
26 #include <stdio.h>
27 #include <fcntl.h>
28 #include <dirent.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
32 #  include <unistd.h>
33 #  include <sys/mman.h>
34 #elif defined(_WIN32)
35 #  include <windows.h>
36 #endif
37
38 #ifndef O_BINARY
39 #define O_BINARY 0
40 #endif
41
42 struct MD5Context {
43         FcChar32 buf[4];
44         FcChar32 bits[2];
45         unsigned char in[64];
46 };
47
48 static void MD5Init(struct MD5Context *ctx);
49 static void MD5Update(struct MD5Context *ctx, unsigned char *buf, unsigned len);
50 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx);
51 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16]);
52
53 #define CACHEBASE_LEN (1 + 32 + 1 + sizeof (FC_ARCHITECTURE) + sizeof (FC_CACHE_SUFFIX))
54
55 static const char bin2hex[] = { '0', '1', '2', '3',
56                                 '4', '5', '6', '7',
57                                 '8', '9', 'a', 'b',
58                                 'c', 'd', 'e', 'f' };
59
60 static FcChar8 *
61 FcDirCacheBasename (const FcChar8 * dir, FcChar8 cache_base[CACHEBASE_LEN])
62 {
63     unsigned char       hash[16];
64     FcChar8             *hex_hash;
65     int                 cnt;
66     struct MD5Context   ctx;
67
68     MD5Init (&ctx);
69     MD5Update (&ctx, (unsigned char *)dir, strlen ((char *) dir));
70
71     MD5Final (hash, &ctx);
72
73     cache_base[0] = '/';
74     hex_hash = cache_base + 1;
75     for (cnt = 0; cnt < 16; ++cnt)
76     {
77         hex_hash[2*cnt  ] = bin2hex[hash[cnt] >> 4];
78         hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
79     }
80     hex_hash[2*cnt] = 0;
81     strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
82
83     return cache_base;
84 }
85
86 FcBool
87 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
88 {
89     FcChar8     *cache_hashed = NULL;
90     FcChar8     cache_base[CACHEBASE_LEN];
91     FcStrList   *list;
92     FcChar8     *cache_dir;
93
94     FcDirCacheBasename (dir, cache_base);
95
96     list = FcStrListCreate (config->cacheDirs);
97     if (!list)
98         return FcFalse;
99         
100     while ((cache_dir = FcStrListNext (list)))
101     {
102         cache_hashed = FcStrPlus (cache_dir, cache_base);
103         if (!cache_hashed)
104             break;
105         (void) unlink ((char *) cache_hashed);
106     }
107     FcStrListDone (list);
108     /* return FcFalse if something went wrong */
109     if (cache_dir)
110         return FcFalse;
111     return FcTrue;
112 }
113
114 static int
115 FcDirCacheOpenFile (const FcChar8 *cache_file, struct stat *file_stat)
116 {
117     int fd;
118
119     fd = open((char *) cache_file, O_RDONLY | O_BINARY);
120     if (fd < 0)
121         return fd;
122     if (fstat (fd, file_stat) < 0)
123     {
124         close (fd);
125         return -1;
126     }
127     return fd;
128 }
129
130 /* 
131  * Look for a cache file for the specified dir. Attempt
132  * to use each one we find, stopping when the callback
133  * indicates success
134  */
135 static FcBool
136 FcDirCacheProcess (FcConfig *config, const FcChar8 *dir, 
137                    FcBool (*callback) (int fd, struct stat *stat, void *closure),
138                    void *closure, FcChar8 **cache_file_ret)
139 {
140     int         fd = -1;
141     FcChar8     cache_base[CACHEBASE_LEN];
142     FcStrList   *list;
143     FcChar8     *cache_dir;
144     struct stat file_stat, dir_stat;
145     FcBool      ret = FcFalse;
146
147     if (stat ((char *) dir, &dir_stat) < 0)
148         return FcFalse;
149
150     FcDirCacheBasename (dir, cache_base);
151
152     list = FcStrListCreate (config->cacheDirs);
153     if (!list)
154         return FcFalse;
155         
156     while ((cache_dir = FcStrListNext (list)))
157     {
158         FcChar8 *cache_hashed = FcStrPlus (cache_dir, cache_base);
159         if (!cache_hashed)
160             break;
161         fd = FcDirCacheOpenFile (cache_hashed, &file_stat);
162         if (fd >= 0) {
163             if (dir_stat.st_mtime <= file_stat.st_mtime)
164             {
165                 ret = (*callback) (fd, &file_stat, closure);
166                 if (ret)
167                 {
168                     if (cache_file_ret)
169                         *cache_file_ret = cache_hashed;
170                     else
171                         FcStrFree (cache_hashed);
172                     close (fd);
173                     break;
174                 }
175             }
176             close (fd);
177         }
178         FcStrFree (cache_hashed);
179     }
180     FcStrListDone (list);
181     
182     return ret;
183 }
184
185 static void
186 FcDirCacheDispose (FcCache *cache)
187 {
188     switch (cache->magic) {
189     case FC_CACHE_MAGIC_ALLOC:
190         free (cache);
191         break;
192     case FC_CACHE_MAGIC_MMAP:
193 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
194         munmap (cache, cache->size);
195 #elif defined(_WIN32)
196         UnmapViewOfFile (cache);
197 #endif
198         break;
199     }
200 }
201
202 #define FC_CACHE_MIN_MMAP   1024
203
204 #define FC_CACHE_HASH_SIZE  67
205
206 typedef struct _FcCacheBucket FcCacheBucket;
207
208 struct _FcCacheBucket {
209     FcCacheBucket   *next;
210     FcCache         *cache;
211     dev_t           cache_dev;
212     ino_t           cache_ino;
213     time_t          cache_mtime;
214 };
215
216 static FcCacheBucket    *FcCacheBuckets[FC_CACHE_HASH_SIZE];
217
218 static uint32_t
219 FcCacheStatHash (struct stat *cache_stat)
220 {
221     return ((uint32_t) cache_stat->st_dev ^
222             (uint32_t) cache_stat->st_ino ^
223             (uint32_t) cache_stat->st_mtime);
224 }
225
226 static FcCache *
227 FcCacheLookup (struct stat *cache_stat)
228 {
229     uint32_t        hash = FcCacheStatHash(cache_stat);
230     FcCacheBucket   **bucket = &FcCacheBuckets[hash % FC_CACHE_HASH_SIZE];
231     FcCacheBucket   *b;
232
233     for (b = *bucket; b; b = b->next)
234         if (b->cache_dev == cache_stat->st_dev &&
235             b->cache_ino == cache_stat->st_ino &&
236             b->cache_mtime == cache_stat->st_mtime)
237             return b->cache;
238     return NULL;
239 }
240
241 static FcBool
242 FcCacheRecord (FcCache *cache, struct stat *cache_stat)
243 {
244     uint32_t        hash = FcCacheStatHash(cache_stat);
245     FcCacheBucket   **bucket = &FcCacheBuckets[hash % FC_CACHE_HASH_SIZE];
246     FcCacheBucket   *b;
247
248     b = malloc (sizeof (FcCacheBucket));
249     if (!b)
250         return FcFalse;
251     b->next = *bucket;
252     b->cache = cache;
253     b->cache_dev = cache_stat->st_dev;
254     b->cache_ino = cache_stat->st_ino;
255     b->cache_mtime = cache_stat->st_mtime;
256     *bucket = b;
257     return FcTrue;
258 }
259
260 void
261 FcCacheFini (void)
262 {
263     int             i;
264     FcCacheBucket   *b, *next;
265
266     for (i = 0; i < FC_CACHE_HASH_SIZE; i++)
267     {
268         for (b = FcCacheBuckets[i]; b; b = next)
269         {
270             next = b->next;
271             FcDirCacheDispose (b->cache);
272             free (b);
273         }
274         FcCacheBuckets[i] = NULL;
275     }
276 }
277
278 /*
279  * Map a cache file into memory
280  */
281 static FcCache *
282 FcDirCacheMapFd (int fd, struct stat *fd_stat)
283 {
284     FcCache     *cache;
285     FcBool      allocated = FcFalse;
286
287     if (fd_stat->st_size < sizeof (FcCache))
288         return NULL;
289     cache = FcCacheLookup (fd_stat);
290     if (cache)
291         return cache;
292     /*
293      * For small cache files, just read them into memory
294      */
295     if (fd_stat->st_size >= FC_CACHE_MIN_MMAP)
296     {
297 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
298         cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
299 #elif defined(_WIN32)
300         {
301             HANDLE hFileMap;
302
303             cache = NULL;
304             hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
305                                          PAGE_READONLY, 0, 0, NULL);
306             if (hFileMap != NULL)
307             {
308                 cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0, size);
309                 CloseHandle (hFileMap);
310             }
311         }
312 #endif
313     }
314     if (!cache)
315     {
316         cache = malloc (fd_stat->st_size);
317         if (!cache)
318             return NULL;
319
320         if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
321         {
322             free (cache);
323             return NULL;
324         }
325         allocated = FcTrue;
326     } 
327     if (cache->magic != FC_CACHE_MAGIC_MMAP || 
328         cache->version < FC_CACHE_CONTENT_VERSION ||
329         cache->size != fd_stat->st_size ||
330         !FcCacheRecord (cache, fd_stat))
331     {
332         if (allocated)
333             free (cache);
334         else
335         {
336 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
337             munmap (cache, fd_stat->st_size);
338 #elif defined(_WIN32)
339             UnmapViewOfFile (cache);
340 #endif
341         }
342         return NULL;
343     }
344
345     /* Mark allocated caches so they're freed rather than unmapped */
346     if (allocated)
347         cache->magic = FC_CACHE_MAGIC_ALLOC;
348         
349     return cache;
350 }
351
352 void
353 FcDirCacheUnload (FcCache *cache)
354 {
355     /* Can't free or unmap the cache as apps may point into it */
356 }
357
358 static FcBool
359 FcDirCacheMapHelper (int fd, struct stat *fd_stat, void *closure)
360 {
361     FcCache *cache = FcDirCacheMapFd (fd, fd_stat);
362
363     if (!cache)
364         return FcFalse;
365     *((FcCache **) closure) = cache;
366     return FcTrue;
367 }
368
369 FcCache *
370 FcDirCacheLoad (const FcChar8 *dir, FcConfig *config, FcChar8 **cache_file)
371 {
372     FcCache *cache = NULL;
373
374     if (!FcDirCacheProcess (config, dir,
375                             FcDirCacheMapHelper,
376                             &cache, cache_file))
377         return NULL;
378     return cache;
379 }
380
381 FcCache *
382 FcDirCacheLoadFile (const FcChar8 *cache_file, struct stat *file_stat)
383 {
384     int fd;
385     FcCache *cache;
386
387     fd = FcDirCacheOpenFile (cache_file, file_stat);
388     if (fd < 0)
389         return NULL;
390     cache = FcDirCacheMapFd (fd, file_stat);
391     close (fd);
392     return cache;
393 }
394
395 /*
396  * Validate a cache file by reading the header and checking
397  * the magic number and the size field
398  */
399 static FcBool
400 FcDirCacheValidateHelper (int fd, struct stat *fd_stat, void *closure)
401 {
402     FcBool  ret = FcTrue;
403     FcCache     c;
404     
405     if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
406         ret = FcFalse;
407     else if (c.magic != FC_CACHE_MAGIC_MMAP)
408         ret = FcFalse;
409     else if (c.version < FC_CACHE_CONTENT_VERSION)
410         ret = FcFalse;
411     else if (fd_stat->st_size != c.size)
412         ret = FcFalse;
413     return ret;
414 }
415
416 static FcBool
417 FcDirCacheValidConfig (const FcChar8 *dir, FcConfig *config)
418 {
419     return FcDirCacheProcess (config, dir, 
420                               FcDirCacheValidateHelper,
421                               NULL, NULL);
422 }
423
424 FcBool
425 FcDirCacheValid (const FcChar8 *dir)
426 {
427     FcConfig    *config;
428     
429     config = FcConfigGetCurrent ();
430     if (!config)
431         return FcFalse;
432
433     return FcDirCacheValidConfig (dir, config);
434 }
435
436 /*
437  * Build a cache structure from the given contents
438  */
439 FcCache *
440 FcDirCacheBuild (FcFontSet *set, const FcChar8 *dir, FcStrSet *dirs)
441 {
442     FcSerialize *serialize = FcSerializeCreate ();
443     FcCache *cache;
444     int i;
445     intptr_t    cache_offset;
446     intptr_t    dirs_offset;
447     FcChar8     *dir_serialize;
448     intptr_t    *dirs_serialize;
449     FcFontSet   *set_serialize;
450     
451     if (!serialize)
452         return NULL;
453     /*
454      * Space for cache structure
455      */
456     cache_offset = FcSerializeReserve (serialize, sizeof (FcCache));
457     /*
458      * Directory name
459      */
460     if (!FcStrSerializeAlloc (serialize, dir))
461         goto bail1;
462     /*
463      * Subdirs
464      */
465     dirs_offset = FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
466     for (i = 0; i < dirs->num; i++)
467         if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
468             goto bail1;
469
470     /*
471      * Patterns
472      */
473     if (!FcFontSetSerializeAlloc (serialize, set))
474         goto bail1;
475     
476     /* Serialize layout complete. Now allocate space and fill it */
477     cache = malloc (serialize->size);
478     if (!cache)
479         goto bail1;
480     /* shut up valgrind */
481     memset (cache, 0, serialize->size);
482
483     serialize->linear = cache;
484
485     cache->magic = FC_CACHE_MAGIC_ALLOC;
486     cache->version = FC_CACHE_CONTENT_VERSION;
487     cache->size = serialize->size;
488
489     /*
490      * Serialize directory name
491      */
492     dir_serialize = FcStrSerialize (serialize, dir);
493     if (!dir_serialize)
494         goto bail2;
495     cache->dir = FcPtrToOffset (cache, dir_serialize);
496     
497     /*
498      * Serialize sub dirs
499      */
500     dirs_serialize = FcSerializePtr (serialize, dirs);
501     if (!dirs_serialize)
502         goto bail2;
503     cache->dirs = FcPtrToOffset (cache, dirs_serialize);
504     cache->dirs_count = dirs->num;
505     for (i = 0; i < dirs->num; i++) 
506     {
507         FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
508         if (!d_serialize)
509             goto bail2;
510         dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
511     }
512     
513     /*
514      * Serialize font set
515      */
516     set_serialize = FcFontSetSerialize (serialize, set);
517     if (!set_serialize)
518         goto bail2;
519     cache->set = FcPtrToOffset (cache, set_serialize);
520
521     FcSerializeDestroy (serialize);
522     
523     return cache;
524
525 bail2:
526     free (cache);
527 bail1:
528     FcSerializeDestroy (serialize);
529     return NULL;
530 }
531
532 static FcBool
533 FcMakeDirectory (const FcChar8 *dir)
534 {
535     FcChar8 *parent;
536     FcBool  ret;
537     
538     if (strlen ((char *) dir) == 0)
539         return FcFalse;
540     
541     parent = FcStrDirname (dir);
542     if (!parent)
543         return FcFalse;
544     if (access ((char *) parent, W_OK|X_OK) == 0)
545         ret = mkdir ((char *) dir, 0777) == 0;
546     else if (access ((char *) parent, F_OK) == -1)
547         ret = FcMakeDirectory (parent) && (mkdir ((char *) dir, 0777) == 0);
548     else
549         ret = FcFalse;
550     FcStrFree (parent);
551     return ret;
552 }
553
554 /* write serialized state to the cache file */
555 FcBool
556 FcDirCacheWrite (FcCache *cache, FcConfig *config)
557 {
558     FcChar8         *dir = FcCacheDir (cache);
559     FcChar8         cache_base[CACHEBASE_LEN];
560     FcChar8         *cache_hashed;
561     int             fd;
562     FcAtomic        *atomic;
563     FcStrList       *list;
564     FcChar8         *cache_dir = NULL;
565     FcChar8         *test_dir;
566     int             magic;
567     int             written;
568
569     /*
570      * Write it to the first directory in the list which is writable
571      */
572     
573     list = FcStrListCreate (config->cacheDirs);
574     if (!list)
575         return FcFalse;
576     while ((test_dir = FcStrListNext (list))) {
577         if (access ((char *) test_dir, W_OK|X_OK) == 0)
578         {
579             cache_dir = test_dir;
580             break;
581         }
582         else
583         {
584             /*
585              * If the directory doesn't exist, try to create it
586              */
587             if (access ((char *) test_dir, F_OK) == -1) {
588                 if (FcMakeDirectory (test_dir))
589                 {
590                     cache_dir = test_dir;
591                     break;
592                 }
593             }
594         }
595     }
596     FcStrListDone (list);
597     if (!cache_dir)
598         return FcFalse;
599
600     FcDirCacheBasename (dir, cache_base);
601     cache_hashed = FcStrPlus (cache_dir, cache_base);
602     if (!cache_hashed)
603         return FcFalse;
604
605     if (FcDebug () & FC_DBG_CACHE)
606         printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
607                 dir, cache_hashed);
608
609     atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
610     if (!atomic)
611         goto bail1;
612
613     if (!FcAtomicLock (atomic))
614         goto bail3;
615
616     fd = open((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
617     if (fd == -1)
618         goto bail4;
619     
620     /* Temporarily switch magic to MMAP while writing to file */
621     magic = cache->magic;
622     if (magic != FC_CACHE_MAGIC_MMAP)
623         cache->magic = FC_CACHE_MAGIC_MMAP;
624     
625     /*
626      * Write cache contents to file
627      */
628     written = write (fd, cache, cache->size);
629     
630     /* Switch magic back */
631     if (magic != FC_CACHE_MAGIC_MMAP)
632         cache->magic = magic;
633     
634     if (written != cache->size)
635     {
636         perror ("write cache");
637         goto bail5;
638     }
639
640     close(fd);
641     if (!FcAtomicReplaceOrig(atomic))
642         goto bail4;
643     FcStrFree (cache_hashed);
644     FcAtomicUnlock (atomic);
645     FcAtomicDestroy (atomic);
646     return FcTrue;
647
648  bail5:
649     close (fd);
650  bail4:
651     FcAtomicUnlock (atomic);
652  bail3:
653     FcAtomicDestroy (atomic);
654  bail1:
655     FcStrFree (cache_hashed);
656     return FcFalse;
657 }
658
659 /*
660  * Hokey little macro trick to permit the definitions of C functions
661  * with the same name as CPP macros
662  */
663 #define args(x...)          (x)
664
665 const FcChar8 *
666 FcCacheDir args(const FcCache *c)
667 {
668     return FcCacheDir (c);
669 }
670
671 FcFontSet *
672 FcCacheCopySet args(const FcCache *c)
673 {
674     FcFontSet   *old = FcCacheSet (c);
675     FcFontSet   *new = FcFontSetCreate ();
676     int         i;
677     
678     if (!new)
679         return NULL;
680     for (i = 0; i < old->nfont; i++)
681         if (!FcFontSetAdd (new, FcFontSetFont (old, i)))
682         {
683             FcFontSetDestroy (new);
684             return NULL;
685         }
686     return new;
687 }
688
689 const FcChar8 *
690 FcCacheSubdir args(const FcCache *c, int i)
691 {
692     return FcCacheSubdir (c, i);
693 }
694
695 int
696 FcCacheNumSubdir args(const FcCache *c)
697 {
698     return c->dirs_count;
699 }
700
701 int
702 FcCacheNumFont args(const FcCache *c)
703 {
704     return FcCacheSet(c)->nfont;
705 }
706
707 /*
708  * This code implements the MD5 message-digest algorithm.
709  * The algorithm is due to Ron Rivest.  This code was
710  * written by Colin Plumb in 1993, no copyright is claimed.
711  * This code is in the public domain; do with it what you wish.
712  *
713  * Equivalent code is available from RSA Data Security, Inc.
714  * This code has been tested against that, and is equivalent,
715  * except that you don't need to include two pages of legalese
716  * with every copy.
717  *
718  * To compute the message digest of a chunk of bytes, declare an
719  * MD5Context structure, pass it to MD5Init, call MD5Update as
720  * needed on buffers full of bytes, and then call MD5Final, which
721  * will fill a supplied 16-byte array with the digest.
722  */
723
724 #ifndef HIGHFIRST
725 #define byteReverse(buf, len)   /* Nothing */
726 #else
727 /*
728  * Note: this code is harmless on little-endian machines.
729  */
730 void byteReverse(unsigned char *buf, unsigned longs)
731 {
732     FcChar32 t;
733     do {
734         t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
735             ((unsigned) buf[1] << 8 | buf[0]);
736         *(FcChar32 *) buf = t;
737         buf += 4;
738     } while (--longs);
739 }
740 #endif
741
742 /*
743  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
744  * initialization constants.
745  */
746 static void MD5Init(struct MD5Context *ctx)
747 {
748     ctx->buf[0] = 0x67452301;
749     ctx->buf[1] = 0xefcdab89;
750     ctx->buf[2] = 0x98badcfe;
751     ctx->buf[3] = 0x10325476;
752
753     ctx->bits[0] = 0;
754     ctx->bits[1] = 0;
755 }
756
757 /*
758  * Update context to reflect the concatenation of another buffer full
759  * of bytes.
760  */
761 static void MD5Update(struct MD5Context *ctx, unsigned char *buf, unsigned len)
762 {
763     FcChar32 t;
764
765     /* Update bitcount */
766
767     t = ctx->bits[0];
768     if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
769         ctx->bits[1]++;         /* Carry from low to high */
770     ctx->bits[1] += len >> 29;
771
772     t = (t >> 3) & 0x3f;        /* Bytes already in shsInfo->data */
773
774     /* Handle any leading odd-sized chunks */
775
776     if (t) {
777         unsigned char *p = (unsigned char *) ctx->in + t;
778
779         t = 64 - t;
780         if (len < t) {
781             memcpy(p, buf, len);
782             return;
783         }
784         memcpy(p, buf, t);
785         byteReverse(ctx->in, 16);
786         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
787         buf += t;
788         len -= t;
789     }
790     /* Process data in 64-byte chunks */
791
792     while (len >= 64) {
793         memcpy(ctx->in, buf, 64);
794         byteReverse(ctx->in, 16);
795         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
796         buf += 64;
797         len -= 64;
798     }
799
800     /* Handle any remaining bytes of data. */
801
802     memcpy(ctx->in, buf, len);
803 }
804
805 /*
806  * Final wrapup - pad to 64-byte boundary with the bit pattern 
807  * 1 0* (64-bit count of bits processed, MSB-first)
808  */
809 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
810 {
811     unsigned count;
812     unsigned char *p;
813
814     /* Compute number of bytes mod 64 */
815     count = (ctx->bits[0] >> 3) & 0x3F;
816
817     /* Set the first char of padding to 0x80.  This is safe since there is
818        always at least one byte free */
819     p = ctx->in + count;
820     *p++ = 0x80;
821
822     /* Bytes of padding needed to make 64 bytes */
823     count = 64 - 1 - count;
824
825     /* Pad out to 56 mod 64 */
826     if (count < 8) {
827         /* Two lots of padding:  Pad the first block to 64 bytes */
828         memset(p, 0, count);
829         byteReverse(ctx->in, 16);
830         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
831
832         /* Now fill the next block with 56 bytes */
833         memset(ctx->in, 0, 56);
834     } else {
835         /* Pad block to 56 bytes */
836         memset(p, 0, count - 8);
837     }
838     byteReverse(ctx->in, 14);
839
840     /* Append length in bits and transform */
841     ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
842     ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
843
844     MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
845     byteReverse((unsigned char *) ctx->buf, 4);
846     memcpy(digest, ctx->buf, 16);
847     memset(ctx, 0, sizeof(ctx));        /* In case it's sensitive */
848 }
849
850
851 /* The four core functions - F1 is optimized somewhat */
852
853 /* #define F1(x, y, z) (x & y | ~x & z) */
854 #define F1(x, y, z) (z ^ (x & (y ^ z)))
855 #define F2(x, y, z) F1(z, x, y)
856 #define F3(x, y, z) (x ^ y ^ z)
857 #define F4(x, y, z) (y ^ (x | ~z))
858
859 /* This is the central step in the MD5 algorithm. */
860 #define MD5STEP(f, w, x, y, z, data, s) \
861         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
862
863 /*
864  * The core of the MD5 algorithm, this alters an existing MD5 hash to
865  * reflect the addition of 16 longwords of new data.  MD5Update blocks
866  * the data and converts bytes into longwords for this routine.
867  */
868 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
869 {
870     register FcChar32 a, b, c, d;
871
872     a = buf[0];
873     b = buf[1];
874     c = buf[2];
875     d = buf[3];
876
877     MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
878     MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
879     MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
880     MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
881     MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
882     MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
883     MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
884     MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
885     MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
886     MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
887     MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
888     MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
889     MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
890     MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
891     MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
892     MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
893
894     MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
895     MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
896     MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
897     MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
898     MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
899     MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
900     MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
901     MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
902     MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
903     MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
904     MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
905     MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
906     MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
907     MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
908     MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
909     MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
910
911     MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
912     MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
913     MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
914     MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
915     MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
916     MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
917     MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
918     MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
919     MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
920     MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
921     MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
922     MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
923     MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
924     MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
925     MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
926     MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
927
928     MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
929     MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
930     MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
931     MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
932     MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
933     MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
934     MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
935     MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
936     MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
937     MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
938     MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
939     MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
940     MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
941     MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
942     MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
943     MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
944
945     buf[0] += a;
946     buf[1] += b;
947     buf[2] += c;
948     buf[3] += d;
949 }