forked from frerich/clcache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclcache.py
More file actions
1609 lines (1253 loc) · 54.7 KB
/
clcache.py
File metadata and controls
1609 lines (1253 loc) · 54.7 KB
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
#
# This file is part of the clcache project.
#
# The contents of this file are subject to the BSD 3-Clause License, the
# full text of which is available in the accompanying LICENSE file at the
# root directory of this project.
#
from ctypes import windll, wintypes
import cProfile
import codecs
from collections import defaultdict, namedtuple
import contextlib
import errno
import hashlib
import json
import os
from shutil import copyfile, rmtree
import subprocess
from subprocess import Popen, PIPE
import sys
import multiprocessing
import re
VERSION = "3.2.0-dev"
HashAlgorithm = hashlib.md5
# try to use os.scandir or scandir.scandir
# fall back to os.listdir if not found
# same for scandir.walk
try:
import scandir # pylint: disable=wrong-import-position
WALK = scandir.walk
LIST = scandir.scandir
except ImportError:
WALK = os.walk
try:
LIST = os.scandir # pylint: disable=no-name-in-module
except AttributeError:
LIST = os.listdir
# The codec that is used by clcache to store compiler STDOUR and STDERR in
# output.txt and stderr.txt.
# This codec is up to us and only used for clcache internal storage.
# For possible values see https://docs.python.org/2/library/codecs.html
CACHE_COMPILER_OUTPUT_STORAGE_CODEC = 'utf-8'
# The cl default codec
CL_DEFAULT_CODEC = 'mbcs'
# 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 = '?'
# `includeFiles`: list of paths to include files, which this source file uses
# `includesContentToObjectMap`: dictionary
# key: cumulative hash of all include files' content in includeFiles
# value: key in the cache, under which the object file is stored
Manifest = namedtuple('Manifest', ['includeFiles', 'includesContentToObjectMap'])
CompilerArtifacts = namedtuple('CompilerArtifacts', ['objectFilePath', 'stdout', 'stderr'])
def printBinary(stream, rawData):
stream.buffer.write(rawData)
def basenameWithoutExtension(path):
basename = os.path.basename(path)
return os.path.splitext(basename)[0]
def filesBeneath(path):
for path, _, filenames in WALK(path):
for filename in filenames:
yield os.path.join(path, filename)
def childDirectories(path, absolute=True):
supportsScandir = (LIST != os.listdir)
for entry in LIST(path):
if supportsScandir:
if entry.is_dir():
yield entry.path if absolute else entry.name
else:
absPath = os.path.join(path, entry)
if os.path.isdir(absPath):
yield absPath if absolute else entry
def normalizeBaseDir(baseDir):
if baseDir:
baseDir = os.path.normcase(baseDir)
if not baseDir.endswith(os.path.sep):
baseDir += os.path.sep
return baseDir
else:
# Converts empty string to None
return None
class IncludeNotFoundException(Exception):
pass
class IncludeChangedException(Exception):
pass
class CacheLockException(Exception):
pass
class LogicException(Exception):
def __init__(self, message):
super(LogicException, self).__init__(message)
self.message = message
def __str__(self):
return repr(self.message)
class ManifestSection(object):
def __init__(self, manifestSectionDir):
self.manifestSectionDir = manifestSectionDir
self.lock = CacheLock.forPath(self.manifestSectionDir)
def manifestPath(self, manifestHash):
return os.path.join(self.manifestSectionDir, manifestHash + ".json")
def manifestFiles(self):
return filesBeneath(self.manifestSectionDir)
def setManifest(self, manifestHash, manifest):
ensureDirectoryExists(self.manifestSectionDir)
with open(self.manifestPath(manifestHash), 'w') as outFile:
# Converting namedtuple to JSON via OrderedDict preserves key names and keys order
json.dump(manifest._asdict(), outFile, sort_keys=True, indent=2)
def getManifest(self, manifestHash):
fileName = self.manifestPath(manifestHash)
if not os.path.exists(fileName):
return None
try:
with open(fileName, 'r') as inFile:
doc = json.load(inFile)
return Manifest(doc['includeFiles'], doc['includesContentToObjectMap'])
except IOError:
return None
@contextlib.contextmanager
def allSectionsLocked(repository):
sections = list(repository.sections())
for section in sections:
section.lock.acquire()
try:
yield
finally:
for section in sections:
section.lock.release()
class ManifestRepository(object):
# Bump this counter whenever the current manifest file format changes.
# E.g. changing the file format from {'oldkey': ...} to {'newkey': ...} requires
# invalidation, such that a manifest that was stored using the old format is not
# interpreted using the new format. Instead the old file will not be touched
# again due to a new manifest hash and is cleaned away after some time.
MANIFEST_FILE_FORMAT_VERSION = 4
def __init__(self, manifestsRootDir):
self._manifestsRootDir = manifestsRootDir
def section(self, manifestHash):
return ManifestSection(os.path.join(self._manifestsRootDir, manifestHash[:2]))
def sections(self):
return (ManifestSection(path) for path in childDirectories(self._manifestsRootDir))
def clean(self, maxManifestsSize):
manifestFileInfos = []
for section in self.sections():
for filePath in section.manifestFiles():
try:
manifestFileInfos.append((os.stat(filePath), filePath))
except OSError:
pass
manifestFileInfos.sort(key=lambda t: t[0].st_atime, reverse=True)
remainingObjectsSize = 0
for stat, filepath in manifestFileInfos:
if remainingObjectsSize + stat.st_size <= maxManifestsSize:
remainingObjectsSize += stat.st_size
else:
os.remove(filepath)
return remainingObjectsSize
@staticmethod
def getManifestHash(compilerBinary, commandLine, sourceFile):
compilerHash = getCompilerHash(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.
# One of the few exceptions to this rule is the /MP switch, which only
# defines how many compiler processes are running simultaneusly.
commandLine = [arg for arg in commandLine if not arg.startswith("/MP")]
additionalData = "{}|{}|{}".format(
compilerHash, commandLine, ManifestRepository.MANIFEST_FILE_FORMAT_VERSION)
return getFileHash(sourceFile, additionalData)
@staticmethod
def getIncludesContentHashForFiles(includes):
listOfIncludesHashes = []
includeMissing = False
for path in sorted(includes.keys()):
try:
fileHash = getFileHash(path)
if fileHash != includes[path]:
raise IncludeChangedException()
listOfIncludesHashes.append(fileHash)
except FileNotFoundError:
includeMissing = True
if includeMissing:
raise IncludeNotFoundException()
return ManifestRepository.getIncludesContentHashForHashes(listOfIncludesHashes)
@staticmethod
def getIncludesContentHashForHashes(listOfIncludesHashes):
return HashAlgorithm(','.join(listOfIncludesHashes).encode()).hexdigest()
class CacheLock(object):
""" Implements a lock for the object cache which
can be used in 'with' statements. """
INFINITE = 0xFFFFFFFF
WAIT_ABANDONED_CODE = 0x00000080
WAIT_TIMEOUT_CODE = 0x00000102
def __init__(self, mutexName, timeoutMs):
self._mutexName = 'Local\\' + mutexName
self._mutex = windll.kernel32.CreateMutexW(
wintypes.INT(0),
wintypes.INT(0),
self._mutexName)
self._timeoutMs = timeoutMs
assert self._mutex
def __enter__(self):
self.acquire()
def __exit__(self, typ, value, traceback):
self.release()
def __del__(self):
windll.kernel32.CloseHandle(self._mutex)
def acquire(self):
result = windll.kernel32.WaitForSingleObject(
self._mutex, wintypes.INT(self._timeoutMs))
if result not in [0, self.WAIT_ABANDONED_CODE]:
if result == self.WAIT_TIMEOUT_CODE:
errorString = \
'Failed to acquire lock {} after {}ms; ' \
'try setting CLCACHE_OBJECT_CACHE_TIMEOUT_MS environment variable to a larger value.'.format(
self._mutexName, self._timeoutMs)
else:
errorString = 'Error! WaitForSingleObject returns {result}, last error {error}'.format(
result=result,
error=windll.kernel32.GetLastError())
raise CacheLockException(errorString)
def release(self):
windll.kernel32.ReleaseMutex(self._mutex)
@staticmethod
def forPath(path):
timeoutMs = int(os.environ.get('CLCACHE_OBJECT_CACHE_TIMEOUT_MS', 10 * 1000))
lockName = path.replace(':', '-').replace('\\', '-')
return CacheLock(lockName, timeoutMs)
class CompilerArtifactsSection(object):
def __init__(self, compilerArtifactsSectionDir):
self.compilerArtifactsSectionDir = compilerArtifactsSectionDir
self.lock = CacheLock.forPath(self.compilerArtifactsSectionDir)
def cacheEntryDir(self, key):
return os.path.join(self.compilerArtifactsSectionDir, key)
def cacheEntries(self):
return childDirectories(self.compilerArtifactsSectionDir, absolute=False)
def cachedObjectName(self, key):
return os.path.join(self.cacheEntryDir(key), "object")
def hasEntry(self, key):
return os.path.exists(self.cacheEntryDir(key))
def setEntry(self, key, artifacts):
ensureDirectoryExists(self.cacheEntryDir(key))
if artifacts.objectFilePath is not None:
copyOrLink(artifacts.objectFilePath, self.cachedObjectName(key))
self._setCachedCompilerConsoleOutput(key, 'output.txt', artifacts.stdout)
if artifacts.stderr != '':
self._setCachedCompilerConsoleOutput(key, 'stderr.txt', artifacts.stderr)
def getEntry(self, key):
assert self.hasEntry(key)
return CompilerArtifacts(
self.cachedObjectName(key),
self._getCachedCompilerConsoleOutput(key, 'output.txt'),
self._getCachedCompilerConsoleOutput(key, 'stderr.txt')
)
def _getCachedCompilerConsoleOutput(self, key, fileName):
try:
outputFilePath = os.path.join(self.cacheEntryDir(key), fileName)
with open(outputFilePath, 'rb') as f:
return f.read().decode(CACHE_COMPILER_OUTPUT_STORAGE_CODEC)
except IOError:
return ''
def _setCachedCompilerConsoleOutput(self, key, fileName, output):
outputFilePath = os.path.join(self.cacheEntryDir(key), fileName)
with open(outputFilePath, 'wb') as f:
f.write(output.encode(CACHE_COMPILER_OUTPUT_STORAGE_CODEC))
class CompilerArtifactsRepository(object):
def __init__(self, compilerArtifactsRootDir):
self._compilerArtifactsRootDir = compilerArtifactsRootDir
def section(self, key):
return CompilerArtifactsSection(os.path.join(self._compilerArtifactsRootDir, key[:2]))
def sections(self):
return (CompilerArtifactsSection(path) for path in childDirectories(self._compilerArtifactsRootDir))
def removeEntry(self, keyToBeRemoved):
compilerArtifactsDir = self.section(keyToBeRemoved).cacheEntryDir(keyToBeRemoved)
rmtree(compilerArtifactsDir, ignore_errors=True)
def clean(self, maxCompilerArtifactsSize):
objectInfos = []
for section in self.sections():
for cachekey in section.cacheEntries():
try:
objectStat = os.stat(section.cachedObjectName(cachekey))
objectInfos.append((objectStat, cachekey))
except OSError:
pass
objectInfos.sort(key=lambda t: t[0].st_atime)
# compute real current size to fix up the stored cacheSize
currentSizeObjects = sum(x[0].st_size for x in objectInfos)
removedItems = 0
for stat, cachekey in objectInfos:
self.removeEntry(cachekey)
removedItems += 1
currentSizeObjects -= stat.st_size
if currentSizeObjects < maxCompilerArtifactsSize:
break
return len(objectInfos)-removedItems, currentSizeObjects
@staticmethod
def computeKeyDirect(manifestHash, includesContentHash):
# We must take into account manifestHash to avoid
# collisions when different source files use the same
# set of includes.
return getStringHash(manifestHash + includesContentHash)
@staticmethod
def computeKeyNodirect(compilerBinary, commandLine, environment):
ppcmd = ["/EP"] + [arg for arg in commandLine if arg not in ("-c", "/c")]
returnCode, preprocessedSourceCode, ppStderrBinary = \
invokeRealCompiler(compilerBinary, ppcmd, captureOutput=True, outputAsString=False, environment=environment)
if returnCode != 0:
printBinary(sys.stderr, ppStderrBinary)
print("clcache: preprocessor failed", file=sys.stderr)
sys.exit(returnCode)
compilerHash = getCompilerHash(compilerBinary)
normalizedCmdLine = CompilerArtifactsRepository._normalizedCommandLine(commandLine)
h = HashAlgorithm()
h.update(compilerHash.encode("UTF-8"))
h.update(' '.join(normalizedCmdLine).encode("UTF-8"))
h.update(preprocessedSourceCode)
return h.hexdigest()
@staticmethod
def _normalizedCommandLine(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",)
# Also strip the switch for specifying the number of parallel compiler
# processes to use (when specifying multiple source files on the
# command line).
argsToStrip += ("MP",)
return [arg for arg in cmdline
if not (arg[0] in "/-" and arg[1:].startswith(argsToStrip))]
class Cache(object):
def __init__(self, cacheDirectory=None):
self.dir = cacheDirectory
if not self.dir:
try:
self.dir = os.environ["CLCACHE_DIR"]
except KeyError:
self.dir = os.path.join(os.path.expanduser("~"), "clcache")
manifestsRootDir = os.path.join(self.dir, "manifests")
ensureDirectoryExists(manifestsRootDir)
self.manifestRepository = ManifestRepository(manifestsRootDir)
compilerArtifactsRootDir = os.path.join(self.dir, "objects")
ensureDirectoryExists(compilerArtifactsRootDir)
self.compilerArtifactsRepository = CompilerArtifactsRepository(compilerArtifactsRootDir)
self.configuration = Configuration(os.path.join(self.dir, "config.txt"))
self.statistics = Statistics(os.path.join(self.dir, "stats.txt"))
@property
@contextlib.contextmanager
def lock(self):
with allSectionsLocked(self.manifestRepository), \
allSectionsLocked(self.compilerArtifactsRepository), \
self.statistics.lock:
yield
def cacheDirectory(self):
return self.dir
def clean(self, stats, maximumSize):
currentSize = stats.currentCacheSize()
if currentSize < maximumSize:
return
# Free at least 10% to avoid cleaning up too often which
# is a big performance hit with large caches.
effectiveMaximumSizeOverall = maximumSize * 0.9
# Split limit in manifests (10 %) and objects (90 %)
effectiveMaximumSizeManifests = effectiveMaximumSizeOverall * 0.1
effectiveMaximumSizeObjects = effectiveMaximumSizeOverall - effectiveMaximumSizeManifests
# Clean manifests
currentSizeManifests = self.manifestRepository.clean(effectiveMaximumSizeManifests)
# Clean artifacts
currentCompilerArtifactsCount, currentCompilerArtifactsSize = self.compilerArtifactsRepository.clean(
effectiveMaximumSizeObjects)
stats.setCacheSize(currentCompilerArtifactsSize + currentSizeManifests)
stats.setNumCacheEntries(currentCompilerArtifactsCount)
class PersistentJSONDict(object):
def __init__(self, fileName):
self._dirty = False
self._dict = {}
self._fileName = fileName
try:
with open(self._fileName, 'r') as f:
self._dict = json.load(f)
except IOError:
pass
def save(self):
if self._dirty:
with open(self._fileName, 'w') as f:
json.dump(self._dict, f, sort_keys=True, indent=4)
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
def __eq__(self, other):
return type(self) is type(other) and self.__dict__ == other.__dict__
class Configuration(object):
_defaultValues = {"MaximumCacheSize": 1073741824} # 1 GiB
def __init__(self, configurationFile):
self._configurationFile = configurationFile
self._cfg = None
def __enter__(self):
self._cfg = PersistentJSONDict(self._configurationFile)
for setting, defaultValue in self._defaultValues.items():
if setting not in self._cfg:
self._cfg[setting] = defaultValue
return self
def __exit__(self, typ, value, traceback):
# Does not write to disc when unchanged
self._cfg.save()
def maximumCacheSize(self):
return self._cfg["MaximumCacheSize"]
def setMaximumCacheSize(self, size):
self._cfg["MaximumCacheSize"] = size
class Statistics(object):
CALLS_WITH_INVALID_ARGUMENT = "CallsWithInvalidArgument"
CALLS_WITHOUT_SOURCE_FILE = "CallsWithoutSourceFile"
CALLS_WITH_MULTIPLE_SOURCE_FILES = "CallsWithMultipleSourceFiles"
CALLS_WITH_PCH = "CallsWithPch"
CALLS_FOR_LINKING = "CallsForLinking"
CALLS_FOR_EXTERNAL_DEBUG_INFO = "CallsForExternalDebugInfo"
CALLS_FOR_PREPROCESSING = "CallsForPreprocessing"
CACHE_HITS = "CacheHits"
CACHE_MISSES = "CacheMisses"
EVICTED_MISSES = "EvictedMisses"
HEADER_CHANGED_MISSES = "HeaderChangedMisses"
SOURCE_CHANGED_MISSES = "SourceChangedMisses"
CACHE_ENTRIES = "CacheEntries"
CACHE_SIZE = "CacheSize"
RESETTABLE_KEYS = {
CALLS_WITH_INVALID_ARGUMENT,
CALLS_WITHOUT_SOURCE_FILE,
CALLS_WITH_MULTIPLE_SOURCE_FILES,
CALLS_WITH_PCH,
CALLS_FOR_LINKING,
CALLS_FOR_EXTERNAL_DEBUG_INFO,
CALLS_FOR_PREPROCESSING,
CACHE_HITS,
CACHE_MISSES,
EVICTED_MISSES,
HEADER_CHANGED_MISSES,
SOURCE_CHANGED_MISSES,
}
NON_RESETTABLE_KEYS = {
CACHE_ENTRIES,
CACHE_SIZE,
}
def __init__(self, statsFile):
self._statsFile = statsFile
self._stats = None
self.lock = CacheLock.forPath(self._statsFile)
def __enter__(self):
self._stats = PersistentJSONDict(self._statsFile)
for k in Statistics.RESETTABLE_KEYS | Statistics.NON_RESETTABLE_KEYS:
if k not in self._stats:
self._stats[k] = 0
return self
def __exit__(self, typ, value, traceback):
# Does not write to disc when unchanged
self._stats.save()
def __eq__(self, other):
return type(self) is type(other) and self.__dict__ == other.__dict__
def numCallsWithInvalidArgument(self):
return self._stats[Statistics.CALLS_WITH_INVALID_ARGUMENT]
def registerCallWithInvalidArgument(self):
self._stats[Statistics.CALLS_WITH_INVALID_ARGUMENT] += 1
def numCallsWithoutSourceFile(self):
return self._stats[Statistics.CALLS_WITHOUT_SOURCE_FILE]
def registerCallWithoutSourceFile(self):
self._stats[Statistics.CALLS_WITHOUT_SOURCE_FILE] += 1
def numCallsWithMultipleSourceFiles(self):
return self._stats[Statistics.CALLS_WITH_MULTIPLE_SOURCE_FILES]
def registerCallWithMultipleSourceFiles(self):
self._stats[Statistics.CALLS_WITH_MULTIPLE_SOURCE_FILES] += 1
def numCallsWithPch(self):
return self._stats[Statistics.CALLS_WITH_PCH]
def registerCallWithPch(self):
self._stats[Statistics.CALLS_WITH_PCH] += 1
def numCallsForLinking(self):
return self._stats[Statistics.CALLS_FOR_LINKING]
def registerCallForLinking(self):
self._stats[Statistics.CALLS_FOR_LINKING] += 1
def numCallsForExternalDebugInfo(self):
return self._stats[Statistics.CALLS_FOR_EXTERNAL_DEBUG_INFO]
def registerCallForExternalDebugInfo(self):
self._stats[Statistics.CALLS_FOR_EXTERNAL_DEBUG_INFO] += 1
def numEvictedMisses(self):
return self._stats[Statistics.EVICTED_MISSES]
def registerEvictedMiss(self):
self.registerCacheMiss()
self._stats[Statistics.EVICTED_MISSES] += 1
def numHeaderChangedMisses(self):
return self._stats[Statistics.HEADER_CHANGED_MISSES]
def registerHeaderChangedMiss(self):
self.registerCacheMiss()
self._stats[Statistics.HEADER_CHANGED_MISSES] += 1
def numSourceChangedMisses(self):
return self._stats[Statistics.SOURCE_CHANGED_MISSES]
def registerSourceChangedMiss(self):
self.registerCacheMiss()
self._stats[Statistics.SOURCE_CHANGED_MISSES] += 1
def numCacheEntries(self):
return self._stats[Statistics.CACHE_ENTRIES]
def setNumCacheEntries(self, number):
self._stats[Statistics.CACHE_ENTRIES] = number
def registerCacheEntry(self, size):
self._stats[Statistics.CACHE_ENTRIES] += 1
self._stats[Statistics.CACHE_SIZE] += size
def unregisterCacheEntry(self, size):
self._stats[Statistics.CACHE_ENTRIES] -= 1
self._stats[Statistics.CACHE_SIZE] -= size
def currentCacheSize(self):
return self._stats[Statistics.CACHE_SIZE]
def setCacheSize(self, size):
self._stats[Statistics.CACHE_SIZE] = size
def numCacheHits(self):
return self._stats[Statistics.CACHE_HITS]
def registerCacheHit(self):
self._stats[Statistics.CACHE_HITS] += 1
def numCacheMisses(self):
return self._stats[Statistics.CACHE_MISSES]
def registerCacheMiss(self):
self._stats[Statistics.CACHE_MISSES] += 1
def numCallsForPreprocessing(self):
return self._stats[Statistics.CALLS_FOR_PREPROCESSING]
def registerCallForPreprocessing(self):
self._stats[Statistics.CALLS_FOR_PREPROCESSING] += 1
def resetCounters(self):
for k in Statistics.RESETTABLE_KEYS:
self._stats[k] = 0
class AnalysisError(Exception):
pass
class NoSourceFileError(AnalysisError):
pass
class MultipleSourceFilesComplexError(AnalysisError):
pass
class CalledForLinkError(AnalysisError):
pass
class CalledWithPchError(AnalysisError):
pass
class ExternalDebugInfoError(AnalysisError):
pass
class CalledForPreprocessingError(AnalysisError):
pass
class InvalidArgumentError(AnalysisError):
pass
def getCompilerHash(compilerBinary):
stat = os.stat(compilerBinary)
data = '|'.join([
str(stat.st_mtime),
str(stat.st_size),
VERSION,
])
hasher = HashAlgorithm()
hasher.update(data.encode("UTF-8"))
return hasher.hexdigest()
def getFileHash(filePath, additionalData=None):
hasher = HashAlgorithm()
with open(filePath, 'rb') as inFile:
hasher.update(inFile.read())
if additionalData is not None:
# Encoding of this additional data does not really matter
# as long as we keep it fixed, otherwise hashes change.
# The string should fit into ASCII, so UTF8 should not change anything
hasher.update(additionalData.encode("UTF-8"))
return hasher.hexdigest()
def getStringHash(dataString):
hasher = HashAlgorithm()
hasher.update(dataString.encode("UTF-8"))
return hasher.hexdigest()
def expandBasedirPlaceholder(path, baseDir):
if path.startswith(BASEDIR_REPLACEMENT):
if not baseDir:
raise LogicException('No CLCACHE_BASEDIR set, but found relative path ' + path)
return path.replace(BASEDIR_REPLACEMENT, baseDir, 1)
else:
return path
def collapseBasedirToPlaceholder(path, baseDir):
assert path == os.path.normcase(path)
assert baseDir == os.path.normcase(baseDir)
if path.startswith(baseDir):
return path.replace(baseDir, BASEDIR_REPLACEMENT, 1)
else:
return path
def ensureDirectoryExists(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def copyOrLink(srcFilePath, dstFilePath):
ensureDirectoryExists(os.path.dirname(os.path.abspath(dstFilePath)))
if "CLCACHE_HARDLINK" in os.environ:
ret = windll.kernel32.CreateHardLinkW(str(dstFilePath), str(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. Always to a temporary path first to
# lower the chances of corrupting it.
tempDst = dstFilePath + '.tmp'
copyfile(srcFilePath, tempDst)
os.rename(tempDst, dstFilePath)
def myExecutablePath():
assert hasattr(sys, "frozen"), "is not frozen by py2exe"
return sys.executable.upper()
def findCompilerBinary():
if "CLCACHE_CL" in os.environ:
path = os.environ["CLCACHE_CL"]
return path if os.path.exists(path) else None
frozenByPy2Exe = hasattr(sys, "frozen")
for p in os.environ["PATH"].split(os.pathsep):
path = os.path.join(p, "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:
scriptDir = os.path.realpath(os.path.dirname(sys.argv[0]))
print(os.path.join(scriptDir, "clcache.py") + " " + msg)
class CommandLineTokenizer(object):
def __init__(self, content):
self.argv = []
self._content = content
self._pos = 0
self._token = ''
self._parser = self._initialState
while self._pos < len(self._content):
self._parser = self._parser(self._content[self._pos])
self._pos += 1
if self._token:
self.argv.append(self._token)
def _initialState(self, currentChar):
if currentChar.isspace():
return self._initialState
if currentChar == '"':
return self._quotedState
if currentChar == '\\':
self._parseBackslash()
return self._unquotedState
self._token += currentChar
return self._unquotedState
def _unquotedState(self, currentChar):
if currentChar.isspace():
self.argv.append(self._token)
self._token = ''
return self._initialState
if currentChar == '"':
return self._quotedState
if currentChar == '\\':
self._parseBackslash()
return self._unquotedState
self._token += currentChar
return self._unquotedState
def _quotedState(self, currentChar):
if currentChar == '"':
return self._unquotedState
if currentChar == '\\':
self._parseBackslash()
return self._quotedState
self._token += currentChar
return self._quotedState
def _parseBackslash(self):
numBackslashes = 0
while self._pos < len(self._content) and self._content[self._pos] == '\\':
self._pos += 1
numBackslashes += 1
followedByDoubleQuote = self._pos < len(self._content) and self._content[self._pos] == '"'
if followedByDoubleQuote:
self._token += '\\' * (numBackslashes // 2)
if numBackslashes % 2 == 0:
self._pos -= 1
else:
self._token += '"'
else:
self._token += '\\' * numBackslashes
self._pos -= 1
def splitCommandsFile(content):
return CommandLineTokenizer(content).argv
def expandCommandLine(cmdline):
ret = []
for arg in cmdline:
if arg[0] == '@':
includeFile = arg[1:]
with open(includeFile, 'rb') as f:
rawBytes = f.read()
encoding = None
bomToEncoding = {
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 bomToEncoding.items():
if rawBytes.startswith(bom):
encoding = enc
rawBytes = rawBytes[len(bom):]
break
if encoding:
includeFileContents = rawBytes.decode(encoding)
else:
includeFileContents = rawBytes.decode("UTF-8")
ret.extend(expandCommandLine(splitCommandsFile(includeFileContents.strip())))
else:
ret.append(arg)
return ret
def extentCommandLineFromEnvironment(cmdLine, environment):
remainingEnvironment = environment.copy()
prependCmdLineString = remainingEnvironment.pop('CL', None)
if prependCmdLineString is not None:
cmdLine = splitCommandsFile(prependCmdLineString.strip()) + cmdLine
appendCmdLineString = remainingEnvironment.pop('_CL_', None)
if appendCmdLineString is not None:
cmdLine = cmdLine + splitCommandsFile(appendCmdLineString.strip())
return cmdLine, remainingEnvironment
class Argument(object):
def __init__(self, name):
self.name = name
def __len__(self):
return len(self.name)
def __str__(self):
return "/" + self.name
def __eq__(self, other):
return type(self) == type(other) and self.name == other.name
def __hash__(self):
key = (type(self), self.name)
return hash(key)
# /NAMEparameter (no space, required parameter).
class ArgumentT1(Argument):
pass
# /NAME[parameter] (no space, optional parameter)
class ArgumentT2(Argument):
pass
# /NAME[ ]parameter (optional space)
class ArgumentT3(Argument):
pass
# /NAME parameter (required space)
class ArgumentT4(Argument):
pass