Improve Wasm Debugging. (flutter/engine#41054)

Improve Wasm Debugging.
This commit is contained in:
Jackson Gardner
2023-04-11 17:52:04 -07:00
committed by GitHub
parent 1f6af2f479
commit 28d9e0df0f
15 changed files with 255 additions and 63 deletions

2
DEPS
View File

@@ -239,7 +239,7 @@ allowed_hosts = [
]
deps = {
'src': 'https://github.com/flutter/buildroot.git' + '@' + 'c26173f545880557c36e8fff8b7b6b5c4385c931',
'src': 'https://github.com/flutter/buildroot.git' + '@' + 'b6c4d42a35088b73125c5d589441b6357d5e91a8',
# Fuchsia compatibility
#

View File

@@ -42,7 +42,10 @@ abstract class BrowserEnvironment {
/// browser in debug mode by pausing test execution after the code is loaded
/// but before calling the `main()` function of the test, giving the
/// developer a chance to set breakpoints.
Future<Browser> launchBrowserInstance(Uri url, {bool debug = false});
Future<Browser> launchBrowserInstance(
Uri url, {
bool debug = false,
});
}
/// An interface for running browser instances.

View File

@@ -9,6 +9,7 @@ import 'package:path/path.dart' as path;
import 'package:watcher/src/watch_event.dart';
import 'environment.dart';
import 'exceptions.dart';
import 'pipeline.dart';
import 'utils.dart';
@@ -17,7 +18,7 @@ const Map<String, String> targetAliases = <String, String>{
'web_sdk': 'flutter/web_sdk',
'canvaskit': 'flutter/third_party/canvaskit:canvaskit_group',
'canvaskit_chromium': 'flutter/third_party/canvaskit:canvaskit_chromium_group',
'skwasm': 'flutter/lib/web_ui/skwasm',
'skwasm': 'flutter/third_party/canvaskit:skwasm_group',
'archive': 'flutter/web_sdk:flutter_web_sdk_archive',
};
@@ -46,6 +47,11 @@ class BuildCommand extends Command<bool> with ArgUtils<bool> {
'output will be located at "out/wasm_debug".\nThis only applies to '
'the wasm build. The host build is always built in release mode.',
);
argParser.addFlag(
'dwarf',
help: 'Embed DWARF debugging info into the output wasm modules. This is '
'only valid in debug mode.',
);
}
@override
@@ -59,14 +65,19 @@ class BuildCommand extends Command<bool> with ArgUtils<bool> {
bool get host => boolArg('host');
List<String> get targets => argResults?.rest ?? <String>[];
bool get embedDwarf => boolArg('dwarf');
@override
FutureOr<bool> run() async {
if (embedDwarf && runtimeMode != RuntimeMode.debug) {
throw ToolExit('Embedding DWARF data requires debug runtime mode.');
}
final FilePath libPath = FilePath.fromWebUi('lib');
final List<PipelineStep> steps = <PipelineStep>[
GnPipelineStep(
host: host,
runtimeMode: runtimeMode,
embedDwarf: embedDwarf,
),
NinjaPipelineStep(
host: host,
@@ -99,10 +110,12 @@ class GnPipelineStep extends ProcessStep {
GnPipelineStep({
required this.host,
required this.runtimeMode,
required this.embedDwarf,
});
final bool host;
final RuntimeMode runtimeMode;
final bool embedDwarf;
@override
String get description => 'gn';
@@ -120,6 +133,10 @@ class GnPipelineStep extends ProcessStep {
return <String>[
'--web',
'--runtime-mode=${runtimeMode.name}',
if (runtimeMode == RuntimeMode.debug)
'--unoptimized',
if (embedDwarf)
'--wasm-use-dwarf',
];
}
}

View File

@@ -8,6 +8,7 @@ import 'dart:io';
import 'dart:math' as math;
import 'package:image/image.dart';
import 'package:path/path.dart' as path;
import 'package:test_api/src/backend/runtime.dart';
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'
as wip;
@@ -21,15 +22,29 @@ import 'environment.dart';
/// Provides an environment for desktop Chrome.
class ChromeEnvironment implements BrowserEnvironment {
ChromeEnvironment(this._enableWasmGC);
ChromeEnvironment({
required bool enableWasmGC,
required bool useDwarf,
}) : _enableWasmGC = enableWasmGC,
_useDwarf = useDwarf;
late final BrowserInstallation _installation;
final bool _enableWasmGC;
final bool _useDwarf;
@override
Future<Browser> launchBrowserInstance(Uri url, {bool debug = false}) async {
return Chrome(url, _installation, debug: debug, enableWasmGC: _enableWasmGC);
Future<Browser> launchBrowserInstance(
Uri url, {
bool debug = false,
}) async {
return Chrome(
url,
_installation,
debug: debug,
enableWasmGC: _enableWasmGC,
useDwarf: _useDwarf
);
}
@override
@@ -64,7 +79,13 @@ class ChromeEnvironment implements BrowserEnvironment {
class Chrome extends Browser {
/// Starts a new instance of Chrome open to the given [url], which may be a
/// [Uri] or a [String].
factory Chrome(Uri url, BrowserInstallation installation, {required bool debug, required bool enableWasmGC}) {
factory Chrome(
Uri url,
BrowserInstallation installation, {
required bool debug,
required bool enableWasmGC,
required bool useDwarf,
}) {
final Completer<Uri> remoteDebuggerCompleter = Completer<Uri>.sync();
return Chrome._(BrowserProcess(() async {
// A good source of various Chrome CLI options:
@@ -79,7 +100,7 @@ class Chrome extends Browser {
// --disable-font-subpixel-positioning
final bool isChromeNoSandbox =
Platform.environment['CHROME_NO_SANDBOX'] == 'true';
final String dir = environment.webUiDartToolDir.createTempSync('test_chrome_user_data_').resolveSymbolicLinksSync();
final String dir = await generateUserDirectory(installation, useDwarf);
final String jsFlags = enableWasmGC ? <String>[
'--experimental-wasm-gc',
'--experimental-wasm-stack-switching',
@@ -101,9 +122,13 @@ class Chrome extends Browser {
'--start-maximized',
if (debug)
'--auto-open-devtools-for-tabs',
if (useDwarf)
'--devtools-flags=enabledExperiments=wasmDWARFDebugging',
// Always run unit tests at a 1x scale factor
'--force-device-scale-factor=1',
'--disable-extensions',
if (!useDwarf)
// DWARF debugging requires a Chrome extension.
'--disable-extensions',
'--disable-popup-blocking',
// Indicates that the browser is in "browse without sign-in" (Guest session) mode.
'--bwsi',
@@ -137,6 +162,64 @@ class Chrome extends Browser {
Chrome._(this._process, this.remoteDebuggerUrl);
static Future<String> generateUserDirectory(
BrowserInstallation installation,
bool useDwarf
) async {
final String userDirectoryPath = environment
.webUiDartToolDir
.createTempSync('test_chrome_user_data_')
.resolveSymbolicLinksSync();
if (!useDwarf) {
return userDirectoryPath;
}
// Using DWARF debugging info requires installation of a Chrome extension.
// We can prompt for this, but in order to avoid prompting on every single
// browser launch, we cache the user directory after it has been installed.
final Directory baselineUserDirectory = Directory(path.join(
environment.webUiDartToolDir.path,
'chrome_user_data_base',
));
final Directory dwarfExtensionInstallDirectory = Directory(path.join(
baselineUserDirectory.path,
'Default',
'Extensions',
// This is the ID of the dwarf debugging extension.
'pdcpmagijalfljmkmjngeonclgbbannb',
));
if (!baselineUserDirectory.existsSync()) {
baselineUserDirectory.createSync(recursive: true);
}
if (!dwarfExtensionInstallDirectory.existsSync()) {
print('DWARF debugging requested. Launching Chrome. Please install the '
'extension and then exit Chrome when the installation is complete...');
final Process addExtension = await Process.start(
installation.executable,
<String>[
'--user-data-dir=${baselineUserDirectory.path}',
'https://goo.gle/wasm-debugging-extension',
'--bwsi',
'--no-first-run',
'--no-default-browser-check',
'--disable-default-apps',
'--disable-translate',
]
);
await addExtension.exitCode;
}
for (final FileSystemEntity input in baselineUserDirectory.listSync(recursive: true)) {
final String relative = path.relative(input.path, from: baselineUserDirectory.path);
final String outputPath = path.join(userDirectoryPath, relative);
if (input is Directory) {
await Directory(outputPath).create(recursive: true);
} else if (input is File) {
await input.copy(outputPath);
}
}
return userDirectoryPath;
}
final BrowserProcess _process;
@override

View File

@@ -262,10 +262,14 @@ const List<String> kAllBrowserNames = <String>[
/// Creates an environment for a browser.
///
/// The [browserName] matches the browser name passed as the `--browser` option.
BrowserEnvironment getBrowserEnvironment(BrowserName browserName, { required bool enableWasmGC }) {
BrowserEnvironment getBrowserEnvironment(
BrowserName browserName, {
required bool enableWasmGC,
required bool useDwarf,
}) {
switch (browserName) {
case BrowserName.chrome:
return ChromeEnvironment(enableWasmGC);
return ChromeEnvironment(enableWasmGC: enableWasmGC, useDwarf: useDwarf);
case BrowserName.edge:
return EdgeEnvironment();
case BrowserName.firefox:

View File

@@ -32,8 +32,8 @@ class Environment {
io.Directory(pathlib.join(outDir.path, 'wasm_release'));
final io.Directory wasmProfileOutDir =
io.Directory(pathlib.join(outDir.path, 'wasm_profile'));
final io.Directory wasmDebugOutDir =
io.Directory(pathlib.join(outDir.path, 'wasm_debug'));
final io.Directory wasmDebugUnoptOutDir =
io.Directory(pathlib.join(outDir.path, 'wasm_debug_unopt'));
final io.Directory hostDebugUnoptDir =
io.Directory(pathlib.join(outDir.path, 'host_debug_unopt'));
final io.Directory dartSdkDir = dartExecutable.parent.parent;
@@ -59,7 +59,7 @@ class Environment {
outDir: outDir,
wasmReleaseOutDir: wasmReleaseOutDir,
wasmProfileOutDir: wasmProfileOutDir,
wasmDebugOutDir: wasmDebugOutDir,
wasmDebugUnoptOutDir: wasmDebugUnoptOutDir,
hostDebugUnoptDir: hostDebugUnoptDir,
dartSdkDir: dartSdkDir,
);
@@ -74,7 +74,7 @@ class Environment {
required this.outDir,
required this.wasmReleaseOutDir,
required this.wasmProfileOutDir,
required this.wasmDebugOutDir,
required this.wasmDebugUnoptOutDir,
required this.hostDebugUnoptDir,
required this.dartSdkDir,
});
@@ -108,7 +108,7 @@ class Environment {
final io.Directory wasmProfileOutDir;
/// The output directory for the wasm_debug build.
final io.Directory wasmDebugOutDir;
final io.Directory wasmDebugUnoptOutDir;
/// The output directory for the host_debug_unopt build.
final io.Directory hostDebugUnoptDir;

View File

@@ -150,6 +150,7 @@ class CopyArtifactsStep implements PipelineStep {
for (final String filename in <String>[
'canvaskit.js',
'canvaskit.wasm',
'canvaskit.wasm.map',
]) {
final io.File sourceFile = io.File(pathlib.join(
sourceDirectoryPath,
@@ -160,7 +161,13 @@ class CopyArtifactsStep implements PipelineStep {
filename,
));
if (!sourceFile.existsSync()) {
throw ToolExit('Built CanvasKit artifact not found at path "$sourceFile".');
if (filename.endsWith('.map')) {
// Sourcemaps are only generated under certain build conditions, so
// they are optional.
continue;
} {
throw ToolExit('Built CanvasKit artifact not found at path "$sourceFile".');
}
}
await targetFile.create(recursive: true);
await sourceFile.copy(targetFile.path);
@@ -179,13 +186,25 @@ class CopyArtifactsStep implements PipelineStep {
for (final String fileName in <String>[
'skwasm.wasm',
'skwasm.wasm.map',
'skwasm.js',
'skwasm.worker.js',
]) {
final io.File sourceFile = io.File(pathlib.join(
outBuildPath,
'flutter_web_sdk',
'canvaskit',
fileName,
));
if (!sourceFile.existsSync()) {
if (fileName.endsWith('.map')) {
// Sourcemaps are only generated under certain build conditions, so
// they are optional.
continue;
} {
throw ToolExit('Built Skwasm artifact not found at path "$sourceFile".');
}
}
final io.File targetFile = io.File(pathlib.join(
targetDir.path,
fileName,

View File

@@ -33,8 +33,9 @@ class RunSuiteStep implements PipelineStep {
required this.isVerbose,
required this.doUpdateScreenshotGoldens,
required this.requireSkiaGold,
this.testFiles,
required this.overridePathToCanvasKit,
required this.useDwarf,
this.testFiles,
});
final TestSuite suite;
@@ -43,6 +44,7 @@ class RunSuiteStep implements PipelineStep {
final bool isVerbose;
final bool doUpdateScreenshotGoldens;
final String? overridePathToCanvasKit;
final bool useDwarf;
/// Require Skia Gold to be available and reachable.
final bool requireSkiaGold;
@@ -63,7 +65,9 @@ class RunSuiteStep implements PipelineStep {
_prepareTestResultsDirectory();
final BrowserEnvironment browserEnvironment = getBrowserEnvironment(
suite.runConfig.browser,
enableWasmGC: isWasm);
enableWasmGC: isWasm,
useDwarf: useDwarf,
);
await browserEnvironment.prepare();
final SkiaGoldClient? skiaClient = await _createSkiaClient();
@@ -93,7 +97,6 @@ class RunSuiteStep implements PipelineStep {
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
skiaClient: skiaClient,
overridePathToCanvasKit: overridePathToCanvasKit,
isWasm: isWasm,
isVerbose: isVerbose,
);
});

View File

@@ -80,21 +80,18 @@ class BrowserPlatform extends PlatformPlugin {
// Serves files from the out/web_tests/artifacts directory at the root (/) URL path.
.add(createSimpleDirectoryHandler(env.environment.webTestsArtifactsDir))
// Serves files from thes test set directory
// Serves files from the test set directory
.add(createSimpleDirectoryHandler(getTestSetDirectory(suite.testBundle.testSet)))
.add(_testImageListingHandler)
// Serves the initial HTML for the test.
.add(_testBootstrapHandler)
// Serves files from the root of web_ui.
//
// This is needed because sourcemaps refer to local files, i.e. those
// that don't come from package dependencies, relative to web_ui/.
//
// Examples of URLs that this handles:
// * /test/alarm_clock_test.dart
// * /lib/src/engine/alarm_clock.dart
// Serves source files from the engine src root for devtools debugging.
.add(_createSourceHandler())
// Serves files from the root of web_ui. Some tests download assets that are embedded
// directly in the test folder, such as test/engine/image/sample_image1.png etc
.add(createStaticHandler(env.environment.webUiRootDir.path))
// Serves absolute package URLs (i.e. not /packages/* but /Users/user/*/hosted/pub.dartlang.org/*).
@@ -123,7 +120,6 @@ class BrowserPlatform extends PlatformPlugin {
required bool doUpdateScreenshotGoldens,
required SkiaGoldClient? skiaClient,
required String? overridePathToCanvasKit,
required bool isWasm,
required bool isVerbose,
}) async {
final shelf_io.IOServer server =
@@ -266,6 +262,26 @@ class BrowserPlatform extends PlatformPlugin {
return shelf.Response.notFound('File not found');
}
shelf.Handler _createSourceHandler() => (shelf.Request request) async {
final String path = p.fromUri(request.url);
final String extension = p.extension(path);
final bool isSource =
extension == '.dart' ||
extension == '.c' ||
extension == '.cc' ||
extension == '.cpp' ||
extension == '.h';
if (isSource && p.isRelative(path)) {
final String fullPath = p.join(env.environment.engineSrcDir.path, path);
final File file = File(fullPath);
if (file.existsSync()) {
return shelf.Response.ok(file.openRead());
}
}
return shelf.Response.notFound('Not found.');
};
/// Handles URLs pointing to Dart sources using absolute URI paths.
///
/// Dart source paths that dart2js puts in source maps for pub packages are
@@ -452,6 +468,7 @@ class BrowserPlatform extends PlatformPlugin {
'.bmp': 'image/bmp',
'.svg': 'image/svg+xml',
'.json': 'application/json',
'.map': 'application/json',
'.ttf': 'font/ttf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
@@ -713,8 +730,13 @@ class OneOffHandler {
class BrowserManager {
/// Creates a new BrowserManager that communicates with the browser over
/// [webSocket].
BrowserManager._(this.packageConfig, this._browser, this._browserEnvironment,
this._sourceMapDirectory, WebSocketChannel webSocket) {
BrowserManager._(
this.packageConfig,
this._browser,
this._browserEnvironment,
this._sourceMapDirectory,
WebSocketChannel webSocket,
) {
// The duration should be short enough that the debugging console is open as
// soon as the user is done setting breakpoints, but long enough that a test
// doing a lot of synchronous work doesn't trigger a false positive.
@@ -725,8 +747,7 @@ class BrowserManager {
for (final RunnerSuiteController controller in _controllers) {
controller.setDebugging(true);
}
})
..cancel();
})..cancel();
// Whenever we get a message, no matter which child channel it's for, we the
// know browser is still running code which means the user isn't debugging.
@@ -830,16 +851,20 @@ class BrowserManager {
Directory? sourceMapDirectory,
bool debug = false,
}) async {
final Browser browser =
await _newBrowser(url, browserEnvironment, debug: debug);
final Browser browser = await _newBrowser(
url,
browserEnvironment,
debug: debug,
);
return _startBrowserManager(
browserEnvironment: browserEnvironment,
url: url,
future: future,
packageConfig: packageConfig,
browser: browser,
sourceMapDirectory: sourceMapDirectory,
debug: debug);
browserEnvironment: browserEnvironment,
url: url,
future: future,
packageConfig: packageConfig,
browser: browser,
sourceMapDirectory: sourceMapDirectory,
debug: debug,
);
}
static Future<BrowserManager?> _startBrowserManager({
@@ -870,7 +895,12 @@ class BrowserManager {
return;
}
completer.complete(BrowserManager._(
packageConfig, browser, browserEnvironment, sourceMapDirectory, webSocket));
packageConfig,
browser,
browserEnvironment,
sourceMapDirectory,
webSocket,
));
}).catchError((Object error, StackTrace stackTrace) {
browser.close();
if (completer.isCompleted) {
@@ -886,15 +916,24 @@ class BrowserManager {
///
/// If [debug] is true, starts the browser in debug mode.
static Future<Browser> _newBrowser(
Uri url, BrowserEnvironment browserEnvironment,
{bool debug = false}) {
return browserEnvironment.launchBrowserInstance(url, debug: debug);
Uri url,
BrowserEnvironment browserEnvironment, {
bool debug = false,
}) {
return browserEnvironment.launchBrowserInstance(
url,
debug: debug,
);
}
/// Loads [_BrowserEnvironment].
Future<_BrowserEnvironment> _loadBrowserEnvironment() async {
return _BrowserEnvironment(this, await _browser.vmServiceUrl,
await _browser.remoteDebuggerUrl, _onRestartController.stream);
return _BrowserEnvironment(
this,
await _browser.vmServiceUrl,
await _browser.remoteDebuggerUrl,
_onRestartController.stream
);
}
/// Tells the browser the load a test suite from the URL [url].

View File

@@ -82,8 +82,11 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
)
..addFlag(
'debug',
help:
'Use artifacts from the debug build instead of release.'
help: 'Use artifacts from the debug build instead of release.'
)
..addFlag(
'dwarf',
help: 'Debug wasm modules using embedded DWARF data.'
)
..addFlag(
'require-skia-gold',
@@ -387,6 +390,7 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
requireSkiaGold: requireSkiaGold,
overridePathToCanvasKit: overridePathToCanvasKit,
testFiles: testFiles,
useDwarf: boolArg('dwarf'),
),
]);

View File

@@ -353,7 +353,7 @@ mixin ArgUtils<T> on Command<T> {
io.Directory getBuildDirectoryForRuntimeMode(RuntimeMode runtimeMode) =>
switch (runtimeMode) {
RuntimeMode.debug => environment.wasmDebugOutDir,
RuntimeMode.debug => environment.wasmDebugUnoptOutDir,
RuntimeMode.profile => environment.wasmProfileOutDir,
RuntimeMode.release => environment.wasmReleaseOutDir,
};

View File

@@ -28,23 +28,20 @@ wasm_lib("skwasm") {
"-sALLOW_TABLE_GROWTH",
"-sUSE_PTHREADS=1",
"-lexports.js",
"-sEXPORTED_FUNCTIONS=[stackAlloc]",
"-sEXPORTED_RUNTIME_METHODS=[addFunction,removeFunction]",
]
cflags = [ "-pthread" ]
if (is_debug) {
ldflags += [
"-sDEMANGLE_SUPPORT=1",
"-sASSERTIONS=1",
"-sGL_ASSERTIONS=1",
"-g3",
]
} else {
ldflags += [
"-Oz",
"--closure=1",
"-sEXPORTED_FUNCTIONS=[stackAlloc]",
"-sEXPORTED_RUNTIME_METHODS=[addFunction,removeFunction]",
]
}

View File

@@ -68,14 +68,29 @@ copy("canvaskit_chromium_group") {
]
}
# This toolchain is only to be used by skwasm_group below.
wasm_toolchain("skwasm") {
extra_toolchain_args = {
skia_enable_skparagraph = false
# skwasm is multithreaded
wasm_use_pthreads = true
}
}
copy("skwasm_group") {
visibility = [ "//flutter/web_sdk:*" ]
public_deps = [ "//flutter/lib/web_ui/skwasm" ]
public_deps = [ "//flutter/lib/web_ui/skwasm(:skwasm)" ]
sources = [
"$root_out_dir/skwasm.js",
"$root_out_dir/skwasm.wasm",
"$root_out_dir/skwasm.worker.js",
"$root_out_dir/skwasm/skwasm.js",
"$root_out_dir/skwasm/skwasm.wasm",
"$root_out_dir/skwasm/skwasm.worker.js",
]
if (is_debug) {
if (!wasm_use_dwarf) {
sources += [ "$root_out_dir/skwasm/skwasm.wasm.map" ]
}
}
outputs = [ "$root_out_dir/flutter_web_sdk/canvaskit/{{source_file_part}}" ]
}

View File

@@ -47,6 +47,7 @@ static_library("icu_bidi") {
"//third_party/icu/source/common/ustrtrns.cpp",
"//third_party/icu/source/common/utf_impl.cpp",
"//third_party/icu/source/common/utrie2.cpp",
"//third_party/icu/source/common/utypes.cpp",
]
public_configs = [ ":icu_bidi_public" ]
cflags = [ "-w" ]

View File

@@ -619,6 +619,7 @@ def to_gn_wasm_args(args, gn_args):
gn_args['is_clang'] = True
gn_args['target_os'] = 'wasm'
gn_args['target_cpu'] = 'wasm'
gn_args['wasm_use_dwarf'] = args.wasm_use_dwarf
gn_args['skia_use_angle'] = False
gn_args['skia_use_dng_sdk'] = False
gn_args['skia_use_expat'] = False
@@ -665,8 +666,7 @@ def to_gn_wasm_args(args, gn_args):
gn_args['skia_canvaskit_enable_paragraph'] = True
gn_args['skia_canvaskit_enable_webgl'] = True
gn_args['skia_canvaskit_enable_webgpu'] = False
is_profile_build = args.runtime_mode == 'profile' or args.runtime_mode == 'debug'
gn_args['skia_canvaskit_profile_build'] = is_profile_build
gn_args['skia_canvaskit_profile_build'] = args.runtime_mode == 'profile'
gn_args['flutter_prebuilt_dart_sdk'] = True
@@ -761,6 +761,13 @@ def parse_args(args):
parser.add_argument(
'--wasm', dest='target_os', action='store_const', const='wasm'
)
parser.add_argument(
'--wasm-use-dwarf',
action='store_true',
default=False,
help='Embed dwarf debugging info in the output module instead of using '
'sourcemap files.'
)
parser.add_argument('--web', action='store_true', default=False)
parser.add_argument(
'--windows', dest='target_os', action='store_const', const='win'