File: config.py

package info (click to toggle)
roc-toolkit 0.4.0%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,700 kB
  • sloc: cpp: 102,987; ansic: 8,959; python: 6,125; sh: 942; makefile: 19; javascript: 9
file content (550 lines) | stat: -rw-r--r-- 16,627 bytes parent folder | download | duplicates (2)
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
import SCons.SConf
import hashlib
import os
import os.path
import re
import textwrap

# Python 2 compatibility.
try:
    from shlex import quote
except:
    from pipes import quote

def _run_prog(context, src, suffix):
    # Workaround for a SCons bug.
    # RunProg uses a global incrementing counter for temporary .c file names. The
    # file name depends on the number of invocations of that function, but not on
    # the file contents. When the user subsequently invokes scons with different
    # options, the sequence of file contents passed to RunProg may vary. However,
    # RunProg may incorrectly use cached results from a previous run saved for
    # different file contents but the same invocation number. To prevent this, we
    # monkey patch its global counter with a hashsum of the file contents.
    # The workaround is needed only for older versions of SCons, where
    # _ac_build_counter was an integer.
    try:
        if type(SCons.SConf._ac_build_counter) is int:
            SCons.SConf._ac_build_counter = int(hashlib.md5(src.encode()).hexdigest(), 16)
    except:
        pass
    return context.RunProg(src, suffix)

def _get_llvm_dir(version):
    def macos_dirs():
        return [
        '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin',
        '/Library/Developer/CommandLineTools/usr/bin',
        ]

    def linux_dirs():
        suffixes = []
        for n in [3, 2, 1]:
            v = '.'.join(map(str, version[:n]))
            suffixes += [
                '-' + v,
                '/' + v,
            ]
        suffixes += ['']
        ret = []
        for s in suffixes:
            ret.append('/usr/lib/llvm{}/bin'.format(s))
        return ret

    for llvmdir in macos_dirs() + linux_dirs():
        if os.path.isdir(llvmdir):
            return llvmdir

# Gets `PKG_CONFIG_PATH` from environment `env`, tries to append `add_prefix`/lib/pkgconfig, and
# returns the result.
# Tolerant to absense of any or both of those two components. If both are absent, returns an
# empty string.
# Doesn't perform quoting.
def _compose_pkg_config_path(env, add_prefix):
    pkg_config_path = env.get('PKG_CONFIG_PATH', '')
    if add_prefix:
        # set user-defined $(add_prefix)/lib/pkgconfig path for pkg-config if needed (lowest
        # priority); otherwise use original PKG_CONFIG_PATH is propagated explicitly
        add_pkg_config_path = os.path.join(add_prefix, 'lib', 'pkgconfig')
        if os.path.isdir(add_pkg_config_path):
            if pkg_config_path:
                pkg_config_path += ':'
            pkg_config_path += add_pkg_config_path
    return pkg_config_path

# Workaround for brew / pkg-config weirdeness
def _fix_brew_libpath(libpath):
    if not '/Cellar/' in libpath:
        return libpath # not in brew (quick check)

    if libpath.endswith('/lib'):
        return libpath # looks good

    brew_prefix = env.GetCommandOutput('brew --prefix')
    if not brew_prefix:
        return libpath # can't help

    if not libpath.startswith(brew_prefix+'/Cellar/'):
        return libpath # not in brew

    if not os.path.isdir(libpath+'/lib'):
        return libpath # can't help

    return libpath+'/lib'

def CheckLibWithHeaderExt(context, libs, headers, language, expr='1', run=True):
    if not isinstance(headers, list):
        headers = [headers]

    if not isinstance(libs, list):
        libs = [libs]

    name = libs[0]
    libs = [l for l in libs if not l in context.env['LIBS']]

    suffix = '.{}'.format(language.lower())
    includes = '\n'.join(['#include <{}>'.format(h) for h in ['stdio.h'] + headers])
    src = textwrap.dedent("""
        {}

        int main() {{
            printf("%d\\n", (int)({}));
            return 0;
        }}
    """).format(includes, expr)

    context.Message("Checking for {} library {} ... ".format(language.upper(), name))

    if run:
        err, out = _run_prog(context, src, suffix)
        if out.strip() == '0':
            err = True
    else:
        err = context.CompileProg(src, suffix)

    if not err:
        context.Result('yes')
        context.env.Append(LIBS=libs)
        return True
    else:
        context.Result('no')
        return False

def CheckProg(context, prog):
    context.Message("Checking for executable {} ... ".format(prog))

    path = context.env.Which(prog)
    if path:
        context.Result(path[0])
        return True
    else:
        context.Result('not found')
        return False

def CheckCanRunProgs(context):
    context.Message("Checking whether we can run compiled executables ... ")

    src = textwrap.dedent("""
        int main() {
            return 0;
        }
    """)

    err, out = _run_prog(context, src, '.c')

    if not err:
        context.Result('yes')
        return True
    else:
        context.Result('no')
        return False

def CheckCompilerOptionSupported(context, opt, language):
    context.Message("Checking whether {} compiler supports {} ... ".format(language.upper(), opt))

    ext = '.' + language.lower()
    src = "int main() { return 0; }"

    orig_env = context.env

    context.env = orig_env.DeepClone()
    context.env.Append(**{language.upper()+'FLAGS': [opt]})

    err = context.CompileProg(src, ext)

    context.env = orig_env

    if not err:
        context.Result('yes')
        return True
    else:
        context.Result('no')
        return False

def FindProgram(context, var, tool):
    if tool:
        context.Message("Searching {} executable ... ".format(var))

        tool_path = context.env.Which(tool)
        if tool_path:
            context.env[var] = tool_path[0]
        else:
            context.env[var] = tool

        context.Result(context.env[var])

    return True

def FindTool(context, var, toolchains, commands,
             compiler_dir=None, prepend_path=[], required=True):
    env = context.env

    context.Message("Searching {} executable ... ".format(var))

    if env.HasArgument(var):
        context.Result(env[var])
        return True

    toolchains = list(toolchains)

    for tc in list(toolchains):
        if '-pc-' in tc:
            toolchains += [tc.replace('-pc-', '-')]

        if 'android' in tc:
            m = re.search(r'((android(eabi)?)\d+)$', tc)
            if m:
                tc = tc.replace(m.group(1), m.group(2))
                toolchains += [tc]
            toolchains += [tc.replace('armv7a', 'arm')]

    if '' in toolchains:
        toolchains.remove('')
        toolchains.append('')

    if compiler_dir:
        toolchains.append(compiler_dir)

    found = False

    for tool_prefix in toolchains:
        for tool_cmd, tool_ver in commands:
            if isinstance(tool_cmd, list):
                tool_name = tool_cmd[0]
                tool_flags = tool_cmd[1:]
            else:
                tool_name = tool_cmd
                tool_flags = []

            if not tool_prefix:
                tool = tool_name
            elif tool_prefix == compiler_dir:
                tool = os.path.join(compiler_dir, tool_name)
            else:
                tool = '{}-{}'.format(tool_prefix, tool_name)

            if tool_ver:
                search_versions = [
                    tool_ver[:3],
                    tool_ver[:2],
                    tool_ver[:1],
                ]

                default_ver = env.ParseCompilerVersion(tool)

                if default_ver and default_ver[:len(tool_ver)] == tool_ver:
                    search_versions += [default_ver]

                for ver in reversed(sorted(set(search_versions))):
                    versioned_tool = '{}-{}'.format(tool, '.'.join(map(str, ver)))
                    if env.Which(versioned_tool, prepend_path):
                        tool = versioned_tool
                        break

            tool_path = env.Which(tool, prepend_path)
            if not tool_path:
                continue

            if tool_ver:
                actual_ver = env.ParseCompilerVersion(tool_path[0])
                if actual_ver:
                    actual_ver = actual_ver[:len(tool_ver)]

                actual_ver_short = actual_ver if len(actual_ver)<=2 else actual_ver[:2]
                tool_ver_short = tool_ver if len(tool_ver)<=2 else tool_ver[:2]

                if actual_ver_short != tool_ver_short:
                    env.Die(
                        ("problem detecting {}: "
                         "found '{}', which reports version {}, but expected version {}").format(
                            var,
                            tool_path[0],
                            '.'.join(map(str, actual_ver)) if actual_ver else '<unknown>',
                            '.'.join(map(str, tool_ver))))

            env[var] = tool_path[0]
            if tool_flags:
                env[var + 'FLAGS'] = ' '.join(tool_flags)

            found = True
            break

        if found:
            break

    if not found:
        if required:
            env.Die("can't find {} executable".format(var))
        else:
            env[var] = None
            context.Result('not found')
            return False

    message = env[var]
    realpath = os.path.realpath(env[var])
    if realpath != env[var]:
        message += ' ({})'.format(realpath)

    context.Result(message)
    return True

def FindClangFormat(context):
    env = context.env

    context.Message("Searching for clang-format ... ")

    if env.HasArgument('CLANG_FORMAT'):
        context.Result(env['CLANG_FORMAT'])
        return True

    min_ver = 10
    max_ver = 99

    def _checkver(exe):
        ver_str = env.ParseToolVersion('{exe} --version'.format(exe=exe))
        try:
            ver = tuple(map(int, ver_str.split('.')))
            return (min_ver, 0, 0) <= ver <= (max_ver, 99, 99)
        except:
            return False

    clang_format = env.Which('clang-format')
    if clang_format and _checkver(clang_format[0]):
        env['CLANG_FORMAT'] = clang_format[0]
        context.Result(env['CLANG_FORMAT'])
        return True

    for ver in range(min_ver,max_ver+1):
        clang_format = env.Which('clang-format-{}'.format(ver))
        if clang_format and _checkver(clang_format[0]):
            env['CLANG_FORMAT'] = clang_format[0]
            context.Result(env['CLANG_FORMAT'])
            return True

        llvmdir = _get_llvm_dir((ver,))
        if llvmdir:
            clang_format = os.path.join(llvmdir, 'clang-format')
            if _checkver(clang_format):
                env['CLANG_FORMAT'] = clang_format
                context.Result(env['CLANG_FORMAT'])
                return True

    env.Die("can't find clang-format >= {} and <= {}".format(min_ver, max_ver))

def FindLLVMDir(context, version):
    context.Message(
        "Searching PATH for llvm {} ... ".format('.'.join(map(str, version))))

    llvmdir = _get_llvm_dir(version)
    if llvmdir:
        context.env['ENV']['PATH'] += ':' + llvmdir
        context.Result(llvmdir)
        return True

    context.Result('not found')
    return True

def FindLibDir(context, prefix, host):
    context.Message("Searching for system library directory ... ")

    def _libdirs(host):
        dirs = ['lib/' + host]
        if 'x86_64-pc-linux-gnu' == host:
            dirs += ['lib/x86_64-linux-gnu']
        if 'x86_64' in host:
            dirs += ['lib64']
        dirs += ['lib']
        return dirs

    for d in _libdirs(host):
        libdir = os.path.join(prefix, d)
        if os.path.isdir(libdir):
            break

    context.env['ROC_SYSTEM_LIBDIR'] = libdir
    context.Result(libdir)
    return True

def FindConfigGuess(context):
    context.Message('Searching CONFIG_GUESS script ... ')

    if context.env.HasArgument('CONFIG_GUESS'):
        context.Result(context.env['CONFIG_GUESS'])
        return True

    prefixes = [
        '/usr',
        '/usr/local',
        '/usr/local/Cellar',
    ]

    dirs = [
        'share/gnuconfig',
        'share/misc',
        'share/automake-*',
        'automake/*/share/automake-*',
        'share/libtool/build-aux',
        'libtool/*/share/libtool/build-aux',
        'lib/php/build',
        'lib/php/*/build',
    ]

    for p in prefixes:
        for d in dirs:
            for f in context.env.Glob(os.path.join(p, d, 'config.guess')):
                path = str(f)
                if not os.access(path, os.X_OK):
                    continue

                context.env['CONFIG_GUESS'] = path
                context.Result(path)

                return True

    context.Result('not found')
    return False

def FindPkgConfig(context, toolchain):
    env = context.env

    context.Message('Searching PKG_CONFIG ... ')

    if env.HasArgument('PKG_CONFIG'):
        context.Result(env['PKG_CONFIG'])
        return True

    # https://autotools.io/pkgconfig/cross-compiling.html
    # http://tiny.cc/lh6upz
    if toolchain:
        pkg_config_cmd = toolchain + '-pkg-config'
        if env.Which(pkg_config_cmd):
            env['PKG_CONFIG'] = env.Which(pkg_config_cmd)[0]
            context.Result(env['PKG_CONFIG'])
            return True

        if 'PKG_CONFIG_PATH' in os.environ \
            or 'PKG_CONFIG_LIBDIR' in os.environ \
            or 'PKG_CONFIG_SYSROOT_DIR' in os.environ:
            if env.Which('pkg-config'):
                env['PKG_CONFIG'] = env.Which('pkg-config')[0]
                context.Result(env['PKG_CONFIG'])
                return True

        context.Result('not found')
        return False

    if env.Which('pkg-config'):
        env['PKG_CONFIG'] = env.Which('pkg-config')[0]
        context.Result(env['PKG_CONFIG'])
        return True

    context.Result('not found')
    return False

def FindPkgConfigPath(context, prefix):
    if not prefix.endswith(os.sep):
        prefix += os.sep

    env = context.env

    context.Message("Searching PKG_CONFIG_PATH ...")

    if env.HasArgument('PKG_CONFIG_PATH'):
        context.Result(env['PKG_CONFIG_PATH'])
        return True

    pkg_config = env.get('PKG_CONFIG', None)
    if pkg_config:
        pkg_config_path = env.GetCommandOutput(
            '{pkg_config_cmd} --variable pc_path pkg-config'.format(
                pkg_config_cmd=quote(pkg_config)))
        if pkg_config_path:
            env['PKG_CONFIG_PATH'] = pkg_config_path
            context.Result(env['PKG_CONFIG_PATH'])
            return True

    # https://linux.die.net/man/1/pkg-config the default is libdir/pkgconfig
    env['PKG_CONFIG_PATH'] = os.path.join(env['ROC_SYSTEM_LIBDIR'], 'pkgconfig')
    context.Result(env['PKG_CONFIG_PATH'])
    return True

def AddPkgConfigDependency(context, package, flags,
                           add_prefix=None, exclude_from_pc=False, exclude_libs=[]):
    context.Message("Searching pkg-config package {} ...".format(package))

    env = context.env

    pkg_config = env.get('PKG_CONFIG', None)
    if not pkg_config:
        context.Result('pkg-config not available')
        return False

    cmd = []
    pkg_config_path = _compose_pkg_config_path(env, add_prefix)
    if pkg_config_path:
        cmd = ['env', 'PKG_CONFIG_PATH={}'.format(pkg_config_path)]

    cmd += [pkg_config, package, '--silence-errors'] + flags.split()
    try:
        old_libs = env['LIBS'][:]
        old_dirs = env['LIBPATH'][:]

        env.ParseConfig(cmd)

        new_libs = env['LIBS'][:]
        new_dirs = env['LIBPATH'][:]

        for lib in exclude_libs:
            if lib not in old_libs and lib in new_libs:
                env['LIBS'].remove(lib)

        for n, libpath in enumerate(new_dirs):
            if not libpath in old_dirs:
                env['LIBPATH'][n] = _fix_brew_libpath(libpath)

        if not exclude_from_pc:
            if '_DEPS_PCFILES' not in env.Dictionary():
                env['_DEPS_PCFILES'] = []
            env.AppendUnique(_DEPS_PCFILES=[package])
    except:
        context.Result('not found')
        return False

    context.Result('yes')
    return True

def init(env):
    env.CustomTests = {
        'CheckLibWithHeaderExt': CheckLibWithHeaderExt,
        'CheckProg': CheckProg,
        'CheckCanRunProgs': CheckCanRunProgs,
        'CheckCompilerOptionSupported': CheckCompilerOptionSupported,
        'FindProgram': FindProgram,
        'FindTool': FindTool,
        'FindClangFormat': FindClangFormat,
        'FindLLVMDir': FindLLVMDir,
        'FindLibDir': FindLibDir,
        'FindConfigGuess': FindConfigGuess,
        'FindPkgConfig': FindPkgConfig,
        'FindPkgConfigPath': FindPkgConfigPath,
        'AddPkgConfigDependency': AddPkgConfigDependency,
    }