1#! /usr/bin/env python3 2assert __name__ == '__main__' 3 4''' 5To update ANGLE in Gecko, use Windows with git-bash, and setup depot_tools, python2, and 6python3. Because depot_tools expects `python` to be `python2` (shame!), python2 must come 7before python3 in your path. 8 9Upstream: https://chromium.googlesource.com/angle/angle 10 11Our repo: https://github.com/mozilla/angle 12It has branches like 'firefox-60' which is the branch we use for pulling into 13Gecko with this script. 14 15This script leaves a record of the merge-base and cherry-picks that we pull into 16Gecko. (gfx/angle/cherries.log) 17 18ANGLE<->Chrome version mappings are here: https://omahaproxy.appspot.com/ 19An easy choice is to grab Chrome's Beta's ANGLE branch. 20 21## Usage 22 23Prepare your env: 24 25~~~ 26export PATH="$PATH:/path/to/depot_tools" 27~~~ 28 29If this is a new repo, don't forget: 30 31~~~ 32# In the angle repo: 33./scripts/bootstrap.py 34gclient sync 35~~~ 36 37Update: (in the angle repo) 38 39~~~ 40# In the angle repo: 41/path/to/gecko/gfx/angle/update-angle.py origin/chromium/XXXX 42git push moz # Push the firefox-XX branch to github.com/mozilla/angle 43~~~~ 44 45''' 46 47import json 48import os 49import pathlib 50import re 51import shutil 52import subprocess 53import sys 54from typing import * # mypy annotations 55 56REPO_DIR = pathlib.Path.cwd() 57 58GN_ENV = dict(os.environ) 59# We need to set DEPOT_TOOLS_WIN_TOOLCHAIN to 0 for non-Googlers, but otherwise 60# leave it unset since vs_toolchain.py assumes that the user is a Googler with 61# the Visual Studio files in depot_tools if DEPOT_TOOLS_WIN_TOOLCHAIN is not 62# explicitly set to 0. 63vs_found = False 64for directory in os.environ['PATH'].split(os.pathsep): 65 vs_dir = os.path.join(directory, 'win_toolchain', 'vs_files') 66 if os.path.exists(vs_dir): 67 vs_found = True 68 break 69if not vs_found: 70 GN_ENV['DEPOT_TOOLS_WIN_TOOLCHAIN'] = '0' 71 72if len(sys.argv) < 3: 73 sys.exit('Usage: export_targets.py OUT_DIR ROOTS...') 74 75(OUT_DIR, *ROOTS) = sys.argv[1:] 76for x in ROOTS: 77 assert x.startswith('//:') 78 79# ------------------------------------------------------------------------------ 80 81def run_checked(*args, **kwargs): 82 print(' ', args, file=sys.stderr) 83 sys.stderr.flush() 84 return subprocess.run(args, check=True, **kwargs) 85 86 87def sortedi(x): 88 return sorted(x, key=str.lower) 89 90 91def dag_traverse(root_keys: Sequence[str], pre_recurse_func: Callable[[str], list]): 92 visited_keys: Set[str] = set() 93 94 def recurse(key): 95 if key in visited_keys: 96 return 97 visited_keys.add(key) 98 99 t = pre_recurse_func(key) 100 try: 101 (next_keys, post_recurse_func) = t 102 except ValueError: 103 (next_keys,) = t 104 post_recurse_func = None 105 106 for x in next_keys: 107 recurse(x) 108 109 if post_recurse_func: 110 post_recurse_func(key) 111 return 112 113 for x in root_keys: 114 recurse(x) 115 return 116 117# ------------------------------------------------------------------------------ 118 119print('Importing graph', file=sys.stderr) 120 121try: 122 p = run_checked('gn', 'desc', '--format=json', str(OUT_DIR), '*', stdout=subprocess.PIPE, 123 env=GN_ENV, shell=(True if sys.platform == 'win32' else False)) 124except subprocess.CalledProcessError: 125 sys.stderr.buffer.write(b'"gn desc" failed. Is depot_tools in your PATH?\n') 126 exit(1) 127 128# - 129 130print('\nProcessing graph', file=sys.stderr) 131descs = json.loads(p.stdout.decode()) 132 133# Ready to traverse 134# ------------------------------------------------------------------------------ 135 136LIBRARY_TYPES = ('shared_library', 'static_library') 137 138def flattened_target(target_name: str, descs: dict, stop_at_lib: bool =True) -> dict: 139 flattened = dict(descs[target_name]) 140 141 EXPECTED_TYPES = LIBRARY_TYPES + ('source_set', 'group', 'action') 142 143 def pre(k): 144 dep = descs[k] 145 146 dep_type = dep['type'] 147 deps = dep['deps'] 148 if stop_at_lib and dep_type in LIBRARY_TYPES: 149 return ((),) 150 151 if dep_type == 'copy': 152 assert not deps, (target_name, dep['deps']) 153 else: 154 assert dep_type in EXPECTED_TYPES, (k, dep_type) 155 for (k,v) in dep.items(): 156 if type(v) in (list, tuple, set): 157 # This is a workaround for 158 # https://bugs.chromium.org/p/gn/issues/detail?id=196, where 159 # the value of "public" can be a string instead of a list. 160 existing = flattened.get(k, []) 161 if isinstance(existing, str): 162 existing = [existing] 163 flattened[k] = sortedi(set(existing + v)) 164 else: 165 #flattened.setdefault(k, v) 166 pass 167 return (deps,) 168 169 dag_traverse(descs[target_name]['deps'], pre) 170 return flattened 171 172# ------------------------------------------------------------------------------ 173# Check that includes are valid. (gn's version of this check doesn't seem to work!) 174 175INCLUDE_REGEX = re.compile(b'(?:^|\\n) *# *include +([<"])([^>"]+)[>"]') 176assert INCLUDE_REGEX.match(b'#include "foo"') 177assert INCLUDE_REGEX.match(b'\n#include "foo"') 178 179# Most of these are ignored because this script does not currently handle 180# #includes in #ifdefs properly, so they will erroneously be marked as being 181# included, but not part of the source list. 182IGNORED_INCLUDES = { 183 b'absl/container/flat_hash_map.h', 184 b'compiler/translator/TranslatorESSL.h', 185 b'compiler/translator/TranslatorGLSL.h', 186 b'compiler/translator/TranslatorHLSL.h', 187 b'compiler/translator/TranslatorMetal.h', 188 b'compiler/translator/TranslatorMetalDirect.h', 189 b'compiler/translator/TranslatorVulkan.h', 190 b'contrib/optimizations/slide_hash_neon.h', 191 b'dirent_on_windows.h', 192 b'dlopen_fuchsia.h', 193 b'kernel/image.h', 194 b'libANGLE/renderer/d3d/d3d11/winrt/NativeWindow11WinRT.h', 195 b'libANGLE/renderer/d3d/DeviceD3D.h', 196 b'libANGLE/renderer/d3d/DisplayD3D.h', 197 b'libANGLE/renderer/d3d/RenderTargetD3D.h', 198 b'libANGLE/renderer/gl/apple/DisplayApple_api.h', 199 b'libANGLE/renderer/gl/cgl/DisplayCGL.h', 200 b'libANGLE/renderer/gl/eagl/DisplayEAGL.h', 201 b'libANGLE/renderer/gl/egl/android/DisplayAndroid.h', 202 b'libANGLE/renderer/gl/egl/DisplayEGL.h', 203 b'libANGLE/renderer/gl/egl/gbm/DisplayGbm.h', 204 b'libANGLE/renderer/gl/glx/DisplayGLX.h', 205 b'libANGLE/renderer/gl/wgl/DisplayWGL.h', 206 b'libANGLE/renderer/metal/DisplayMtl_api.h', 207 b'libANGLE/renderer/null/DisplayNULL.h', 208 b'libANGLE/renderer/vulkan/android/AHBFunctions.h', 209 b'libANGLE/renderer/vulkan/android/DisplayVkAndroid.h', 210 b'libANGLE/renderer/vulkan/DisplayVk_api.h', 211 b'libANGLE/renderer/vulkan/fuchsia/DisplayVkFuchsia.h', 212 b'libANGLE/renderer/vulkan/ggp/DisplayVkGGP.h', 213 b'libANGLE/renderer/vulkan/mac/DisplayVkMac.h', 214 b'libANGLE/renderer/vulkan/win32/DisplayVkWin32.h', 215 b'libANGLE/renderer/vulkan/xcb/DisplayVkXcb.h', 216 b'loader_cmake_config.h', 217 b'optick.h', 218 b'spirv-tools/libspirv.h', 219 b'third_party/volk/volk.h', 220 b'vk_loader_extensions.c', 221 b'vk_snippets.h', 222 b'vulkan_android.h', 223 b'vulkan_beta.h', 224 b'vulkan_directfb.h', 225 b'vulkan_fuchsia.h', 226 b'vulkan_ggp.h', 227 b'vulkan_ios.h', 228 b'vulkan_macos.h', 229 b'vulkan_metal.h', 230 b'vulkan_vi.h', 231 b'vulkan_wayland.h', 232 b'vulkan_win32.h', 233 b'vulkan_xcb.h', 234 b'vulkan_xlib.h', 235 b'vulkan_xlib_xrandr.h', 236# rapidjson adds these include stubs into their documentation 237# comments. Since the script doesn't skip comments they are 238# erroneously marked as valid includes 239 b'rapidjson/...', 240 # Validation layers support building with robin hood hashing, but we are not enabling that 241 # See http://anglebug.com/5791 242 b'robin_hood.h', 243} 244 245IGNORED_INCLUDE_PREFIXES = { 246 b'android', 247 b'Carbon', 248 b'CoreFoundation', 249 b'CoreServices', 250 b'IOSurface', 251 b'mach', 252 b'mach-o', 253 b'OpenGL', 254 b'pci', 255 b'sys', 256 b'wrl', 257 b'X11', 258} 259 260IGNORED_DIRECTORIES = { 261 '//buildtools/third_party/libc++', 262 '//third_party/abseil-cpp', 263 '//third_party/SwiftShader', 264} 265 266def has_all_includes(target_name: str, descs: dict) -> bool: 267 for ignored_directory in IGNORED_DIRECTORIES: 268 if target_name.startswith(ignored_directory): 269 return True 270 271 flat = flattened_target(target_name, descs, stop_at_lib=False) 272 acceptable_sources = flat.get('sources', []) + flat.get('outputs', []) 273 acceptable_sources = {x.rsplit('/', 1)[-1].encode() for x in acceptable_sources} 274 275 ret = True 276 desc = descs[target_name] 277 for cur_file in desc.get('sources', []): 278 assert cur_file.startswith('/'), cur_file 279 if not cur_file.startswith('//'): 280 continue 281 cur_file = pathlib.Path(cur_file[2:]) 282 text = cur_file.read_bytes() 283 for m in INCLUDE_REGEX.finditer(text): 284 if m.group(1) == b'<': 285 continue 286 include = m.group(2) 287 if include in IGNORED_INCLUDES: 288 continue 289 try: 290 (prefix, _) = include.split(b'/', 1) 291 if prefix in IGNORED_INCLUDE_PREFIXES: 292 continue 293 except ValueError: 294 pass 295 296 include_file = include.rsplit(b'/', 1)[-1] 297 if include_file not in acceptable_sources: 298 #print(' acceptable_sources:') 299 #for x in sorted(acceptable_sources): 300 # print(' ', x) 301 print('Warning in {}: {}: Invalid include: {}'.format(target_name, cur_file, include), file=sys.stderr) 302 ret = False 303 #print('Looks valid:', m.group()) 304 continue 305 306 return ret 307 308# - 309# Gather real targets: 310 311def gather_libraries(roots: Sequence[str], descs: dict) -> Set[str]: 312 libraries = set() 313 def fn(target_name): 314 cur = descs[target_name] 315 print(' ' + cur['type'], target_name, file=sys.stderr) 316 assert has_all_includes(target_name, descs), target_name 317 318 if cur['type'] in ('shared_library', 'static_library'): 319 libraries.add(target_name) 320 return (cur['deps'], ) 321 322 dag_traverse(roots, fn) 323 return libraries 324 325# - 326 327libraries = gather_libraries(ROOTS, descs) 328print(f'\n{len(libraries)} libraries:', file=sys.stderr) 329for k in libraries: 330 print(f' {k}', file=sys.stderr) 331print('\nstdout begins:', file=sys.stderr) 332sys.stderr.flush() 333 334# ------------------------------------------------------------------------------ 335# Output 336 337out = {k: flattened_target(k, descs) for k in libraries} 338 339for (k,desc) in out.items(): 340 dep_libs: Set[str] = set() 341 for dep_name in set(desc['deps']): 342 dep = descs[dep_name] 343 if dep['type'] in LIBRARY_TYPES: 344 dep_libs.add(dep_name) 345 desc['dep_libs'] = sortedi(dep_libs) 346 347json.dump(out, sys.stdout, indent=' ') 348exit(0) 349