1#!/usr/bin/env python3 2# Copyright 2018 The Chromium Authors 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6from __future__ import print_function 7 8import copy 9import json 10import os 11import re 12import subprocess 13import sys 14 15# Add src/testing/ into sys.path for importing common without pylint errors. 16sys.path.append( 17 os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) 18from scripts import common 19 20# A list of filename regexes that are allowed to have static initializers. 21# If something adds a static initializer, revert it. We don't accept regressions 22# in static initializers. 23_LINUX_SI_ALLOWLIST = { 24 'chrome': [ 25 # Only in coverage builds, not production. 26 'InstrProfilingRuntime\\.cpp : ' + 27 '_GLOBAL__sub_I_InstrProfilingRuntime\\.cpp', 28 29 # TODO(crbug.com/973554): Remove. 30 'iostream\\.cpp : _GLOBAL__I_000100', 31 32 # TODO(crbug.com/1445935): Rust stdlib argv handling. 33 # https://github.com/rust-lang/rust/blob/b08148f6a76010ea3d4e91d61245aa7aac59e4b4/library/std/src/sys/unix/args.rs#L107-L127 34 # https://github.com/rust-lang/rust/issues/111921 35 '.* : std::sys::pal::unix::args::imp::ARGV_INIT_ARRAY::init_wrapper', 36 37 # Added by libgcc due to USE_EH_FRAME_REGISTRY. 38 'crtstuff\\.c : frame_dummy', 39 ], 40} 41 42# Mac can use this list when a dsym is available, otherwise it will fall back 43# to checking the count. 44_MAC_SI_FILE_ALLOWLIST = [ 45 'InstrProfilingRuntime\\.cpp', # Only in coverage builds, not in production. 46 'sysinfo\\.cc', # Only in coverage builds, not in production. 47 'iostream\\.cpp', # Used to setup std::cin/cout/cerr. 48 '000100', # Used to setup std::cin/cout/cerr 49] 50 51# Two static initializers are needed on Mac for libc++ to set up 52# std::cin/cout/cerr before main() runs. Only iostream.cpp needs to be counted 53# here. Plus, PartitionAlloc-Everywhere uses one static initializer 54# (InitializeDefaultMallocZoneWithPartitionAlloc) to install a malloc zone. 55FALLBACK_EXPECTED_MAC_SI_COUNT = 3 56 57# Similar to mac, iOS needs the iosstream and PartitionAlloc-Everywhere static 58# initializer (InitializeDefaultMallocZoneWithPartitionAlloc) to install a 59# malloc zone. 60FALLBACK_EXPECTED_IOS_SI_COUNT = 2 61 62# For coverage builds, also allow 'IntrProfilingRuntime.cpp' 63COVERAGE_BUILD_FALLBACK_EXPECTED_MAC_SI_COUNT = 4 64 65 66# Returns true if args contains properties which look like a chromeos-esque 67# builder. 68def check_if_chromeos(args): 69 return 'buildername' in args.properties and \ 70 'chromeos' in args.properties['buildername'] 71 72def get_mod_init_count(src_dir, executable, hermetic_xcode_path): 73 show_mod_init_func = os.path.join(src_dir, 'tools', 'mac', 74 'show_mod_init_func.py') 75 args = [show_mod_init_func] 76 args.append(executable) 77 if os.path.exists(hermetic_xcode_path): 78 args.extend(['--xcode-path', hermetic_xcode_path]) 79 stdout = run_process(args) 80 si_count = len(stdout.splitlines()) - 1 # -1 for executable name 81 return (stdout, si_count) 82 83def run_process(command): 84 p = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True) 85 stdout = p.communicate()[0] 86 if p.returncode != 0: 87 raise Exception( 88 'ERROR from command "%s": %d' % (' '.join(command), p.returncode)) 89 return stdout 90 91def main_ios(src_dir, hermetic_xcode_path): 92 base_names = ('Chromium', 'Chrome') 93 ret = 0 94 for base_name in base_names: 95 app_bundle = base_name + '.app' 96 chromium_executable = os.path.join(app_bundle, base_name) 97 if os.path.exists(chromium_executable): 98 stdout, si_count = get_mod_init_count(src_dir, chromium_executable, 99 hermetic_xcode_path) 100 expected_si_count = FALLBACK_EXPECTED_IOS_SI_COUNT 101 if si_count != expected_si_count: 102 print('Expected %d static initializers in %s, but found %d' % 103 (expected_si_count, chromium_executable, si_count)) 104 print(stdout) 105 ret = 1 106 return ret 107 108 109def main_mac(src_dir, hermetic_xcode_path, allow_coverage_initializer = False): 110 base_names = ('Chromium', 'Google Chrome') 111 ret = 0 112 for base_name in base_names: 113 app_bundle = base_name + '.app' 114 framework_name = base_name + ' Framework' 115 framework_bundle = framework_name + '.framework' 116 chromium_executable = os.path.join(app_bundle, 'Contents', 'MacOS', 117 base_name) 118 chromium_framework_executable = os.path.join(framework_bundle, 119 framework_name) 120 if os.path.exists(chromium_executable): 121 # Count the number static initializers. 122 stdout, si_count = get_mod_init_count(src_dir, 123 chromium_framework_executable, 124 hermetic_xcode_path) 125 min_si_count = allowed_si_count = FALLBACK_EXPECTED_MAC_SI_COUNT 126 if allow_coverage_initializer: 127 allowed_si_count = COVERAGE_BUILD_FALLBACK_EXPECTED_MAC_SI_COUNT 128 if si_count > allowed_si_count or si_count < min_si_count: 129 print('Expected %d static initializers in %s, but found %d' % 130 (allowed_si_count, chromium_framework_executable, 131 si_count)) 132 print(stdout) 133 ret = 1 134 return ret 135 136 137def main_linux(src_dir): 138 ret = 0 139 allowlist = _LINUX_SI_ALLOWLIST 140 for binary_name in allowlist: 141 if not os.path.exists(binary_name): 142 continue 143 144 dump_static_initializers = os.path.join(src_dir, 'tools', 'linux', 145 'dump-static-initializers.py') 146 stdout = run_process([dump_static_initializers, '--json', binary_name]) 147 entries = json.loads(stdout)['entries'] 148 149 for e in entries: 150 # Get the basename and remove line number suffix. 151 basename = os.path.basename(e['filename']).split(':')[0] 152 symbol = e['symbol_name'] 153 descriptor = f"{basename} : {symbol}" 154 if not any(re.match(p, descriptor) for p in allowlist[binary_name]): 155 ret = 1 156 print(('Error: file "%s" is not expected to have static initializers in' 157 ' binary "%s", but found "%s"') % (e['filename'], binary_name, 158 e['symbol_name'])) 159 160 print('\n# Static initializers in %s:' % binary_name) 161 for e in entries: 162 print('# 0x%x %s %s' % (e['address'], e['filename'], e['symbol_name'])) 163 print(e['disassembly']) 164 165 print('Found %d files containing static initializers.' % len(entries)) 166 return ret 167 168 169def main_run(args): 170 if args.build_config_fs != 'Release': 171 raise Exception('Only release builds are supported') 172 173 src_dir = args.paths['checkout'] 174 build_dir = os.path.join(src_dir, 'out', args.build_config_fs) 175 os.chdir(build_dir) 176 177 if sys.platform.startswith('darwin'): 178 # If the checkout uses the hermetic xcode binaries, then otool must be 179 # directly invoked. The indirection via /usr/bin/otool won't work unless 180 # there's an actual system install of Xcode. 181 hermetic_xcode_path = os.path.join(src_dir, 'build', 'mac_files', 182 'xcode_binaries') 183 184 is_ios = 'target_platform' in args.properties and \ 185 'ios' in args.properties['target_platform'] 186 if is_ios: 187 rc = main_ios(src_dir, hermetic_xcode_path) 188 else: 189 rc = main_mac(src_dir, hermetic_xcode_path, 190 allow_coverage_initializer = '--allow-coverage-initializer' in \ 191 args.args) 192 elif sys.platform.startswith('linux'): 193 # TODO(crbug.com/1492865): Delete this assert if it's not seen to fail 194 # anywhere. 195 assert not check_if_chromeos(args), ( 196 "This script is no longer supported for CrOS") 197 rc = main_linux(src_dir) 198 else: 199 sys.stderr.write('Unsupported platform %s.\n' % repr(sys.platform)) 200 return 2 201 202 common.record_local_script_results( 203 'check_static_initializers', args.output, [], rc == 0) 204 205 return rc 206 207 208def main_compile_targets(args): 209 if sys.platform.startswith('darwin'): 210 if 'ios' in args.properties.get('target_platform', []): 211 compile_targets = ['ios/chrome/app:chrome'] 212 else: 213 compile_targets = ['chrome'] 214 elif sys.platform.startswith('linux'): 215 compile_targets = ['chrome'] 216 else: 217 compile_targets = [] 218 219 json.dump(compile_targets, args.output) 220 221 return 0 222 223 224if __name__ == '__main__': 225 funcs = { 226 'run': main_run, 227 'compile_targets': main_compile_targets, 228 } 229 sys.exit(common.run_script(sys.argv[1:], funcs)) 230