This file is indexed.

/usr/lib/python2.7/dist-packages/pyopencl/cache.py is in python-pyopencl 2015.1-2build3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
"""PyOpenCL compiler cache."""

from __future__ import division

__copyright__ = "Copyright (C) 2011 Andreas Kloeckner"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import pyopencl._cl as _cl
import re
import sys
import os
from pytools import Record

try:
    import hashlib
    new_hash = hashlib.md5
except ImportError:
    # for Python << 2.5
    import md5
    new_hash = md5.new


def _erase_dir(dir):
    from os import listdir, unlink, rmdir
    from os.path import join
    for name in listdir(dir):
        unlink(join(dir, name))
    rmdir(dir)


def update_checksum(checksum, obj):
    if isinstance(obj, unicode):
        checksum.update(obj.encode("utf8"))
    else:
        checksum.update(obj)


# {{{ cleanup

class CleanupBase(object):
    pass


class CleanupManager(CleanupBase):
    def __init__(self):
        self.cleanups = []

    def register(self, c):
        self.cleanups.insert(0, c)

    def clean_up(self):
        for c in self.cleanups:
            c.clean_up()

    def error_clean_up(self):
        for c in self.cleanups:
            c.error_clean_up()


class CacheLockManager(CleanupBase):
    def __init__(self, cleanup_m, cache_dir):
        if cache_dir is not None:
            self.lock_file = os.path.join(cache_dir, "lock")

            attempts = 0
            while True:
                try:
                    self.fd = os.open(self.lock_file,
                            os.O_CREAT | os.O_WRONLY | os.O_EXCL)
                    break
                except OSError:
                    pass

                from time import sleep
                sleep(1)

                attempts += 1

                if attempts > 10:
                    from warnings import warn
                    warn("could not obtain cache lock--delete '%s' if necessary"
                            % self.lock_file)

            cleanup_m.register(self)

    def clean_up(self):
        import os
        os.close(self.fd)
        os.unlink(self.lock_file)

    def error_clean_up(self):
        pass


class ModuleCacheDirManager(CleanupBase):
    def __init__(self, cleanup_m, path):
        from os import mkdir

        self.path = path
        try:
            mkdir(self.path)
            cleanup_m.register(self)
            self.existed = False
        except OSError:
            self.existed = True

    def sub(self, n):
        from os.path import join
        return join(self.path, n)

    def reset(self):
        import os
        _erase_dir(self.path)
        os.mkdir(self.path)

    def clean_up(self):
        pass

    def error_clean_up(self):
        _erase_dir(self.path)

# }}}


# {{{ #include dependency handling

C_INCLUDE_RE = re.compile(r'^\s*\#\s*include\s+[<"](.+)[">]\s*$',
        re.MULTILINE)


def get_dependencies(src, include_path):
    result = {}

    from os.path import realpath, join

    def _inner(src):
        for match in C_INCLUDE_RE.finditer(src):
            included = match.group(1)

            found = False
            for ipath in include_path:
                included_file_name = realpath(join(ipath, included))

                if included_file_name not in result:
                    try:
                        src_file = open(included_file_name, "rt")
                    except IOError:
                        continue

                    try:
                        included_src = src_file.read()
                    finally:
                        src_file.close()

                    # jrevent infinite recursion if some header file appears to
                    # include itself
                    result[included_file_name] = None

                    checksum = new_hash()
                    update_checksum(checksum, included_src)
                    _inner(included_src)

                    result[included_file_name] = (
                            os.stat(included_file_name).st_mtime,
                            checksum.hexdigest(),
                            )

                    found = True
                    break  # stop searching the include path

            if not found:
                pass

    _inner(src)

    result = list((name,) + vals for name, vals in result.iteritems())
    result.sort()

    return result


def get_file_md5sum(fname):
    checksum = new_hash()
    inf = open(fname)
    try:
        contents = inf.read()
    finally:
        inf.close()
    update_checksum(checksum, contents)
    return checksum.hexdigest()


def check_dependencies(deps):
    for name, date, md5sum in deps:
        try:
            possibly_updated = os.stat(name).st_mtime != date
        except OSError:
            return False
        else:
            if possibly_updated and md5sum != get_file_md5sum(name):
                return False

    return True

# }}}


# {{{ key generation

def get_device_cache_id(device):
    from pyopencl.version import VERSION
    platform = device.platform
    return (VERSION,
            platform.vendor, platform.name, platform.version,
            device.vendor, device.name, device.version, device.driver_version)


def get_cache_key(device, options, src):
    checksum = new_hash()
    update_checksum(checksum, src)
    update_checksum(checksum, " ".join(options))
    update_checksum(checksum, str(get_device_cache_id(device)))
    return checksum.hexdigest()

# }}}


def retrieve_from_cache(cache_dir, cache_key):
    class _InvalidInfoFile(RuntimeError):
        pass

    from os.path import join, isdir
    module_cache_dir = join(cache_dir, cache_key)
    if not isdir(module_cache_dir):
        return None

    cleanup_m = CleanupManager()
    try:
        try:
            CacheLockManager(cleanup_m, cache_dir)

            mod_cache_dir_m = ModuleCacheDirManager(cleanup_m, module_cache_dir)
            info_path = mod_cache_dir_m.sub("info")
            binary_path = mod_cache_dir_m.sub("binary")

            # {{{ load info file

            try:
                from cPickle import load

                try:
                    info_file = open(info_path, "rb")
                except IOError:
                    raise _InvalidInfoFile()

                try:
                    try:
                        info = load(info_file)
                    except EOFError:
                        raise _InvalidInfoFile()
                finally:
                    info_file.close()

            except _InvalidInfoFile:
                mod_cache_dir_m.reset()
                from warnings import warn
                warn("PyOpenCL encountered an invalid info file for cache key %s"
                        % cache_key)
                return None

            # }}}

            # {{{ load binary

            binary_file = open(binary_path, "rb")
            try:
                binary = binary_file.read()
            finally:
                binary_file.close()

            # }}}

            if check_dependencies(info.dependencies):
                return binary, info.log
            else:
                mod_cache_dir_m.reset()

        except:
            cleanup_m.error_clean_up()
            raise
    finally:
        cleanup_m.clean_up()


# {{{ top-level driver

class _SourceInfo(Record):
    pass


def _create_built_program_from_source_cached(ctx, src, options, devices, cache_dir):
    from os.path import join

    include_path = ["."]

    option_idx = 0
    while option_idx < len(options):
        option = options[option_idx].strip()
        if option.startswith("-I") or option.startswith("/I"):
            if len(option) == 2:
                if option_idx+1 < len(options):
                    include_path.append(options[option_idx+1])
                option_idx += 2
            else:
                include_path.append(option[2:].lstrip())
                option_idx += 1
        else:
            option_idx += 1

    if cache_dir is None:
        import appdirs
        cache_dir = join(appdirs.user_cache_dir("pyopencl", "pyopencl"),
                "pyopencl-compiler-cache-v2-py%s" % (
                    ".".join(str(i) for i in sys.version_info),))

    # {{{ ensure cache directory exists

    try:
        os.makedirs(cache_dir)
    except OSError, e:
        from errno import EEXIST
        if e.errno != EEXIST:
            raise

    # }}}

    if devices is None:
        devices = ctx.devices

    cache_keys = [get_cache_key(device, options, src) for device in devices]

    binaries = []
    to_be_built_indices = []
    logs = []
    for i, (device, cache_key) in enumerate(zip(devices, cache_keys)):
        cache_result = retrieve_from_cache(cache_dir, cache_key)

        if cache_result is None:
            to_be_built_indices.append(i)
            binaries.append(None)
            logs.append(None)
        else:
            binary, log = cache_result
            binaries.append(binary)
            logs.append(log)

    message = (75*"="+"\n").join(
            "Build on %s succeeded, but said:\n\n%s" % (dev, log)
            for dev, log in zip(devices, logs)
            if log is not None and log.strip())

    if message:
        from pyopencl import compiler_output
        compiler_output(
                "Built kernel retrieved from cache. Original from-source "
                "build had warnings:\n"+message)

    # {{{ build on the build-needing devices, in one go

    result = None
    already_built = False

    if to_be_built_indices:
        # defeat implementation caches:
        from uuid import uuid4
        src = src + "\n\n__constant int pyopencl_defeat_cache_%s = 0;" % (
                uuid4().hex)

        prg = _cl._Program(ctx, src)
        prg.build(options, [devices[i] for i in to_be_built_indices])

        prg_devs = prg.get_info(_cl.program_info.DEVICES)
        prg_bins = prg.get_info(_cl.program_info.BINARIES)
        prg_logs = prg._get_build_logs()

        for dest_index in to_be_built_indices:
            dev = devices[dest_index]
            src_index = prg_devs.index(dev)
            binaries[dest_index] = prg_bins[src_index]
            _, logs[dest_index] = prg_logs[src_index]

        if len(to_be_built_indices) == len(devices):
            # Important special case: if code for all devices was built,
            # then we may simply use the program that we just built as the
            # final result.

            result = prg
            already_built = True

    if result is None:
        result = _cl._Program(ctx, devices, binaries)

    # }}}

    # {{{ save binaries to cache

    if to_be_built_indices:
        cleanup_m = CleanupManager()
        try:
            try:
                CacheLockManager(cleanup_m, cache_dir)

                for i in to_be_built_indices:
                    cache_key = cache_keys[i]
                    device = devices[i]
                    binary = binaries[i]

                    mod_cache_dir_m = ModuleCacheDirManager(cleanup_m,
                            join(cache_dir, cache_key))
                    info_path = mod_cache_dir_m.sub("info")
                    binary_path = mod_cache_dir_m.sub("binary")
                    source_path = mod_cache_dir_m.sub("source.cl")

                    outf = open(source_path, "wt")
                    outf.write(src)
                    outf.close()

                    outf = open(binary_path, "wb")
                    outf.write(binary)
                    outf.close()

                    from cPickle import dump
                    info_file = open(info_path, "wb")
                    dump(_SourceInfo(
                        dependencies=get_dependencies(src, include_path),
                        log=logs[i]), info_file)
                    info_file.close()

            except:
                cleanup_m.error_clean_up()
                raise
        finally:
            cleanup_m.clean_up()

    # }}}

    return result, already_built


def create_built_program_from_source_cached(ctx, src, options=[], devices=None,
        cache_dir=None):
    try:
        if cache_dir is not False:
            prg, already_built = _create_built_program_from_source_cached(
                    ctx, src, options, devices, cache_dir)
        else:
            prg = _cl._Program(ctx, src)
            already_built = False

    except Exception, e:
        raise
        from pyopencl import Error
        if (isinstance(e, Error)
                and e.code == _cl.status_code.BUILD_PROGRAM_FAILURE):
            # no need to try again
            raise

        from warnings import warn
        from traceback import format_exc
        warn("PyOpenCL compiler caching failed with an exception:\n"
                "[begin exception]\n%s[end exception]"
                % format_exc())

        prg = _cl._Program(ctx, src)
        already_built = False

    if not already_built:
        prg.build(options, devices)

    return prg

# }}}

# vim: foldmethod=marker