-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflutter_tools.patch
More file actions
348 lines (343 loc) · 12.1 KB
/
Copy pathflutter_tools.patch
File metadata and controls
348 lines (343 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
diff --git a/packages/flutter_tools/lib/src/aop/aopd_hook.dart b/packages/flutter_tools/lib/src/aop/aopd_hook.dart
new file mode 100644
index 00000000000..f6b6ee904b2
--- /dev/null
+++ b/packages/flutter_tools/lib/src/aop/aopd_hook.dart
@@ -0,0 +1,232 @@
+import 'package:file/file.dart' as file;
+import 'package:package_config/package_config.dart';
+import 'package:yaml/yaml.dart';
+
+import '../artifacts.dart';
+import '../base/common.dart';
+import '../base/io.dart';
+import '../cache.dart';
+import '../dart/package_map.dart';
+import '../globals.dart' as globals;
+
+const _pubspecName = 'pubspec.yaml';
+const _keyAopd = 'aopd';
+const _keyEnabled = 'enabled';
+const _keyTrackWidgetCreation = 'track_widget_creation';
+const _aopdPackageName = 'aopd';
+const _prepareSnapshotScript = 'prepare_frontend_server_snapshot.dart';
+const _snapshotPathMarker = 'AOPD_SNAPSHOT_PATH=';
+
+class AopdHookConfig {
+ const AopdHookConfig({
+ required this.enabled,
+ this.frontendServerSnapshotPath,
+ this.trackWidgetCreation = false,
+ });
+
+ final bool enabled;
+ final String? frontendServerSnapshotPath;
+ final bool trackWidgetCreation;
+}
+
+class _AopdPubspecConfig {
+ const _AopdPubspecConfig({
+ required this.enabled,
+ required this.trackWidgetCreation,
+ });
+
+ final bool enabled;
+ final bool trackWidgetCreation;
+}
+
+class AopdHook {
+ static Future<AopdHookConfig> resolve() async {
+ // Resolve the Flutter app/package root by walking up from the current
+ // directory to the nearest pubspec.yaml, rather than assuming cwd IS the
+ // app root. This keeps AOPD enabled when the tool is invoked from a
+ // subdirectory (e.g. android/ via Gradle, or an IDE build cwd). In a pub
+ // workspace the nearest pubspec.yaml is the app member's (which holds the
+ // `aopd:` config); the shared package_config.json is still located by
+ // walking up (see _findPackagePath).
+ final file.Directory appRoot = _findAppRoot();
+ final file.File pubspecFile = globals.fs.file(
+ globals.fs.path.join(appRoot.path, _pubspecName),
+ );
+ if (!pubspecFile.existsSync()) {
+ return const AopdHookConfig(enabled: false);
+ }
+
+ final _AopdPubspecConfig? pubspecConfig = _readPubspecConfig(pubspecFile);
+ if (pubspecConfig == null || !pubspecConfig.enabled) {
+ return const AopdHookConfig(enabled: false);
+ }
+
+ final String? packagePath = await _findPackagePath(appRoot, _aopdPackageName);
+ if (packagePath == null) {
+ throwToolExit(
+ '[AOPD] pubspec.yaml enables AOPD, but package "$_aopdPackageName" was not found. '
+ 'Run "flutter pub get" and make sure "$_aopdPackageName" is a dependency.',
+ );
+ }
+
+ final String snapshotPath = await _prepareFrontendServerSnapshot(
+ appRoot,
+ packagePath,
+ );
+ return AopdHookConfig(
+ enabled: true,
+ frontendServerSnapshotPath: snapshotPath,
+ trackWidgetCreation: pubspecConfig.trackWidgetCreation,
+ );
+ }
+
+ /// Walks up from the current directory to the nearest ancestor (inclusive)
+ /// containing a pubspec.yaml. Falls back to the current directory when none
+ /// is found.
+ static file.Directory _findAppRoot() {
+ file.Directory dir = globals.fs.currentDirectory;
+ while (true) {
+ final file.File pubspec = globals.fs.file(
+ globals.fs.path.join(dir.path, _pubspecName),
+ );
+ if (pubspec.existsSync()) {
+ return dir;
+ }
+ final file.Directory parent = dir.parent;
+ if (parent.path == dir.path) {
+ // Reached the filesystem root without finding a pubspec.
+ return globals.fs.currentDirectory;
+ }
+ dir = parent;
+ }
+ }
+
+
+ static _AopdPubspecConfig? _readPubspecConfig(file.File pubspecFile) {
+ final Object? yamlInfo = loadYaml(pubspecFile.readAsStringSync());
+ if (yamlInfo is! YamlMap) {
+ return null;
+ }
+ final Object? aopdConfig = yamlInfo[_keyAopd];
+ if (aopdConfig == null) {
+ return null;
+ }
+ if (aopdConfig is! YamlMap) {
+ throwToolExit('[AOPD] pubspec.yaml "aopd" must be a map.');
+ }
+ final Object? enabled = aopdConfig[_keyEnabled];
+ final Object? trackWidgetCreation = aopdConfig[_keyTrackWidgetCreation];
+ return _AopdPubspecConfig(
+ enabled: enabled == true,
+ trackWidgetCreation: trackWidgetCreation == true,
+ );
+ }
+
+ static Future<String?> _findPackagePath(
+ file.Directory appRoot,
+ String packageName,
+ ) async {
+ try {
+ final file.File packageFile = findPackageConfigFileOrDefault(appRoot);
+ final PackageConfig packageConfig = await loadPackageConfigWithLogging(
+ packageFile,
+ logger: globals.logger,
+ throwOnError: false,
+ );
+ for (final Package package in packageConfig.packages) {
+ if (package.name == packageName) {
+ return package.root.toFilePath();
+ }
+ }
+ } on Exception catch (error) {
+ globals.printTrace('[AOPD] Invalid package config file: $error');
+ }
+ return null;
+ }
+
+ static Future<String> _prepareFrontendServerSnapshot(
+ file.Directory appRoot,
+ String packagePath,
+ ) async {
+ final file.File prepareScript = globals.fs.file(
+ globals.fs.path.join(packagePath, 'bin', _prepareSnapshotScript),
+ );
+ if (!prepareScript.existsSync()) {
+ throwToolExit('[AOPD] Snapshot prepare script not found: ${prepareScript.path}');
+ }
+
+ final String dartPath = globals.artifacts!.getArtifactPath(Artifact.engineDartBinary);
+ if (!globals.processManager.canRun(dartPath)) {
+ throwToolExit('[AOPD] Unable to find Dart binary at $dartPath');
+ }
+
+ final command = <String>[
+ dartPath,
+ prepareScript.path,
+ '--app-root',
+ appRoot.path,
+ '--aopd-root',
+ packagePath,
+ '--flutter-root',
+ Cache.flutterRoot!,
+ '--dart',
+ dartPath,
+ ];
+ globals.printTrace('[AOPD] prepare snapshot command: ${command.join(' ')}');
+
+ final ProcessResult result = await globals.processManager.run(
+ command,
+ workingDirectory: appRoot.path,
+ environment: <String, String>{
+ ...globals.platform.environment,
+ 'DART_SUPPRESS_ANALYTICS': 'true',
+ 'FLUTTER_SUPPRESS_ANALYTICS': 'true',
+ },
+ );
+
+ final stdoutText = result.stdout.toString();
+ final stderrText = result.stderr.toString();
+ _printPrepareOutput(stdoutText, isError: false);
+ _printPrepareOutput(stderrText, isError: true);
+
+ if (result.exitCode != 0) {
+ throwToolExit(
+ '[AOPD] Failed to prepare frontend_server snapshot. Exit code: ${result.exitCode}',
+ );
+ }
+
+ final String? snapshotPath = _extractSnapshotPath(stdoutText);
+ if (snapshotPath == null || snapshotPath.isEmpty) {
+ throwToolExit('[AOPD] Snapshot prepare script did not return a snapshot path.');
+ }
+ if (!globals.fs.file(snapshotPath).existsSync()) {
+ throwToolExit('[AOPD] Prepared frontend_server snapshot does not exist: $snapshotPath');
+ }
+ return snapshotPath;
+ }
+
+ static void _printPrepareOutput(String output, {required bool isError}) {
+ if (output.trim().isEmpty) {
+ return;
+ }
+ for (final String line in output.split(RegExp(r'\r?\n'))) {
+ if (line.isEmpty || line.startsWith(_snapshotPathMarker)) {
+ continue;
+ }
+ if (isError) {
+ globals.printError(line);
+ } else {
+ globals.printStatus(line);
+ }
+ }
+ }
+
+ static String? _extractSnapshotPath(String stdoutText) {
+ for (final String line in stdoutText.split(RegExp(r'\r?\n'))) {
+ if (line.startsWith(_snapshotPathMarker)) {
+ return line.substring(_snapshotPathMarker.length).trim();
+ }
+ }
+ return null;
+ }
+}
diff --git a/packages/flutter_tools/lib/src/compile.dart b/packages/flutter_tools/lib/src/compile.dart
index 1e8f435351a..94e67bbd13d 100644
--- a/packages/flutter_tools/lib/src/compile.dart
+++ b/packages/flutter_tools/lib/src/compile.dart
@@ -10,6 +10,7 @@ import 'package:package_config/package_config.dart';
import 'package:process/process.dart';
import 'package:usage/uuid/uuid.dart';
+import 'aop/aopd_hook.dart';
import 'artifacts.dart';
import 'base/common.dart';
import 'base/config.dart';
@@ -270,6 +271,8 @@ class KernelCompiler {
required PackageConfig packageConfig,
String? nativeAssets,
}) async {
+ final AopdHookConfig aopdHookConfig = await AopdHook.resolve();
+
final TargetPlatform? platform = targetModel == TargetModel.dartdevc
? TargetPlatform.web_javascript
: null;
@@ -334,10 +337,11 @@ class KernelCompiler {
}
commandToStartFrontendServer = <String>[
engineDartAotRuntimePath,
- _artifacts.getArtifactPath(
- Artifact.frontendServerSnapshotForEngineDartSdk,
- platform: platform,
- ),
+ aopdHookConfig.frontendServerSnapshotPath ??
+ _artifacts.getArtifactPath(
+ Artifact.frontendServerSnapshotForEngineDartSdk,
+ platform: platform,
+ ),
];
}
@@ -382,6 +386,11 @@ class KernelCompiler {
'-Dflutter.dart_plugin_registrant=$dartPluginRegistrantUri',
],
if (nativeAssets != null) ...<String>['--native-assets', nativeAssets],
+ if (aopdHookConfig.enabled) ...<String>[
+ '--aop',
+ '1',
+ if (aopdHookConfig.trackWidgetCreation) ...<String>['--aop-track-widget-creation', '1'],
+ ],
// See: https://github.com/flutter/flutter/issues/103994
'--verbosity=error',
...?_filterExtraFrontEndOptions(extraFrontEndOptions),
@@ -389,6 +398,12 @@ class KernelCompiler {
];
_logger.printTrace(command.join(' '));
+ if (aopdHookConfig.enabled) {
+ _logger.printStatus(
+ '[AOPD] Using frontend_server snapshot: ${aopdHookConfig.frontendServerSnapshotPath}',
+ );
+ _logger.printTrace('[AOPD] frontend_server start args: ${command.skip(1).join(' ')}');
+ }
final Process server = await _processManager.start(command);
server.stderr.transform<String>(utf8.decoder).listen(_logger.printError);
@@ -923,6 +938,8 @@ class DefaultResidentCompiler implements ResidentCompiler {
String? additionalSourceUri,
String? nativeAssetsUri,
}) async {
+ final AopdHookConfig aopdHookConfig = await AopdHook.resolve();
+
final TargetPlatform? platform = (targetModel == TargetModel.dartdevc)
? TargetPlatform.web_javascript
: null;
@@ -935,10 +952,11 @@ class DefaultResidentCompiler implements ResidentCompiler {
} else {
commandToStartFrontendServer = <String>[
artifacts.getArtifactPath(Artifact.engineDartAotRuntime, platform: platform),
- artifacts.getArtifactPath(
- Artifact.frontendServerSnapshotForEngineDartSdk,
- platform: platform,
- ),
+ aopdHookConfig.frontendServerSnapshotPath ??
+ artifacts.getArtifactPath(
+ Artifact.frontendServerSnapshotForEngineDartSdk,
+ platform: platform,
+ ),
];
}
@@ -978,11 +996,22 @@ class DefaultResidentCompiler implements ResidentCompiler {
],
if (nativeAssetsUri != null) ...<String>['--native-assets', nativeAssetsUri],
if (platformDill != null) ...<String>['--platform', platformDill!],
+ if (aopdHookConfig.enabled) ...<String>[
+ '--aop',
+ '1',
+ if (aopdHookConfig.trackWidgetCreation) ...<String>['--aop-track-widget-creation', '1'],
+ ],
// See: https://github.com/flutter/flutter/issues/103994
'--verbosity=error',
...?_filterExtraFrontEndOptions(extraFrontEndOptions),
];
_logger.printTrace(command.join(' '));
+ if (aopdHookConfig.enabled) {
+ _logger.printStatus(
+ '[AOPD] Using frontend_server snapshot: ${aopdHookConfig.frontendServerSnapshotPath}',
+ );
+ _logger.printTrace('[AOPD] frontend_server start args: ${command.skip(1).join(' ')}');
+ }
_server = await _processManager.start(command);
_server?.stdout
.transform(utf8LineDecoder)