1
import os.path, sys, shutil, hashlib, cPickle, zlib, time
5
# Permanent cache for dlmalloc and stdlibc++
7
def __init__(self, dirname=None, debug=False):
9
dirname = os.environ.get('EM_CACHE')
11
dirname = os.path.expanduser(os.path.join('~', '.emscripten_cache'))
12
self.dirname = dirname
16
if not os.path.exists(self.dirname):
17
os.makedirs(self.dirname)
20
tempfiles.try_delete(self.dirname)
22
open(self.dirname + '__last_clear', 'w').write('last clear: ' + time.asctime() + '\n')
24
print >> sys.stderr, 'failed to save last clear time: ', e
26
def get_path(self, shortname):
27
return os.path.join(self.dirname, shortname)
29
# Request a cached file. If it isn't in the cache, it will be created with
30
# the given creator function
31
def get(self, shortname, creator, extension='.bc'):
32
if not shortname.endswith(extension): shortname += extension
33
cachename = os.path.join(self.dirname, shortname)
34
if os.path.exists(cachename):
37
shutil.copyfile(creator(), cachename)
40
# JS-specific cache. We cache the results of compilation and optimization,
41
# so that in incremental builds we can just load from cache.
42
# We cache reasonably-large-sized chunks
44
def __init__(self, cache):
46
self.dirname = os.path.join(cache.dirname, 'jcache')
47
self.debug = cache.debug
51
if not os.path.exists(self.dirname):
52
os.makedirs(self.dirname)
54
def get_shortkey(self, keys):
55
if type(keys) not in [list, tuple]:
59
assert type(key) == str
60
ret += hashlib.md5(key).hexdigest()
63
def get_cachename(self, shortkey):
64
return os.path.join(self.dirname, shortkey)
66
# Returns a cached value, if it exists. Make sure the full key matches
67
def get(self, shortkey, keys):
68
if self.debug: print >> sys.stderr, 'jcache get?', shortkey
69
cachename = self.get_cachename(shortkey)
70
if not os.path.exists(cachename):
71
if self.debug: print >> sys.stderr, 'jcache none at all'
74
data = cPickle.loads(zlib.decompress(open(cachename).read()))
76
if self.debug: print >> sys.stderr, 'jcache decompress/unpickle error:', e
79
if self.debug: print >> sys.stderr, 'jcache error in get'
82
if len(oldkeys) != len(keys):
83
if self.debug: print >> sys.stderr, 'jcache collision (a)'
85
for i in range(len(oldkeys)):
86
if oldkeys[i] != keys[i]:
87
if self.debug: print >> sys.stderr, 'jcache collision (b)'
89
if self.debug: print >> sys.stderr, 'jcache win'
92
# Sets the cached value for a key (from get_key)
93
def set(self, shortkey, keys, value):
94
cachename = self.get_cachename(shortkey)
96
f = open(cachename, 'w')
97
f.write(zlib.compress(cPickle.dumps([keys, value])))
100
if self.debug: print >> sys.stderr, 'jcache compress/pickle error:', e
102
# for i in range(len(keys)):
103
# open(cachename + '.key' + str(i), 'w').write(keys[i])
104
# open(cachename + '.value', 'w').write(value)
106
# Given a set of functions of form (ident, text), and a preferred chunk size,
107
# generates a set of chunks for parallel processing and caching.
108
# It is very important to generate similar chunks in incremental builds, in
109
# order to maximize the chance of cache hits. To achieve that, we save the
110
# chunking used in the previous compilation of this phase, and we try to
111
# generate the same chunks, barring big differences in function sizes that
112
# violate our chunk size guideline. If caching is not used, chunking_file
114
def chunkify(funcs, chunk_size, chunking_file, DEBUG=False):
115
previous_mapping = None
117
chunking_file = chunking_file
118
if os.path.exists(chunking_file):
120
previous_mapping = cPickle.Unpickler(open(chunking_file, 'rb')).load() # maps a function identifier to the chunk number it will be in
121
#if DEBUG: print >> sys.stderr, 'jscache previous mapping', previous_mapping
126
# initialize with previous chunking
130
assert ident, 'need names for jcache chunking'
131
if not ident in previous_mapping:
134
n = previous_mapping[ident]
135
while n >= len(chunks): chunks.append([])
136
chunks[n].append(func)
137
if DEBUG: print >> sys.stderr, 'jscache not in previous chunking', len(news)
138
# add news and adjust for new sizes
140
for i in range(len(chunks)):
142
size = sum([len(func[1]) for func in chunk])
143
#if DEBUG: print >> sys.stderr, 'need spilling?', i, size, len(chunk), 'vs', chunk_size, 1.5*chunk_size
144
while size > 1.5*chunk_size and len(chunk) > 1:
146
spilled.append(spill)
147
size -= len(spill[1])
148
#if DEBUG: print >> sys.stderr, 'jscache new + spilled', len(spilled)
150
size = sum([len(func[1]) for func in chunk])
151
while size < 0.66*chunk_size and len(spilled) > 0:
152
spill = spilled.pop()
154
size += len(spill[1])
155
chunks = filter(lambda chunk: len(chunk) > 0, chunks) # might have empty ones, eliminate them
156
funcs = spilled # we will allocate these into chunks as if they were normal inputs
157
#if DEBUG: print >> sys.stderr, 'leftover spills', len(spilled)
158
# initialize reasonably, the rest of the funcs we need to split out
161
for i in range(len(funcs)):
163
curr_size = len(func[1])
164
if total_size + curr_size < chunk_size:
166
total_size += curr_size
170
total_size = curr_size
175
# sort within each chunk, to keep the order identical
177
chunk.sort(key=lambda func: func[0])
178
# save new mapping info
180
for i in range(len(chunks)):
182
for ident, data in chunk:
183
assert ident not in new_mapping, 'cannot have duplicate names in jcache chunking'
184
new_mapping[ident] = i
185
cPickle.Pickler(open(chunking_file, 'wb')).dump(new_mapping)
187
# for i in range(len(chunks)):
189
# print >> sys.stderr, 'final chunk', i, len(chunk)
190
# print >> sys.stderr, 'new mapping:', new_mapping
191
# if previous_mapping:
192
# for ident in set(previous_mapping.keys() + new_mapping.keys()):
193
# if previous_mapping.get(ident) != new_mapping.get(ident):
194
# print >> sys.stderr, 'mapping inconsistency', ident, previous_mapping.get(ident), new_mapping.get(ident)
195
return [''.join([func[1] for func in chunk]) for chunk in chunks] # remove function names