source: trunk/src/kObjCache/kObjCache.c@ 1084

Last change on this file since 1084 was 1055, checked in by bird, 18 years ago

_mkdir is in direct.h.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 115.9 KB
Line 
1/* $Id: kObjCache.c 1055 2007-06-11 09:35:21Z bird $ */
2/** @file
3 *
4 * kObjCache - Object Cache.
5 *
6 * Copyright (c) 2007 knut st. osmundsen <bird-src-spam@anduin.net>
7 *
8 *
9 * This file is part of kBuild.
10 *
11 * kBuild is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * kBuild is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with kBuild; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 *
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#if 0
32# define ELECTRIC_HEAP
33# include "../kmk/electric.h"
34#endif
35#include <string.h>
36#include <stdlib.h>
37#include <stdarg.h>
38#include <stdio.h>
39#include <errno.h>
40#include <assert.h>
41#include <sys/stat.h>
42#include <fcntl.h>
43#include <limits.h>
44#include <ctype.h>
45#ifndef PATH_MAX
46# define PATH_MAX _MAX_PATH /* windows */
47#endif
48#if defined(__OS2__) || defined(__WIN__)
49# include <process.h>
50# include <io.h>
51# ifdef __OS2__
52# include <unistd.h>
53# endif
54# if defined(_MSC_VER)
55# include <direct.h>
56 typedef intptr_t pid_t;
57# endif
58#else
59# include <unistd.h>
60# include <sys/wait.h>
61# ifndef O_BINARY
62# define O_BINARY 0
63# endif
64#endif
65#if defined(__WIN__)
66# include <Windows.h>
67#endif
68
69#include "crc32.h"
70#include "md5.h"
71
72
73/*******************************************************************************
74* Defined Constants And Macros *
75*******************************************************************************/
76/** The max line length in a cache file. */
77#define KOBJCACHE_MAX_LINE_LEN 16384
78#if defined(__WIN__)
79# define PATH_SLASH '\\'
80#else
81# define PATH_SLASH '/'
82#endif
83#if defined(__OS2__) || defined(__WIN__)
84# define IS_SLASH(ch) ((ch) == '/' || (ch) == '\\')
85# define IS_SLASH_DRV(ch) ((ch) == '/' || (ch) == '\\' || (ch) == ':')
86#else
87# define IS_SLASH(ch) ((ch) == '/')
88# define IS_SLASH_DRV(ch) ((ch) == '/')
89#endif
90
91#ifndef STDIN_FILENO
92# define STDIN_FILENO 0
93#endif
94#ifndef STDOUT_FILENO
95# define STDOUT_FILENO 1
96#endif
97#ifndef STDERR_FILENO
98# define STDERR_FILENO 2
99#endif
100
101
102/*******************************************************************************
103* Global Variables *
104*******************************************************************************/
105/** Whether verbose output is enabled. */
106static unsigned g_cVerbosityLevel = 0;
107/** What to prefix the errors with. */
108static char g_szErrorPrefix[128];
109
110/** Read buffer shared by the cache components. */
111static char g_szLine[KOBJCACHE_MAX_LINE_LEN + 16];
112
113
114/*******************************************************************************
115* Internal Functions *
116*******************************************************************************/
117static char *MakePathFromDirAndFile(const char *pszName, const char *pszDir);
118static char *CalcRelativeName(const char *pszPath, const char *pszDir);
119static FILE *FOpenFileInDir(const char *pszName, const char *pszDir, const char *pszMode);
120static int UnlinkFileInDir(const char *pszName, const char *pszDir);
121static int RenameFileInDir(const char *pszOldName, const char *pszNewName, const char *pszDir);
122static int DoesFileInDirExist(const char *pszName, const char *pszDir);
123static void *ReadFileInDir(const char *pszName, const char *pszDir, size_t *pcbFile);
124
125
126void FatalMsg(const char *pszFormat, ...)
127{
128 va_list va;
129
130 if (g_szErrorPrefix[0])
131 fprintf(stderr, "%s - fatal error: ", g_szErrorPrefix);
132 else
133 fprintf(stderr, "fatal error: ");
134
135 va_start(va, pszFormat);
136 vfprintf(stderr, pszFormat, va);
137 va_end(va);
138}
139
140
141void FatalDie(const char *pszFormat, ...)
142{
143 va_list va;
144
145 if (g_szErrorPrefix[0])
146 fprintf(stderr, "%s - fatal error: ", g_szErrorPrefix);
147 else
148 fprintf(stderr, "fatal error: ");
149
150 va_start(va, pszFormat);
151 vfprintf(stderr, pszFormat, va);
152 va_end(va);
153
154 exit(1);
155}
156
157
158static void ErrorMsg(const char *pszFormat, ...)
159{
160 va_list va;
161
162 if (g_szErrorPrefix[0])
163 fprintf(stderr, "%s - error: ", g_szErrorPrefix);
164 else
165 fprintf(stderr, "error: ");
166
167 va_start(va, pszFormat);
168 vfprintf(stderr, pszFormat, va);
169 va_end(va);
170}
171
172
173static void InfoMsg(unsigned uLevel, const char *pszFormat, ...)
174{
175 if (uLevel <= g_cVerbosityLevel)
176 {
177 va_list va;
178
179 if (g_szErrorPrefix[0])
180 fprintf(stderr, "%s - info: ", g_szErrorPrefix);
181 else
182 fprintf(stderr, "info: ");
183
184 va_start(va, pszFormat);
185 vfprintf(stderr, pszFormat, va);
186 va_end(va);
187 }
188}
189
190
191static void SetErrorPrefix(const char *pszPrefix, ...)
192{
193 int cch;
194 va_list va;
195
196 va_start(va, pszPrefix);
197#if defined(_MSC_VER) || defined(__sun__)
198 cch = vsprintf(g_szErrorPrefix, pszPrefix, va);
199 if (cch >= sizeof(g_szErrorPrefix))
200 FatalDie("Buffer overflow setting error prefix!\n");
201#else
202 vsnprintf(g_szErrorPrefix, sizeof(g_szErrorPrefix), pszPrefix, va);
203#endif
204 va_end(va);
205 (void)cch;
206}
207
208#ifndef ELECTRIC_HEAP
209void *xmalloc(size_t cb)
210{
211 void *pv = malloc(cb);
212 if (!pv)
213 FatalDie("out of memory (%d)\n", (int)cb);
214 return pv;
215}
216
217
218void *xrealloc(void *pvOld, size_t cb)
219{
220 void *pv = realloc(pvOld, cb);
221 if (!pv)
222 FatalDie("out of memory (%d)\n", (int)cb);
223 return pv;
224}
225
226
227char *xstrdup(const char *pszIn)
228{
229 char *psz = strdup(pszIn);
230 if (!psz)
231 FatalDie("out of memory (%d)\n", (int)strlen(pszIn));
232 return psz;
233}
234#endif
235
236
237void *xmallocz(size_t cb)
238{
239 void *pv = xmalloc(cb);
240 memset(pv, 0, cb);
241 return pv;
242}
243
244
245
246
247
248/**
249 * Gets the absolute path
250 *
251 * @returns A new heap buffer containing the absolute path.
252 * @param pszPath The path to make absolute. (Readonly)
253 */
254static char *AbsPath(const char *pszPath)
255{
256 char szTmp[PATH_MAX];
257#if defined(__OS2__) || defined(__WIN__)
258 if (!_fullpath(szTmp, *pszPath ? pszPath : ".", sizeof(szTmp)))
259 return xstrdup(pszPath);
260#else
261 if (!realpath(pszPath, szTmp))
262 return xstrdup(pszPath);
263#endif
264 return xstrdup(szTmp);
265}
266
267
268/**
269 * Utility function that finds the filename part in a path.
270 *
271 * @returns Pointer to the file name part (this may be "").
272 * @param pszPath The path to parse.
273 */
274static const char *FindFilenameInPath(const char *pszPath)
275{
276 const char *pszFilename = strchr(pszPath, '\0') - 1;
277 while ( pszFilename > pszPath
278 && !IS_SLASH_DRV(pszFilename[-1]))
279 pszFilename--;
280 return pszFilename;
281}
282
283
284/**
285 * Utility function that combines a filename and a directory into a path.
286 *
287 * @returns malloced buffer containing the result.
288 * @param pszName The file name.
289 * @param pszDir The directory path.
290 */
291static char *MakePathFromDirAndFile(const char *pszName, const char *pszDir)
292{
293 size_t cchName = strlen(pszName);
294 size_t cchDir = strlen(pszDir);
295 char *pszBuf = xmalloc(cchName + cchDir + 2);
296 memcpy(pszBuf, pszDir, cchDir);
297 if (cchDir > 0 && !IS_SLASH_DRV(pszDir[cchDir - 1]))
298 pszBuf[cchDir++] = PATH_SLASH;
299 memcpy(pszBuf + cchDir, pszName, cchName + 1);
300 return pszBuf;
301}
302
303
304/**
305 * Compares two path strings to see if they are identical.
306 *
307 * This doesn't do anything fancy, just the case ignoring and
308 * slash unification.
309 *
310 * @returns 1 if equal, 0 otherwise.
311 * @param pszPath1 The first path.
312 * @param pszPath2 The second path.
313 * @param cch The number of characters to compare.
314 */
315static int ArePathsIdentical(const char *pszPath1, const char *pszPath2, size_t cch)
316{
317#if defined(__OS2__) || defined(__WIN__)
318 if (strnicmp(pszPath1, pszPath2, cch))
319 {
320 /* Slashes may differ, compare char by char. */
321 const char *psz1 = pszPath1;
322 const char *psz2 = pszPath2;
323 for (;cch; psz1++, psz2++, cch--)
324 {
325 if (*psz1 != *psz2)
326 {
327 if ( tolower(*psz1) != tolower(*psz2)
328 && toupper(*psz1) != toupper(*psz2)
329 && *psz1 != '/'
330 && *psz1 != '\\'
331 && *psz2 != '/'
332 && *psz2 != '\\')
333 return 0;
334 }
335 }
336 }
337 return 1;
338#else
339 return !strncmp(pszPath1, pszPath2, cch);
340#endif
341}
342
343
344/**
345 * Calculate how to get to pszPath from pszDir.
346 *
347 * @returns The relative path from pszDir to path pszPath.
348 * @param pszPath The path to the object.
349 * @param pszDir The directory it shall be relative to.
350 */
351static char *CalcRelativeName(const char *pszPath, const char *pszDir)
352{
353 char *pszRet = NULL;
354 char *pszAbsPath = NULL;
355 size_t cchDir = strlen(pszDir);
356
357 /*
358 * This is indeed a bit tricky, so we'll try the easy way first...
359 */
360 if (ArePathsIdentical(pszPath, pszDir, cchDir))
361 {
362 if (pszPath[cchDir])
363 pszRet = (char *)pszPath + cchDir;
364 else
365 pszRet = "./";
366 }
367 else
368 {
369 pszAbsPath = AbsPath(pszPath);
370 if (ArePathsIdentical(pszAbsPath, pszDir, cchDir))
371 {
372 if (pszPath[cchDir])
373 pszRet = pszAbsPath + cchDir;
374 else
375 pszRet = "./";
376 }
377 }
378 if (pszRet)
379 {
380 while (IS_SLASH_DRV(*pszRet))
381 pszRet++;
382 pszRet = xstrdup(pszRet);
383 free(pszAbsPath);
384 return pszRet;
385 }
386
387 /*
388 * Damn, it's gonna be complicated. Deal with that later.
389 */
390 FatalDie("complicated relative path stuff isn't implemented yet. sorry.\n");
391 return NULL;
392}
393
394
395/**
396 * Utility function that combines a filename and directory and passes it onto fopen.
397 *
398 * @returns fopen return value.
399 * @param pszName The file name.
400 * @param pszDir The directory path.
401 * @param pszMode The fopen mode string.
402 */
403static FILE *FOpenFileInDir(const char *pszName, const char *pszDir, const char *pszMode)
404{
405 char *pszPath = MakePathFromDirAndFile(pszName, pszDir);
406 FILE *pFile = fopen(pszPath, pszMode);
407 free(pszPath);
408 return pFile;
409}
410
411
412/**
413 * Utility function that combines a filename and directory and passes it onto open.
414 *
415 * @returns open return value.
416 * @param pszName The file name.
417 * @param pszDir The directory path.
418 * @param fFlags The open flags.
419 * @param fCreateMode The file creation mode.
420 */
421static int OpenFileInDir(const char *pszName, const char *pszDir, int fFlags, int fCreateMode)
422{
423 char *pszPath = MakePathFromDirAndFile(pszName, pszDir);
424 int fd = open(pszPath, fFlags, fCreateMode);
425 free(pszPath);
426 return fd;
427}
428
429
430
431/**
432 * Deletes a file in a directory.
433 *
434 * @returns whatever unlink returns.
435 * @param pszName The file name.
436 * @param pszDir The directory path.
437 */
438static int UnlinkFileInDir(const char *pszName, const char *pszDir)
439{
440 char *pszPath = MakePathFromDirAndFile(pszName, pszDir);
441 int rc = unlink(pszPath);
442 free(pszPath);
443 return rc;
444}
445
446
447/**
448 * Renames a file in a directory.
449 *
450 * @returns whatever rename returns.
451 * @param pszOldName The new file name.
452 * @param pszNewName The old file name.
453 * @param pszDir The directory path.
454 */
455static int RenameFileInDir(const char *pszOldName, const char *pszNewName, const char *pszDir)
456{
457 char *pszOldPath = MakePathFromDirAndFile(pszOldName, pszDir);
458 char *pszNewPath = MakePathFromDirAndFile(pszNewName, pszDir);
459 int rc = rename(pszOldPath, pszNewPath);
460 free(pszOldPath);
461 free(pszNewPath);
462 return rc;
463}
464
465
466/**
467 * Check if a (regular) file exists in a directory.
468 *
469 * @returns 1 if it exists and is a regular file, 0 if not.
470 * @param pszName The file name.
471 * @param pszDir The directory path.
472 */
473static int DoesFileInDirExist(const char *pszName, const char *pszDir)
474{
475 char *pszPath = MakePathFromDirAndFile(pszName, pszDir);
476 struct stat st;
477 int rc = stat(pszPath, &st);
478 free(pszPath);
479#ifdef S_ISREG
480 return !rc && S_ISREG(st.st_mode);
481#elif defined(_MSC_VER)
482 return !rc && (st.st_mode & _S_IFMT) == _S_IFREG;
483#else
484#error "Port me"
485#endif
486}
487
488
489/**
490 * Reads into memory an entire file.
491 *
492 * @returns Pointer to the heap allocation containing the file.
493 * On failure NULL and errno is returned.
494 * @param pszName The file.
495 * @param pszDir The directory the file resides in.
496 * @param pcbFile Where to store the file size.
497 */
498static void *ReadFileInDir(const char *pszName, const char *pszDir, size_t *pcbFile)
499{
500 int SavedErrno;
501 char *pszPath = MakePathFromDirAndFile(pszName, pszDir);
502 int fd = open(pszPath, O_RDONLY | O_BINARY);
503 if (fd >= 0)
504 {
505 off_t cbFile = lseek(fd, 0, SEEK_END);
506 if ( cbFile >= 0
507 && lseek(fd, 0, SEEK_SET) == 0)
508 {
509 char *pb = malloc(cbFile + 1);
510 if (pb)
511 {
512 if (read(fd, pb, cbFile) == cbFile)
513 {
514 close(fd);
515 pb[cbFile] = '\0';
516 *pcbFile = (size_t)cbFile;
517 return pb;
518 }
519 SavedErrno = errno;
520 free(pb);
521 }
522 else
523 SavedErrno = ENOMEM;
524 }
525 else
526 SavedErrno = errno;
527 close(fd);
528 }
529 else
530 SavedErrno = errno;
531 free(pszPath);
532 errno = SavedErrno;
533 return NULL;
534}
535
536
537/**
538 * Creates a directory including all necessary parent directories.
539 *
540 * @returns 0 on success, -1 + errno on failure.
541 * @param pszDir The directory.
542 */
543static int MakePath(const char *pszPath)
544{
545 int iErr = 0;
546 char *pszAbsPath = AbsPath(pszPath);
547 char *psz = pszAbsPath;
548
549 /* Skip to the root slash (PC). */
550 while (!IS_SLASH(*psz) && *psz)
551 psz++;
552/** @todo UNC */
553 for (;;)
554 {
555 char chSaved;
556
557 /* skip slashes */
558 while (IS_SLASH(*psz))
559 psz++;
560 if (!*psz)
561 break;
562
563 /* find the next slash or end and terminate the string. */
564 while (!IS_SLASH(*psz) && *psz)
565 psz++;
566 chSaved = *psz;
567 *psz = '\0';
568
569 /* try create the directory, ignore failure because the directory already exists. */
570 errno = 0;
571#ifdef _MSC_VER
572 if ( _mkdir(pszAbsPath)
573 && errno != EEXIST)
574#else
575 if ( mkdir(pszAbsPath, 0777)
576 && errno != EEXIST)
577#endif
578 {
579 iErr = errno;
580 break;
581 }
582
583 /* restore the slash/terminator */
584 *psz = chSaved;
585 }
586
587 free(pszAbsPath);
588 return iErr ? -1 : 0;
589}
590
591
592/**
593 * Adds the arguments found in the pszCmdLine string to argument vector.
594 *
595 * The parsing of the pszCmdLine string isn't very sophisticated, no
596 * escaping or quotes.
597 *
598 * @param pcArgs Pointer to the argument counter.
599 * @param ppapszArgs Pointer to the argument vector pointer.
600 * @param pszCmdLine The command line to parse and append.
601 * @param pszWedgeArg Argument to put infront of anything found in pszCmdLine.
602 */
603static void AppendArgs(int *pcArgs, char ***ppapszArgs, const char *pszCmdLine, const char *pszWedgeArg)
604{
605 int i;
606 int cExtraArgs;
607 const char *psz;
608 char **papszArgs;
609
610 /*
611 * Count the new arguments.
612 */
613 cExtraArgs = 0;
614 psz = pszCmdLine;
615 while (*psz)
616 {
617 while (isspace(*psz))
618 psz++;
619 if (!psz)
620 break;
621 cExtraArgs++;
622 while (!isspace(*psz) && *psz)
623 psz++;
624 }
625 if (!cExtraArgs)
626 return;
627
628 /*
629 * Allocate a new vector that can hold the arguments.
630 * (Reallocating might not work since the argv might not be allocated
631 * from the heap but off the stack or somewhere... )
632 */
633 i = *pcArgs;
634 *pcArgs = i + cExtraArgs + !!pszWedgeArg;
635 papszArgs = xmalloc((*pcArgs + 1) * sizeof(char *));
636 *ppapszArgs = memcpy(papszArgs, *ppapszArgs, i * sizeof(char *));
637
638 if (pszWedgeArg)
639 papszArgs[i++] = xstrdup(pszWedgeArg);
640
641 psz = pszCmdLine;
642 while (*psz)
643 {
644 size_t cch;
645 const char *pszEnd;
646 while (isspace(*psz))
647 psz++;
648 if (!psz)
649 break;
650 pszEnd = psz;
651 while (!isspace(*pszEnd) && *pszEnd)
652 pszEnd++;
653
654 cch = pszEnd - psz;
655 papszArgs[i] = xmalloc(cch + 1);
656 memcpy(papszArgs[i], psz, cch);
657 papszArgs[i][cch] = '\0';
658
659 i++;
660 psz = pszEnd;
661 }
662
663 papszArgs[i] = NULL;
664}
665
666
667
668
669
670/** A checksum list entry.
671 * We keep a list checksums (of precompiler output) that matches, The planned
672 * matching algorithm doesn't require the precompiler output to be indentical,
673 * only to produce the same object files.
674 */
675typedef struct KOCSUM
676{
677 /** The next checksum. */
678 struct KOCSUM *pNext;
679 /** The crc32 checksum. */
680 uint32_t crc32;
681 /** The MD5 digest. */
682 unsigned char md5[16];
683 /** Valid or not. */
684 unsigned fUsed;
685} KOCSUM;
686/** Pointer to a KOCSUM. */
687typedef KOCSUM *PKOCSUM;
688/** Pointer to a const KOCSUM. */
689typedef const KOCSUM *PCKOCSUM;
690
691
692/**
693 * Temporary context record used when calculating
694 * the checksum of some data.
695 */
696typedef struct KOCSUMCTX
697{
698 /** The MD5 context. */
699 struct MD5Context MD5Ctx;
700} KOCSUMCTX;
701/** Pointer to a check context record. */
702typedef KOCSUMCTX *PKOCSUMCTX;
703
704
705
706/**
707 * Initializes a checksum object with an associated context.
708 *
709 * @param pSum The checksum object.
710 * @param pCtx The checksum context.
711 */
712static void kOCSumInitWithCtx(PKOCSUM pSum, PKOCSUMCTX pCtx)
713{
714 memset(pSum, 0, sizeof(*pSum));
715 MD5Init(&pCtx->MD5Ctx);
716}
717
718
719/**
720 * Updates the checksum calculation.
721 *
722 * @param pSum The checksum.
723 * @param pCtx The checksum calcuation context.
724 * @param pvBuf The input data to checksum.
725 * @param cbBuf The size of the input data.
726 */
727static void kOCSumUpdate(PKOCSUM pSum, PKOCSUMCTX pCtx, const void *pvBuf, size_t cbBuf)
728{
729 /*
730 * Take in relativly small chunks to try keep it in the cache.
731 */
732 const unsigned char *pb = (const unsigned char *)pvBuf;
733 while (cbBuf > 0)
734 {
735 size_t cb = cbBuf >= 128*1024 ? 128*1024 : cbBuf;
736 pSum->crc32 = crc32(pSum->crc32, pb, cb);
737 MD5Update(&pCtx->MD5Ctx, pb, cb);
738 cbBuf -= cb;
739 }
740}
741
742
743/**
744 * Finalizes a checksum calculation.
745 *
746 * @param pSum The checksum.
747 * @param pCtx The checksum calcuation context.
748 */
749static void kOCSumFinalize(PKOCSUM pSum, PKOCSUMCTX pCtx)
750{
751 MD5Final(&pSum->md5[0], &pCtx->MD5Ctx);
752 pSum->fUsed = 1;
753}
754
755
756/**
757 * Init a check sum chain head.
758 *
759 * @param pSumHead The checksum head to init.
760 */
761static void kOCSumInit(PKOCSUM pSumHead)
762{
763 memset(pSumHead, 0, sizeof(*pSumHead));
764}
765
766
767/**
768 * Parses the given string into a checksum head object.
769 *
770 * @returns 0 on success, -1 on format error.
771 * @param pSumHead The checksum head to init.
772 * @param pszVal The string to initialized it from.
773 */
774static int kOCSumInitFromString(PKOCSUM pSumHead, const char *pszVal)
775{
776 unsigned i;
777 char *pszNext;
778 char *pszMD5;
779
780 memset(pSumHead, 0, sizeof(*pSumHead));
781
782 pszMD5 = strchr(pszVal, ':');
783 if (pszMD5 == NULL)
784 return -1;
785 *pszMD5++ = '\0';
786
787 /* crc32 */
788 pSumHead->crc32 = (uint32_t)strtoul(pszVal, &pszNext, 16);
789 if (pszNext && *pszNext)
790 return -1;
791
792 /* md5 */
793 for (i = 0; i < sizeof(pSumHead->md5) * 2; i++)
794 {
795 unsigned char ch = pszMD5[i];
796 int x;
797 if ((unsigned char)(ch - '0') <= 9)
798 x = ch - '0';
799 else if ((unsigned char)(ch - 'a') <= 5)
800 x = ch - 'a' + 10;
801 else if ((unsigned char)(ch - 'A') <= 5)
802 x = ch - 'A' + 10;
803 else
804 return -1;
805 if (!(i & 1))
806 pSumHead->md5[i >> 1] = x << 4;
807 else
808 pSumHead->md5[i >> 1] |= x;
809 }
810
811 pSumHead->fUsed = 1;
812 return 0;
813}
814
815
816/**
817 * Delete a check sum chain.
818 *
819 * @param pSumHead The head of the checksum chain.
820 */
821static void kOCSumDeleteChain(PKOCSUM pSumHead)
822{
823 void *pv;
824 while ((pv = pSumHead->pNext))
825 {
826 pSumHead = pSumHead->pNext;
827 free(pv);
828 }
829 memset(pSumHead, 0, sizeof(*pSumHead));
830}
831
832
833/**
834 * Insert a check sum into the chain.
835 *
836 * @param pSumHead The head of the checksum list.
837 * @param pSumAdd The checksum to add (duplicate).
838 */
839static void kOCSumAdd(PKOCSUM pSumHead, PCKOCSUM pSumAdd)
840{
841 if (pSumHead->fUsed)
842 {
843 PKOCSUM pNew = xmalloc(sizeof(*pNew));
844 *pNew = *pSumAdd;
845 pNew->pNext = pSumHead->pNext;
846 pNew->fUsed = 1;
847 pSumHead->pNext = pNew;
848 }
849 else
850 {
851 *pSumHead = *pSumAdd;
852 pSumHead->pNext = NULL;
853 pSumHead->fUsed = 1;
854 }
855}
856
857
858/**
859 * Inserts an entrie chain into the given check sum chain.
860 *
861 * @param pSumHead The head of the checksum list.
862 * @param pSumHeadAdd The head of the checksum list to be added.
863 */
864static void kOCSumAddChain(PKOCSUM pSumHead, PCKOCSUM pSumHeadAdd)
865{
866 while (pSumHeadAdd)
867 {
868 kOCSumAdd(pSumHead, pSumHeadAdd);
869 pSumHeadAdd = pSumHeadAdd->pNext;
870 }
871}
872
873
874
875/**
876 * Prints the checksum to the specified stream.
877 *
878 * @param pSum The checksum.
879 * @param pFile The output file stream
880 */
881static void kOCSumFPrintf(PCKOCSUM pSum, FILE *pFile)
882{
883 fprintf(pFile, "%#x:%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
884 pSum->crc32,
885 pSum->md5[0], pSum->md5[1], pSum->md5[2], pSum->md5[3],
886 pSum->md5[4], pSum->md5[5], pSum->md5[6], pSum->md5[7],
887 pSum->md5[8], pSum->md5[9], pSum->md5[10], pSum->md5[11],
888 pSum->md5[12], pSum->md5[13], pSum->md5[14], pSum->md5[15]);
889}
890
891
892/**
893 * Displays the checksum (not chain!) using the InfoMsg() method.
894 *
895 * @param pSum The checksum.
896 * @param uLevel The info message level.
897 * @param pszMsg Message to prefix the info message with.
898 */
899static void kOCSumInfo(PCKOCSUM pSum, unsigned uLevel, const char *pszMsg)
900{
901 InfoMsg(uLevel,
902 "%s: crc32=%#010x md5=%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
903 pszMsg,
904 pSum->crc32,
905 pSum->md5[0], pSum->md5[1], pSum->md5[2], pSum->md5[3],
906 pSum->md5[4], pSum->md5[5], pSum->md5[6], pSum->md5[7],
907 pSum->md5[8], pSum->md5[9], pSum->md5[10], pSum->md5[11],
908 pSum->md5[12], pSum->md5[13], pSum->md5[14], pSum->md5[15]);
909}
910
911
912/**
913 * Compares two check sum entries.
914 *
915 * @returns 1 if equal, 0 if not equal.
916 *
917 * @param pSum1 The first checksum.
918 * @param pSum2 The second checksum.
919 */
920static int kOCSumIsEqual(PCKOCSUM pSum1, PCKOCSUM pSum2)
921{
922 if (pSum1 == pSum2)
923 return 1;
924 if (!pSum1 || !pSum2)
925 return 0;
926 if (pSum1->crc32 != pSum2->crc32)
927 return 0;
928 if (memcmp(&pSum1->md5[0], &pSum2->md5[0], sizeof(pSum1->md5)))
929 return 0;
930 return 1;
931}
932
933
934/**
935 * Checks if the specified checksum equals one of the
936 * checksums in the chain.
937 *
938 * @returns 1 if equals one of them, 0 if not.
939 *
940 * @param pSumHead The checksum chain too look in.
941 * @param pSum The checksum to look for.
942 * @todo ugly name. fix.
943 */
944static int kOCSumHasEqualInChain(PCKOCSUM pSumHead, PCKOCSUM pSum)
945{
946 for (; pSumHead; pSumHead = pSumHead->pNext)
947 {
948 if (pSumHead == pSum)
949 return 1;
950 if (pSumHead->crc32 != pSum->crc32)
951 continue;
952 if (memcmp(&pSumHead->md5[0], &pSum->md5[0], sizeof(pSumHead->md5)))
953 continue;
954 return 1;
955 }
956 return 0;
957}
958
959
960/**
961 * Checks if the checksum (chain) empty.
962 *
963 * @returns 1 if empty, 0 if it there is one or more checksums.
964 * @param pSum The checksum to test.
965 */
966static int kOCSumIsEmpty(PCKOCSUM pSum)
967{
968 return !pSum->fUsed;
969}
970
971
972
973
974
975
976/**
977 * The representation of a cache entry.
978 */
979typedef struct KOCENTRY
980{
981 /** The name of the cache entry. */
982 const char *pszName;
983 /** The dir that all other names are relative to. */
984 char *pszDir;
985 /** The absolute path. */
986 char *pszAbsPath;
987 /** Set if the object needs to be (re)compiled. */
988 unsigned fNeedCompiling;
989 /** Whether the precompiler runs in piped mode. If clear it's file
990 * mode (it could be redirected stdout, but that's essentially the
991 * same from our point of view). */
992 unsigned fPipedPreComp;
993 /** Whether the compiler runs in piped mode (precompiler output on stdin). */
994 unsigned fPipedCompile;
995 /** Cache entry key that's used for some quick digest validation. */
996 uint32_t uKey;
997
998 /** The file data. */
999 struct KOCENTRYDATA
1000 {
1001 /** The name of file containing the precompiler output. */
1002 char *pszCppName;
1003 /** Pointer to the precompiler output. */
1004 char *pszCppMapping;
1005 /** The size of the precompiler output. 0 if not determined. */
1006 size_t cbCpp;
1007 /** The precompiler output checksums that will produce the cached object. */
1008 KOCSUM SumHead;
1009 /** The object filename (relative to the cache file). */
1010 char *pszObjName;
1011 /** The compile argument vector used to build the object. */
1012 char **papszArgvCompile;
1013 /** The size of the compile */
1014 unsigned cArgvCompile;
1015 /** The checksum of the compiler argument vector. */
1016 KOCSUM SumCompArgv;
1017 /** The target os/arch identifier. */
1018 char *pszTarget;
1019 }
1020 /** The old data.*/
1021 Old,
1022 /** The new data. */
1023 New;
1024} KOCENTRY;
1025/** Pointer to a KOCENTRY. */
1026typedef KOCENTRY *PKOCENTRY;
1027/** Pointer to a const KOCENTRY. */
1028typedef const KOCENTRY *PCKOCENTRY;
1029
1030
1031/**
1032 * Creates a cache entry for the given cache file name.
1033 *
1034 * @returns Pointer to a cache entry.
1035 * @param pszFilename The cache file name.
1036 */
1037static PKOCENTRY kOCEntryCreate(const char *pszFilename)
1038{
1039 PKOCENTRY pEntry;
1040 size_t off;
1041
1042 /*
1043 * Allocate an empty entry.
1044 */
1045 pEntry = xmallocz(sizeof(*pEntry));
1046
1047 kOCSumInit(&pEntry->New.SumHead);
1048 kOCSumInit(&pEntry->Old.SumHead);
1049
1050 kOCSumInit(&pEntry->New.SumCompArgv);
1051 kOCSumInit(&pEntry->Old.SumCompArgv);
1052
1053 /*
1054 * Setup the directory and cache file name.
1055 */
1056 pEntry->pszAbsPath = AbsPath(pszFilename);
1057 pEntry->pszName = FindFilenameInPath(pEntry->pszAbsPath);
1058 off = pEntry->pszName - pEntry->pszAbsPath;
1059 if (!off)
1060 FatalDie("Failed to find abs path for '%s'!\n", pszFilename);
1061 pEntry->pszDir = xmalloc(off);
1062 memcpy(pEntry->pszDir, pEntry->pszAbsPath, off - 1);
1063 pEntry->pszDir[off - 1] = '\0';
1064
1065 return pEntry;
1066}
1067
1068
1069/**
1070 * Destroys the cache entry freeing up all it's resources.
1071 *
1072 * @param pEntry The entry to free.
1073 */
1074static void kOCEntryDestroy(PKOCENTRY pEntry)
1075{
1076 free(pEntry->pszDir);
1077 free(pEntry->pszAbsPath);
1078
1079 kOCSumDeleteChain(&pEntry->New.SumHead);
1080 kOCSumDeleteChain(&pEntry->Old.SumHead);
1081
1082 kOCSumDeleteChain(&pEntry->New.SumCompArgv);
1083 kOCSumDeleteChain(&pEntry->Old.SumCompArgv);
1084
1085 free(pEntry->New.pszCppName);
1086 free(pEntry->Old.pszCppName);
1087
1088 free(pEntry->New.pszCppMapping);
1089 free(pEntry->Old.pszCppMapping);
1090
1091 free(pEntry->New.pszObjName);
1092 free(pEntry->Old.pszObjName);
1093
1094 free(pEntry->New.pszTarget);
1095 free(pEntry->Old.pszTarget);
1096
1097 while (pEntry->New.cArgvCompile > 0)
1098 free(pEntry->New.papszArgvCompile[--pEntry->New.cArgvCompile]);
1099 while (pEntry->Old.cArgvCompile > 0)
1100 free(pEntry->Old.papszArgvCompile[--pEntry->Old.cArgvCompile]);
1101
1102 free(pEntry->New.papszArgvCompile);
1103 free(pEntry->Old.papszArgvCompile);
1104
1105 free(pEntry);
1106}
1107
1108
1109/**
1110 * Calculates the checksum of an compiler argument vector.
1111 *
1112 * @param pEntry The cache entry.
1113 * @param papszArgv The argument vector.
1114 * @param cArgc The number of entries in the vector.
1115 * @param pszIgnorePath Path to ignore when encountered at the end of arguments.
1116 * (Not quite safe for simple file names, but what the heck.)
1117 * @param pSum Where to store the check sum.
1118 */
1119static void kOCEntryCalcArgvSum(PKOCENTRY pEntry, const char * const *papszArgv, unsigned cArgc,
1120 const char *pszIgnorePath, PKOCSUM pSum)
1121{
1122 size_t cchIgnorePath = strlen(pszIgnorePath);
1123 KOCSUMCTX Ctx;
1124 unsigned i;
1125
1126 kOCSumInitWithCtx(pSum, &Ctx);
1127 for (i = 0; i < cArgc; i++)
1128 {
1129 size_t cch = strlen(papszArgv[i]);
1130 if ( cch < cchIgnorePath
1131 || !ArePathsIdentical(papszArgv[i] + cch - cchIgnorePath, pszIgnorePath, cch))
1132 kOCSumUpdate(pSum, &Ctx, papszArgv[i], cch + 1);
1133 }
1134 kOCSumFinalize(pSum, &Ctx);
1135}
1136
1137
1138/**
1139 * Reads and parses the cache file.
1140 *
1141 * @param pEntry The entry to read it into.
1142 */
1143static void kOCEntryRead(PKOCENTRY pEntry)
1144{
1145 FILE *pFile;
1146 pFile = FOpenFileInDir(pEntry->pszName, pEntry->pszDir, "rb");
1147 if (pFile)
1148 {
1149 InfoMsg(4, "reading cache entry...\n");
1150
1151 /*
1152 * Check the magic.
1153 */
1154 if ( !fgets(g_szLine, sizeof(g_szLine), pFile)
1155 || strcmp(g_szLine, "magic=kObjCacheEntry-v0.1.0\n"))
1156 {
1157 InfoMsg(2, "bad cache file (magic)\n");
1158 pEntry->fNeedCompiling = 1;
1159 }
1160 else
1161 {
1162 /*
1163 * Parse the rest of the file (relaxed order).
1164 */
1165 unsigned i;
1166 int fBad = 0;
1167 int fBadBeforeMissing = 1;
1168 while (fgets(g_szLine, sizeof(g_szLine), pFile))
1169 {
1170 char *pszNl;
1171 char *pszVal;
1172
1173 /* Split the line and drop the trailing newline. */
1174 pszVal = strchr(g_szLine, '=');
1175 if ((fBad = pszVal == NULL))
1176 break;
1177 *pszVal++ = '\0';
1178
1179 pszNl = strchr(pszVal, '\n');
1180 if (pszNl)
1181 *pszNl = '\0';
1182
1183 /* string case on variable name */
1184 if (!strcmp(g_szLine, "obj"))
1185 {
1186 if ((fBad = pEntry->Old.pszObjName != NULL))
1187 break;
1188 pEntry->Old.pszObjName = xstrdup(pszVal);
1189 }
1190 else if (!strcmp(g_szLine, "cpp"))
1191 {
1192 if ((fBad = pEntry->Old.pszCppName != NULL))
1193 break;
1194 pEntry->Old.pszCppName = xstrdup(pszVal);
1195 }
1196 else if (!strcmp(g_szLine, "cpp-size"))
1197 {
1198 char *pszNext;
1199 if ((fBad = pEntry->Old.cbCpp != 0))
1200 break;
1201 pEntry->Old.cbCpp = strtoul(pszVal, &pszNext, 0);
1202 if ((fBad = pszNext && *pszNext))
1203 break;
1204 }
1205 else if (!strcmp(g_szLine, "cpp-sum"))
1206 {
1207 KOCSUM Sum;
1208 if ((fBad = kOCSumInitFromString(&Sum, pszVal)))
1209 break;
1210 kOCSumAdd(&pEntry->Old.SumHead, &Sum);
1211 }
1212 else if (!strcmp(g_szLine, "cc-argc"))
1213 {
1214 if ((fBad = pEntry->Old.papszArgvCompile != NULL))
1215 break;
1216 pEntry->Old.cArgvCompile = atoi(pszVal); /* if wrong, we'll fail below. */
1217 pEntry->Old.papszArgvCompile = xmallocz((pEntry->Old.cArgvCompile + 1) * sizeof(pEntry->Old.papszArgvCompile[0]));
1218 }
1219 else if (!strncmp(g_szLine, "cc-argv-#", sizeof("cc-argv-#") - 1))
1220 {
1221 char *pszNext;
1222 unsigned i = strtoul(&g_szLine[sizeof("cc-argv-#") - 1], &pszNext, 0);
1223 if ((fBad = i >= pEntry->Old.cArgvCompile || pEntry->Old.papszArgvCompile[i] || (pszNext && *pszNext)))
1224 break;
1225 pEntry->Old.papszArgvCompile[i] = xstrdup(pszVal);
1226 }
1227 else if (!strcmp(g_szLine, "cc-argv-sum"))
1228 {
1229 if ((fBad = !kOCSumIsEmpty(&pEntry->Old.SumCompArgv)))
1230 break;
1231 if ((fBad = kOCSumInitFromString(&pEntry->Old.SumCompArgv, pszVal)))
1232 break;
1233 }
1234 else if (!strcmp(g_szLine, "target"))
1235 {
1236 if ((fBad = pEntry->Old.pszTarget != NULL))
1237 break;
1238 pEntry->Old.pszTarget = xstrdup(pszVal);
1239 }
1240 else if (!strcmp(g_szLine, "key"))
1241 {
1242 char *pszNext;
1243 if ((fBad = pEntry->uKey != 0))
1244 break;
1245 pEntry->uKey = strtoul(pszVal, &pszNext, 0);
1246 if ((fBad = pszNext && *pszNext))
1247 break;
1248 }
1249 else if (!strcmp(g_szLine, "the-end"))
1250 {
1251 fBadBeforeMissing = fBad = strcmp(pszVal, "fine");
1252 break;
1253 }
1254 else
1255 {
1256 fBad = 1;
1257 break;
1258 }
1259 } /* parse loop */
1260
1261 /*
1262 * Did we find everything and does it add up correctly?
1263 */
1264 if (!fBad && fBadBeforeMissing)
1265 {
1266 InfoMsg(2, "bad cache file (no end)\n");
1267 fBad = 1;
1268 }
1269 else
1270 {
1271 fBadBeforeMissing = fBad;
1272 if ( !fBad
1273 && ( !pEntry->Old.papszArgvCompile
1274 || !pEntry->Old.pszObjName
1275 || !pEntry->Old.pszCppName
1276 || kOCSumIsEmpty(&pEntry->Old.SumHead)))
1277 fBad = 1;
1278 if (!fBad)
1279 for (i = 0; i < pEntry->Old.cArgvCompile; i++)
1280 if ((fBad = !pEntry->Old.papszArgvCompile[i]))
1281 break;
1282 if (!fBad)
1283 {
1284 KOCSUM Sum;
1285 kOCEntryCalcArgvSum(pEntry, (const char * const *)pEntry->Old.papszArgvCompile,
1286 pEntry->Old.cArgvCompile, pEntry->Old.pszObjName, &Sum);
1287 fBad = !kOCSumIsEqual(&pEntry->Old.SumCompArgv, &Sum);
1288 }
1289 if (fBad)
1290 InfoMsg(2, "bad cache file (%s)\n", fBadBeforeMissing ? g_szLine : "missing stuff");
1291 else if (ferror(pFile))
1292 {
1293 InfoMsg(2, "cache file read error\n");
1294 fBad = 1;
1295 }
1296
1297 /*
1298 * Verify the existance of the object file.
1299 */
1300 if (!fBad)
1301 {
1302 struct stat st;
1303 char *pszPath = MakePathFromDirAndFile(pEntry->Old.pszObjName, pEntry->pszDir);
1304 if (stat(pszPath, &st) != 0)
1305 {
1306 InfoMsg(2, "failed to stat object file: %s\n", strerror(errno));
1307 fBad = 1;
1308 }
1309 else
1310 {
1311 /** @todo verify size and the timestamp. */
1312 }
1313 }
1314 }
1315 pEntry->fNeedCompiling = fBad;
1316 }
1317 fclose(pFile);
1318 }
1319 else
1320 {
1321 InfoMsg(2, "no cache file\n");
1322 pEntry->fNeedCompiling = 1;
1323 }
1324}
1325
1326
1327/**
1328 * Writes the cache file.
1329 *
1330 * @param pEntry The entry to write.
1331 */
1332static void kOCEntryWrite(PKOCENTRY pEntry)
1333{
1334 FILE *pFile;
1335 PCKOCSUM pSum;
1336 unsigned i;
1337
1338 InfoMsg(4, "writing cache entry '%s'...\n", pEntry->pszName);
1339 pFile = FOpenFileInDir(pEntry->pszName, pEntry->pszDir, "wb");
1340 if (!pFile)
1341 FatalDie("Failed to open '%s' in '%s': %s\n",
1342 pEntry->pszName, pEntry->pszDir, strerror(errno));
1343
1344#define CHECK_LEN(expr) \
1345 do { int cch = expr; if (cch >= KOBJCACHE_MAX_LINE_LEN) FatalDie("Line too long: %d (max %d)\nexpr: %s\n", cch, KOBJCACHE_MAX_LINE_LEN, #expr); } while (0)
1346
1347 fprintf(pFile, "magic=kObjCacheEntry-v0.1.0\n");
1348 CHECK_LEN(fprintf(pFile, "target=%s\n", pEntry->New.pszTarget ? pEntry->New.pszTarget : pEntry->Old.pszTarget));
1349 CHECK_LEN(fprintf(pFile, "key=%u\n", (unsigned long)pEntry->uKey));
1350 CHECK_LEN(fprintf(pFile, "obj=%s\n", pEntry->New.pszObjName ? pEntry->New.pszObjName : pEntry->Old.pszObjName));
1351 CHECK_LEN(fprintf(pFile, "cpp=%s\n", pEntry->New.pszCppName ? pEntry->New.pszCppName : pEntry->Old.pszCppName));
1352 CHECK_LEN(fprintf(pFile, "cpp-size=%lu\n", pEntry->New.pszCppName ? pEntry->New.cbCpp : pEntry->Old.cbCpp));
1353
1354 if (!kOCSumIsEmpty(&pEntry->New.SumCompArgv))
1355 {
1356 CHECK_LEN(fprintf(pFile, "cc-argc=%u\n", pEntry->New.cArgvCompile));
1357 for (i = 0; i < pEntry->New.cArgvCompile; i++)
1358 CHECK_LEN(fprintf(pFile, "cc-argv-#%u=%s\n", i, pEntry->New.papszArgvCompile[i]));
1359 fprintf(pFile, "cc-argv-sum=");
1360 kOCSumFPrintf(&pEntry->New.SumCompArgv, pFile);
1361 }
1362 else
1363 {
1364 CHECK_LEN(fprintf(pFile, "cc-argc=%u\n", pEntry->Old.cArgvCompile));
1365 for (i = 0; i < pEntry->Old.cArgvCompile; i++)
1366 CHECK_LEN(fprintf(pFile, "cc-argv-#%u=%s\n", i, pEntry->Old.papszArgvCompile[i]));
1367 fprintf(pFile, "cc-argv-sum=");
1368 kOCSumFPrintf(&pEntry->Old.SumCompArgv, pFile);
1369 }
1370
1371
1372 for (pSum = !kOCSumIsEmpty(&pEntry->New.SumHead) ? &pEntry->New.SumHead : &pEntry->Old.SumHead;
1373 pSum;
1374 pSum = pSum->pNext)
1375 {
1376 fprintf(pFile, "cpp-sum=");
1377 kOCSumFPrintf(pSum, pFile);
1378 }
1379
1380 fprintf(pFile, "the-end=fine\n");
1381
1382#undef CHECK_LEN
1383
1384 /*
1385 * Flush the file and check for errors.
1386 * On failure delete the file so we won't be seeing any invalid
1387 * files the next time or upset make with new timestamps.
1388 */
1389 errno = 0;
1390 if ( fflush(pFile) < 0
1391 || ferror(pFile))
1392 {
1393 int iErr = errno;
1394 fclose(pFile);
1395 UnlinkFileInDir(pEntry->pszName, pEntry->pszDir);
1396 FatalDie("Stream error occured while writing '%s' in '%s': %s\n",
1397 pEntry->pszName, pEntry->pszDir, strerror(iErr));
1398 }
1399 fclose(pFile);
1400}
1401
1402
1403/**
1404 * Checks that the read cache entry is valid.
1405 * It sets fNeedCompiling if it isn't.
1406 *
1407 * @returns 1 valid, 0 invalid.
1408 * @param pEntry The cache entry.
1409 */
1410static int kOCEntryCheck(PKOCENTRY pEntry)
1411{
1412 return !pEntry->fNeedCompiling;
1413}
1414
1415
1416/**
1417 * Sets the object name and compares it with the old name if present.
1418 *
1419 * @param pEntry The cache entry.
1420 * @param pszObjName The new object name.
1421 */
1422static void kOCEntrySetCompileObjName(PKOCENTRY pEntry, const char *pszObjName)
1423{
1424 assert(!pEntry->New.pszObjName);
1425 pEntry->New.pszObjName = CalcRelativeName(pszObjName, pEntry->pszDir);
1426
1427 if ( !pEntry->fNeedCompiling
1428 && ( !pEntry->Old.pszObjName
1429 || strcmp(pEntry->New.pszObjName, pEntry->Old.pszObjName)))
1430 {
1431 InfoMsg(2, "object file name differs\n");
1432 pEntry->fNeedCompiling = 1;
1433 }
1434
1435 if ( !pEntry->fNeedCompiling
1436 && !DoesFileInDirExist(pEntry->New.pszObjName, pEntry->pszDir))
1437 {
1438 InfoMsg(2, "object file doesn't exist\n");
1439 pEntry->fNeedCompiling = 1;
1440 }
1441}
1442
1443
1444/**
1445 * Set the new compiler args, calc their checksum, and comparing them with any old ones.
1446 *
1447 * @param pEntry The cache entry.
1448 * @param papszArgvCompile The new argument vector for compilation.
1449 * @param cArgvCompile The number of arguments in the vector.
1450 *
1451 * @remark Must call kOCEntrySetCompileObjName before this function!
1452 */
1453static void kOCEntrySetCompileArgv(PKOCENTRY pEntry, const char * const *papszArgvCompile, unsigned cArgvCompile)
1454{
1455 unsigned i;
1456
1457 /* call me only once! */
1458 assert(!pEntry->New.cArgvCompile);
1459 /* call kOCEntrySetCompilerObjName first! */
1460 assert(pEntry->New.pszObjName);
1461
1462 /*
1463 * Copy the argument vector and calculate the checksum.
1464 */
1465 pEntry->New.cArgvCompile = cArgvCompile;
1466 pEntry->New.papszArgvCompile = xmalloc((cArgvCompile + 1) * sizeof(pEntry->New.papszArgvCompile[0]));
1467 for (i = 0; i < cArgvCompile; i++)
1468 pEntry->New.papszArgvCompile[i] = xstrdup(papszArgvCompile[i]);
1469 pEntry->New.papszArgvCompile[i] = NULL; /* for exev/spawnv */
1470
1471 kOCEntryCalcArgvSum(pEntry, papszArgvCompile, cArgvCompile, pEntry->New.pszObjName, &pEntry->New.SumCompArgv);
1472 kOCSumInfo(&pEntry->New.SumCompArgv, 4, "comp-argv");
1473
1474 /*
1475 * Compare with the old argument vector.
1476 */
1477 if ( !pEntry->fNeedCompiling
1478 && !kOCSumIsEqual(&pEntry->New.SumCompArgv, &pEntry->Old.SumCompArgv))
1479 {
1480 InfoMsg(2, "compiler args differs\n");
1481 pEntry->fNeedCompiling = 1;
1482 }
1483}
1484
1485
1486/**
1487 * Sets the arch/os target and compares it with the old name if present.
1488 *
1489 * @param pEntry The cache entry.
1490 * @param pszObjName The new object name.
1491 */
1492static void kOCEntrySetTarget(PKOCENTRY pEntry, const char *pszTarget)
1493{
1494 assert(!pEntry->New.pszTarget);
1495 pEntry->New.pszTarget = xstrdup(pszTarget);
1496
1497 if ( !pEntry->fNeedCompiling
1498 && ( !pEntry->Old.pszTarget
1499 || strcmp(pEntry->New.pszTarget, pEntry->Old.pszTarget)))
1500 {
1501 InfoMsg(2, "target differs\n");
1502 pEntry->fNeedCompiling = 1;
1503 }
1504}
1505
1506
1507/**
1508 * Sets the precompiler output filename.
1509 * We don't generally care if this matches the old name or not.
1510 *
1511 * @param pEntry The cache entry.
1512 * @param pszCppName The precompiler output filename.
1513 */
1514static void kOCEntrySetCppName(PKOCENTRY pEntry, const char *pszCppName)
1515{
1516 assert(!pEntry->New.pszCppName);
1517 pEntry->New.pszCppName = CalcRelativeName(pszCppName, pEntry->pszDir);
1518}
1519
1520
1521/**
1522 * Sets the piped mode of the precompiler and compiler.
1523 *
1524 * @param pEntry The cache entry.
1525 * @param fRedirPreCompStdOut Whether the precompiler is in piped mode.
1526 * @param fRedirCompileStdIn Whether the compiler is in piped mode.
1527 */
1528static void kOCEntrySetPipedMode(PKOCENTRY pEntry, int fRedirPreCompStdOut, int fRedirCompileStdIn)
1529{
1530 pEntry->fPipedPreComp = fRedirPreCompStdOut;
1531 pEntry->fPipedCompile = fRedirCompileStdIn;
1532}
1533
1534
1535/**
1536 * Spawns a child in a synchronous fashion.
1537 * Terminating on failure.
1538 *
1539 * @param papszArgv Argument vector. The cArgv element is NULL.
1540 * @param cArgv The number of arguments in the vector.
1541 */
1542static void kOCEntrySpawn(PCKOCENTRY pEntry, const char * const *papszArgv, unsigned cArgv, const char *pszMsg, const char *pszStdOut)
1543{
1544#if defined(__OS2__) || defined(__WIN__)
1545 intptr_t rc;
1546 int fdStdOut = -1;
1547 if (pszStdOut)
1548 {
1549 int fdReDir;
1550 fdStdOut = dup(STDOUT_FILENO);
1551 close(STDOUT_FILENO);
1552 fdReDir = open(pszStdOut, O_CREAT | O_TRUNC | O_WRONLY, 0666);
1553 if (fdReDir < 0)
1554 FatalDie("%s - failed to create stdout redirection file '%s': %s\n",
1555 pszMsg, pszStdOut, strerror(errno));
1556
1557 if (fdReDir != STDOUT_FILENO)
1558 {
1559 if (dup2(fdReDir, STDOUT_FILENO) < 0)
1560 FatalDie("%s - dup2 failed: %s\n", pszMsg, strerror(errno));
1561 close(fdReDir);
1562 }
1563 }
1564
1565 errno = 0;
1566 rc = _spawnvp(_P_WAIT, papszArgv[0], papszArgv);
1567 if (rc < 0)
1568 FatalDie("%s - _spawnvp failed (rc=0x%p): %s\n", pszMsg, rc, strerror(errno));
1569 if (rc > 0)
1570 FatalDie("%s - failed rc=%d\n", pszMsg, (int)rc);
1571 if (fdStdOut)
1572 {
1573 close(STDOUT_FILENO);
1574 fdStdOut = dup2(fdStdOut, STDOUT_FILENO);
1575 close(fdStdOut);
1576 }
1577
1578#else
1579 int iStatus;
1580 pid_t pidWait;
1581 pid_t pid = fork();
1582 if (!pid)
1583 {
1584 if (pszStdOut)
1585 {
1586 int fdReDir;
1587
1588 close(STDOUT_FILENO);
1589 fdReDir = open(pszStdOut, O_CREAT | O_TRUNC | O_WRONLY, 0666);
1590 if (fdReDir < 0)
1591 FatalDie("%s - failed to create stdout redirection file '%s': %s\n",
1592 pszMsg, pszStdOut, strerror(errno));
1593 if (fdReDir != STDOUT_FILENO)
1594 {
1595 if (dup2(fdReDir, STDOUT_FILENO) < 0)
1596 FatalDie("%s - dup2 failed: %s\n", pszMsg, strerror(errno));
1597 close(fdReDir);
1598 }
1599 }
1600
1601 execvp(papszArgv[0], (char **)papszArgv);
1602 FatalDie("%s - execvp failed: %s\n",
1603 pszMsg, strerror(errno));
1604 }
1605 if (pid == -1)
1606 FatalDie("%s - fork() failed: %s\n", pszMsg, strerror(errno));
1607
1608 pidWait = waitpid(pid, &iStatus, 0);
1609 while (pidWait < 0 && errno == EINTR)
1610 pidWait = waitpid(pid, &iStatus, 0);
1611 if (pidWait != pid)
1612 FatalDie("%s - waitpid failed rc=%d: %s\n",
1613 pszMsg, pidWait, strerror(errno));
1614 if (!WIFEXITED(iStatus))
1615 FatalDie("%s - abended (iStatus=%#x)\n", pszMsg, iStatus);
1616 if (WEXITSTATUS(iStatus))
1617 FatalDie("%s - failed with rc %d\n", pszMsg, WEXITSTATUS(iStatus));
1618#endif
1619 (void)cArgv;
1620}
1621
1622
1623/**
1624 * Spawns child with optional redirection of stdin and stdout.
1625 *
1626 * @param pEntry The cache entry.
1627 * @param papszArgv Argument vector. The cArgv element is NULL.
1628 * @param cArgv The number of arguments in the vector.
1629 * @param fdStdIn Child stdin, -1 if it should inherit our stdin. Will be closed.
1630 * @param fdStdOut Child stdout, -1 if it should inherit our stdout. Will be closed.
1631 * @param pszMsg Message to start the info/error messages with.
1632 */
1633static pid_t kOCEntrySpawnChild(PCKOCENTRY pEntry, const char * const *papszArgv, unsigned cArgv, int fdStdIn, int fdStdOut, const char *pszMsg)
1634{
1635 pid_t pid;
1636 int fdSavedStdOut = -1;
1637 int fdSavedStdIn = -1;
1638
1639 /*
1640 * Setup redirection.
1641 */
1642 if (fdStdOut != -1 && fdStdOut != STDOUT_FILENO)
1643 {
1644 fdSavedStdOut = dup(STDOUT_FILENO);
1645 if (dup2(fdStdOut, STDOUT_FILENO) < 0)
1646 FatalDie("%s - dup2(,1) failed: %s\n", pszMsg, strerror(errno));
1647 close(fdStdOut);
1648#ifndef __WIN__
1649 fcntl(fdSavedStdOut, F_SETFD, FD_CLOEXEC);
1650#endif
1651 }
1652 if (fdStdIn != -1 && fdStdIn != STDIN_FILENO)
1653 {
1654 fdSavedStdIn = dup(STDIN_FILENO);
1655 if (dup2(fdStdIn, STDIN_FILENO) < 0)
1656 FatalDie("%s - dup2(,0) failed: %s\n", pszMsg, strerror(errno));
1657 close(fdStdIn);
1658#ifndef __WIN__
1659 fcntl(fdSavedStdIn, F_SETFD, FD_CLOEXEC);
1660#endif
1661 }
1662
1663 /*
1664 * Create the child process.
1665 */
1666#if defined(__OS2__) || defined(__WIN__)
1667 errno = 0;
1668 pid = _spawnvp(_P_NOWAIT, papszArgv[0], papszArgv);
1669 if (pid == -1)
1670 FatalDie("precompile - _spawnvp failed: %s\n", strerror(errno));
1671
1672#else
1673 pid = fork();
1674 if (!pid)
1675 {
1676 execvp(papszArgv[0], (char **)papszArgv);
1677 FatalDie("precompile - execvp failed: %s\n", strerror(errno));
1678 }
1679 if (pid == -1)
1680 FatalDie("precompile - fork() failed: %s\n", strerror(errno));
1681#endif
1682
1683 /*
1684 * Restore stdout & stdin.
1685 */
1686 if (fdSavedStdIn != -1)
1687 {
1688 close(STDIN_FILENO);
1689 dup2(fdStdOut, STDIN_FILENO);
1690 close(fdSavedStdIn);
1691 }
1692 if (fdSavedStdOut != -1)
1693 {
1694 close(STDOUT_FILENO);
1695 dup2(fdSavedStdOut, STDOUT_FILENO);
1696 close(fdSavedStdOut);
1697 }
1698
1699 InfoMsg(3, "%s - spawned %ld\n", pszMsg, (long)pid);
1700 (void)cArgv;
1701 (void)pEntry;
1702 return pid;
1703}
1704
1705
1706/**
1707 * Waits for a child and exits fatally if the child failed in any way.
1708 *
1709 * @param pEntry The cache entry.
1710 * @param pid The child to wait for.
1711 * @param pszMsg Message to start the info/error messages with.
1712 */
1713static void kOCEntryWaitChild(PCKOCENTRY pEntry, pid_t pid, const char *pszMsg)
1714{
1715 int iStatus = -1;
1716 pid_t pidWait;
1717 InfoMsg(3, "%s - wait-child %ld\n", pszMsg, (long)pid);
1718
1719#ifdef __WIN__
1720 pidWait = _cwait(&iStatus, pid, _WAIT_CHILD);
1721 if (pidWait == -1)
1722 FatalDie("%s - waitpid failed: %s\n", pszMsg, strerror(errno));
1723 if (iStatus)
1724 FatalDie("%s - failed with rc %d\n", pszMsg, iStatus);
1725#else
1726 pidWait = waitpid(pid, &iStatus, 0);
1727 while (pidWait < 0 && errno == EINTR)
1728 pidWait = waitpid(pid, &iStatus, 0);
1729 if (pidWait != pid)
1730 FatalDie("%s - waitpid failed rc=%d: %s\n", pidWait, strerror(errno));
1731 if (!WIFEXITED(iStatus))
1732 FatalDie("%s - abended (iStatus=%#x)\n", pszMsg, iStatus);
1733 if (WEXITSTATUS(iStatus))
1734 FatalDie("%s - failed with rc %d\n", pszMsg, WEXITSTATUS(iStatus));
1735#endif
1736 (void)pEntry;
1737}
1738
1739
1740/**
1741 * Creates a pipe for setting up redirected stdin/stdout.
1742 *
1743 * @param pEntry The cache entry.
1744 * @param pFDs Where to store the two file descriptors.
1745 * @param pszMsg The operation message for info/error messages.
1746 */
1747static void kOCEntryCreatePipe(PKOCENTRY pEntry, int *pFDs, const char *pszMsg)
1748{
1749 pFDs[0] = pFDs[1] = -1;
1750#if defined(__WIN__)
1751 if (_pipe(pFDs, 0, _O_NOINHERIT | _O_BINARY) < 0)
1752#else
1753 if (pipe(pFDs) < 0)
1754#endif
1755 FatalDie("%s - pipe failed: %s\n", pszMsg, strerror(errno));
1756#if !defined(__WIN__)
1757 fcntl(pFDs[0], F_SETFD, FD_CLOEXEC);
1758 fcntl(pFDs[1], F_SETFD, FD_CLOEXEC);
1759#endif
1760}
1761
1762
1763/**
1764 * Spawns a child that produces output to stdout.
1765 *
1766 * @param papszArgv Argument vector. The cArgv element is NULL.
1767 * @param cArgv The number of arguments in the vector.
1768 * @param pszMsg The operation message for info/error messages.
1769 * @param pfnConsumer Pointer to a consumer callback function that is responsible
1770 * for servicing the child output and closing the pipe.
1771 */
1772static void kOCEntrySpawnProducer(PKOCENTRY pEntry, const char * const *papszArgv, unsigned cArgv, const char *pszMsg,
1773 void (*pfnConsumer)(PKOCENTRY, int))
1774{
1775 int fds[2];
1776 pid_t pid;
1777
1778 kOCEntryCreatePipe(pEntry, fds, pszMsg);
1779 pid = kOCEntrySpawnChild(pEntry, papszArgv, cArgv, -1, fds[1 /* write */], pszMsg);
1780
1781 pfnConsumer(pEntry, fds[0 /* read */]);
1782
1783 kOCEntryWaitChild(pEntry, pid, pszMsg);
1784}
1785
1786
1787/**
1788 * Spawns a child that consumes input on stdin.
1789 *
1790 * @param papszArgv Argument vector. The cArgv element is NULL.
1791 * @param cArgv The number of arguments in the vector.
1792 * @param pszMsg The operation message for info/error messages.
1793 * @param pfnProducer Pointer to a producer callback function that is responsible
1794 * for serving the child input and closing the pipe.
1795 */
1796static void kOCEntrySpawnConsumer(PKOCENTRY pEntry, const char * const *papszArgv, unsigned cArgv, const char *pszMsg,
1797 void (*pfnProducer)(PKOCENTRY, int))
1798{
1799 int fds[2];
1800 pid_t pid;
1801
1802 kOCEntryCreatePipe(pEntry, fds, pszMsg);
1803 pid = kOCEntrySpawnChild(pEntry, papszArgv, cArgv, fds[0 /* read */], -1, pszMsg);
1804
1805 pfnProducer(pEntry, fds[1 /* write */]);
1806
1807 kOCEntryWaitChild(pEntry, pid, pszMsg);
1808}
1809
1810
1811/**
1812 * Spawns two child processes, one producing output and one consuming.
1813 * Terminating on failure.
1814 *
1815 * @param papszArgv Argument vector. The cArgv element is NULL.
1816 * @param cArgv The number of arguments in the vector.
1817 * @param pszMsg The operation message for info/error messages.
1818 * @param pfnConsumer Pointer to a consumer callback function that is responsible
1819 * for servicing the child output and closing the pipe.
1820 */
1821static void kOCEntrySpawnTee(PKOCENTRY pEntry, const char * const *papszProdArgv, unsigned cProdArgv,
1822 const char * const *papszConsArgv, unsigned cConsArgv,
1823 const char *pszMsg, void (*pfnTeeConsumer)(PKOCENTRY, int, int))
1824{
1825 int fds[2];
1826 int fdIn, fdOut;
1827 pid_t pidProducer, pidConsumer;
1828
1829 /*
1830 * The producer.
1831 */
1832 kOCEntryCreatePipe(pEntry, fds, pszMsg);
1833 pidConsumer = kOCEntrySpawnChild(pEntry, papszProdArgv, cProdArgv, -1, fds[1 /* write */], pszMsg);
1834 fdIn = fds[0 /* read */];
1835
1836 /*
1837 * The consumer.
1838 */
1839 kOCEntryCreatePipe(pEntry, fds, pszMsg);
1840 pidProducer = kOCEntrySpawnChild(pEntry, papszConsArgv, cConsArgv, fds[0 /* read */], -1, pszMsg);
1841 fdOut = fds[1 /* write */];
1842
1843 /*
1844 * Hand it on to the tee consumer.
1845 */
1846 pfnTeeConsumer(pEntry, fdIn, fdOut);
1847
1848 /*
1849 * Reap the children.
1850 */
1851 kOCEntryWaitChild(pEntry, pidProducer, pszMsg);
1852 kOCEntryWaitChild(pEntry, pidConsumer, pszMsg);
1853}
1854
1855
1856/**
1857 * Reads the output from the precompiler.
1858 *
1859 * @param pEntry The cache entry. New.cbCpp and New.pszCppMapping will be updated.
1860 * @param pWhich Specifies what to read (old/new).
1861 * @param fNonFatal Whether failure is fatal or not.
1862 */
1863static int kOCEntryReadCppOutput(PKOCENTRY pEntry, struct KOCENTRYDATA *pWhich, int fNonFatal)
1864{
1865 pWhich->pszCppMapping = ReadFileInDir(pWhich->pszCppName, pEntry->pszDir, &pWhich->cbCpp);
1866 if (!pWhich->pszCppMapping)
1867 {
1868 if (!fNonFatal)
1869 FatalDie("failed to open/read '%s' in '%s': %s\n",
1870 pWhich->pszCppName, pEntry->pszDir, strerror(errno));
1871 InfoMsg(2, "failed to open/read '%s' in '%s': %s\n",
1872 pWhich->pszCppName, pEntry->pszDir, strerror(errno));
1873 return -1;
1874 }
1875
1876 InfoMsg(3, "precompiled file is %lu bytes long\n", (unsigned long)pWhich->cbCpp);
1877 return 0;
1878}
1879
1880
1881/**
1882 * Worker for kOCEntryPreCompile and calculates the checksum of
1883 * the precompiler output.
1884 *
1885 * @param pEntry The cache entry. NewSum will be updated.
1886 */
1887static void kOCEntryCalcChecksum(PKOCENTRY pEntry)
1888{
1889 KOCSUMCTX Ctx;
1890 kOCSumInitWithCtx(&pEntry->New.SumHead, &Ctx);
1891 kOCSumUpdate(&pEntry->New.SumHead, &Ctx, pEntry->New.pszCppMapping, pEntry->New.cbCpp);
1892 kOCSumFinalize(&pEntry->New.SumHead, &Ctx);
1893 kOCSumInfo(&pEntry->New.SumHead, 4, "cpp (file)");
1894}
1895
1896
1897/**
1898 * This consumes the precompiler output and checksums it.
1899 *
1900 * @param pEntry The cache entry.
1901 * @param fdIn The precompiler output pipe.
1902 * @param fdOut The compiler input pipe, -1 if no compiler.
1903 */
1904static void kOCEntryPreCompileConsumer(PKOCENTRY pEntry, int fdIn)
1905{
1906 KOCSUMCTX Ctx;
1907 long cbLeft;
1908 long cbAlloc;
1909 char *psz;
1910
1911 kOCSumInitWithCtx(&pEntry->New.SumHead, &Ctx);
1912 cbAlloc = pEntry->Old.cbCpp ? (pEntry->Old.cbCpp + 4*1024*1024 + 4096) & ~(4*1024*1024 - 1) : 4*1024*1024;
1913 cbLeft = cbAlloc;
1914 pEntry->New.pszCppMapping = psz = xmalloc(cbAlloc);
1915 for (;;)
1916 {
1917 /*
1918 * Read data from the pipe.
1919 */
1920 long cbRead = read(fdIn, psz, cbLeft - 1);
1921 if (!cbRead)
1922 break;
1923 if (cbRead < 0)
1924 {
1925 if (errno == EINTR)
1926 continue;
1927 FatalDie("precompile - read(%d,,%ld) failed: %s\n",
1928 fdIn, (long)cbLeft, strerror(errno));
1929 }
1930
1931 /*
1932 * Process the data.
1933 */
1934 psz[cbRead] = '\0';
1935 kOCSumUpdate(&pEntry->New.SumHead, &Ctx, psz, cbRead);
1936
1937 /*
1938 * Advance.
1939 */
1940 psz += cbRead;
1941 cbLeft -= cbRead;
1942 if (cbLeft <= 1)
1943 {
1944 size_t off = psz - pEntry->New.pszCppMapping;
1945 cbLeft = 4*1024*1024;
1946 cbAlloc += cbLeft;
1947 pEntry->New.pszCppMapping = xrealloc(pEntry->New.pszCppMapping, cbAlloc);
1948 psz = pEntry->New.pszCppMapping + off;
1949 }
1950 }
1951
1952 close(fdIn);
1953 pEntry->New.cbCpp = cbAlloc - cbLeft;
1954 kOCSumFinalize(&pEntry->New.SumHead, &Ctx);
1955 kOCSumInfo(&pEntry->New.SumHead, 4, "cpp (pipe)");
1956}
1957
1958
1959
1960
1961/**
1962 * Run the precompiler and calculate the checksum of the output.
1963 *
1964 * @param pEntry The cache entry.
1965 * @param papszArgvPreComp The argument vector for executing precompiler. The cArgvPreComp'th argument must be NULL.
1966 * @param cArgvPreComp The number of arguments.
1967 */
1968static void kOCEntryPreCompile(PKOCENTRY pEntry, const char * const *papszArgvPreComp, unsigned cArgvPreComp)
1969{
1970 /*
1971 * If we're executing the precompiler in piped mode, it's relatively simple.
1972 */
1973 if (pEntry->fPipedPreComp)
1974 kOCEntrySpawnProducer(pEntry, papszArgvPreComp, cArgvPreComp, "precompile",
1975 kOCEntryPreCompileConsumer);
1976 else
1977 {
1978 /*
1979 * Rename the old precompiled output to '-old' so the precompiler won't
1980 * overwrite it when we execute it.
1981 */
1982 if ( pEntry->Old.pszCppName
1983 && DoesFileInDirExist(pEntry->Old.pszCppName, pEntry->pszDir))
1984 {
1985 size_t cch = strlen(pEntry->Old.pszCppName);
1986 char *psz = xmalloc(cch + sizeof("-old"));
1987 memcpy(psz, pEntry->Old.pszCppName, cch);
1988 memcpy(psz + cch, "-old", sizeof("-old"));
1989
1990 InfoMsg(3, "renaming '%s' to '%s' in '%s'\n", pEntry->Old.pszCppName, psz, pEntry->pszDir);
1991 UnlinkFileInDir(psz, pEntry->pszDir);
1992 if (RenameFileInDir(pEntry->Old.pszCppName, psz, pEntry->pszDir))
1993 FatalDie("failed to rename '%s' -> '%s' in '%s': %s\n",
1994 pEntry->Old.pszCppName, psz, pEntry->pszDir, strerror(errno));
1995 free(pEntry->Old.pszCppName);
1996 pEntry->Old.pszCppName = psz;
1997 }
1998
1999 /*
2000 * Precompile it and calculate the checksum on the output.
2001 */
2002 InfoMsg(3, "precompiling -> '%s'...\n", pEntry->New.pszCppName);
2003 kOCEntrySpawn(pEntry, papszArgvPreComp, cArgvPreComp, "precompile", NULL);
2004 kOCEntryReadCppOutput(pEntry, &pEntry->New, 0 /* fatal */);
2005 kOCEntryCalcChecksum(pEntry);
2006 }
2007}
2008
2009
2010/**
2011 * Worker function for kOCEntryTeeConsumer and kOCEntryCompileIt that
2012 * writes the precompiler output to disk.
2013 *
2014 * @param pEntry The cache entry.
2015 * @param fFreeIt Whether we can free it after writing it or not.
2016 */
2017static void kOCEntryWriteCppOutput(PKOCENTRY pEntry, int fFreeIt)
2018{
2019 /*
2020 * Remove old files.
2021 */
2022 if (pEntry->Old.pszCppName)
2023 UnlinkFileInDir(pEntry->Old.pszCppName, pEntry->pszDir);
2024 if (pEntry->New.pszCppName)
2025 UnlinkFileInDir(pEntry->New.pszCppName, pEntry->pszDir);
2026
2027 /*
2028 * Write it to disk if we've got a file name.
2029 */
2030 if (pEntry->New.pszCppName)
2031 {
2032 long cbLeft;
2033 char *psz;
2034 int fd = OpenFileInDir(pEntry->New.pszCppName, pEntry->pszDir,
2035 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
2036 if (fd == -1)
2037 FatalDie("Failed to create '%s' in '%s': %s\n",
2038 pEntry->New.pszCppName, pEntry->pszDir, strerror(errno));
2039 psz = pEntry->New.pszCppMapping;
2040 cbLeft = pEntry->New.cbCpp;
2041 while (cbLeft > 0)
2042 {
2043 long cbWritten = write(fd, psz, cbLeft);
2044 if (cbWritten < 0)
2045 {
2046 int iErr = errno;
2047 if (iErr == EINTR)
2048 continue;
2049 close(fd);
2050 UnlinkFileInDir(pEntry->New.pszCppName, pEntry->pszDir);
2051 FatalDie("error writing '%s' in '%s': %s\n",
2052 pEntry->New.pszCppName, pEntry->pszDir, strerror(iErr));
2053 }
2054
2055 psz += cbWritten;
2056 cbLeft -= cbWritten;
2057 }
2058 close(fd);
2059 }
2060
2061 /*
2062 * Free it.
2063 */
2064 if (fFreeIt)
2065 {
2066 free(pEntry->New.pszCppMapping);
2067 pEntry->New.pszCppMapping = NULL;
2068 }
2069}
2070
2071
2072/**
2073 * kOCEntrySpawnConsumer callback that passes the precompiler
2074 * output to the compiler and writes it to the disk (latter only when necesary).
2075 *
2076 * @param pEntry The cache entry.
2077 * @param fdOut The pipe handle connected to the childs stdin.
2078 */
2079static void kOCEntryCompileProducer(PKOCENTRY pEntry, int fdOut)
2080{
2081 const char *psz = pEntry->New.pszCppMapping;
2082 long cbLeft = pEntry->New.cbCpp;
2083 while (cbLeft > 0)
2084 {
2085 long cbWritten = write(fdOut, psz, cbLeft);
2086 if (cbWritten < 0)
2087 {
2088 if (errno == EINTR)
2089 continue;
2090 FatalDie("compile - write(%d,,%ld) failed: %s\n", fdOut, cbLeft, strerror(errno));
2091 }
2092 psz += cbWritten;
2093 cbLeft -= cbWritten;
2094 }
2095 close(fdOut);
2096
2097 if (pEntry->fPipedPreComp)
2098 kOCEntryWriteCppOutput(pEntry, 1 /* free it */);
2099}
2100
2101
2102/**
2103 * Does the actual compiling.
2104 *
2105 * @param pEntry The cache entry.
2106 */
2107static void kOCEntryCompileIt(PKOCENTRY pEntry)
2108{
2109 /*
2110 * Delete the object files and free old cpp output that's no longer needed.
2111 */
2112 if (pEntry->Old.pszObjName)
2113 UnlinkFileInDir(pEntry->Old.pszObjName, pEntry->pszDir);
2114 UnlinkFileInDir(pEntry->New.pszObjName, pEntry->pszDir);
2115
2116 free(pEntry->Old.pszCppMapping);
2117 pEntry->Old.pszCppMapping = NULL;
2118 if (!pEntry->fPipedPreComp && !pEntry->fPipedCompile)
2119 {
2120 free(pEntry->New.pszCppMapping);
2121 pEntry->New.pszCppMapping = NULL;
2122 }
2123
2124 /*
2125 * Do the (re-)compile job.
2126 */
2127 if (pEntry->fPipedCompile)
2128 {
2129 if ( !pEntry->fPipedPreComp
2130 && !pEntry->New.pszCppMapping)
2131 kOCEntryReadCppOutput(pEntry, &pEntry->New, 0 /* fatal */);
2132 InfoMsg(3, "compiling -> '%s'...\n", pEntry->New.pszObjName);
2133 kOCEntrySpawnConsumer(pEntry, (const char * const *)pEntry->New.papszArgvCompile, pEntry->New.cArgvCompile,
2134 "compile", kOCEntryCompileProducer);
2135 }
2136 else
2137 {
2138 if (pEntry->fPipedPreComp)
2139 kOCEntryWriteCppOutput(pEntry, 1 /* free it */);
2140 InfoMsg(3, "compiling -> '%s'...\n", pEntry->New.pszObjName);
2141 kOCEntrySpawn(pEntry, (const char * const *)pEntry->New.papszArgvCompile, pEntry->New.cArgvCompile, "compile", NULL);
2142 }
2143}
2144
2145
2146/**
2147 * kOCEntrySpawnTee callback that works sort of like 'tee'.
2148 *
2149 * It will calculate the precompiled output checksum and
2150 * write it to disk while the compiler is busy compiling it.
2151 *
2152 * @param pEntry The cache entry.
2153 * @param fdIn The input handle (connected to the precompiler).
2154 * @param fdOut The output handle (connected to the compiler).
2155 */
2156static void kOCEntryTeeConsumer(PKOCENTRY pEntry, int fdIn, int fdOut)
2157{
2158 KOCSUMCTX Ctx;
2159 long cbLeft;
2160 long cbAlloc;
2161 char *psz;
2162
2163 kOCSumInitWithCtx(&pEntry->New.SumHead, &Ctx);
2164 cbAlloc = pEntry->Old.cbCpp ? (pEntry->Old.cbCpp + 4*1024*1024 + 4096) & ~(4*1024*1024 - 1) : 4*1024*1024;
2165 cbLeft = cbAlloc;
2166 pEntry->New.pszCppMapping = psz = xmalloc(cbAlloc);
2167 InfoMsg(3, "precompiler|compile - starting passhtru...\n");
2168 for (;;)
2169 {
2170 /*
2171 * Read data from the pipe.
2172 */
2173 long cbRead = read(fdIn, psz, cbLeft - 1);
2174 if (!cbRead)
2175 break;
2176 if (cbRead < 0)
2177 {
2178 if (errno == EINTR)
2179 continue;
2180 FatalDie("precompile|compile - read(%d,,%ld) failed: %s\n",
2181 fdIn, (long)cbLeft, strerror(errno));
2182 }
2183 InfoMsg(3, "precompiler|compile - read %d\n", cbRead);
2184
2185 /*
2186 * Process the data.
2187 */
2188 psz[cbRead] = '\0';
2189 kOCSumUpdate(&pEntry->New.SumHead, &Ctx, psz, cbRead);
2190 do
2191 {
2192 long cbWritten = write(fdOut, psz, cbRead);
2193 if (cbWritten < 0)
2194 {
2195 if (errno == EINTR)
2196 continue;
2197 FatalDie("precompile|compile - write(%d,,%ld) failed: %s\n", fdOut, cbRead, strerror(errno));
2198 }
2199 psz += cbWritten;
2200 cbRead -= cbWritten;
2201 cbLeft -= cbWritten;
2202 } while (cbRead > 0);
2203
2204 /*
2205 * Expand the buffer?
2206 */
2207 if (cbLeft <= 1)
2208 {
2209 size_t off = psz - pEntry->New.pszCppMapping;
2210 cbLeft = 4*1024*1024;
2211 cbAlloc += cbLeft;
2212 pEntry->New.pszCppMapping = xrealloc(pEntry->New.pszCppMapping, cbAlloc);
2213 psz = pEntry->New.pszCppMapping + off;
2214 }
2215 }
2216 InfoMsg(3, "precompiler|compile - done passhtru\n");
2217
2218 close(fdIn);
2219 close(fdOut);
2220 pEntry->New.cbCpp = cbAlloc - cbLeft;
2221 kOCSumFinalize(&pEntry->New.SumHead, &Ctx);
2222 kOCSumInfo(&pEntry->New.SumHead, 4, "cpp (tee)");
2223
2224 /*
2225 * Write the precompiler output to disk and free the memory it
2226 * occupies while the compiler is busy compiling.
2227 */
2228 kOCEntryWriteCppOutput(pEntry, 1 /* free it */);
2229}
2230
2231
2232/**
2233 * Performs pre-compile and compile in one go (typical clean build scenario).
2234 *
2235 * @param pEntry The cache entry.
2236 * @param papszArgvPreComp The argument vector for executing precompiler. The cArgvPreComp'th argument must be NULL.
2237 * @param cArgvPreComp The number of arguments.
2238 */
2239static void kOCEntryPreCompileAndCompile(PKOCENTRY pEntry, const char * const *papszArgvPreComp, unsigned cArgvPreComp)
2240{
2241 if ( pEntry->fPipedCompile
2242 && pEntry->fPipedPreComp)
2243 {
2244 /*
2245 * Clean up old stuff first.
2246 */
2247 if (pEntry->Old.pszObjName)
2248 UnlinkFileInDir(pEntry->Old.pszObjName, pEntry->pszDir);
2249 if (pEntry->New.pszObjName)
2250 UnlinkFileInDir(pEntry->New.pszObjName, pEntry->pszDir);
2251 if (pEntry->Old.pszCppName)
2252 UnlinkFileInDir(pEntry->Old.pszCppName, pEntry->pszDir);
2253 if (pEntry->New.pszCppName)
2254 UnlinkFileInDir(pEntry->New.pszCppName, pEntry->pszDir);
2255
2256 /*
2257 * Do the actual compile and write the precompiler output to disk.
2258 */
2259 kOCEntrySpawnTee(pEntry, papszArgvPreComp, cArgvPreComp,
2260 (const char * const *)pEntry->New.papszArgvCompile, pEntry->New.cArgvCompile,
2261 "precompile|compile", kOCEntryTeeConsumer);
2262 }
2263 else
2264 {
2265 kOCEntryPreCompile(pEntry, papszArgvPreComp, cArgvPreComp);
2266 kOCEntryCompileIt(pEntry);
2267 }
2268}
2269
2270
2271/**
2272 * Check whether the string is a '#line' statement.
2273 *
2274 * @returns 1 if it is, 0 if it isn't.
2275 * @param psz The line to examin.
2276 * @parma piLine Where to store the line number.
2277 * @parma ppszFile Where to store the start of the filename.
2278 */
2279static int kOCEntryIsLineStatement(const char *psz, unsigned *piLine, const char **ppszFile)
2280{
2281 unsigned iLine;
2282
2283 /* Expect a hash. */
2284 if (*psz++ != '#')
2285 return 0;
2286
2287 /* Skip blanks between '#' and the line / number */
2288 while (*psz == ' ' || *psz == '\t')
2289 psz++;
2290
2291 /* Skip the 'line' if present. */
2292 if (!strncmp(psz, "line", sizeof("line") - 1))
2293 psz += sizeof("line");
2294
2295 /* Expect a line number now. */
2296 if ((unsigned char)(*psz - '0') > 9)
2297 return 0;
2298 iLine = 0;
2299 do
2300 {
2301 iLine *= 10;
2302 iLine += (*psz - '0');
2303 psz++;
2304 }
2305 while ((unsigned char)(*psz - '0') <= 9);
2306
2307 /* Expect one or more space now. */
2308 if (*psz != ' ' && *psz != '\t')
2309 return 0;
2310 do psz++;
2311 while (*psz == ' ' || *psz == '\t');
2312
2313 /* that's good enough. */
2314 *piLine = iLine;
2315 *ppszFile = psz;
2316 return 1;
2317}
2318
2319
2320/**
2321 * Scan backwards for the previous #line statement.
2322 *
2323 * @returns The filename in the previous statement.
2324 * @param pszStart Where to start.
2325 * @param pszStop Where to stop. Less than pszStart.
2326 * @param piLine The line number count to adjust.
2327 */
2328static const char *kOCEntryFindFileStatement(const char *pszStart, const char *pszStop, unsigned *piLine)
2329{
2330 unsigned iLine = *piLine;
2331 assert(pszStart >= pszStop);
2332 while (pszStart >= pszStop)
2333 {
2334 if (*pszStart == '\n')
2335 iLine++;
2336 else if (*pszStart == '#')
2337 {
2338 unsigned iLineTmp;
2339 const char *pszFile;
2340 const char *psz = pszStart - 1;
2341 while (psz >= pszStop && (*psz == ' ' || *psz =='\t'))
2342 psz--;
2343 if ( (psz < pszStop || *psz == '\n')
2344 && kOCEntryIsLineStatement(pszStart, &iLineTmp, &pszFile))
2345 {
2346 *piLine = iLine + iLineTmp - 1;
2347 return pszFile;
2348 }
2349 }
2350 pszStart--;
2351 }
2352 return NULL;
2353}
2354
2355
2356/**
2357 * Worker for kOCEntryCompareOldAndNewOutput() that compares the
2358 * precompiled output using a fast but not very good method.
2359 *
2360 * @returns 1 if matching, 0 if not matching.
2361 * @param pEntry The entry containing the names of the files to compare.
2362 * The entry is not updated in any way.
2363 */
2364static int kOCEntryCompareFast(PCKOCENTRY pEntry)
2365{
2366 const char * psz1 = pEntry->New.pszCppMapping;
2367 const char * const pszEnd1 = psz1 + pEntry->New.cbCpp;
2368 const char * psz2 = pEntry->Old.pszCppMapping;
2369 const char * const pszEnd2 = psz2 + pEntry->Old.cbCpp;
2370
2371 assert(*pszEnd1 == '\0');
2372 assert(*pszEnd2 == '\0');
2373
2374 /*
2375 * Iterate block by block and backtrack when we find a difference.
2376 */
2377 for (;;)
2378 {
2379 size_t cch = pszEnd1 - psz1;
2380 if (cch > (size_t)(pszEnd2 - psz2))
2381 cch = pszEnd2 - psz2;
2382 if (cch > 4096)
2383 cch = 4096;
2384 if ( cch
2385 && !memcmp(psz1, psz2, cch))
2386 {
2387 /* no differences */
2388 psz1 += cch;
2389 psz2 += cch;
2390 }
2391 else
2392 {
2393 /*
2394 * Pinpoint the difference exactly and the try find the start
2395 * of that line. Then skip forward until we find something to
2396 * work on that isn't spaces, #line statements or closing curly
2397 * braces.
2398 *
2399 * The closing curly braces are ignored because they are frequently
2400 * found at the end of header files (__END_DECLS) and the worst
2401 * thing that may happen if it isn't one of these braces we're
2402 * ignoring is that the final line in a function block is a little
2403 * bit off in the debug info.
2404 *
2405 * Since we might be skipping a few new empty headers, it is
2406 * possible that we will omit this header from the dependencies
2407 * when using VCC. This might not be a problem, since it seems
2408 * we'll have to use the precompiler output to generate the deps
2409 * anyway.
2410 */
2411 const char *psz;
2412 const char *pszMismatch1;
2413 const char *pszFile1 = NULL;
2414 unsigned iLine1 = 0;
2415 unsigned cCurlyBraces1 = 0;
2416 const char *pszMismatch2;
2417 const char *pszFile2 = NULL;
2418 unsigned iLine2 = 0;
2419 unsigned cCurlyBraces2 = 0;
2420
2421 /* locate the difference. */
2422 while (cch >= 512 && !memcmp(psz1, psz2, 512))
2423 psz1 += 512, psz2 += 512, cch -= 512;
2424 while (cch >= 64 && !memcmp(psz1, psz2, 64))
2425 psz1 += 64, psz2 += 64, cch -= 64;
2426 while (*psz1 == *psz2 && cch > 0)
2427 psz1++, psz2++, cch--;
2428
2429 /* locate the start of that line. */
2430 psz = psz1;
2431 while ( psz > pEntry->New.pszCppMapping
2432 && psz[-1] != '\n')
2433 psz--;
2434 psz2 -= (psz1 - psz);
2435 pszMismatch2 = psz2;
2436 pszMismatch1 = psz1 = psz;
2437
2438 /* Parse the 1st file line by line. */
2439 while (psz1 < pszEnd1)
2440 {
2441 if (*psz1 == '\n')
2442 {
2443 psz1++;
2444 iLine1++;
2445 }
2446 else
2447 {
2448 psz = psz1;
2449 while (isspace(*psz) && *psz != '\n')
2450 psz++;
2451 if (*psz == '\n')
2452 {
2453 psz1 = psz + 1;
2454 iLine1++;
2455 }
2456 else if (*psz == '#' && kOCEntryIsLineStatement(psz, &iLine1, &pszFile1))
2457 {
2458 psz1 = memchr(psz, '\n', pszEnd1 - psz);
2459 if (!psz1++)
2460 psz1 = pszEnd1;
2461 }
2462 else if (*psz == '}')
2463 {
2464 do psz++;
2465 while (isspace(*psz) && *psz != '\n');
2466 if (*psz == '\n')
2467 iLine1++;
2468 else if (psz != pszEnd1)
2469 break;
2470 cCurlyBraces1++;
2471 psz1 = psz;
2472 }
2473 else if (psz == pszEnd1)
2474 psz1 = psz;
2475 else /* found something that can be compared. */
2476 break;
2477 }
2478 }
2479
2480 /* Ditto for the 2nd file. */
2481 while (psz2 < pszEnd2)
2482 {
2483 if (*psz2 == '\n')
2484 {
2485 psz2++;
2486 iLine2++;
2487 }
2488 else
2489 {
2490 psz = psz2;
2491 while (isspace(*psz) && *psz != '\n')
2492 psz++;
2493 if (*psz == '\n')
2494 {
2495 psz2 = psz + 1;
2496 iLine2++;
2497 }
2498 else if (*psz == '#' && kOCEntryIsLineStatement(psz, &iLine2, &pszFile2))
2499 {
2500 psz2 = memchr(psz, '\n', pszEnd2 - psz);
2501 if (!psz2++)
2502 psz2 = pszEnd2;
2503 }
2504 else if (*psz == '}')
2505 {
2506 do psz++;
2507 while (isspace(*psz) && *psz != '\n');
2508 if (*psz == '\n')
2509 iLine2++;
2510 else if (psz != pszEnd2)
2511 break;
2512 cCurlyBraces2++;
2513 psz2 = psz;
2514 }
2515 else if (psz == pszEnd2)
2516 psz2 = psz;
2517 else /* found something that can be compared. */
2518 break;
2519 }
2520 }
2521
2522 /* Match the number of ignored closing curly braces. */
2523 if (cCurlyBraces1 != cCurlyBraces2)
2524 return 0;
2525
2526 /* Reaching the end of any of them means the return statement can decide. */
2527 if ( psz1 == pszEnd1
2528 || psz2 == pszEnd2)
2529 break;
2530
2531 /* Match the current line. */
2532 psz = memchr(psz1, '\n', pszEnd1 - psz1);
2533 if (!psz)
2534 psz = pszEnd1;
2535 cch = psz - psz1;
2536 if (psz2 + cch > pszEnd2)
2537 break;
2538 if (memcmp(psz1, psz2, cch))
2539 break;
2540
2541 /* Check that we're at the same location now. */
2542 if (!pszFile1)
2543 pszFile1 = kOCEntryFindFileStatement(pszMismatch1, pEntry->New.pszCppMapping, &iLine1);
2544 if (!pszFile2)
2545 pszFile2 = kOCEntryFindFileStatement(pszMismatch2, pEntry->Old.pszCppMapping, &iLine2);
2546 if (pszFile1 && pszFile2)
2547 {
2548 if (iLine1 != iLine2)
2549 break;
2550 while (*pszFile1 == *pszFile2 && *pszFile1 != '\n' && *pszFile1)
2551 pszFile1++, pszFile2++;
2552 if (*pszFile1 != *pszFile2)
2553 break;
2554 }
2555 else if (pszFile1 || pszFile2)
2556 {
2557 assert(0); /* this shouldn't happen. */
2558 break;
2559 }
2560
2561 /* Try align psz1 on 8 or 4 bytes so at least one of the buffers are aligned. */
2562 psz1 += cch;
2563 psz2 += cch;
2564 if (cch >= ((uintptr_t)psz1 & 7))
2565 {
2566 psz2 -= ((uintptr_t)psz1 & 7);
2567 psz1 -= ((uintptr_t)psz1 & 7);
2568 }
2569 else if (cch >= ((uintptr_t)psz1 & 3))
2570 {
2571 psz2 -= ((uintptr_t)psz1 & 3);
2572 psz1 -= ((uintptr_t)psz1 & 3);
2573 }
2574 }
2575 }
2576
2577 return psz1 == pszEnd1
2578 && psz2 == pszEnd2;
2579}
2580
2581
2582/**
2583 * Worker for kOCEntryCompileIfNeeded that compares the
2584 * precompiled output.
2585 *
2586 * @returns 1 if matching, 0 if not matching.
2587 * @param pEntry The entry containing the names of the files to compare.
2588 * This will load the old cpp output (changing pszOldCppName and Old.cbCpp).
2589 */
2590static int kOCEntryCompareOldAndNewOutput(PKOCENTRY pEntry)
2591{
2592 /*
2593 * I may implement a more sophisticated alternative method later... maybe.
2594 */
2595 if (kOCEntryReadCppOutput(pEntry, &pEntry->Old, 1 /* nonfatal */) == -1)
2596 return 0;
2597 //if ()
2598 // return kOCEntryCompareBest(pEntry);
2599 return kOCEntryCompareFast(pEntry);
2600}
2601
2602
2603/**
2604 * Check if re-compilation is required.
2605 * This sets the fNeedCompile flag.
2606 *
2607 * @param pEntry The cache entry.
2608 */
2609static void kOCEntryCalcRecompile(PKOCENTRY pEntry)
2610{
2611 if (pEntry->fNeedCompiling)
2612 return;
2613
2614 /*
2615 * Check if the precompiler output differ in any significant way?
2616 */
2617 if (!kOCSumHasEqualInChain(&pEntry->Old.SumHead, &pEntry->New.SumHead))
2618 {
2619 InfoMsg(2, "no checksum match - comparing output\n");
2620 if (!kOCEntryCompareOldAndNewOutput(pEntry))
2621 pEntry->fNeedCompiling = 1;
2622 else
2623 kOCSumAddChain(&pEntry->New.SumHead, &pEntry->Old.SumHead);
2624 }
2625}
2626
2627
2628/**
2629 * Does this cache entry need compiling or what?
2630 *
2631 * @returns 1 if it does, 0 if it doesn't.
2632 * @param pEntry The cache entry in question.
2633 */
2634static int kOCEntryNeedsCompiling(PCKOCENTRY pEntry)
2635{
2636 return pEntry->fNeedCompiling;
2637}
2638
2639
2640/**
2641 * Worker function for kOCEntryCopy.
2642 *
2643 * @param pEntry The entry we're coping to, which pszTo is relative to.
2644 * @param pszTo The destination.
2645 * @param pszFrom The source. This path will be freed.
2646 */
2647static void kOCEntryCopyFile(PCKOCENTRY pEntry, const char *pszTo, char *pszSrc)
2648{
2649 char *pszDst = MakePathFromDirAndFile(pszTo, pEntry->pszDir);
2650 char *pszBuf = xmalloc(256 * 1024);
2651 char *psz;
2652 int fdSrc;
2653 int fdDst;
2654
2655 /*
2656 * Open the files.
2657 */
2658 fdSrc = open(pszSrc, O_RDONLY | O_BINARY);
2659 if (fdSrc == -1)
2660 FatalDie("failed to open '%s': %s\n", pszSrc, strerror(errno));
2661
2662 unlink(pszDst);
2663 fdDst = open(pszDst, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
2664 if (fdDst == -1)
2665 FatalDie("failed to create '%s': %s\n", pszDst, strerror(errno));
2666
2667 /*
2668 * Copy them.
2669 */
2670 for (;;)
2671 {
2672 /* read a chunk. */
2673 long cbRead = read(fdSrc, pszBuf, 256*1024);
2674 if (cbRead < 0)
2675 {
2676 if (errno == EINTR)
2677 continue;
2678 FatalDie("read '%s' failed: %s\n", pszSrc, strerror(errno));
2679 }
2680 if (!cbRead)
2681 break; /* eof */
2682
2683 /* write the chunk. */
2684 psz = pszBuf;
2685 do
2686 {
2687 long cbWritten = write(fdDst, psz, cbRead);
2688 if (cbWritten < 0)
2689 {
2690 if (errno == EINTR)
2691 continue;
2692 FatalDie("write '%s' failed: %s\n", pszSrc, strerror(errno));
2693 }
2694 psz += cbWritten;
2695 cbRead -= cbWritten;
2696 } while (cbRead > 0);
2697 }
2698
2699 /* cleanup */
2700 if (close(fdDst) != 0)
2701 FatalDie("closing '%s' failed: %s\n", pszDst, strerror(errno));
2702 close(fdSrc);
2703 free(pszBuf);
2704 free(pszDst);
2705 free(pszSrc);
2706}
2707
2708
2709/**
2710 * Copies the object (and whatever else) from one cache entry to another.
2711 *
2712 * This is called when a matching cache entry has been found and we don't
2713 * need to recompile anything.
2714 *
2715 * @param pEntry The entry to copy to.
2716 * @param pFrom The entry to copy from.
2717 */
2718static void kOCEntryCopy(PKOCENTRY pEntry, PCKOCENTRY pFrom)
2719{
2720 kOCEntryCopyFile(pEntry, pEntry->New.pszObjName,
2721 MakePathFromDirAndFile(pFrom->New.pszObjName
2722 ? pFrom->New.pszObjName : pFrom->Old.pszObjName,
2723 pFrom->pszDir));
2724}
2725
2726
2727/**
2728 * Gets the absolute path to the cache entry.
2729 *
2730 * @returns absolute path to the cache entry.
2731 * @param pEntry The cache entry in question.
2732 */
2733static const char *kOCEntryAbsPath(PCKOCENTRY pEntry)
2734{
2735 return pEntry->pszAbsPath;
2736}
2737
2738
2739
2740
2741
2742
2743/**
2744 * Digest of one cache entry.
2745 *
2746 * This contains all the information required to find a matching
2747 * cache entry without having to open each of the files.
2748 */
2749typedef struct KOCDIGEST
2750{
2751 /** The relative path to the entry. Optional if pszAbsPath is set. */
2752 char *pszRelPath;
2753 /** The absolute path to the entry. Optional if pszRelPath is set. */
2754 char *pszAbsPath;
2755 /** The target os/arch identifier. */
2756 char *pszTarget;
2757 /** A unique number assigned to the entry when it's (re)-inserted
2758 * into the cache. This is used for simple consitency checking. */
2759 uint32_t uKey;
2760 /** The checksum of the compile argument vector. */
2761 KOCSUM SumCompArgv;
2762 /** The list of precompiler output checksums that's . */
2763 KOCSUM SumHead;
2764} KOCDIGEST;
2765/** Pointer to a file digest. */
2766typedef KOCDIGEST *PKOCDIGEST;
2767/** Pointer to a const file digest. */
2768typedef KOCDIGEST *PCKOCDIGEST;
2769
2770
2771/**
2772 * Initializes the specified digest.
2773 *
2774 * @param pDigest The digest.
2775 */
2776static void kOCDigestInit(PKOCDIGEST pDigest)
2777{
2778 memset(pDigest, 0, sizeof(*pDigest));
2779 kOCSumInit(&pDigest->SumHead);
2780}
2781
2782
2783/**
2784 * Initializes the digest for the specified entry.
2785 *
2786 * @param pDigest The (uninitialized) digest.
2787 * @param pEntry The entry.
2788 */
2789static void kOCDigestInitFromEntry(PKOCDIGEST pDigest, PCKOCENTRY pEntry)
2790{
2791 kOCDigestInit(pDigest);
2792
2793 pDigest->uKey = pEntry->uKey;
2794 pDigest->pszTarget = xstrdup(pEntry->New.pszTarget ? pEntry->New.pszTarget : pEntry->Old.pszTarget);
2795
2796 kOCSumInit(&pDigest->SumCompArgv);
2797 if (!kOCSumIsEmpty(&pEntry->New.SumCompArgv))
2798 kOCSumAdd(&pDigest->SumCompArgv, &pEntry->New.SumCompArgv);
2799 else
2800 kOCSumAdd(&pDigest->SumCompArgv, &pEntry->Old.SumCompArgv);
2801
2802 kOCSumInit(&pDigest->SumHead);
2803 if (!kOCSumIsEmpty(&pEntry->New.SumHead))
2804 kOCSumAddChain(&pDigest->SumHead, &pEntry->New.SumHead);
2805 else
2806 kOCSumAddChain(&pDigest->SumHead, &pEntry->Old.SumHead);
2807
2808 /** @todo implement selective relative path support. */
2809 pDigest->pszRelPath = NULL;
2810 pDigest->pszAbsPath = xstrdup(kOCEntryAbsPath(pEntry));
2811}
2812
2813
2814/**
2815 * Purges a digest, freeing all resources and returning
2816 * it to the initial state.
2817 *
2818 * @param pDigest The digest.
2819 */
2820static void kOCDigestPurge(PKOCDIGEST pDigest)
2821{
2822 free(pDigest->pszRelPath);
2823 free(pDigest->pszAbsPath);
2824 free(pDigest->pszTarget);
2825 pDigest->pszTarget = pDigest->pszAbsPath = pDigest->pszRelPath = NULL;
2826 pDigest->uKey = 0;
2827 kOCSumDeleteChain(&pDigest->SumCompArgv);
2828 kOCSumDeleteChain(&pDigest->SumHead);
2829}
2830
2831
2832/**
2833 * Returns the absolute path to the entry, calculating
2834 * the path if necessary.
2835 *
2836 * @returns absolute path.
2837 * @param pDigest The digest.
2838 * @param pszDir The cache directory that it might be relative to.
2839 */
2840static const char *kOCDigestAbsPath(PCKOCDIGEST pDigest, const char *pszDir)
2841{
2842 if (!pDigest->pszAbsPath)
2843 {
2844 char *pszPath = MakePathFromDirAndFile(pDigest->pszRelPath, pszDir);
2845 ((PKOCDIGEST)pDigest)->pszAbsPath = AbsPath(pszPath);
2846 free(pszPath);
2847 }
2848 return pDigest->pszAbsPath;
2849}
2850
2851
2852/**
2853 * Checks that the digest matches the
2854 *
2855 * @returns 1 if valid, 0 if invalid in some way.
2856 *
2857 * @param pDigest The digest to validate.
2858 * @param pEntry What to validate it against.
2859 */
2860static int kOCDigestIsValid(PCKOCDIGEST pDigest, PCKOCENTRY pEntry)
2861{
2862 PCKOCSUM pSum;
2863 PCKOCSUM pSumEntry;
2864
2865 if (pDigest->uKey != pEntry->uKey)
2866 return 0;
2867
2868 if (!kOCSumIsEqual(&pDigest->SumCompArgv,
2869 kOCSumIsEmpty(&pEntry->New.SumCompArgv)
2870 ? &pEntry->Old.SumCompArgv : &pEntry->New.SumCompArgv))
2871 return 0;
2872
2873 if (strcmp(pDigest->pszTarget, pEntry->New.pszTarget ? pEntry->New.pszTarget : pEntry->Old.pszTarget))
2874 return 0;
2875
2876 /* match the checksums */
2877 pSumEntry = kOCSumIsEmpty(&pEntry->New.SumHead)
2878 ? &pEntry->Old.SumHead : &pEntry->New.SumHead;
2879 for (pSum = &pDigest->SumHead; pSum; pSum = pSum->pNext)
2880 if (!kOCSumHasEqualInChain(pSumEntry, pSum))
2881 return 0;
2882
2883 return 1;
2884}
2885
2886
2887
2888
2889
2890/**
2891 * The structure for the central cache entry.
2892 */
2893typedef struct KOBJCACHE
2894{
2895 /** The entry name. */
2896 const char *pszName;
2897 /** The dir that relative names in the digest are relative to. */
2898 char *pszDir;
2899 /** The absolute path. */
2900 char *pszAbsPath;
2901
2902 /** The cache file descriptor. */
2903 int fd;
2904 /** The stream associated with fd. */
2905 FILE *pFile;
2906 /** Whether it's currently locked or not. */
2907 unsigned fLocked;
2908 /** Whether the cache file is dirty and needs writing back. */
2909 unsigned fDirty;
2910 /** Whether this is a new cache or not. */
2911 unsigned fNewCache;
2912
2913 /** The cache file generation. */
2914 uint32_t uGeneration;
2915 /** The next valid key. (Determin at load time.) */
2916 uint32_t uNextKey;
2917
2918 /** Number of digests in paDigests. */
2919 unsigned cDigests;
2920 /** Array of digests for the KOCENTRY objects in the cache. */
2921 PKOCDIGEST paDigests;
2922
2923} KOBJCACHE;
2924/** Pointer to a cache. */
2925typedef KOBJCACHE *PKOBJCACHE;
2926/** Pointer to a const cache. */
2927typedef KOBJCACHE const *PCKOBJCACHE;
2928
2929
2930/**
2931 * Creates an empty cache.
2932 *
2933 * This doesn't touch the file system, it just create the data structure.
2934 *
2935 * @returns Pointer to a cache.
2936 * @param pszCacheFile The cache file.
2937 */
2938static PKOBJCACHE kObjCacheCreate(const char *pszCacheFile)
2939{
2940 PKOBJCACHE pCache;
2941 size_t off;
2942
2943 /*
2944 * Allocate an empty entry.
2945 */
2946 pCache = xmallocz(sizeof(*pCache));
2947 pCache->fd = -1;
2948
2949 /*
2950 * Setup the directory and cache file name.
2951 */
2952 pCache->pszAbsPath = AbsPath(pszCacheFile);
2953 pCache->pszName = FindFilenameInPath(pCache->pszAbsPath);
2954 off = pCache->pszName - pCache->pszAbsPath;
2955 if (!off)
2956 FatalDie("Failed to find abs path for '%s'!\n", pszCacheFile);
2957 pCache->pszDir = xmalloc(off);
2958 memcpy(pCache->pszDir, pCache->pszAbsPath, off - 1);
2959 pCache->pszDir[off - 1] = '\0';
2960
2961 return pCache;
2962}
2963
2964
2965/**
2966 * Destroys the cache - closing any open files, freeing up heap memory and such.
2967 *
2968 * @param pCache The cache.
2969 */
2970static void kObjCacheDestroy(PKOBJCACHE pCache)
2971{
2972 if (pCache->pFile)
2973 {
2974 errno = 0;
2975 if (fclose(pCache->pFile) != 0)
2976 FatalMsg("fclose failed: %s\n", strerror(errno));
2977 pCache->pFile = NULL;
2978 pCache->fd = -1;
2979 }
2980 free(pCache->paDigests);
2981 free(pCache->pszAbsPath);
2982 free(pCache->pszDir);
2983 free(pCache);
2984}
2985
2986
2987/**
2988 * Purges the data in the cache object.
2989 *
2990 * @param pCache The cache object.
2991 */
2992static void kObjCachePurge(PKOBJCACHE pCache)
2993{
2994 while (pCache->cDigests > 0)
2995 kOCDigestPurge(&pCache->paDigests[--pCache->cDigests]);
2996 free(pCache->paDigests);
2997 pCache->paDigests = NULL;
2998 pCache->uGeneration = 0;
2999 pCache->uNextKey = 0;
3000}
3001
3002
3003/**
3004 * (Re-)reads the file.
3005 *
3006 * @param pCache The cache to (re)-read.
3007 */
3008static void kObjCacheRead(PKOBJCACHE pCache)
3009{
3010 unsigned i;
3011 char szBuf[8192];
3012 int fBad = 0;
3013
3014 InfoMsg(4, "reading cache file...\n");
3015
3016 /*
3017 * Rewind the file & stream, and associate a temporary buffer
3018 * with the stream to speed up reading.
3019 */
3020 if (lseek(pCache->fd, 0, SEEK_SET) == -1)
3021 FatalDie("lseek(cache-fd) failed: %s\n", strerror(errno));
3022 rewind(pCache->pFile);
3023 if (setvbuf(pCache->pFile, szBuf, _IOFBF, sizeof(szBuf)) != 0)
3024 FatalDie("fdopen(cache-fd,rb) failed: %s\n", strerror(errno));
3025
3026 /*
3027 * Read magic and generation.
3028 */
3029 if ( !fgets(g_szLine, sizeof(g_szLine), pCache->pFile)
3030 || strcmp(g_szLine, "magic=kObjCache-v0.1.0\n"))
3031 {
3032 InfoMsg(2, "bad cache file (magic)\n");
3033 fBad = 1;
3034 }
3035 else if ( !fgets(g_szLine, sizeof(g_szLine), pCache->pFile)
3036 || strncmp(g_szLine, "generation=", sizeof("generation=") - 1))
3037 {
3038 InfoMsg(2, "bad cache file (generation)\n");
3039 fBad = 1;
3040 }
3041 else if ( pCache->uGeneration
3042 && pCache->uGeneration == atol(&g_szLine[sizeof("generation=") - 1]))
3043 {
3044 InfoMsg(3, "drop re-read unmodified cache file\n");
3045 fBad = 0;
3046 }
3047 else
3048 {
3049 int fBadBeforeMissing;
3050
3051 /*
3052 * Read everything (anew).
3053 */
3054 kObjCachePurge(pCache);
3055 do
3056 {
3057 PKOCDIGEST pDigest;
3058 char *pszNl;
3059 char *pszVal;
3060 char *psz;
3061
3062 /* Split the line and drop the trailing newline. */
3063 pszVal = strchr(g_szLine, '=');
3064 if ((fBad = pszVal == NULL))
3065 break;
3066 *pszVal++ = '\0';
3067
3068 pszNl = strchr(pszVal, '\n');
3069 if (pszNl)
3070 *pszNl = '\0';
3071
3072 /* digest '#'? */
3073 psz = strchr(g_szLine, '#');
3074 if (psz)
3075 {
3076 char *pszNext;
3077 i = strtoul(++psz, &pszNext, 0);
3078 if ((fBad = pszNext && *pszNext))
3079 break;
3080 if ((fBad = i >= pCache->cDigests))
3081 break;
3082 pDigest = &pCache->paDigests[i];
3083 *psz = '\0';
3084 }
3085 else
3086 pDigest = NULL;
3087
3088
3089 /* string case on value name. */
3090 if (!strcmp(g_szLine, "sum-#"))
3091 {
3092 KOCSUM Sum;
3093 if ((fBad = kOCSumInitFromString(&Sum, pszVal) != 0))
3094 break;
3095 kOCSumAdd(&pDigest->SumHead, &Sum);
3096 }
3097 else if (!strcmp(g_szLine, "digest-abs-#"))
3098 {
3099 if ((fBad = pDigest->pszAbsPath != NULL))
3100 break;
3101 pDigest->pszAbsPath = xstrdup(pszVal);
3102 }
3103 else if (!strcmp(g_szLine, "digest-rel-#"))
3104 {
3105 if ((fBad = pDigest->pszRelPath != NULL))
3106 break;
3107 pDigest->pszRelPath = xstrdup(pszVal);
3108 }
3109 else if (!strcmp(g_szLine, "key-#"))
3110 {
3111 if ((fBad = pDigest->uKey != 0))
3112 break;
3113 pDigest->uKey = strtoul(pszVal, &psz, 0);
3114 if ((fBad = psz && *psz))
3115 break;
3116 if (pDigest->uKey >= pCache->uNextKey)
3117 pCache->uNextKey = pDigest->uKey + 1;
3118 }
3119 else if (!strcmp(g_szLine, "comp-argv-sum-#"))
3120 {
3121 if ((fBad = !kOCSumIsEmpty(&pDigest->SumCompArgv)))
3122 break;
3123 if ((fBad = kOCSumInitFromString(&pDigest->SumCompArgv, pszVal) != 0))
3124 break;
3125 }
3126 else if (!strcmp(g_szLine, "target-#"))
3127 {
3128 if ((fBad = pDigest->pszTarget != NULL))
3129 break;
3130 pDigest->pszTarget = xstrdup(pszVal);
3131 }
3132 else if (!strcmp(g_szLine, "digests"))
3133 {
3134 if ((fBad = pCache->paDigests != NULL))
3135 break;
3136 pCache->cDigests = strtoul(pszVal, &psz, 0);
3137 if ((fBad = psz && *psz))
3138 break;
3139 i = (pCache->cDigests + 4) & ~3;
3140 pCache->paDigests = xmalloc(i * sizeof(pCache->paDigests[0]));
3141 for (i = 0; i < pCache->cDigests; i++)
3142 kOCDigestInit(&pCache->paDigests[i]);
3143 }
3144 else if (!strcmp(g_szLine, "generation"))
3145 {
3146 if ((fBad = pCache->uGeneration != 0))
3147 break;
3148 pCache->uGeneration = strtoul(pszVal, &psz, 0);
3149 if ((fBad = psz && *psz))
3150 break;
3151 }
3152 else if (!strcmp(g_szLine, "the-end"))
3153 {
3154 fBad = strcmp(pszVal, "fine");
3155 break;
3156 }
3157 else
3158 {
3159 fBad = 1;
3160 break;
3161 }
3162 } while (fgets(g_szLine, sizeof(g_szLine), pCache->pFile));
3163
3164 /*
3165 * Did we find everything?
3166 */
3167 fBadBeforeMissing = fBad;
3168 if ( !fBad
3169 && !pCache->uGeneration)
3170 fBad = 1;
3171 if (!fBad)
3172 for (i = 0; i < pCache->cDigests; i++)
3173 {
3174 if ((fBad = kOCSumIsEmpty(&pCache->paDigests[i].SumCompArgv)))
3175 break;
3176 if ((fBad = kOCSumIsEmpty(&pCache->paDigests[i].SumHead)))
3177 break;
3178 if ((fBad = pCache->paDigests[i].uKey == 0))
3179 break;
3180 if ((fBad = pCache->paDigests[i].pszAbsPath == NULL
3181 && pCache->paDigests[i].pszRelPath == NULL))
3182 break;
3183 if ((fBad = pCache->paDigests[i].pszTarget == NULL))
3184 break;
3185 InfoMsg(4, "digest-%u: %s\n", i, pCache->paDigests[i].pszAbsPath
3186 ? pCache->paDigests[i].pszAbsPath : pCache->paDigests[i].pszRelPath);
3187 }
3188 if (fBad)
3189 InfoMsg(2, "bad cache file (%s)\n", fBadBeforeMissing ? g_szLine : "missing stuff");
3190 else if (ferror(pCache->pFile))
3191 {
3192 InfoMsg(2, "cache file read error\n");
3193 fBad = 1;
3194 }
3195 }
3196 if (fBad)
3197 {
3198 kObjCachePurge(pCache);
3199 pCache->fNewCache = 1;
3200 }
3201
3202 /*
3203 * Disassociate the buffer from the stream changing
3204 * it to non-buffered mode.
3205 */
3206 if (setvbuf(pCache->pFile, NULL, _IONBF, 0) != 0)
3207 FatalDie("setvbuf(,0,,0) failed: %s\n", strerror(errno));
3208}
3209
3210
3211/**
3212 * Re-writes the cache file.
3213 *
3214 * @param pCache The cache to commit and unlock.
3215 */
3216static void kObjCacheWrite(PKOBJCACHE pCache)
3217{
3218 unsigned i;
3219 off_t cb;
3220 char szBuf[8192];
3221 assert(pCache->fLocked);
3222 assert(pCache->fDirty);
3223
3224 /*
3225 * Rewind the file & stream, and associate a temporary buffer
3226 * with the stream to speed up the writing.
3227 */
3228 if (lseek(pCache->fd, 0, SEEK_SET) == -1)
3229 FatalDie("lseek(cache-fd) failed: %s\n", strerror(errno));
3230 rewind(pCache->pFile);
3231 if (setvbuf(pCache->pFile, szBuf, _IOFBF, sizeof(szBuf)) != 0)
3232 FatalDie("setvbuf failed: %s\n", strerror(errno));
3233
3234 /*
3235 * Write the header.
3236 */
3237 pCache->uGeneration++;
3238 fprintf(pCache->pFile,
3239 "magic=kObjCache-v0.1.0\n"
3240 "generation=%d\n"
3241 "digests=%d\n",
3242 pCache->uGeneration,
3243 pCache->cDigests);
3244
3245 /*
3246 * Write the digests.
3247 */
3248 for (i = 0; i < pCache->cDigests; i++)
3249 {
3250 PCKOCDIGEST pDigest = &pCache->paDigests[i];
3251 PKOCSUM pSum;
3252
3253 if (pDigest->pszAbsPath)
3254 fprintf(pCache->pFile, "digest-abs-#%u=%s\n", i, pDigest->pszAbsPath);
3255 if (pDigest->pszRelPath)
3256 fprintf(pCache->pFile, "digest-rel-#%u=%s\n", i, pDigest->pszRelPath);
3257 fprintf(pCache->pFile, "key-#%u=%u\n", i, pDigest->uKey);
3258 fprintf(pCache->pFile, "target-#%u=%s\n", i, pDigest->pszTarget);
3259 fprintf(pCache->pFile, "comp-argv-sum-#%u=", i);
3260 kOCSumFPrintf(&pDigest->SumCompArgv, pCache->pFile);
3261 for (pSum = &pDigest->SumHead; pSum; pSum = pSum->pNext)
3262 {
3263 fprintf(pCache->pFile, "sum-#%u=", i);
3264 kOCSumFPrintf(pSum, pCache->pFile);
3265 }
3266 }
3267
3268 /*
3269 * Close the stream and unlock fhe file.
3270 * (Closing the stream shouldn't close the file handle IIRC...)
3271 */
3272 fprintf(pCache->pFile, "the-end=fine\n");
3273 errno = 0;
3274 if ( fflush(pCache->pFile) < 0
3275 || ferror(pCache->pFile))
3276 {
3277 int iErr = errno;
3278 fclose(pCache->pFile);
3279 UnlinkFileInDir(pCache->pszName, pCache->pszDir);
3280 FatalDie("Stream error occured while writing '%s' in '%s': %s\n",
3281 pCache->pszName, pCache->pszDir, strerror(iErr));
3282 }
3283 if (setvbuf(pCache->pFile, NULL, _IONBF, 0) != 0)
3284 FatalDie("setvbuf(,0,,0) failed: %s\n", strerror(errno));
3285
3286 cb = lseek(pCache->fd, 0, SEEK_CUR);
3287 if (cb == -1)
3288 FatalDie("lseek(cache-file,0,CUR) failed: %s\n", strerror(errno));
3289#if defined(__WIN__)
3290 if (_chsize(pCache->fd, cb) == -1)
3291#else
3292 if (ftruncate(pCache->fd, cb) == -1)
3293#endif
3294 FatalDie("file truncation failed: %s\n", strerror(errno));
3295 InfoMsg(4, "wrote '%s' in '%s', %d bytes\n", pCache->pszName, pCache->pszDir, cb);
3296}
3297
3298
3299/**
3300 * Cleans out all invalid digests.s
3301 *
3302 * This is done periodically from the unlock routine to make
3303 * sure we don't accidentally accumulate stale digests.
3304 *
3305 * @param pCache The cache to chek.
3306 */
3307static void kObjCacheClean(PKOBJCACHE pCache)
3308{
3309 unsigned i = pCache->cDigests;
3310 while (i-- > 0)
3311 {
3312 /*
3313 * Try open it and purge it if it's bad.
3314 * (We don't kill the entry file because that's kmk clean's job.)
3315 */
3316 PCKOCDIGEST pDigest = &pCache->paDigests[i];
3317 PKOCENTRY pEntry = kOCEntryCreate(kOCDigestAbsPath(pDigest, pCache->pszDir));
3318 kOCEntryRead(pEntry);
3319 if ( !kOCEntryCheck(pEntry)
3320 || !kOCDigestIsValid(pDigest, pEntry))
3321 {
3322 unsigned cLeft;
3323 kOCDigestPurge(pDigest);
3324
3325 pCache->cDigests--;
3326 cLeft = pCache->cDigests - i;
3327 if (cLeft)
3328 memmove(pDigest, pDigest + 1, cLeft * sizeof(*pDigest));
3329
3330 pCache->fDirty = 1;
3331 }
3332 kOCEntryDestroy(pEntry);
3333 }
3334}
3335
3336
3337/**
3338 * Locks the cache for exclusive access.
3339 *
3340 * This will open the file if necessary and lock the entire file
3341 * using the best suitable platform API (tricky).
3342 *
3343 * @param pCache The cache to lock.
3344 */
3345static void kObjCacheLock(PKOBJCACHE pCache)
3346{
3347 struct stat st;
3348#if defined(__WIN__)
3349 OVERLAPPED OverLapped;
3350#endif
3351
3352 assert(!pCache->fLocked);
3353
3354 /*
3355 * Open it?
3356 */
3357 if (pCache->fd < 0)
3358 {
3359 pCache->fd = OpenFileInDir(pCache->pszName, pCache->pszDir, O_CREAT | O_RDWR | O_BINARY, 0666);
3360 if (pCache->fd == -1)
3361 {
3362 MakePath(pCache->pszDir);
3363 pCache->fd = OpenFileInDir(pCache->pszName, pCache->pszDir, O_CREAT | O_RDWR | O_BINARY, 0666);
3364 if (pCache->fd == -1)
3365 FatalDie("Failed to create '%s' in '%s': %s\n", pCache->pszName, pCache->pszDir, strerror(errno));
3366 }
3367
3368 pCache->pFile = fdopen(pCache->fd, "r+b");
3369 if (!pCache->pFile)
3370 FatalDie("fdopen failed: %s\n", strerror(errno));
3371 if (setvbuf(pCache->pFile, NULL, _IONBF, 0) != 0)
3372 FatalDie("setvbuf(,0,,0) failed: %s\n", strerror(errno));
3373 }
3374
3375 /*
3376 * Lock it.
3377 */
3378#if defined(__WIN__)
3379 memset(&OverLapped, 0, sizeof(OverLapped));
3380 if (!LockFileEx((HANDLE)_get_osfhandle(pCache->fd), LOCKFILE_EXCLUSIVE_LOCK, 0, ~0, 0, &OverLapped))
3381 FatalDie("Failed to lock the cache file: Windows Error %d\n", GetLastError());
3382#else
3383 if (flock(pCache->fd, LOCK_EX) != 0)
3384 FatalDie("Failed to lock the cache file: %s\n", strerror(errno));
3385#endif
3386 pCache->fLocked = 1;
3387
3388 /*
3389 * Check for new cache and read it it's an existing cache.
3390 *
3391 * There is no point in initializing a new cache until we've finished
3392 * compiling and has something to put into it, so we'll leave it as a
3393 * 0 byte file.
3394 */
3395 if (fstat(pCache->fd, &st) == -1)
3396 FatalDie("fstat(cache-fd) failed: %s\n", strerror(errno));
3397 if (st.st_size)
3398 kObjCacheRead(pCache);
3399 else
3400 {
3401 pCache->fNewCache = 1;
3402 InfoMsg(2, "the cache file is empty\n");
3403 }
3404}
3405
3406
3407/**
3408 * Unlocks the cache (without writing anything back).
3409 *
3410 * @param pCache The cache to unlock.
3411 */
3412static void kObjCacheUnlock(PKOBJCACHE pCache)
3413{
3414#if defined(__WIN__)
3415 OVERLAPPED OverLapped;
3416#endif
3417 assert(pCache->fLocked);
3418
3419 /*
3420 * Write it back if it's dirty.
3421 */
3422 if (pCache->fDirty)
3423 {
3424 if ( pCache->cDigests >= 16
3425 && (pCache->uGeneration % 19) == 19)
3426 kObjCacheClean(pCache);
3427 kObjCacheWrite(pCache);
3428 pCache->fDirty = 0;
3429 }
3430
3431 /*
3432 * Lock it.
3433 */
3434#if defined(__WIN__)
3435 memset(&OverLapped, 0, sizeof(OverLapped));
3436 if (!UnlockFileEx((HANDLE)_get_osfhandle(pCache->fd), 0, ~0U, 0, &OverLapped))
3437 FatalDie("Failed to unlock the cache file: Windows Error %d\n", GetLastError());
3438#else
3439 if (flock(pCache->fd, LOCK_UN) != 0)
3440 FatalDie("Failed to unlock the cache file: %s\n", strerror(errno));
3441#endif
3442 pCache->fLocked = 0;
3443}
3444
3445
3446/**
3447 * Removes the entry from the cache.
3448 *
3449 * The entry doesn't need to be in the cache.
3450 * The cache entry (file) itself is not touched.
3451 *
3452 * @param pCache The cache.
3453 * @param pEntry The entry.
3454 */
3455static void kObjCacheRemoveEntry(PKOBJCACHE pCache, PCKOCENTRY pEntry)
3456{
3457 unsigned i = pCache->cDigests;
3458 while (i-- > 0)
3459 {
3460 PKOCDIGEST pDigest = &pCache->paDigests[i];
3461 if (ArePathsIdentical(kOCDigestAbsPath(pDigest, pCache->pszDir),
3462 kOCEntryAbsPath(pEntry), ~0U))
3463 {
3464 unsigned cLeft;
3465 kOCDigestPurge(pDigest);
3466
3467 pCache->cDigests--;
3468 cLeft = pCache->cDigests - i;
3469 if (cLeft)
3470 memmove(pDigest, pDigest + 1, cLeft * sizeof(*pDigest));
3471
3472 pCache->fDirty = 1;
3473 InfoMsg(3, "removing entry '%s'; %d left.\n", kOCEntryAbsPath(pEntry), pCache->cDigests);
3474 }
3475 }
3476}
3477
3478
3479/**
3480 * Inserts the entry into the cache.
3481 *
3482 * The cache entry (file) itself is not touched by this operation,
3483 * the pEntry object otoh is.
3484 *
3485 * @param pCache The cache.
3486 * @param pEntry The entry.
3487 */
3488static void kObjCacheInsertEntry(PKOBJCACHE pCache, PKOCENTRY pEntry)
3489{
3490 unsigned i;
3491
3492 /*
3493 * Find a new key.
3494 */
3495 pEntry->uKey = pCache->uNextKey++;
3496 if (!pEntry->uKey)
3497 pEntry->uKey = pCache->uNextKey++;
3498 i = pCache->cDigests;
3499 while (i-- > 0)
3500 if (pCache->paDigests[i].uKey == pEntry->uKey)
3501 {
3502 pEntry->uKey = pCache->uNextKey++;
3503 if (!pEntry->uKey)
3504 pEntry->uKey = pCache->uNextKey++;
3505 i = pCache->cDigests;
3506 }
3507
3508 /*
3509 * Reallocate the digest array?
3510 */
3511 if ( !(pCache->cDigests & 3)
3512 && (pCache->cDigests || !pCache->paDigests))
3513 pCache->paDigests = xrealloc(pCache->paDigests, sizeof(pCache->paDigests[0]) * (pCache->cDigests + 4));
3514
3515 /*
3516 * Create a new digest.
3517 */
3518 kOCDigestInitFromEntry(&pCache->paDigests[pCache->cDigests], pEntry);
3519 pCache->cDigests++;
3520 InfoMsg(4, "Inserted digest #%u: %s\n", pCache->cDigests - 1, kOCEntryAbsPath(pEntry));
3521
3522 pCache->fDirty = 1;
3523}
3524
3525
3526/**
3527 * Find a matching cache entry.
3528 */
3529static PKOCENTRY kObjCacheFindMatchingEntry(PKOBJCACHE pCache, PCKOCENTRY pEntry)
3530{
3531 unsigned i = pCache->cDigests;
3532
3533 assert(pEntry->fNeedCompiling);
3534 assert(!kOCSumIsEmpty(&pEntry->New.SumCompArgv));
3535 assert(!kOCSumIsEmpty(&pEntry->New.SumHead));
3536
3537 while (i-- > 0)
3538 {
3539 /*
3540 * Matching?
3541 */
3542 PCKOCDIGEST pDigest = &pCache->paDigests[i];
3543 if ( kOCSumIsEqual(&pDigest->SumCompArgv, &pEntry->New.SumCompArgv)
3544 && kOCSumHasEqualInChain(&pDigest->SumHead, &pEntry->New.SumHead))
3545 {
3546 /*
3547 * Try open it.
3548 */
3549 unsigned cLeft;
3550 PKOCENTRY pRetEntry = kOCEntryCreate(kOCDigestAbsPath(pDigest, pCache->pszDir));
3551 kOCEntryRead(pRetEntry);
3552 if ( kOCEntryCheck(pRetEntry)
3553 && kOCDigestIsValid(pDigest, pRetEntry))
3554 return pRetEntry;
3555 kOCEntryDestroy(pRetEntry);
3556
3557 /* bad entry, purge it. */
3558 InfoMsg(3, "removing bad digest '%s'\n", kOCDigestAbsPath(pDigest, pCache->pszDir));
3559 kOCDigestPurge(pDigest);
3560
3561 pCache->cDigests--;
3562 cLeft = pCache->cDigests - i;
3563 if (cLeft)
3564 memmove(pDigest, pDigest + 1, cLeft * sizeof(*pDigest));
3565
3566 pCache->fDirty = 1;
3567 }
3568 }
3569
3570 return NULL;
3571}
3572
3573
3574/**
3575 * Is this a new cache?
3576 *
3577 * @returns 1 if new, 0 if not new.
3578 * @param pEntry The entry.
3579 */
3580static int kObjCacheIsNew(PKOBJCACHE pCache)
3581{
3582 return pCache->fNewCache;
3583}
3584
3585
3586/**
3587 * Prints a syntax error and returns the appropriate exit code
3588 *
3589 * @returns approriate exit code.
3590 * @param pszFormat The syntax error message.
3591 * @param ... Message args.
3592 */
3593static int SyntaxError(const char *pszFormat, ...)
3594{
3595 va_list va;
3596 fprintf(stderr, "kObjCache: syntax error: ");
3597 va_start(va, pszFormat);
3598 vfprintf(stderr, pszFormat, va);
3599 va_end(va);
3600 return 1;
3601}
3602
3603
3604/**
3605 * Prints the usage.
3606 * @returns 0.
3607 */
3608static int usage(void)
3609{
3610 printf("syntax: kObjCache [--kObjCache-options] [-v|--verbose]\n"
3611 " < [-c|--cache-file <cache-file>]\n"
3612 " | [-n|--name <name-in-cache>] [[-d|--cache-dir <cache-dir>]] >\n"
3613 " <-f|--file <local-cache-file>>\n"
3614 " <-t|--target <target-name>>\n"
3615 " [-r|--redir-stdout] [-p|--passthru]\n"
3616 " --kObjCache-cpp <filename> <precompiler + args>\n"
3617 " --kObjCache-cc <object> <compiler + args>\n"
3618 " [--kObjCache-both [args]]\n"
3619 " [--kObjCache-cpp|--kObjCache-cc [more args]]\n"
3620 " kObjCache <-V|--version>\n"
3621 " kObjCache [-?|/?|-h|/h|--help|/help]\n"
3622 "\n"
3623 "The env.var. KOBJCACHE_DIR sets the default cache diretory (-d).\n"
3624 "The env.var. KOBJCACHE_OPTS allow you to specifie additional options\n"
3625 "without having to mess with the makefiles. These are appended with "
3626 "a --kObjCache-options between them and the command args.\n"
3627 "\n");
3628 return 0;
3629}
3630
3631
3632int main(int argc, char **argv)
3633{
3634 PKOBJCACHE pCache;
3635 PKOCENTRY pEntry;
3636
3637 const char *pszCacheDir = getenv("KOBJCACHE_DIR");
3638 const char *pszCacheName = NULL;
3639 const char *pszCacheFile = NULL;
3640 const char *pszEntryFile = NULL;
3641
3642 const char **papszArgvPreComp = NULL;
3643 unsigned cArgvPreComp = 0;
3644 const char *pszPreCompName = NULL;
3645 int fRedirPreCompStdOut = 0;
3646
3647 const char **papszArgvCompile = NULL;
3648 unsigned cArgvCompile = 0;
3649 const char *pszObjName = NULL;
3650 int fRedirCompileStdIn = 0;
3651
3652 const char *pszTarget = NULL;
3653
3654 enum { kOC_Options, kOC_CppArgv, kOC_CcArgv, kOC_BothArgv } enmMode = kOC_Options;
3655
3656 size_t cch;
3657 char *psz;
3658 int i;
3659
3660 SetErrorPrefix("kObjCache");
3661
3662 /*
3663 * Arguments passed in the environmnet?
3664 */
3665 psz = getenv("KOBJCACHE_OPTS");
3666 if (psz)
3667 AppendArgs(&argc, &argv, psz, "--kObjCache-options");
3668
3669 /*
3670 * Parse the arguments.
3671 */
3672 if (argc <= 1)
3673 return usage();
3674 for (i = 1; i < argc; i++)
3675 {
3676 if (!strcmp(argv[i], "--kObjCache-cpp"))
3677 {
3678 enmMode = kOC_CppArgv;
3679 if (!pszPreCompName)
3680 {
3681 if (++i >= argc)
3682 return SyntaxError("--kObjCache-cpp requires an object filename!\n");
3683 pszPreCompName = argv[i];
3684 }
3685 }
3686 else if (!strcmp(argv[i], "--kObjCache-cc"))
3687 {
3688 enmMode = kOC_CcArgv;
3689 if (!pszObjName)
3690 {
3691 if (++i >= argc)
3692 return SyntaxError("--kObjCache-cc requires an precompiler output filename!\n");
3693 pszObjName = argv[i];
3694 }
3695 }
3696 else if (!strcmp(argv[i], "--kObjCache-both"))
3697 enmMode = kOC_BothArgv;
3698 else if (!strcmp(argv[i], "--kObjCache-options"))
3699 enmMode = kOC_Options;
3700 else if (!strcmp(argv[i], "--help"))
3701 return usage();
3702 else if (enmMode != kOC_Options)
3703 {
3704 if (enmMode == kOC_CppArgv || enmMode == kOC_BothArgv)
3705 {
3706 if (!(cArgvPreComp % 16))
3707 papszArgvPreComp = xrealloc((void *)papszArgvPreComp, (cArgvPreComp + 17) * sizeof(papszArgvPreComp[0]));
3708 papszArgvPreComp[cArgvPreComp++] = argv[i];
3709 papszArgvPreComp[cArgvPreComp] = NULL;
3710 }
3711 if (enmMode == kOC_CcArgv || enmMode == kOC_BothArgv)
3712 {
3713 if (!(cArgvCompile % 16))
3714 papszArgvCompile = xrealloc((void *)papszArgvCompile, (cArgvCompile + 17) * sizeof(papszArgvCompile[0]));
3715 papszArgvCompile[cArgvCompile++] = argv[i];
3716 papszArgvCompile[cArgvCompile] = NULL;
3717 }
3718 }
3719 else if (!strcmp(argv[i], "-f") || !strcmp(argv[i], "--entry-file"))
3720 {
3721 if (i + 1 >= argc)
3722 return SyntaxError("%s requires a cache entry filename!\n", argv[i]);
3723 pszEntryFile = argv[++i];
3724 }
3725 else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--cache-file"))
3726 {
3727 if (i + 1 >= argc)
3728 return SyntaxError("%s requires a cache filename!\n", argv[i]);
3729 pszCacheFile = argv[++i];
3730 }
3731 else if (!strcmp(argv[i], "-n") || !strcmp(argv[i], "--name"))
3732 {
3733 if (i + 1 >= argc)
3734 return SyntaxError("%s requires a cache name!\n", argv[i]);
3735 pszCacheName = argv[++i];
3736 }
3737 else if (!strcmp(argv[i], "-d") || !strcmp(argv[i], "--cache-dir"))
3738 {
3739 if (i + 1 >= argc)
3740 return SyntaxError("%s requires a cache directory!\n", argv[i]);
3741 pszCacheDir = argv[++i];
3742 }
3743 else if (!strcmp(argv[i], "-t") || !strcmp(argv[i], "--target"))
3744 {
3745 if (i + 1 >= argc)
3746 return SyntaxError("%s requires a target platform/arch name!\n", argv[i]);
3747 pszTarget = argv[++i];
3748 }
3749 else if (!strcmp(argv[i], "-p") || !strcmp(argv[i], "--passthru"))
3750 fRedirPreCompStdOut = fRedirCompileStdIn = 1;
3751 else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--redir-stdout"))
3752 fRedirPreCompStdOut = 1;
3753 else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose"))
3754 g_cVerbosityLevel++;
3755 else if (!strcmp(argv[i], "-q") || !strcmp(argv[i], "--quiet"))
3756 g_cVerbosityLevel = 0;
3757 else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "-?")
3758 || !strcmp(argv[i], "/h") || !strcmp(argv[i], "/?") || !strcmp(argv[i], "/help"))
3759 return usage();
3760 else if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version"))
3761 {
3762 printf("kObjCache v0.1.0 ($Revision: 1055 $)\n");
3763 return 0;
3764 }
3765 else
3766 return SyntaxError("Doesn't grok '%s'!\n", argv[i]);
3767 }
3768 if (!pszEntryFile)
3769 return SyntaxError("No cache entry filename (-f)!\n");
3770 if (!pszTarget)
3771 return SyntaxError("No target name (-t)!\n");
3772 if (!cArgvCompile)
3773 return SyntaxError("No compiler arguments (--kObjCache-cc)!\n");
3774 if (!cArgvPreComp)
3775 return SyntaxError("No precompiler arguments (--kObjCache-cc)!\n");
3776
3777 /*
3778 * Calc the cache file name.
3779 * It's a bit messy since the extension has to be replaced.
3780 */
3781 if (!pszCacheFile)
3782 {
3783 if (!pszCacheDir)
3784 return SyntaxError("No cache dir (-d / KOBJCACHE_DIR) and no cache filename!\n");
3785 if (!pszCacheName)
3786 {
3787 psz = (char *)FindFilenameInPath(pszEntryFile);
3788 if (!*psz)
3789 return SyntaxError("The cache file (-f) specifies a directory / nothing!\n");
3790 cch = psz - pszEntryFile;
3791 pszCacheName = memcpy(xmalloc(cch + 5), psz, cch + 1);
3792 psz = strrchr(pszCacheName, '.');
3793 if (!psz || psz <= pszCacheName)
3794 psz = (char *)pszCacheName + cch;
3795 memcpy(psz, ".koc", sizeof(".koc") - 1);
3796 }
3797 pszCacheFile = MakePathFromDirAndFile(pszCacheName, pszCacheDir);
3798 }
3799
3800 /*
3801 * Create and initialize the two objects we'll be working on.
3802 *
3803 * We're supposed to be the only ones actually writing to the local file,
3804 * so it's perfectly fine to read it here before we lock it. This simplifies
3805 * the detection of object name and compiler argument changes.
3806 */
3807 SetErrorPrefix("kObjCache - %s", FindFilenameInPath(pszCacheFile));
3808 pCache = kObjCacheCreate(pszCacheFile);
3809
3810 pEntry = kOCEntryCreate(pszEntryFile);
3811 kOCEntryRead(pEntry);
3812 kOCEntrySetCompileObjName(pEntry, pszObjName);
3813 kOCEntrySetCompileArgv(pEntry, papszArgvCompile, cArgvCompile);
3814 kOCEntrySetTarget(pEntry, pszTarget);
3815 kOCEntrySetCppName(pEntry, pszPreCompName);
3816 kOCEntrySetPipedMode(pEntry, fRedirPreCompStdOut, fRedirCompileStdIn);
3817
3818 /*
3819 * Open (& lock) the two files and do validity checks and such.
3820 */
3821 kObjCacheLock(pCache);
3822 if ( kObjCacheIsNew(pCache)
3823 && kOCEntryNeedsCompiling(pEntry))
3824 {
3825 /*
3826 * Both files are missing/invalid.
3827 * Optimize this path as it is frequently used when making a clean build.
3828 */
3829 kObjCacheUnlock(pCache);
3830 InfoMsg(1, "doing full compile\n");
3831 kOCEntryPreCompileAndCompile(pEntry, papszArgvPreComp, cArgvPreComp);
3832 kObjCacheLock(pCache);
3833 }
3834 else
3835 {
3836 /*
3837 * Do the precompile (don't need to lock the cache file for this).
3838 */
3839 kObjCacheUnlock(pCache);
3840 kOCEntryPreCompile(pEntry, papszArgvPreComp, cArgvPreComp);
3841
3842 /*
3843 * Check if we need to recompile. If we do, try see if the is a cache entry first.
3844 */
3845 kOCEntryCalcRecompile(pEntry);
3846 if (kOCEntryNeedsCompiling(pEntry))
3847 {
3848 PKOCENTRY pUseEntry;
3849 kObjCacheLock(pCache);
3850 kObjCacheRemoveEntry(pCache, pEntry);
3851 pUseEntry = kObjCacheFindMatchingEntry(pCache, pEntry);
3852 if (pUseEntry)
3853 {
3854 InfoMsg(1, "using cache entry '%s'\n", kOCEntryAbsPath(pUseEntry));
3855 kOCEntryCopy(pEntry, pUseEntry);
3856 kOCEntryDestroy(pUseEntry);
3857 }
3858 else
3859 {
3860 kObjCacheUnlock(pCache);
3861 InfoMsg(1, "recompiling\n");
3862 kOCEntryCompileIt(pEntry);
3863 kObjCacheLock(pCache);
3864 }
3865 }
3866 else
3867 {
3868 InfoMsg(1, "no need to recompile\n");
3869 kObjCacheLock(pCache);
3870 }
3871 }
3872
3873 /*
3874 * Update the cache files.
3875 */
3876 kObjCacheRemoveEntry(pCache, pEntry);
3877 kObjCacheInsertEntry(pCache, pEntry);
3878 kOCEntryWrite(pEntry);
3879 kObjCacheUnlock(pCache);
3880 kObjCacheDestroy(pCache);
3881 return 0;
3882}
3883
3884
3885/** @page kObjCache Benchmarks.
3886 *
3887 * (2007-06-10)
3888 *
3889 * Mac OS X debug -j 3 cached clobber build (rm -Rf out ; sync ; svn diff ; sync ; sleep 1 ; time kmk -j 3 USE_KOBJCACHE=1):
3890 * real 11m28.811s
3891 * user 13m59.291s
3892 * sys 3m24.590s
3893 *
3894 * Mac OS X debug -j 3 cached depend build [cdefs.h] (touch include/iprt/cdefs.h ; sync ; svn diff ; sync ; sleep 1 ; time kmk -j 3 USE_KOBJCACHE=1):
3895 * real 1m26.895s
3896 * user 1m26.971s
3897 * sys 0m32.532s
3898 *
3899 * Mac OS X debug -j 3 cached depend build [err.h] (touch include/iprt/err.h ; sync ; svn diff ; sync ; sleep 1 ; time kmk -j 3 USE_KOBJCACHE=1):
3900 * real 1m18.049s
3901 * user 1m20.462s
3902 * sys 0m27.887s
3903 *
3904 * Mac OS X release -j 3 cached clobber build (rm -Rf out/darwin.x86/release ; sync ; svn diff ; sync ; sleep 1 ; time kmk -j 3 USE_KOBJCACHE=1 BUILD_TYPE=release):
3905 * real 13m27.751s
3906 * user 18m12.654s
3907 * sys 3m25.170s
3908 *
3909 * Mac OS X profile -j 3 cached clobber build (rm -Rf out/darwin.x86/profile ; sync ; svn diff ; sync ; sleep 1 ; time kmk -j 3 USE_KOBJCACHE=1 BUILD_TYPE=profile):
3910 * real 9m9.720s
3911 * user 8m53.005s
3912 * sys 2m13.110s
3913 *
3914 * Mac OS X debug -j 3 clobber build (rm -Rf out/darwin.x86/debug ; sync ; svn diff ; sync ; sleep 1 ; time kmk -j 3 BUILD_TYPE=debug):
3915 * real 10m18.129s
3916 * user 12m52.687s
3917 * sys 2m51.277s
3918 *
3919 * Mac OS X debug -j 3 debug build [cdefs.h] (touch include/iprt/cdefs.h ; sync ; svn diff ; sync ; sleep 1 ; time kmk -j 3 BUILD_TYPE=debug):
3920 * real 4m46.147s
3921 * user 5m27.087s
3922 * sys 1m11.775s
3923 *
3924 * Mac OS X debug -j 3 debug build [err.h] (touch include/iprt/cdefs.h ; sync ; svn diff ; sync ; sleep 1 ; time kmk -j 3 BUILD_TYPE=debug):
3925 * real 4m17.572s
3926 * user 5m7.450s
3927 * sys 1m3.450s
3928 *
3929 * Mac OS X release -j 3 clobber build (rm -Rf out/darwin.x86/release ; sync ; svn diff ; sync ; sleep 1 ; time kmk -j 3 BUILD_TYPE=release):
3930 * real 12m14.742s
3931 * user 17m11.794s
3932 * sys 2m51.454s
3933 *
3934 * Mac OS X profile -j 3 clobber build (rm -Rf out/darwin.x86/profile ; sync ; svn diff ; sync ; sleep 1 ; time kmk -j 3 BUILD_TYPE=profile):
3935 * real 12m33.821s
3936 * user 17m35.086s
3937 * sys 2m53.312s
3938 *
3939 * Note. The profile build can pick object files from the release build.
3940 * (all with KOBJCACHE_OPTS=-v; which means a bit more output and perhaps a second or two slower.)
3941 */
3942
Note: See TracBrowser for help on using the repository browser.