1#!/usr/bin/env python
2#
3# Copyright (C) 2019 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18import logging
19import os
20import subprocess
21import sys
22import tempfile
23import zipfile
24
25THIS_DIR = os.path.realpath(os.path.dirname(__file__))
26
27
28def logger():
29    """Returns the module level logger."""
30    return logging.getLogger(__name__)
31
32
33def unchecked_call(cmd, *args, **kwargs):
34    """subprocess.call with logging."""
35    logger().info('unchecked_call: %s', subprocess.list2cmdline(cmd))
36    return subprocess.call(cmd, *args, **kwargs)
37
38
39def check_call(cmd, *args, **kwargs):
40    """subprocess.check_call with logging."""
41    logger().info('check_call: %s', subprocess.list2cmdline(cmd))
42    subprocess.check_call(cmd, *args, **kwargs)
43
44
45def check_output(cmd, *args, **kwargs):
46    """subprocess.check_output with logging."""
47    logger().info('check_output: %s', subprocess.list2cmdline(cmd))
48    return subprocess.run(
49        cmd, *args, **kwargs, check=True, text=True,
50        stdout=subprocess.PIPE).stdout
51
52
53def android_build_top():
54    return os.path.realpath(os.path.join(THIS_DIR, '../../..'))
55
56
57def clang_build():
58    gofilename = os.path.join(android_build_top(), 'build', 'soong', 'cc',
59                              'config', 'global.go')
60    try:
61        with open(gofilename) as gofile:
62            lines = gofile.readlines()
63        versionLine = [l for l in lines if 'ClangDefaultVersion' in l][0]
64        start, end = versionLine.index('"'), versionLine.rindex('"')
65        return versionLine[start + 1:end]
66    except Exception as err:
67        raise RuntimeError(
68            'Extracting Clang version failed with {0}'.format(err))
69
70
71def llvm_profdata():
72    return os.path.join(android_build_top(), 'prebuilts', 'clang', 'host',
73                        'linux-x86', clang_build(), 'bin', 'llvm-profdata')
74
75
76def run_llvm_profdata(inputs, output):
77    check_call([llvm_profdata(), 'merge', '-output=' + output] + inputs)
78
79
80def check_gcertstatus():
81    """Ensure gcert valid for > 1 hour."""
82    try:
83        check_call(['gcertstatus', '-quiet', '-check_remaining=1h'])
84    except subprocess.CalledProcessError:
85        print('Run prodaccess before executing this script.')
86        raise
87