forked from frerich/clcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclcache.py
1498 lines (1297 loc) · 57.4 KB
/
clcache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# clcache.py - a compiler cache for Microsoft Visual Studio
#
# Copyright (c) 2010, 2011, 2012, 2013 froglogic GmbH <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <organization> nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
from ctypes import windll, wintypes
import codecs
from collections import defaultdict, namedtuple
import cPickle as pickle
import hashlib
import json
import os
from shutil import copyfile, rmtree
import subprocess
from subprocess import Popen, PIPE, STDOUT
import sys
import struct
import tempfile
import multiprocessing
import re
HASH_ALGORITHM = hashlib.sha1
# Manifest file will have at most this number of hash lists in it. Need to avoi
# manifests grow too large.
MAX_MANIFEST_HASHES = 100
# String, by which BASE_DIR will be replaced in paths, stored in manifests.
# ? is invalid character for file name, so it seems ok
# to use it as mark for relative path.
BASEDIR_REPLACEMENT = '?'
# Size of buffers or pipes, used by daemons.
PIPE_BUFFER_SIZE = 1024
# includeFiles - list of paths toi include files, which this source file use.
# hashes - dictionary.
# Key - cumulative hash of all include files in includeFiles;
# Value - key in the cache, under which output file is stored.
Manifest = namedtuple('Manifest', ['includeFiles', 'hashes'])
# It is expected that during building we have only few possible
# PATH variants, so caching should work great here in dameon mode.
COMPILER_PATH_CACHE = {}
VERIFIED_COMPILER_HINTS = set()
# Many source files will include the same includes (e.g system includes).
# We will cache their hashes based on path and file modification time, to
# speed up build process.
HEADER_HASH_CACHE = {}
# When clearing objects from cache we need to remove also orphaned manifests.
# Without this manifest count will grow infinitely consuming disk space
# and slowing further cache clearing.
# So, we add empty "mark" files to the directories with cache entries.
# By names of these "mark" files we can determine cache key of corresponding
# manifest and update/remove it during cache clearing.
MANIFEST_MARK_EXTENSION = '.mark'
# Path - either absolute or relative to BASE_DIR (if possible) path,
# mtime - modification time of file. We need use it since some headers may be
# re-generated during build process.
def get_header_key(path, mtime):
return '{mtime}:{path}'.format(mtime=mtime, path=path)
class ObjectCacheLockException(Exception):
pass
class LogicException(Exception):
def __init__(self, message):
self.value = message
def __str__(self):
return repr(self.message)
class ObjectCacheLock:
""" Implements a lock for the object cache which
can be used in 'with' statements. """
INFINITE = 0xFFFFFFFF
def __init__(self, mutexName, timeoutMs):
mutexName = 'Local\\' + mutexName
self._mutex = windll.kernel32.CreateMutexW(
wintypes.c_int(0),
wintypes.c_int(0),
unicode(mutexName))
self._timeoutMs = timeoutMs
# We use this class only for inter-process synchronization, so
# we can use local variable here to avoid too many calls of system APIs
self._acquire_count = 0
assert self._mutex
def __enter__(self):
self.acquire()
def __exit__(self, type, value, traceback):
self.release()
def __del__(self):
windll.kernel32.CloseHandle(self._mutex)
def acquire(self):
self._acquire_count += 1
if self._acquire_count > 1:
return
WAIT_ABANDONED = 0x00000080
result = windll.kernel32.WaitForSingleObject(
self._mutex, wintypes.c_int(self._timeoutMs))
if result != 0 and result != WAIT_ABANDONED:
errorString ='Error! WaitForSingleObject returns {result}, last error {error}'.format(
result=result,
error=windll.kernel32.GetLastError())
raise ObjectCacheLockException(errorString)
def release(self):
self._acquire_count -= 1
if self._acquire_count > 0:
return
windll.kernel32.ReleaseMutex(self._mutex)
class ObjectCache:
def __init__(self):
try:
self.dir = os.environ["CLCACHE_DIR"]
except KeyError:
self.dir = os.path.join(os.path.expanduser("~"), "clcache")
lockName = self.cacheDirectory().replace(':', '-').replace('\\', '-')
self.lock = ObjectCacheLock(lockName, ObjectCacheLock.INFINITE)
self.tempDir = os.path.join(self.dir, '.temp')
self.daemonsDir = os.path.join(self.dir, '.daemons')
self.manifestsDir = os.path.join(self.dir, "manifests")
self.objectsDir = os.path.join(self.dir, "objects")
# Creates both self.dir and self.tempDir if neccessary
if (not (os.path.exists(self.tempDir)) or
not (os.path.exists(self.daemonsDir)) or
not (os.path.exists(self.manifestsDir)) or
not (os.path.exists(self.objectsDir))):
# Guarded by lock to avoid exceptions when multiple processes started
# and try to create the same dir.
with self.lock:
if not os.path.exists(self.tempDir):
os.makedirs(self.tempDir)
if not os.path.exists(self.daemonsDir):
os.makedirs(self.daemonsDir)
if not os.path.exists(self.manifestsDir):
os.makedirs(self.manifestsDir)
if not os.path.exists(self.objectsDir):
os.makedirs(self.objectsDir)
def cacheDirectory(self):
return self.dir
def clean(self, stats, maximumSize):
with self.lock:
currentSize = stats.currentCacheSize()
if currentSize < maximumSize:
return
currentEntriesCount = stats.numCacheEntries()
# Free at least 10% to avoid cleaning up too often which
# is a big performance hit with large caches.
effectiveMaximumSize = maximumSize * 0.9
objects = [os.path.join(root, "object")
for root, folder, files in os.walk(self.objectsDir)
if "object" in files]
objectInfos = [(os.stat(fn), fn) for fn in objects]
objectInfos.sort(key=lambda t: t[0].st_atime)
for stat, fn in objectInfos:
entryDir = os.path.split(fn)[0]
entryHash = os.path.basename(entryDir)
# Find all manifests and remove link from them
for file in os.listdir(entryDir):
nameBase, ext = os.path.splitext(file)
if ext != MANIFEST_MARK_EXTENSION:
continue
self._removeEntryFromManifest(nameBase, entryHash, stats)
rmtree(entryDir)
currentEntriesCount -= 1
currentSize -= stat.st_size
if currentSize < effectiveMaximumSize:
break
stats.setCacheSize(currentSize, currentEntriesCount)
def _removeEntryFromManifest(self, manifestHash, entryHash, stats):
manifest = self.getManifest(manifestHash)
if not manifest:
return
for keyInManifest, cacheKey in manifest.hashes.items():
if cacheKey == entryHash:
del manifest.hashes[keyInManifest]
if len(manifest.hashes) == 0:
self.removeManifest(manifestHash)
stats.removeManifest()
else:
self.setManifest(manifestHash, manifest)
def removeObjects(self, stats, removedObjects):
if len(removedObjects) == 0:
return
with self.lock:
currentSize = stats.currentCacheSize()
currentEntriesCount = stats.numCacheEntries()
for hash in removedObjects:
dirPath = self._cacheEntryDir(hash)
if not os.path.exists(dirPath):
continue # May be if object already evicted.
objectPath = os.path.join(dirPath, "object")
if os.path.exists(objectPath):
# May be absent if this if cached compiler
# output (for preprocess-only).
fileStat = os.stat(objectPath)
currentSize -= fileStat.st_size
rmtree(dirPath)
currentEntriesCount -= 1
stats.setCacheSize(currentSize, currentEntriesCount)
def getManifestHash(self, compilerBinary, commandLine, sourceFile):
stat = os.stat(compilerBinary)
# NOTE: We intentionally do not normalize command line to include
# preprocessor options. In direct mode we do not perform
# preprocessing before cache lookup, so all parameters are important
additionalData = '{mtime}{size}{cmdLine}'.format(
mtime=stat.st_mtime,
size=stat.st_size,
cmdLine=' '.join(commandLine));
return getFileHash(sourceFile, additionalData)
def computeKey(self, compilerBinary, commandLine):
ppcmd = [compilerBinary, "/EP"]
ppcmd += [arg for arg in commandLine if not arg in ("-c", "/c")]
preprocessor = Popen(ppcmd, stdout=PIPE, stderr=PIPE)
(preprocessedSourceCode, pperr) = preprocessor.communicate()
if preprocessor.returncode != 0:
sys.stderr.write(pperr)
sys.stderr.write("clcache: preprocessor failed\n")
sys.exit(preprocessor.returncode)
normalizedCmdLine = self._normalizedCommandLine(commandLine)
stat = os.stat(compilerBinary)
h = HASH_ALGORITHM()
h.update(str(stat.st_mtime))
h.update(str(stat.st_size))
h.update(' '.join(normalizedCmdLine))
h.update(preprocessedSourceCode)
return h.hexdigest()
def getKeyInManifest(self, listOfHeaderHashes):
return getHash(','.join(listOfHeaderHashes))
def getDirectCacheKey(self, manifestHash, keyInManifest):
# We must take into account manifestHash to avoid
# collisions when different source files use the same
# set of includes.
return getHash(manifestHash + keyInManifest)
def hasEntry(self, key, needObject):
with self.lock:
objectFileName = self.cachedObjectName(key)
if os.path.exists(objectFileName):
# Sometimes empty .obj files appears in cache (e.g. if computer is incorrectly
# turned off during build process). Do not use these files, since they will fail
# the build. They will be evicted normally during some cache clean.
return os.path.getsize(objectFileName) > 0
if needObject:
return False
# If there are no .obj file, it may appear that we just cached compiler output
# (e.g. if this is cached preprocessor invocation).
return os.path.exists(self._cachedCompilerOutputName(key))
def setEntry(self, key, objectFileName, compilerOutput, compilerStderr, manifestHash):
with self.lock:
if not os.path.exists(self._cacheEntryDir(key)):
os.makedirs(self._cacheEntryDir(key))
if objectFileName != '':
copyOrLink(objectFileName, self.cachedObjectName(key))
open(self._cachedCompilerOutputName(key), 'w').write(compilerOutput)
if compilerStderr != '':
open(self._cachedCompilerStderrName(key), 'w').write(compilerStderr)
if manifestHash:
# Save hash of the parent manifest to ensure reference will
# be removed from it during cache cleaning.
manifestMarkFileName = os.path.join(
self._cacheEntryDir(key),
manifestHash + MANIFEST_MARK_EXTENSION)
open(manifestMarkFileName, 'w').close()
# Returns true if this is new manifest
def setManifest(self, manifestHash, manifest):
with self.lock:
if not os.path.exists(self._manifestDir(manifestHash)):
os.makedirs(self._manifestDir(manifestHash))
fileName = self._manifestName(manifestHash)
result = not os.path.exists(fileName)
with open(fileName, 'wb') as outFile:
pickle.dump(manifest, outFile)
return result
def removeManifest(self, manifestHash):
with self.lock:
fileName = self._manifestName(manifestHash)
if os.path.exists(fileName):
os.remove(fileName)
def getManifest(self, manifestHash):
with self.lock:
fileName = self._manifestName(manifestHash)
if not os.path.exists(fileName):
return None
with open(fileName, 'rb') as inFile:
try:
return pickle.load(inFile)
except:
# Seems, file is corrupted
return None
def cachedObjectName(self, key):
return os.path.join(self._cacheEntryDir(key), "object")
def cachedCompilerOutput(self, key):
return open(self._cachedCompilerOutputName(key), 'r').read()
def cachedCompilerStderr(self, key):
fileName = self._cachedCompilerStderrName(key)
if os.path.exists(fileName):
return open(fileName, 'r').read()
return ''
def getTempFilePath(self, sourceFile):
ext = os.path.splitext(sourceFile)[1]
handle, path = tempfile.mkstemp(suffix=ext, dir=self.tempDir)
os.close(handle)
return path
def getDaemonDir(self, daemonPid):
return os.path.join(self.daemonsDir, str(daemonPid))
def regiterDaemon(self, daemonPid):
with self.lock:
os.makedirs(self.getDaemonDir(daemonPid))
def _outputFile(self, daemonDir, fileName):
print 'DAEMON ' + fileName
filePath = os.path.join(daemonDir, fileName)
if os.path.exists(filePath):
with open(filePath, 'r') as f:
sys.stdout.write(f.read())
else:
print '<No file present>'
def unregiterDaemon(self, daemonPid):
with self.lock:
daemonDir = self.getDaemonDir(daemonPid)
self._outputFile(daemonDir, 'stdout.txt')
self._outputFile(daemonDir, 'stderr.txt')
rmtree(daemonDir)
def getAllDaemonPids(self):
with self.lock:
dirs = os.listdir(self.daemonsDir)
return [int(d) for d in dirs]
def _cacheEntryDir(self, key):
return os.path.join(self.objectsDir, key[:2], key)
def _manifestDir(self, manifestHash):
return os.path.join(self.manifestsDir, manifestHash[:2])
def _manifestName(self, manifestHash):
return os.path.join(self._manifestDir(manifestHash), manifestHash + ".dat")
def _cachedCompilerOutputName(self, key):
return os.path.join(self._cacheEntryDir(key), "output.txt")
def _cachedCompilerStderrName(self, key):
return os.path.join(self._cacheEntryDir(key), "stderr.txt")
def _normalizedCommandLine(self, cmdline):
# Remove all arguments from the command line which only influence the
# preprocessor; the preprocessor's output is already included into the
# hash sum so we don't have to care about these switches in the
# command line as well.
_argsToStrip = ("AI", "C", "E", "P", "FI", "u", "X",
"FU", "D", "EP", "Fx", "U", "I")
# Also remove the switch for specifying the output file name; we don't
# want two invocations which are identical except for the output file
# name to be treated differently.
_argsToStrip += ("Fo",)
return [arg for arg in cmdline
if not (arg[0] in "/-" and arg[1:].startswith(_argsToStrip))]
class PersistentJSONDict:
def __init__(self, fileName):
self._dirty = False
self._dict = {}
self._fileName = fileName
try:
self._dict = json.load(open(self._fileName, 'r'))
except:
pass
def save(self):
if self._dirty:
json.dump(self._dict, open(self._fileName, 'w'))
def __setitem__(self, key, value):
self._dict[key] = value
self._dirty = True
def __getitem__(self, key):
return self._dict[key]
def __contains__(self, key):
return key in self._dict
class Configuration:
_defaultValues = { "MaximumCacheSize": 1024 * 1024 * 1000 }
def __init__(self, objectCache):
self._objectCache = objectCache
with objectCache.lock:
self._cfg = PersistentJSONDict(os.path.join(objectCache.cacheDirectory(),
"config.txt"))
for setting, defaultValue in self._defaultValues.iteritems():
if not setting in self._cfg:
self._cfg[setting] = defaultValue
def maximumCacheSize(self):
return self._cfg["MaximumCacheSize"]
def setMaximumCacheSize(self, size):
self._cfg["MaximumCacheSize"] = size
def save(self):
with self._objectCache.lock:
self._cfg.save()
class CacheStatistics:
def __init__(self, objectCache):
# Use two dictionaries to ensure we'll grab cache lock on the smallest
# possible time. We collect increment _incremental_stats while possible
# and then merge it with stats on disk.
self._incremental_stats = defaultdict(int)
self._stats = None
self._objectCache = objectCache
def numCallsWithoutSourceFile(self):
self.ensureLoadedAndLocked()
return self._stats["CallsWithoutSourceFile"]
def registerCallWithoutSourceFile(self):
stats = self._stats if self._stats else self._incremental_stats
stats["CallsWithoutSourceFile"] += 1
def numCallsWithMultipleSourceFiles(self):
self.ensureLoadedAndLocked()
return self._stats["CallsWithMultipleSourceFiles"]
def registerCallWithMultipleSourceFiles(self):
stats = self._stats if self._stats else self._incremental_stats
stats["CallsWithMultipleSourceFiles"] += 1
def numCallsWithPch(self):
self.ensureLoadedAndLocked()
return self._stats["CallsWithPch"]
def registerCallWithPch(self):
stats = self._stats if self._stats else self._incremental_stats
stats["CallsWithPch"] += 1
def numCallsForLinking(self):
self.ensureLoadedAndLocked()
return self._stats["CallsForLinking"]
def registerCallForLinking(self):
stats = self._stats if self._stats else self._incremental_stats
stats["CallsForLinking"] += 1
def numEvictedMisses(self):
self.ensureLoadedAndLocked()
return self._stats["EvictedMisses"]
def registerEvictedMiss(self):
self.registerCacheMiss()
stats = self._stats if self._stats else self._incremental_stats
stats["EvictedMisses"] += 1
def numHeaderChangedMisses(self):
self.ensureLoadedAndLocked()
return self._stats["HeaderChangedMisses"]
def registerHeaderChangedMiss(self):
self.registerCacheMiss()
stats = self._stats if self._stats else self._incremental_stats
stats["HeaderChangedMisses"] += 1
def numSourceChangedMisses(self):
return self._stats["SourceChangedMisses"]
def registerSourceChangedMiss(self):
self.registerCacheMiss()
stats = self._stats if self._stats else self._incremental_stats
stats["SourceChangedMisses"] += 1
def numCacheEntries(self):
self.ensureLoadedAndLocked()
return self._stats["CacheEntries"]
def registerCacheEntry(self, size):
stats = self._stats if self._stats else self._incremental_stats
stats["CacheEntries"] += 1
stats["CacheSize"] += size
def numManifests(self):
self.ensureLoadedAndLocked()
return self._stats["ManifestsCount"]
def registerManifest(self):
stats = self._stats if self._stats else self._incremental_stats
stats["ManifestsCount"] += 1
def removeManifest(self):
stats = self._stats if self._stats else self._incremental_stats
stats["ManifestsCount"] -= 1
def currentCacheSize(self):
self.ensureLoadedAndLocked()
return self._stats["CacheSize"]
def setCacheSize(self, size, entriesCount):
self.ensureLoadedAndLocked()
self._stats["CacheSize"] = size
self._stats["CacheEntries"] = entriesCount
def numCacheHits(self):
self.ensureLoadedAndLocked()
return self._stats["CacheHits"]
def registerCacheHit(self):
stats = self._stats if self._stats else self._incremental_stats
stats["CacheHits"] += 1
def numCacheMisses(self):
self.ensureLoadedAndLocked()
return self._stats["CacheMisses"]
def registerCacheMiss(self):
stats = self._stats if self._stats else self._incremental_stats
stats["CacheMisses"] += 1
def ensureLoadedAndLocked(self):
if self._stats:
return
self._objectCache.lock.acquire()
self._stats = PersistentJSONDict(os.path.join(self._objectCache.cacheDirectory(),
"stats.txt"))
for k in ["CallsWithoutSourceFile",
"CallsWithMultipleSourceFiles",
"CallsWithPch",
"CallsForLinking",
"CacheEntries", "CacheSize",
"CacheHits", "CacheMisses",
"EvictedMisses", "HeaderChangedMisses",
"SourceChangedMisses", "ManifestsCount"]:
if not k in self._stats:
self._stats[k] = 0
for key, value in self._incremental_stats.items():
self._stats[key] += value
self._incremental_stats = defaultdict(int)
def resetCounters(self):
self.ensureLoadedAndLocked()
for k in ["CallsWithoutSourceFile",
"CallsWithMultipleSourceFiles",
"CallsWithPch",
"CallsForLinking",
"CacheHits", "CacheMisses",
"EvictedMisses", "HeaderChangedMisses",
"SourceChangedMisses"]:
self._stats[k] = 0
def save(self):
self.ensureLoadedAndLocked()
self._stats.save()
self._objectCache.lock.release()
self._stats = None # Force reload stats when we'll re-acuire lock
class AnalysisResult:
Ok, NoSourceFile, MultipleSourceFilesSimple, \
MultipleSourceFilesComplex, CalledForLink, \
CalledWithPch, ExternalDebugInfo = range(7)
def getFileHash(filePath, additionalData = None):
hasher = HASH_ALGORITHM()
with open(filePath, 'rb') as inFile:
hasher.update(inFile.read())
if additionalData is not None:
hasher.update(additionalData)
return hasher.hexdigest()
def getRelFileHash(filePath, baseDir):
absFilePath = filePath
if absFilePath.startswith(BASEDIR_REPLACEMENT):
if not baseDir:
raise LogicException('No CLCACHE_BASEDIR set, but found relative path ' + filePath)
absFilePath = absFilePath.replace(BASEDIR_REPLACEMENT, baseDir, 1)
if not os.path.exists(absFilePath):
return None
key = get_header_key(filePath, os.path.getmtime(absFilePath))
result = HEADER_HASH_CACHE.get(key)
if result is not None:
return result
result = getFileHash(absFilePath)
HEADER_HASH_CACHE[key] = result
return result
def getHash(data):
hasher = HASH_ALGORITHM()
hasher.update(data)
return hasher.hexdigest()
def copyOrLink(srcFilePath, dstFilePath):
if "CLCACHE_HARDLINK" in os.environ:
ret = windll.kernel32.CreateHardLinkW(unicode(dstFilePath), unicode(srcFilePath), None)
if ret != 0:
# Touch the time stamp of the new link so that the build system
# doesn't confused by a potentially old time on the file. The
# hard link gets the same timestamp as the cached file.
# Note that touching the time stamp of the link also touches
# the time stamp on the cache (and hence on all over hard
# links). This shouldn't be a problem though.
os.utime(dstFilePath, None)
return
# If hardlinking fails for some reason (or it's not enabled), just
# fall back to moving bytes around...
copyfile(srcFilePath, dstFilePath)
def findCompilerBinary(pathVariable, hint):
if hint:
if hint in VERIFIED_COMPILER_HINTS:
return hint
if os.path.isfile(hint):
VERIFIED_COMPILER_HINTS.add(hint)
return hint
compiler = COMPILER_PATH_CACHE.get(pathVariable)
if compiler:
return compiler
compiler = findCompilerBinaryImpl(pathVariable)
if compiler:
COMPILER_PATH_CACHE[pathVariable] = compiler
return compiler
def findCompilerBinaryImpl(pathVariable):
if "CLCACHE_CL" in os.environ:
path = os.environ["CLCACHE_CL"]
return path if os.path.exists(path) else None
frozenByPy2Exe = hasattr(sys, "frozen")
if frozenByPy2Exe:
myExecutablePath = unicode(sys.executable, sys.getfilesystemencoding()).upper()
for dir in pathVariable.split(os.pathsep):
path = os.path.join(dir, "cl.exe")
if os.path.exists(path):
if not frozenByPy2Exe:
return path
# Guard against recursively calling ourselves
if path.upper() != myExecutablePath:
return path
return None
def printTraceStatement(msg):
if "CLCACHE_LOG" in os.environ:
script_dir = os.path.realpath(os.path.dirname(sys.argv[0]))
print os.path.join(script_dir, "clcache.py") + " " + msg
def extractArgument(line, start, end):
# If there are quotes from both sides of argument, remove them
# "-Isome path" must becomse -Isome path
if line[start] == '"' and line[end-1] == '"' and start != (end-1):
start += 1
end -= 1
# Strings like -D"MAX_REPORT_COUNT=L\"999\"" should be replaced by
# -DMAX_REPORT_COUNT=L\"999\"
unescaped_result = line[start:end]
if line[end-1] == '"' and (end-start) > 3 and line[start:start+3] == '-D"':
unescaped_result = '-D' + line[start+3:end-1]
# Unescape quotes.
return unescaped_result.replace('\\"','"').strip()
def splitCommandsFile(line):
# Note, we must treat lines in quotes as one argument. We do not use shlex
# since seems it difficult to set up it to correctly parse escaped quotes.
# A good test line to split is
# '"-IC:\\Program files\\Some library" -DX=1 -DVERSION=\\"1.0\\"
# -I..\\.. -I"..\\..\\lib" -DMYPATH=\\"C:\\Path\\"'
i = 0
wordStart = -1
insideQuotes = False
result = []
while i < len(line):
if line[i] == ' ' and not insideQuotes and wordStart >= 0:
result.append(extractArgument(line, wordStart, i))
wordStart = -1
if line[i] == '"' and ((i == 0) or (i > 0 and line[i - 1] != '\\')):
insideQuotes = not insideQuotes
if line[i] != ' ' and wordStart < 0:
wordStart = i
i += 1
if wordStart >= 0:
result.append(extractArgument(line, wordStart, len(line)))
return result
def expandCommandLine(cmdline):
ret = []
for arg in cmdline:
if arg[0] == '@':
includeFile = arg[1:]
with open(includeFile, 'rb') as file:
rawBytes = file.read()
encoding = None
encodingByBOM = {
codecs.BOM_UTF32_BE: 'utf-32-be',
codecs.BOM_UTF32_LE: 'utf-32-le',
codecs.BOM_UTF16_BE: 'utf-16-be',
codecs.BOM_UTF16_LE: 'utf-16-le',
}
for bom, enc in encodingByBOM.items():
if rawBytes.startswith(bom):
encoding = encodingByBOM[bom]
rawBytes = rawBytes[len(bom):]
break
includeFileContents = rawBytes.decode(encoding) if encoding is not None else rawBytes
ret.extend(expandCommandLine(splitCommandsFile(includeFileContents.strip())))
else:
ret.append(arg)
return ret
def parseCommandLine(cmdline):
optionsWithParameter = ['Ob', 'Gs', 'Fa', 'Fd', 'Fm',
'Fp', 'FR', 'doc', 'FA', 'Fe',
'Fo', 'Fr', 'AI', 'FI', 'FU',
'D', 'U', 'I', 'Zp', 'vm',
'MP', 'Tc', 'V', 'wd', 'wo',
'W', 'Yc', 'Yl', 'Tp', 'we',
'Yu', 'Zm', 'F', 'Fi', 'Xclang']
options = defaultdict(list)
responseFile = ""
sourceFiles = []
i = 0
while i < len(cmdline):
arg = cmdline[i]
# Plain arguments startign with / or -
if arg[0] == '/' or arg[0] == '-':
isParametrized = False
for opt in optionsWithParameter:
if arg[1:len(opt)+1] == opt:
isParametrized = True
key = opt
if len(arg) > len(opt) + 1:
value = arg[len(opt)+1:]
else:
value = cmdline[i+1]
i += 1
options[key].append(value)
break
if not isParametrized:
options[arg[1:]] = []
# Reponse file
elif arg[0] == '@':
responseFile = arg[1:]
# Source file arguments
else:
sourceFiles.append(arg)
i += 1
return options, responseFile, sourceFiles
def analyzeCommandLine(cmdline):
options, responseFile, sourceFiles = parseCommandLine(cmdline)
compl = False
# Technically, it would be possible to support /Zi: we'd just need to
# copy the generated .pdb files into/out of the cache.
if 'Zi' in options:
return AnalysisResult.ExternalDebugInfo, None, None
if 'Yu' in options:
return AnalysisResult.CalledWithPch, None, None
if 'Tp' in options:
sourceFiles += options['Tp']
compl = True
if 'Tc' in options:
sourceFiles += options['Tc']
compl = True
preprocessing = False
for opt in ['E', 'EP', 'P']:
if opt in options:
preprocessing = True
break
if 'link' in options or (not 'c' in options and not preprocessing):
return AnalysisResult.CalledForLink, None, None
if len(sourceFiles) == 0:
return AnalysisResult.NoSourceFile, None, None
if len(sourceFiles) > 1:
if compl:
return AnalysisResult.MultipleSourceFilesComplex, None, None
return AnalysisResult.MultipleSourceFilesSimple, sourceFiles, None
outputFile = None
if 'Fo' in options:
outputFile = options['Fo'][0]
if os.path.isdir(outputFile):
srcFileName = os.path.basename(sourceFiles[0])
outputFile = os.path.join(outputFile,
os.path.splitext(srcFileName)[0] + ".obj")
elif preprocessing:
if 'P' in options:
# Prerpocess to file.
if 'Fi' in options:
outputFile = options['Fi'][0]
else:
srcFileName = os.path.basename(sourceFiles[0])
outputFile = os.path.join(os.getcwd(),
os.path.splitext(srcFileName)[0] + ".i")
else:
# Prerocess to stdout. Use empty string rather then None to ease
# output to log.
outputFile = ''
else:
srcFileName = os.path.basename(sourceFiles[0])
outputFile = os.path.join(os.getcwd(),
os.path.splitext(srcFileName)[0] + ".obj")
# Strip quotes around file names; seems to happen with source files
# with spaces in their names specified via a response file generated
# by Visual Studio.
if outputFile.startswith('"') and outputFile.endswith('"'):
outputFile = outputFile[1:-1]
printTraceStatement("Compiler output file: '%s'" % outputFile)
return AnalysisResult.Ok, sourceFiles[0], outputFile
def invokeRealCompiler(compilerBinary, cmdLine, captureOutput=False):
realCmdline = [compilerBinary] + cmdLine
if not '/showIncludes' in realCmdline:
realCmdline.append('/showIncludes')
printTraceStatement("Invoking real compiler as '%s'" % ' '.join(realCmdline))
returnCode = None
stdout = ''
stderr = ''
if captureOutput:
compilerProcess = Popen(realCmdline, universal_newlines=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = compilerProcess.communicate()
returnCode = compilerProcess.returncode
else:
returnCode = subprocess.call(realCmdline, universal_newlines=True)
printTraceStatement("Real compiler returned code %d" % returnCode)
return returnCode, stdout, stderr
# Given a list of Popen objects, removes and returns
# a completed Popen object.
#
# FIXME: this is a bit inefficient, Python on Windows does not appear
# to provide any blocking "wait for any process to complete" out of the
# box.
def waitForAnyProcess(procs):
out = [p for p in procs if p.poll() != None]
if len(out) >= 1:
out = out[0]
procs.remove(out)
return out
# Damn, none finished yet.
# Do a blocking wait for the first one.
# This could waste time waiting for one process while others have
# already finished :(
out = procs.pop(0)
out.wait()
return out
# Returns the amount of jobs which should be run in parallel when
# invoked in batch mode.
#
# The '/MP' option determines this, which may be set in cmdLine or
# in the CL environment variable.
def jobCount(cmdLine):
switches = []
if 'CL' in os.environ:
switches.extend(os.environ['CL'].split(' '))
switches.extend(cmdLine)
mp_switch = [switch for switch in switches if re.search(r'^/MP\d+$', switch) != None]
if len(mp_switch) == 0:
return 1
# the last instance of /MP takes precedence
mp_switch = mp_switch.pop()
count = mp_switch[3:]
if count != "":
return int(count)
# /MP, but no count specified; use CPU count
try:
return multiprocessing.cpu_count()
except:
# not expected to happen
return 2
# Run commands, up to j concurrently.
# Aborts on first failure and returns the first non-zero exit code.
def runJobs(commands, j=1):
running = []
returncode = 0
while len(commands):
while len(running) > j:
thiscode = waitForAnyProcess(running).returncode
if thiscode != 0:
return thiscode
thiscmd = commands.pop(0)
running.append(Popen(thiscmd))
while len(running) > 0:
thiscode = waitForAnyProcess(running).returncode
if thiscode != 0:
return thiscode
return 0
# re-invoke clcache.py once per source file.
# Used when called via nmake 'batch mode'.
# Returns the first non-zero exit code encountered, or 0 if all jobs succeed.
def reinvokePerSourceFile(cmdLine, sourceFiles):