|
| 1 | +// Copyright 2014 The Flutter Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +/// @docImport '../xcode_project.dart'; |
| 6 | +library; |
| 7 | + |
| 8 | +import 'dart:async'; |
| 9 | + |
| 10 | +import '../base/io.dart'; |
| 11 | +import '../base/logger.dart'; |
| 12 | +import '../base/process.dart'; |
| 13 | +import '../convert.dart'; |
| 14 | + |
| 15 | +/// LLDB is the default debugger in Xcode on macOS. Once the application has |
| 16 | +/// launched on a physical iOS device, you can attach to it using LLDB. |
| 17 | +/// |
| 18 | +/// See `xcrun devicectl device process launch --help` for more information. |
| 19 | +class LLDB { |
| 20 | + LLDB({required Logger logger, required ProcessUtils processUtils}) |
| 21 | + : _logger = logger, |
| 22 | + _processUtils = processUtils; |
| 23 | + |
| 24 | + final Logger _logger; |
| 25 | + final ProcessUtils _processUtils; |
| 26 | + |
| 27 | + _LLDBProcess? _lldbProcess; |
| 28 | + |
| 29 | + /// Whether or not a LLDB process is running. |
| 30 | + bool get isRunning => _lldbProcess != null; |
| 31 | + |
| 32 | + /// The process id of the application running on the iOS device. |
| 33 | + int? get appProcessId => _lldbProcess?.appProcessId; |
| 34 | + |
| 35 | + _LLDBLogPatternCompleter? _logCompleter; |
| 36 | + |
| 37 | + /// Pattern of lldb log when the process is stopped. |
| 38 | + /// |
| 39 | + /// Example: (lldb) Process 6152 stopped |
| 40 | + static final _lldbProcessStopped = RegExp(r'Process \d* stopped'); |
| 41 | + |
| 42 | + /// Pattern of lldb log when the process is resuming. |
| 43 | + /// |
| 44 | + /// Example: (lldb) Process 6152 resuming |
| 45 | + static final _lldbProcessResuming = RegExp(r'Process \d+ resuming'); |
| 46 | + |
| 47 | + /// Pattern of lldb log when the breakpoint is added. |
| 48 | + /// |
| 49 | + /// Example: Breakpoint 1: no locations (pending). |
| 50 | + static final _breakpointPattern = RegExp(r'Breakpoint (\d+)*:'); |
| 51 | + |
| 52 | + /// Breakpoint script required for JIT on iOS. |
| 53 | + /// |
| 54 | + /// This should match the "handle_new_rx_page" function in [IosProject._lldbPythonHelperTemplate]. |
| 55 | + static const _pythonScript = ''' |
| 56 | +"""Intercept NOTIFY_DEBUGGER_ABOUT_RX_PAGES and touch the pages.""" |
| 57 | +base = frame.register["x0"].GetValueAsAddress() |
| 58 | +page_len = frame.register["x1"].GetValueAsUnsigned() |
| 59 | +
|
| 60 | +# Note: NOTIFY_DEBUGGER_ABOUT_RX_PAGES will check contents of the |
| 61 | +# first page to see if handled it correctly. This makes diagnosing |
| 62 | +# misconfiguration (e.g. missing breakpoint) easier. |
| 63 | +data = bytearray(page_len) |
| 64 | +data[0:8] = b'IHELPED!' |
| 65 | +
|
| 66 | +error = lldb.SBError() |
| 67 | +frame.GetThread().GetProcess().WriteMemory(base, data, error) |
| 68 | +if not error.Success(): |
| 69 | + print(f'Failed to write into {base}[+{page_len}]', error) |
| 70 | + return |
| 71 | +
|
| 72 | +# If the returned value is False, that tells LLDB not to stop at the breakpoint |
| 73 | +return False |
| 74 | +'''; |
| 75 | + |
| 76 | + /// Starts an LLDB process and inputs commands to start debugging the [appProcessId]. |
| 77 | + /// This will start a debugserver on the device, which is required for JIT. |
| 78 | + Future<bool> attachAndStart(String deviceId, int appProcessId) async { |
| 79 | + Timer? timer; |
| 80 | + try { |
| 81 | + timer = Timer(const Duration(minutes: 1), () { |
| 82 | + _logger.printError( |
| 83 | + 'LLDB is taking longer than expected to start debugging the app. ' |
| 84 | + "LLDB debugging can be disabled for the project by adding the following in the project's pubspec.yaml:\n" |
| 85 | + 'flutter:\n' |
| 86 | + ' config:\n' |
| 87 | + ' enable-lldb-debugging: false\n' |
| 88 | + 'Or disable LLDB debugging globally with the following command:\n' |
| 89 | + ' "flutter config --no-enable-lldb-debugging"', |
| 90 | + ); |
| 91 | + }); |
| 92 | + |
| 93 | + final bool start = await _startLLDB(appProcessId); |
| 94 | + if (!start) { |
| 95 | + return false; |
| 96 | + } |
| 97 | + await _selectDevice(deviceId); |
| 98 | + await _setBreakpoint(); |
| 99 | + await _attachToAppProcess(appProcessId); |
| 100 | + await _resumeProcess(); |
| 101 | + } on _LLDBError catch (e) { |
| 102 | + _logger.printError('lldb failed with error: ${e.message}'); |
| 103 | + exit(); |
| 104 | + return false; |
| 105 | + } finally { |
| 106 | + timer?.cancel(); |
| 107 | + } |
| 108 | + return true; |
| 109 | + } |
| 110 | + |
| 111 | + /// Starts LLDB process and leave it running. |
| 112 | + /// |
| 113 | + /// Streams `stdout` and `stderr`. When receiving a log from `stdout`, check |
| 114 | + /// if it matches the pattern [_logCompleter] is waiting for. If a log is sent |
| 115 | + /// to `stderr`, complete with an error and stop the process. |
| 116 | + Future<bool> _startLLDB(int appProcessId) async { |
| 117 | + if (_lldbProcess != null) { |
| 118 | + _logger.printError( |
| 119 | + 'An LLDB process is already running. It must be stopped before starting a new one.', |
| 120 | + ); |
| 121 | + return false; |
| 122 | + } |
| 123 | + try { |
| 124 | + _lldbProcess = _LLDBProcess( |
| 125 | + process: await _processUtils.start(<String>['lldb']), |
| 126 | + appProcessId: appProcessId, |
| 127 | + logger: _logger, |
| 128 | + ); |
| 129 | + |
| 130 | + final StreamSubscription<String> stdoutSubscription = _lldbProcess!.stdout |
| 131 | + .transform<String>(utf8.decoder) |
| 132 | + .transform<String>(const LineSplitter()) |
| 133 | + .listen((String line) { |
| 134 | + _logger.printTrace('[lldb]: $line'); |
| 135 | + _logCompleter?.checkForMatch(line); |
| 136 | + }); |
| 137 | + |
| 138 | + final StreamSubscription<String> stderrSubscription = _lldbProcess!.stderr |
| 139 | + .transform<String>(utf8.decoder) |
| 140 | + .transform<String>(const LineSplitter()) |
| 141 | + .listen((String line) { |
| 142 | + _logger.printError('[lldb]: $line'); |
| 143 | + _monitorError(line); |
| 144 | + }); |
| 145 | + |
| 146 | + unawaited( |
| 147 | + _lldbProcess!.exitCode |
| 148 | + .then((int status) async { |
| 149 | + _logger.printTrace('lldb exited with code $status'); |
| 150 | + await stdoutSubscription.cancel(); |
| 151 | + await stderrSubscription.cancel(); |
| 152 | + }) |
| 153 | + .whenComplete(() async { |
| 154 | + _lldbProcess = null; |
| 155 | + }), |
| 156 | + ); |
| 157 | + } on ProcessException catch (exception) { |
| 158 | + _logger.printError('Process exception running lldb:\n$exception'); |
| 159 | + return false; |
| 160 | + } |
| 161 | + return true; |
| 162 | + } |
| 163 | + |
| 164 | + /// Kill [_lldbProcess] if available and set it to null. |
| 165 | + bool exit() { |
| 166 | + final bool success = (_lldbProcess == null) || _lldbProcess!.kill(); |
| 167 | + _lldbProcess = null; |
| 168 | + _logCompleter = null; |
| 169 | + return success; |
| 170 | + } |
| 171 | + |
| 172 | + /// Selects a device for LLDB to interact with. |
| 173 | + Future<void> _selectDevice(String deviceId) async { |
| 174 | + await _lldbProcess?.stdinWriteln('device select $deviceId'); |
| 175 | + } |
| 176 | + |
| 177 | + /// Attaches LLDB to the [appProcessId] running on the device. |
| 178 | + Future<void> _attachToAppProcess(int appProcessId) async { |
| 179 | + // Since the app starts stopped (--start-stopped), we expect a stopped state |
| 180 | + // after attaching. |
| 181 | + final Future<String> futureLog = _startWaitingForLog( |
| 182 | + _lldbProcessStopped, |
| 183 | + ).then((value) => value, onError: _handleAsyncError); |
| 184 | + |
| 185 | + await _lldbProcess?.stdinWriteln('device process attach --pid $appProcessId'); |
| 186 | + await futureLog; |
| 187 | + } |
| 188 | + |
| 189 | + /// Sets a breakpoint, waits for it print the breakpoint id, and adds a python |
| 190 | + /// script command to be executed whenever the breakpoint is hit. |
| 191 | + Future<void> _setBreakpoint() async { |
| 192 | + final Future<String> futureLog = _startWaitingForLog( |
| 193 | + _breakpointPattern, |
| 194 | + ).then((value) => value, onError: _handleAsyncError); |
| 195 | + |
| 196 | + await _lldbProcess?.stdinWriteln( |
| 197 | + r"breakpoint set --func-regex '^NOTIFY_DEBUGGER_ABOUT_RX_PAGES$'", |
| 198 | + ); |
| 199 | + final String log = await futureLog; |
| 200 | + final Match? match = _breakpointPattern.firstMatch(log); |
| 201 | + final String? breakpointId = match?.group(1); |
| 202 | + if (breakpointId == null) { |
| 203 | + throw _LLDBError('LLDB failed to get breakpoint from log: $log'); |
| 204 | + } |
| 205 | + |
| 206 | + // Once it has the breakpoint id, set the python script. |
| 207 | + // For more information, see: lldb > help break command add |
| 208 | + await _lldbProcess?.stdinWriteln('breakpoint command add --script-type python $breakpointId'); |
| 209 | + await _lldbProcess?.stdinWriteln(_pythonScript); |
| 210 | + await _lldbProcess?.stdinWriteln('DONE'); |
| 211 | + } |
| 212 | + |
| 213 | + /// Resume the stopped process. |
| 214 | + Future<void> _resumeProcess() async { |
| 215 | + final Future<String> futureLog = _startWaitingForLog( |
| 216 | + _lldbProcessResuming, |
| 217 | + ).then((value) => value, onError: _handleAsyncError); |
| 218 | + |
| 219 | + await _lldbProcess?.stdinWriteln('process continue'); |
| 220 | + await futureLog; |
| 221 | + } |
| 222 | + |
| 223 | + /// Creates a completer and returns its future. Methods that utilize this should |
| 224 | + /// start waiting for the log before writing to stdin to avoid race conditions. |
| 225 | + /// |
| 226 | + /// When the [_lldbProcess]'s `stdout` receives a log that matches the [pattern], |
| 227 | + /// the future will complete. |
| 228 | + Future<String> _startWaitingForLog(RegExp pattern) async { |
| 229 | + if (_lldbProcess == null) { |
| 230 | + throw _LLDBError('LLDB is not running.'); |
| 231 | + } |
| 232 | + _logCompleter = _LLDBLogPatternCompleter(pattern); |
| 233 | + return _logCompleter!.future; |
| 234 | + } |
| 235 | + |
| 236 | + Future<String> _handleAsyncError(Object error) async { |
| 237 | + if (error is _LLDBError) { |
| 238 | + throw error; |
| 239 | + } |
| 240 | + throw _LLDBError('Unexpected error when waiting for lldb.'); |
| 241 | + } |
| 242 | + |
| 243 | + /// Checks if [error] is a fatal error and stops the process if so. |
| 244 | + void _monitorError(String error) { |
| 245 | + // The LLDB process does not stop when it receives these errors but is no |
| 246 | + // longer debugging the application. When one of these errors is received, |
| 247 | + // stop the LLDB process. |
| 248 | + final fatalErrors = <String>[ |
| 249 | + "error: 'device' is not a valid command.", |
| 250 | + "no device selected: use 'device select <identifier>' to select a device.", |
| 251 | + 'The specified device was not found.', |
| 252 | + 'Timeout while connecting to remote device.', |
| 253 | + 'Internal logic error: Connection was invalidated', |
| 254 | + ]; |
| 255 | + |
| 256 | + if (fatalErrors.contains(error)) { |
| 257 | + _logCompleter?.completeError(_LLDBError(error)); |
| 258 | + exit(); |
| 259 | + } |
| 260 | + } |
| 261 | +} |
| 262 | + |
| 263 | +class _LLDBError implements Exception { |
| 264 | + _LLDBError(this.message); |
| 265 | + |
| 266 | + final String message; |
| 267 | +} |
| 268 | + |
| 269 | +/// A completer that waits for a log line to match a pattern. |
| 270 | +class _LLDBLogPatternCompleter { |
| 271 | + _LLDBLogPatternCompleter(this._pattern); |
| 272 | + |
| 273 | + final RegExp _pattern; |
| 274 | + final _completer = Completer<String>(); |
| 275 | + |
| 276 | + Future<String> get future => _completer.future; |
| 277 | + |
| 278 | + void checkForMatch(String line) { |
| 279 | + if (_completer.isCompleted) { |
| 280 | + return; |
| 281 | + } |
| 282 | + if (_pattern.hasMatch(line)) { |
| 283 | + _completer.complete(line); |
| 284 | + } |
| 285 | + } |
| 286 | + |
| 287 | + void completeError(Object error, [StackTrace? stackTrace]) { |
| 288 | + if (!_completer.isCompleted) { |
| 289 | + _completer.completeError(error, stackTrace); |
| 290 | + } |
| 291 | + } |
| 292 | +} |
| 293 | + |
| 294 | +/// A container class for associating a [Process] that is is running LLDB with |
| 295 | +/// the iOS device process of an application. |
| 296 | +class _LLDBProcess { |
| 297 | + _LLDBProcess({required Process process, required this.appProcessId, required Logger logger}) |
| 298 | + : _lldbProcess = process, |
| 299 | + _logger = logger; |
| 300 | + |
| 301 | + final Process _lldbProcess; |
| 302 | + final int appProcessId; |
| 303 | + |
| 304 | + final Logger _logger; |
| 305 | + |
| 306 | + Stream<List<int>> get stdout => _lldbProcess.stdout; |
| 307 | + |
| 308 | + Stream<List<int>> get stderr => _lldbProcess.stderr; |
| 309 | + |
| 310 | + Future<int> get exitCode => _lldbProcess.exitCode; |
| 311 | + |
| 312 | + Future<void>? _stdinWriteFuture; |
| 313 | + |
| 314 | + bool kill() { |
| 315 | + return _lldbProcess.kill(); |
| 316 | + } |
| 317 | + |
| 318 | + /// Writes [line] to [_lldbProcess]'s `stdin` and catches exceptions |
| 319 | + /// (see https://github.com/flutter/flutter/pull/139784). |
| 320 | + Future<void> stdinWriteln(String line, {void Function(Object, StackTrace)? onError}) async { |
| 321 | + Future<void> writeln() { |
| 322 | + return ProcessUtils.writelnToStdinGuarded( |
| 323 | + stdin: _lldbProcess.stdin, |
| 324 | + line: line, |
| 325 | + onError: |
| 326 | + onError ?? |
| 327 | + (Object error, _) { |
| 328 | + _logger.printTrace('Could not write "$line" to stdin: $error'); |
| 329 | + }, |
| 330 | + ); |
| 331 | + } |
| 332 | + |
| 333 | + _stdinWriteFuture = _stdinWriteFuture?.then<void>((_) => writeln()) ?? writeln(); |
| 334 | + return _stdinWriteFuture; |
| 335 | + } |
| 336 | +} |
0 commit comments