Debian Codegraph @

third_party/dawn/cmake_utils.py

raw
1 #!/usr/bin/env python3
2 #
3 # Copyright 2025 Google LLC
4 #
5 # Use of this source code is governed by a BSD-style license that can be
6 # found in the LICENSE file.
7 #
8 import argparse
9 import hashlib
10 import os
11 import shutil
12 import subprocess
13 import sys
14
15
16 def add_common_cmake_args(parser):
17 """Adds common arguments used for building with CMake."""
18 print(f"Running with Python executable: {sys.executable}")
19
20 parser.add_argument("--cc", required=True, help="Path to the C compiler.")
21 parser.add_argument("--cxx", required=True, help="Path to the C++ compiler.")
22 parser.add_argument(
23 "--cxx_flags",
24 default=[],
25 action="append",
26 help="C++ compiler flags. Can be specified multiple times.")
27 parser.add_argument(
28 "--ld_flags",
29 default=[],
30 action="append",
31 help="Linker flags. Can be specified multiple times.")
32 parser.add_argument(
33 "--output_path", required=True, help="Path to the output library.")
34 parser.add_argument(
35 "--depfile_path", required=True, help="Path to the depfile to generate.")
36 parser.add_argument(
37 "--target_os", required=True, help="Target OS for cross-compilation.")
38 parser.add_argument(
39 "--target_cpu", required=True, help="Target CPU for cross-compilation.")
40 parser.add_argument(
41 "--win_sdk", default="", help="Path to the Windows SDK.")
42 parser.add_argument(
43 "--win_sdk_version", default="", help="Version of the Windows SDK.")
44 parser.add_argument(
45 "--win_vc", default="", help="Path to Visual C++.")
46 parser.add_argument(
47 "--win_toolchain_version",
48 default="",
49 help="Version of the MSVC toolchain.")
50 parser.add_argument(
51 "--build_type", default="Release", help="CMake build type.")
52 parser.add_argument(
53 "--build_dir",
54 required=True,
55 help="A short name for the build directory.")
56 parser.add_argument("--is_clang", action=argparse.BooleanOptionalAction)
57 parser.add_argument(
58 "--enable_rtti", action=argparse.BooleanOptionalAction, help="Enable RTTI.")
59
60 def add_next_batch_to_command(base_cmd, workset):
61 if sys.platform != 'win32':
62 batch = list(workset)
63 return base_cmd + batch, batch
64 # Windows has a limit of about 8100 characters on command line commands.
65 # Thus we batch our commands to fit under this. 100 is usually short enough
66 # but with fluctuations on the order returned by ninja and set(), this can
67 # still sometimes be too long, so we ensure we don't go over the limit.
68 BATCH_SIZE = 100
69 batch = list(workset)[:BATCH_SIZE]
70 cmd = base_cmd + batch
71
72 while len(' '.join(cmd)) > 8100:
73 assert(len(batch) > 1)
74 batch.pop()
75 cmd = base_cmd + batch
76
77 return cmd, batch
78
79 def discover_dependencies(build_dir, targets):
80 """Runs ninja -tinputs recursively to discover all targets, then uses
81 ninja -tdeps to get all source files and object files for those targets.
82 Returns a tuple of (list of source files, list of object files)."""
83 # The worklist contains ninja targets we need to find the inputs for.
84 worklist = set(targets)
85 # We keep track of all ninja targets we've ever seen to avoid cycles and
86 # redundant processing.
87 seen_targets = set(targets)
88
89 source_files = set()
90
91 ninja = shutil.which("ninja");
92 if not ninja:
93 print("Error: ninja not found in PATH.")
94 sys.exit(1)
95
96 while len(worklist) > 0:
97 cmd, current_batch = add_next_batch_to_command([ninja, "-C", build_dir, "-tinputs"],
98 worklist)
99 worklist = worklist.difference(current_batch)
100
101 inputs = subprocess.check_output(cmd).decode("utf-8").splitlines()
102 # inputs looks like:
103 # /home/user/skia/third_party/externals/dawn/src/tint/utils/text/styled_text_theme.cc
104 # /home/user/skia/third_party/externals/dawn/src/tint/utils/text/unicode.cc
105 # cmake_object_order_depends_target_tint_api_common
106 # cmake_object_order_depends_target_tint_lang_core
107 # src/tint/CMakeFiles/tint_api_common.dir/api/common/vertex_pulling_config.cc.o
108 # src/tint/CMakeFiles/tint_lang_core.dir/lang/core/binary_op.cc.o
109 # src/tint/libtint_api_common.a
110 # src/tint/libtint_lang_core.a
111 # Some of these are files (which we can add to the source file list), some are more targets,
112 # which we should recursively get targets for to make sure we have the whole dependency graph.
113 for line in inputs:
114 line = line.strip()
115 if os.path.isabs(line):
116 # Absolute paths are source files.
117 source_files.add(line)
118 continue
119 if line not in seen_targets:
120 worklist.add(line)
121 seen_targets.add(line)
122
123 object_files = []
124 for target in seen_targets:
125 if target.endswith(".o") or target.endswith(".obj"):
126 object_files.append(target)
127 object_files.sort()
128
129 # Now that we have all the targets and some of the source files, get the dependencies for them.
130 abs_build_dir = os.path.abspath(build_dir)
131
132 worklist = set(seen_targets)
133 while len(worklist) > 0:
134 cmd, current_batch = add_next_batch_to_command([ninja, "-C", build_dir, "-tdeps"],
135 worklist)
136 worklist = worklist.difference(current_batch)
137
138 output = subprocess.check_output(cmd).decode("utf-8").splitlines()
139 # When a target has deps, which are read from the .d files generated from the "-dkeepdepfile
140 # option earlier, the ninja command outputs something like this:
141 # third_party/spirv-tools/source/opt/CMakeFiles/SPIRV-Tools-opt.dir/eliminate_dead_functions_util.cpp.o: #deps 408, deps mtime 1755004530688332629 (VALID)
142 # /home/user/skia/third_party/externals/dawn/third_party/spirv-tools/src/source/opt/eliminate_dead_functions_util.cpp
143 # /usr/include/stdc-predef.h
144 # /home/user/skia/third_party/externals/dawn/third_party/spirv-tools/src/source/opt/eliminate_dead_functions_util.h
145 # /home/user/skia/third_party/externals/dawn/third_party/spirv-tools/src/source/opt/ir_context.h
146 # /usr/include/c++/14/algorithm
147 # These can sometimes be relative files (on Windows) with the base path being the build_dir
148 # src/tint/CMakeFiles/tint_lang_wgsl_sem.dir/lang/wgsl/sem/variable.cc.obj: #deps 300, deps mtime 7816349331123163 (VALID)
149 # ../../../../../cipd/clang_win/lib/clang/18/include/x86gprintrin.h
150 # ../../../../../cipd/win_toolchain/VC/Tools/MSVC/14.39.33519/include/__msvc_bit_utils.hpp
151 # ../../../../../cipd/win_toolchain/VC/Tools/MSVC/14.39.33519/include/cctype
152 # ../../../../../cipd/win_toolchain/win_sdk/Include/10.0.22621.0/ucrt/wchar.h
153 # ../../../third_party/externals/dawn/src/tint/api/common/binding_point.h
154 # ../../../third_party/externals/dawn/src/tint/lang/core/constant/clone_context.h
155 # If there's not a match, it's a simple message like:
156 # src/tint/libtint_utils_text_generator.a: deps not found
157 # We want to aggregate all the indented files
158 for line in output:
159 if not line.startswith(" ") or "deps not found" in line:
160 continue
161 line = line.strip()
162 if os.path.isabs(line):
163 source_files.add(line)
164 else:
165 dep = os.path.normpath(os.path.join(abs_build_dir, line))
166 source_files.add(dep)
167
168 result = list(source_files)
169 result.sort()
170 return result, object_files
171
172
173 def write_depfile(output_path, depfile_path, dependencies):
174 """Generates a .d file that lists all discovered source files as
175 dependencies for the given output library."""
176 os.makedirs(os.path.dirname(depfile_path), exist_ok=True)
177 with open(depfile_path, "w") as f:
178 f.write(f"{output_path}:")
179 # Make sure to use forward slashes for paths in the depfile, even on
180 # Windows, for consistency.
181 for dep in dependencies:
182 f.write(" \\\n" + dep.replace("\\", "/"))
183 f.write("\n")
184
185
186 def quote_if_needed(path):
187 """Adds quotes to a path if it contains spaces."""
188 if " " in path:
189 return f'"{path}"'
190 return path
191
192
193 def copy_if_changed(src, dest):
194 """Copies the file from src to dest if dest doesn't exist or if the
195 contents of src and dest are different."""
196 if os.path.exists(dest):
197 src_hash = hashlib.sha256(open(src, "rb").read()).hexdigest()
198 dest_hash = hashlib.sha256(open(dest, "rb").read()).hexdigest()
199 if src_hash == dest_hash:
200 # The files are identical, no need to copy.
201 return
202
203 # Either the destination does not exist or it is different.
204 shutil.copyfile(src, dest)
205 os.chmod(dest, 0o755)
206
207
208 def get_cmake_os_cpu(os, cpu):
209 # https://stackoverflow.com/a/70498851
210 os = os.lower().strip()
211 cpu = cpu.lower().strip()
212 if os == "android":
213 target_cpu_map = {
214 "arm": "armeabi-v7a",
215 "arm64": "arm64-v8a",
216 "x64": "x86_64",
217 "x86": "x86",
218 }
219 return "Android", target_cpu_map[cpu]
220
221 if os == "linux":
222 target_cpu_map = {
223 "arm": "arm",
224 "arm64": "aarch64",
225 "x64": "x86_64",
226 "x86": "i686",
227 }
228 return "Linux", target_cpu_map[cpu]
229
230 if os == "mac":
231 target_cpu_map = {
232 "arm64": "arm64",
233 "x64": "x86_64",
234 }
235 return "Darwin", target_cpu_map[cpu]
236
237 if os == "win":
238 target_cpu_map = {
239 "arm64": "ARM64",
240 "x64": "AMD64",
241 }
242 return "Windows", target_cpu_map[cpu]
243
244 if os == "wasm":
245 return "wasm", "wasm"
246
247 print("Unsupported OS")
248 sys.exit(1)
249
250
251 def get_windows_settings(args):
252 """The Windows toolchain requires a lot of setup for cmake to use it.
253 This encapsulates all that setup.
254 """
255
256 assert(args.win_vc)
257 assert(args.win_sdk)
258 assert(args.win_sdk_version)
259
260 win_cfgs, win_cxx, win_ld = [], [], []
261
262 # Set the Windows SDK version for CMake.
263 win_cfgs.append(
264 f"-DCMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION={args.win_sdk_version}")
265
266 # Explicitly tell CMake where to find the Resource Compiler, Manifest Tool, and Archiver.
267 rc_exe_path = os.path.join(args.win_sdk, "bin", args.win_sdk_version,
268 args.target_cpu, "rc.exe")
269 win_cfgs.append(f"-DCMAKE_RC_COMPILER={rc_exe_path.replace(os.sep, '/')}")
270 mt_exe_path = os.path.join(args.win_sdk, "bin", args.win_sdk_version,
271 args.target_cpu, "mt.exe")
272 win_cfgs.append(f"-DCMAKE_MT={mt_exe_path.replace(os.sep, '/')}")
273
274 ar_exe_path = os.path.join(args.win_vc, "Tools", "MSVC",
275 args.win_toolchain_version, "bin", "Hostx64",
276 args.target_cpu, "lib.exe")
277 win_cfgs.append(f"-DCMAKE_AR={ar_exe_path.replace(os.sep, '/')}")
278
279 # On Windows, we need to explicitly tell clang where to find the toolchain
280 # headers and libraries.
281 um_lib_path = os.path.join(args.win_sdk, "Lib", args.win_sdk_version, "um", args.target_cpu)
282 ucrt_lib_path = os.path.join(args.win_sdk, "Lib", args.win_sdk_version, "ucrt", args.target_cpu)
283 msvc_lib_path = os.path.join(args.win_vc, "Tools", "MSVC", args.win_toolchain_version, "lib", args.target_cpu)
284
285 win_ld += [
286 f"/LIBPATH:{quote_if_needed(um_lib_path.replace(os.sep, '/'))}",
287 f"/LIBPATH:{quote_if_needed(ucrt_lib_path.replace(os.sep, '/'))}",
288 f"/LIBPATH:{quote_if_needed(msvc_lib_path.replace(os.sep, '/'))}",
289 ]
290
291 # Skia builds with exceptions and RTTI disabled so we must also build Dawn that way.
292 win_cxx += [
293 "-D_HAS_EXCEPTIONS=0",
294 "/GR-",
295 "/w", # Dawn's warnings are noisy
296 ]
297
298 # Skia uses a hermetic toolchain, so we need to tell clang where to
299 # find the MSVC headers and libraries. If we pass the MSVC style flags (/I)
300 # to clang, then abseil fails to compile with errors about using a
301 # reinterpret_cast in a static_assert.
302 if args.is_clang:
303 win_cxx += [
304 "-imsvc",
305 quote_if_needed(os.path.join(args.win_vc, "Tools", "MSVC", args.win_toolchain_version, "include")),
306 "-imsvc",
307 quote_if_needed(os.path.join(args.win_sdk, "Include", args.win_sdk_version, "ucrt")),
308 "-imsvc",
309 quote_if_needed(os.path.join(args.win_sdk, "Include", args.win_sdk_version, "shared")),
310 "-imsvc",
311 quote_if_needed(os.path.join(args.win_sdk, "Include", args.win_sdk_version, "um")),
312 "-imsvc",
313 quote_if_needed(os.path.join(args.win_sdk, "Include", args.win_sdk_version, "winrt")),
314 ]
315 else:
316 win_cxx += [
317 "/I" + quote_if_needed(os.path.join(args.win_vc, "Tools", "MSVC", args.win_toolchain_version, "include")),
318 "/I" + quote_if_needed(os.path.join(args.win_sdk, "Include", args.win_sdk_version, "ucrt")),
319 "/I" + quote_if_needed(os.path.join(args.win_sdk, "Include", args.win_sdk_version, "shared")),
320 "/I" + quote_if_needed(os.path.join(args.win_sdk, "Include", args.win_sdk_version, "um")),
321 "/I" + quote_if_needed(os.path.join(args.win_sdk, "Include", args.win_sdk_version, "winrt")),
322 ]
323
324 # We want to build Dawn (and its dependencies) with /MT so we can statically
325 # link it into Skia.
326 win_cfgs.append("-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded")
327 win_cfgs.append("-DABSL_MSVC_STATIC_RUNTIME=ON")
328
329 return win_cfgs, win_cxx, win_ld
330
331
332 def combine_into_library(args, output_path, build_dir, target_os, object_files):
333 """Combine all the object files into a single .a/.lib file so it's easier to
334 give this to GN."""
335
336 # Delete generated library if it exists already (otherwise ar sometimes chokes)
337 lib_name = os.path.basename(output_path)
338 gen_library_path = os.path.join(build_dir, lib_name)
339 if os.path.exists(gen_library_path):
340 os.remove(gen_library_path)
341
342 assert len(object_files) > 0
343 # Use ar/lib to join all the object files that comprise the necessary
344 # libraries and any transitive dependencies into one .a file.
345 if target_os == "Windows":
346 # On Windows, we use lld-link.exe for clang, and lib.exe for MSVC.
347 if args.is_clang:
348 linker_exe = os.path.join(os.path.dirname(args.cc), "lld-link.exe")
349 else:
350 # We can't just use ar.exe because it is not shipped with MSVC.
351 # We must use lib.exe, which has a different command line.
352 linker_exe = os.path.join(args.win_vc, "Tools", "MSVC",
353 args.win_toolchain_version, "bin", "Hostx64",
354 args.target_cpu, "lib.exe")
355 # The command line can be too long, so we use a response file.
356 response_file_name = "objects.rsp"
357 response_file_path = os.path.join(build_dir, response_file_name)
358 with open(response_file_path, "w") as f:
359 for obj in object_files:
360 f.write(f'"{obj}"\n')
361 combine_obj_cmd = [
362 linker_exe, "/LIB", f"/OUT:{lib_name}", f"@{response_file_name}"
363 ]
364 else:
365 combine_obj_cmd = ["ar", "rcs", lib_name] + object_files
366 subprocess.run(combine_obj_cmd, cwd=build_dir, check=True)
367
368 copy_if_changed(gen_library_path, os.path.join(os.getcwd(), output_path))
369
370
371
372 def get_third_party_locations():
373 """Return CMake configure arguments to point to or disable third_party deps"""
374 def verify_and_get(subpath):
375 third_party_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "externals")
376 third_party_dir = os.path.abspath(third_party_dir)
377 path = os.path.join(third_party_dir, subpath)
378 if not os.path.exists(path):
379 print(f"Third party path {path} not found - did you sync your DEPS?")
380 sys.exit(1)
381 return path
382
383 return [
384 # Actually downloading the 3p repos is handled by DEPS / tools/git-sync-deps
385 "-DDAWN_FETCH_DEPENDENCIES=OFF",
386 # Necessary 3p deps
387 f"-DDAWN_ABSEIL_DIR={verify_and_get('abseil-cpp')}",
388 f"-DDAWN_EGL_REGISTRY_DIR={verify_and_get('egl-registry')}",
389 f"-DDAWN_GLSLANG_DIR={verify_and_get('glslang')}",
390 f"-DDAWN_JINJA2_DIR={verify_and_get('jinja2')}",
391 f"-DDAWN_MARKUPSAFE_DIR={verify_and_get('markupsafe')}",
392 f"-DDAWN_OPENGL_REGISTRY_DIR={verify_and_get('opengl-registry')}",
393 f"-DDAWN_SPIRV_HEADERS_DIR={verify_and_get('spirv-headers')}",
394 f"-DDAWN_SPIRV_TOOLS_DIR={verify_and_get('spirv-tools')}",
395 f"-DDAWN_VULKAN_HEADERS_DIR={verify_and_get('vulkan-headers')}",
396 f"-DDAWN_VULKAN_UTILITY_LIBRARIES_DIR={verify_and_get('vulkan-utility-libraries')}",
397 f"-DDAWN_WEBGPU_HEADERS_DIR={verify_and_get('webgpu-headers')}",
398 f"-DDAWN_SWIFTSHADER_DIR={verify_and_get('swiftshader')}",
399
400 # Disable unnecessary deps
401 "-DDAWN_BUILD_BENCHMARKS=OFF",
402 "-DDAWN_BUILD_PROTOBUF=OFF",
403 "-DDAWN_BUILD_SAMPLES=OFF",
404 "-DDAWN_BUILD_TESTS=OFF",
405 "-DDAWN_USE_GLFW=OFF",
406 "-DTINT_BUILD_BENCHMARKS=OFF",
407 "-DTINT_BUILD_IR_BINARY=OFF",
408 "-DTINT_BUILD_TESTS=OFF",
409 "-DDAWN_USE_X11=OFF",
410
411 # Explicitly mark third_party deps as not here to make debugging easier
412 "-DDAWN_EMDAWNWEBGPU_DIR=NOT_SYNCED_BY_SKIA",
413 "-DDAWN_GLFW_DIR=NOT_SYNCED_BY_SKIA",
414 "-DDAWN_LPM_DIR=NOT_SYNCED_BY_SKIA",
415 "-DDAWN_PROTOBUF_DIR=NOT_SYNCED_BY_SKIA",
416 ]