Feat: dSYM debug info for iOS & macOS builds (#101586)

This commit is contained in:
Ivan Dlugos
2022-09-05 20:16:16 +02:00
committed by GitHub
parent 96345a4bb9
commit 723b82e4f0
15 changed files with 601 additions and 81 deletions

View File

@@ -139,10 +139,17 @@ class AOTSnapshotter {
'--deterministic',
];
final bool targetingApplePlatform =
platform == TargetPlatform.ios || platform == TargetPlatform.darwin;
_logger.printTrace('targetingApplePlatform = $targetingApplePlatform');
final bool extractAppleDebugSymbols =
buildMode == BuildMode.profile || buildMode == BuildMode.release;
_logger.printTrace('extractAppleDebugSymbols = $extractAppleDebugSymbols');
// We strip snapshot by default, but allow to suppress this behavior
// by supplying --no-strip in extraGenSnapshotOptions.
bool shouldStrip = true;
if (extraGenSnapshotOptions != null && extraGenSnapshotOptions.isNotEmpty) {
_logger.printTrace('Extra gen_snapshot options: $extraGenSnapshotOptions');
for (final String option in extraGenSnapshotOptions) {
@@ -168,8 +175,20 @@ class AOTSnapshotter {
]);
}
if (shouldStrip) {
genSnapshotArgs.add('--strip');
// When buiding for iOS and splitting out debug info, we want to strip
// manually after the dSYM export, instead of in the `gen_snapshot`.
final bool stripAfterBuild;
if (targetingApplePlatform) {
stripAfterBuild = shouldStrip;
if (stripAfterBuild) {
_logger.printTrace('Will strip AOT snapshot manual after build and dSYM generation.');
}
} else {
stripAfterBuild = false;
if (shouldStrip) {
genSnapshotArgs.add('--strip');
_logger.printTrace('Will strip AOT snapshot during build.');
}
}
if (platform == TargetPlatform.android_arm) {
@@ -218,8 +237,8 @@ class AOTSnapshotter {
// On iOS and macOS, we use Xcode to compile the snapshot into a dynamic library that the
// end-developer can link into their app.
if (platform == TargetPlatform.ios || platform == TargetPlatform.darwin) {
final RunResult result = await _buildFramework(
if (targetingApplePlatform) {
return _buildFramework(
appleArch: darwinArch!,
isIOS: platform == TargetPlatform.ios,
sdkRoot: sdkRoot,
@@ -227,24 +246,26 @@ class AOTSnapshotter {
outputPath: outputDir.path,
bitcode: bitcode,
quiet: quiet,
stripAfterBuild: stripAfterBuild,
extractAppleDebugSymbols: extractAppleDebugSymbols
);
if (result.exitCode != 0) {
return result.exitCode;
}
} else {
return 0;
}
return 0;
}
/// Builds an iOS or macOS framework at [outputPath]/App.framework from the assembly
/// source at [assemblyPath].
Future<RunResult> _buildFramework({
Future<int> _buildFramework({
required DarwinArch appleArch,
required bool isIOS,
String? sdkRoot,
required String assemblyPath,
required String outputPath,
required bool bitcode,
required bool quiet
required bool quiet,
required bool stripAfterBuild,
required bool extractAppleDebugSymbols
}) async {
final String targetArch = getNameForDarwinArch(appleArch);
if (!quiet) {
@@ -278,7 +299,7 @@ class AOTSnapshotter {
]);
if (compileResult.exitCode != 0) {
_logger.printError('Failed to compile AOT snapshot. Compiler terminated with exit code ${compileResult.exitCode}');
return compileResult;
return compileResult.exitCode;
}
final String frameworkDir = _fileSystem.path.join(outputPath, 'App.framework');
@@ -294,11 +315,33 @@ class AOTSnapshotter {
'-o', appLib,
assemblyO,
];
final RunResult linkResult = await _xcode.clang(linkArgs);
if (linkResult.exitCode != 0) {
_logger.printError('Failed to link AOT snapshot. Linker terminated with exit code ${compileResult.exitCode}');
_logger.printError('Failed to link AOT snapshot. Linker terminated with exit code ${linkResult.exitCode}');
return linkResult.exitCode;
}
return linkResult;
if (extractAppleDebugSymbols) {
final RunResult dsymResult = await _xcode.dsymutil(<String>['-o', '$frameworkDir.dSYM', appLib]);
if (dsymResult.exitCode != 0) {
_logger.printError('Failed to generate dSYM - dsymutil terminated with exit code ${dsymResult.exitCode}');
return dsymResult.exitCode;
}
if (stripAfterBuild) {
// See https://www.unix.com/man-page/osx/1/strip/ for arguments
final RunResult stripResult = await _xcode.strip(<String>['-S', appLib, '-o', appLib]);
if (stripResult.exitCode != 0) {
_logger.printError('Failed to strip debugging symbols from the generated AOT snapshot - strip terminated with exit code ${stripResult.exitCode}');
return stripResult.exitCode;
}
}
} else {
assert(stripAfterBuild == false);
}
return 0;
}
bool _isValidAotPlatform(TargetPlatform platform, BuildMode buildMode) {

View File

@@ -7,6 +7,7 @@ import 'package:package_config/package_config.dart';
import '../../artifacts.dart';
import '../../base/build.dart';
import '../../base/file_system.dart';
import '../../base/io.dart';
import '../../build_info.dart';
import '../../compile.dart';
import '../../dart/package_map.dart';
@@ -394,3 +395,48 @@ abstract class CopyFlutterAotBundle extends Target {
environment.buildDir.childFile('app.so').copySync(outputFile.path);
}
}
/// Lipo CLI tool wrapper shared by iOS and macOS builds.
class Lipo {
/// Static only.
Lipo._();
/// Create a "fat" binary by combining multiple architecture-specific ones.
/// `skipMissingInputs` can be changed to `true` to first check whether
/// the expected input paths exist and ignore the command if they don't.
/// Otherwise, `lipo` would fail if the given paths didn't exist.
static Future<void> create(
Environment environment,
List<DarwinArch> darwinArchs, {
required String relativePath,
required String inputDir,
bool skipMissingInputs = false,
}) async {
final String resultPath = environment.fileSystem.path.join(environment.buildDir.path, relativePath);
environment.fileSystem.directory(resultPath).parent.createSync(recursive: true);
Iterable<String> inputPaths = darwinArchs.map(
(DarwinArch iosArch) => environment.fileSystem.path.join(inputDir, getNameForDarwinArch(iosArch), relativePath)
);
if (skipMissingInputs) {
inputPaths = inputPaths.where(environment.fileSystem.isFileSync);
if (inputPaths.isEmpty) {
return;
}
}
final List<String> lipoArgs = <String>[
'lipo',
...inputPaths,
'-create',
'-output',
resultPath,
];
final ProcessResult result = await environment.processManager.run(lipoArgs);
if (result.exitCode != 0) {
throw Exception('lipo exited with code ${result.exitCode}.\n${result.stderr}');
}
}
}

View File

@@ -112,19 +112,24 @@ abstract class AotAssemblyBase extends Target {
if (results.any((int result) => result != 0)) {
throw Exception('AOT snapshotter exited with code ${results.join()}');
}
final String resultPath = environment.fileSystem.path.join(environment.buildDir.path, 'App.framework', 'App');
environment.fileSystem.directory(resultPath).parent.createSync(recursive: true);
final ProcessResult result = await environment.processManager.run(<String>[
'lipo',
...darwinArchs.map((DarwinArch iosArch) =>
environment.fileSystem.path.join(buildOutputPath, getNameForDarwinArch(iosArch), 'App.framework', 'App')),
'-create',
'-output',
resultPath,
]);
if (result.exitCode != 0) {
throw Exception('lipo exited with code ${result.exitCode}.\n${result.stderr}');
}
// Combine the app lib into a fat framework.
await Lipo.create(
environment,
darwinArchs,
relativePath: 'App.framework/App',
inputDir: buildOutputPath,
);
// And combine the dSYM for each architecture too, if it was created.
await Lipo.create(
environment,
darwinArchs,
relativePath: 'App.framework.dSYM/Contents/Resources/DWARF/App',
inputDir: buildOutputPath,
// Don't fail if the dSYM wasn't created (i.e. during a debug build).
skipMissingInputs: true,
);
}
}
@@ -489,6 +494,26 @@ abstract class IosAssetBundle extends Target {
.copySync(frameworkBinaryPath);
}
// Copy the dSYM
if (environment.buildDir.childDirectory('App.framework.dSYM').existsSync()) {
final File dsymOutputBinary = environment
.outputDir
.childDirectory('App.framework.dSYM')
.childDirectory('Contents')
.childDirectory('Resources')
.childDirectory('DWARF')
.childFile('App');
dsymOutputBinary.parent.createSync(recursive: true);
environment
.buildDir
.childDirectory('App.framework.dSYM')
.childDirectory('Contents')
.childDirectory('Resources')
.childDirectory('DWARF')
.childFile('App')
.copySync(dsymOutputBinary.path);
}
// Copy the assets.
final Depfile assetDepfile = await copyAssets(
environment,
@@ -547,8 +572,25 @@ class DebugIosApplicationBundle extends IosAssetBundle {
];
}
/// IosAssetBundle with debug symbols, used for Profile and Release builds.
abstract class _IosAssetBundleWithDSYM extends IosAssetBundle {
const _IosAssetBundleWithDSYM();
@override
List<Source> get inputs => <Source>[
...super.inputs,
const Source.pattern('{BUILD_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
];
@override
List<Source> get outputs => <Source>[
...super.outputs,
const Source.pattern('{OUTPUT_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
];
}
/// Build a profile iOS application bundle.
class ProfileIosApplicationBundle extends IosAssetBundle {
class ProfileIosApplicationBundle extends _IosAssetBundleWithDSYM {
const ProfileIosApplicationBundle();
@override
@@ -561,7 +603,7 @@ class ProfileIosApplicationBundle extends IosAssetBundle {
}
/// Build a release iOS application bundle.
class ReleaseIosApplicationBundle extends IosAssetBundle {
class ReleaseIosApplicationBundle extends _IosAssetBundleWithDSYM {
const ReleaseIosApplicationBundle();
@override

View File

@@ -302,19 +302,23 @@ class CompileMacOSFramework extends Target {
throw Exception('AOT snapshotter exited with code ${results.join()}');
}
final String resultPath = environment.fileSystem.path.join(environment.buildDir.path, 'App.framework', 'App');
environment.fileSystem.directory(resultPath).parent.createSync(recursive: true);
final ProcessResult result = await environment.processManager.run(<String>[
'lipo',
...darwinArchs.map((DarwinArch iosArch) =>
environment.fileSystem.path.join(buildOutputPath, getNameForDarwinArch(iosArch), 'App.framework', 'App')),
'-create',
'-output',
resultPath,
]);
if (result.exitCode != 0) {
throw Exception('lipo exited with code ${result.exitCode}.\n${result.stderr}');
}
// Combine the app lib into a fat framework.
await Lipo.create(
environment,
darwinArchs,
relativePath: 'App.framework/App',
inputDir: buildOutputPath,
);
// And combine the dSYM for each architecture too, if it was created.
await Lipo.create(
environment,
darwinArchs,
relativePath: 'App.framework.dSYM/Contents/Resources/DWARF/App',
inputDir: buildOutputPath,
// Don't fail if the dSYM wasn't created (i.e. during a debug build).
skipMissingInputs: true,
);
}
@override
@@ -332,6 +336,7 @@ class CompileMacOSFramework extends Target {
@override
List<Source> get outputs => const <Source>[
Source.pattern('{BUILD_DIR}/App.framework/App'),
Source.pattern('{BUILD_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
];
}
@@ -382,6 +387,26 @@ abstract class MacOSBundleFlutterAssets extends Target {
.childFile('App')
.copySync(outputDirectory.childFile('App').path);
// Copy the dSYM
if (environment.buildDir.childDirectory('App.framework.dSYM').existsSync()) {
final File dsymOutputBinary = environment
.outputDir
.childDirectory('App.framework.dSYM')
.childDirectory('Contents')
.childDirectory('Resources')
.childDirectory('DWARF')
.childFile('App');
dsymOutputBinary.parent.createSync(recursive: true);
environment
.buildDir
.childDirectory('App.framework.dSYM')
.childDirectory('Contents')
.childDirectory('Resources')
.childDirectory('DWARF')
.childFile('App')
.copySync(dsymOutputBinary.path);
}
// Copy assets into asset directory.
final Directory assetDirectory = outputDirectory
.childDirectory('Resources')
@@ -530,6 +555,18 @@ class ProfileMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets {
CompileMacOSFramework(),
ProfileUnpackMacOS(),
];
@override
List<Source> get inputs => <Source>[
...super.inputs,
const Source.pattern('{BUILD_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
];
@override
List<Source> get outputs => <Source>[
...super.outputs,
const Source.pattern('{OUTPUT_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
];
}
@@ -546,6 +583,18 @@ class ReleaseMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets {
ReleaseUnpackMacOS(),
];
@override
List<Source> get inputs => <Source>[
...super.inputs,
const Source.pattern('{BUILD_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
];
@override
List<Source> get outputs => <Source>[
...super.outputs,
const Source.pattern('{OUTPUT_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
];
@override
Future<void> build(Environment environment) async {
bool buildSuccess = true;

View File

@@ -68,8 +68,11 @@ class SymbolizeCommand extends FlutterCommand {
if (argResults?.wasParsed('debug-info') != true) {
throwToolExit('"--debug-info" is required to symbolize stack traces.');
}
if (!_fileSystem.isFileSync(stringArgDeprecated('debug-info')!)) {
throwToolExit('${stringArgDeprecated('debug-info')} does not exist.');
final String debugInfoPath = stringArgDeprecated('debug-info')!;
if (debugInfoPath.endsWith('.dSYM')
? !_fileSystem.isDirectorySync(debugInfoPath)
: !_fileSystem.isFileSync(debugInfoPath)) {
throwToolExit('$debugInfoPath does not exist.');
}
if ((argResults?.wasParsed('input') ?? false) && !_fileSystem.isFileSync(stringArgDeprecated('input')!)) {
throwToolExit('${stringArgDeprecated('input')} does not exist.');
@@ -105,7 +108,25 @@ class SymbolizeCommand extends FlutterCommand {
input = _stdio.stdin;
}
final Uint8List symbols = _fileSystem.file(stringArgDeprecated('debug-info')).readAsBytesSync();
String debugInfoPath = stringArgDeprecated('debug-info')!;
// If it's a dSYM container, expand the path to the actual DWARF.
if (debugInfoPath.endsWith('.dSYM')) {
final Directory debugInfoDir = _fileSystem
.directory(debugInfoPath)
.childDirectory('Contents')
.childDirectory('Resources')
.childDirectory('DWARF');
final List<FileSystemEntity> dwarfFiles = debugInfoDir.listSync().whereType<File>().toList();
if (dwarfFiles.length == 1) {
debugInfoPath = dwarfFiles.first.path;
} else {
throwToolExit('Expected a single DWARF file in a dSYM container.');
}
}
final Uint8List symbols = _fileSystem.file(debugInfoPath).readAsBytesSync();
await _dwarfSymbolizationService.decode(
input: input,
output: output,

View File

@@ -165,16 +165,17 @@ class Xcode {
/// See [XcodeProjectInterpreter.xcrunCommand].
List<String> xcrunCommand() => _xcodeProjectInterpreter.xcrunCommand();
Future<RunResult> cc(List<String> args) {
return _processUtils.run(
<String>[...xcrunCommand(), 'cc', ...args],
throwOnError: true,
);
}
Future<RunResult> cc(List<String> args) => _run('cc', args);
Future<RunResult> clang(List<String> args) {
Future<RunResult> clang(List<String> args) => _run('clang', args);
Future<RunResult> dsymutil(List<String> args) => _run('dsymutil', args);
Future<RunResult> strip(List<String> args) => _run('strip', args);
Future<RunResult> _run(String command, List<String> args) {
return _processUtils.run(
<String>[...xcrunCommand(), 'clang', ...args],
<String>[...xcrunCommand(), command, ...args],
throwOnError: true,
);
}