error_handling_io.dart 25.9 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
// @dart = 2.8

7
import 'dart:convert';
8
import 'dart:io' as io show Directory, File, Link, ProcessException, ProcessResult, ProcessSignal, systemEncoding, Process, ProcessStartMode;
9
import 'dart:typed_data';
10 11 12

import 'package:file/file.dart';
import 'package:meta/meta.dart';
13
import 'package:path/path.dart' as p; // ignore: package_path_import
14
import 'package:process/process.dart';
15

16
import '../reporting/reporting.dart';
17
import 'common.dart' show throwToolExit;
18
import 'platform.dart';
19

20
// The Flutter tool hits file system and process errors that only the end-user can address.
21 22 23 24 25 26 27 28 29 30 31 32 33 34
// We would like these errors to not hit crash logging. In these cases, we
// should exit gracefully and provide potentially useful advice. For example, if
// a write fails because the target device is full, we can explain that with a
// ToolExit and a message that is more clear than the FileSystemException by
// itself.

/// A [FileSystem] that throws a [ToolExit] on certain errors.
///
/// If a [FileSystem] error is not caused by the Flutter tool, and can only be
/// addressed by the user, it should be caught by this [FileSystem] and thrown
/// as a [ToolExit] using [throwToolExit].
///
/// Cf. If there is some hope that the tool can continue when an operation fails
/// with an error, then that error/operation should not be handled here. For
35
/// example, the tool should generally be able to continue executing even if it
36 37
/// fails to delete a file.
class ErrorHandlingFileSystem extends ForwardingFileSystem {
38 39 40 41 42 43 44 45
  ErrorHandlingFileSystem({
    @required FileSystem delegate,
    @required Platform platform,
  }) :
      assert(delegate != null),
      assert(platform != null),
      _platform = platform,
      super(delegate);
46 47 48 49

  @visibleForTesting
  FileSystem get fileSystem => delegate;

50 51
  final Platform _platform;

52 53 54 55 56 57 58 59
  /// Allow any file system operations executed within the closure to fail with any
  /// operating system error, rethrowing an [Exception] instead of a [ToolExit].
  ///
  /// This should not be used with async file system operation.
  ///
  /// This can be used to bypass the [ErrorHandlingFileSystem] permission exit
  /// checks for situations where failure is acceptable, such as the flutter
  /// persistent settings cache.
60
  static void noExitOnFailure(void Function() operation) {
61 62 63
    final bool previousValue = ErrorHandlingFileSystem._noExitOnFailure;
    try {
      ErrorHandlingFileSystem._noExitOnFailure = true;
64
      operation();
65 66 67 68 69
    } finally {
      ErrorHandlingFileSystem._noExitOnFailure = previousValue;
    }
  }

70 71 72
  /// Delete the file or directory and return true if it exists, take no
  /// action and return false if it does not.
  ///
73
  /// This method should be preferred to checking if it exists and
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
  /// then deleting, because it handles the edge case where the file or directory
  /// is deleted by a different program between the two calls.
  static bool deleteIfExists(FileSystemEntity file, {bool recursive = false}) {
    if (!file.existsSync()) {
      return false;
    }
    try {
      file.deleteSync(recursive: recursive);
    } on FileSystemException catch (err) {
      // Certain error codes indicate the file could not be found. It could have
      // been deleted by a different program while the tool was running.
      // if it still exists, the file likely exists on a read-only volume.
      //
      // On windows this is error code 2: ERROR_FILE_NOT_FOUND, and on
      // macOS/Linux it is error code 2/ENOENT: No such file or directory.
      const int kSystemCannotFindFile = 2;
      if (err?.osError?.errorCode != kSystemCannotFindFile || _noExitOnFailure) {
        rethrow;
      }
      if (file.existsSync()) {
        throwToolExit(
          'The Flutter tool tried to delete the file or directory ${file.path} but was '
          'unable to. This may be due to the file and/or project\'s location on a read-only '
          'volume. Consider relocating the project and trying again',
        );
      }
    }
    return true;
  }

104 105
  static bool _noExitOnFailure = false;

106
  @override
107 108 109
  Directory get currentDirectory {
    return _runSync(() =>  directory(delegate.currentDirectory), platform: _platform);
  }
110

111 112 113 114 115 116 117 118 119 120 121 122 123 124
  @override
  File file(dynamic path) => ErrorHandlingFile(
    platform: _platform,
    fileSystem: delegate,
    delegate: delegate.file(path),
  );

  @override
  Directory directory(dynamic path) => ErrorHandlingDirectory(
    platform: _platform,
    fileSystem: delegate,
    delegate: delegate.directory(path),
  );

125
  @override
126 127 128 129 130
  Link link(dynamic path) => ErrorHandlingLink(
    platform: _platform,
    fileSystem: delegate,
    delegate: delegate.link(path),
  );
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

  // Caching the path context here and clearing when the currentDirectory setter
  // is updated works since the flutter tool restricts usage of dart:io directly
  // via the forbidden import tests. Otherwise, the path context's current
  // working directory might get out of sync, leading to unexpected results from
  // methods like `path.relative`.
  @override
  p.Context get path => _cachedPath ??= delegate.path;
  p.Context _cachedPath;

  @override
  set currentDirectory(dynamic path) {
    _cachedPath = null;
    delegate.currentDirectory = path;
  }
146 147 148

  @override
  String toString() => delegate.toString();
149 150 151 152 153
}

class ErrorHandlingFile
    extends ForwardingFileSystemEntity<File, io.File>
    with ForwardingFile {
154 155 156 157 158 159 160 161 162
  ErrorHandlingFile({
    @required Platform platform,
    @required this.fileSystem,
    @required this.delegate,
  }) :
    assert(platform != null),
    assert(fileSystem != null),
    assert(delegate != null),
    _platform = platform;
163 164 165 166 167 168 169

  @override
  final io.File delegate;

  @override
  final FileSystem fileSystem;

170 171
  final Platform _platform;

172
  @override
173 174 175 176 177
  File wrapFile(io.File delegate) => ErrorHandlingFile(
    platform: _platform,
    fileSystem: fileSystem,
    delegate: delegate,
  );
178 179

  @override
180 181 182 183 184
  Directory wrapDirectory(io.Directory delegate) => ErrorHandlingDirectory(
    platform: _platform,
    fileSystem: fileSystem,
    delegate: delegate,
  );
185 186

  @override
187 188 189 190 191
  Link wrapLink(io.Link delegate) => ErrorHandlingLink(
    platform: _platform,
    fileSystem: fileSystem,
    delegate: delegate,
  );
192 193 194 195 196 197 198 199 200 201 202 203 204

  @override
  Future<File> writeAsBytes(
    List<int> bytes, {
    FileMode mode = FileMode.write,
    bool flush = false,
  }) async {
    return _run<File>(
      () async => wrap(await delegate.writeAsBytes(
        bytes,
        mode: mode,
        flush: flush,
      )),
205
      platform: _platform,
206 207 208 209
      failureMessage: 'Flutter failed to write to a file at "${delegate.path}"',
    );
  }

210 211 212 213 214 215 216 217 218
  @override
  String readAsStringSync({Encoding encoding = utf8}) {
    return _runSync<String>(
      () => delegate.readAsStringSync(),
      platform: _platform,
      failureMessage: 'Flutter failed to read a file at "${delegate.path}"',
    );
  }

219 220 221 222 223 224 225 226
  @override
  void writeAsBytesSync(
    List<int> bytes, {
    FileMode mode = FileMode.write,
    bool flush = false,
  }) {
    _runSync<void>(
      () => delegate.writeAsBytesSync(bytes, mode: mode, flush: flush),
227
      platform: _platform,
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
      failureMessage: 'Flutter failed to write to a file at "${delegate.path}"',
    );
  }

  @override
  Future<File> writeAsString(
    String contents, {
    FileMode mode = FileMode.write,
    Encoding encoding = utf8,
    bool flush = false,
  }) async {
    return _run<File>(
      () async => wrap(await delegate.writeAsString(
        contents,
        mode: mode,
        encoding: encoding,
        flush: flush,
      )),
246
      platform: _platform,
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
      failureMessage: 'Flutter failed to write to a file at "${delegate.path}"',
    );
  }

  @override
  void writeAsStringSync(
    String contents, {
    FileMode mode = FileMode.write,
    Encoding encoding = utf8,
    bool flush = false,
  }) {
    _runSync<void>(
      () => delegate.writeAsStringSync(
        contents,
        mode: mode,
        encoding: encoding,
        flush: flush,
      ),
265
      platform: _platform,
266 267 268 269
      failureMessage: 'Flutter failed to write to a file at "${delegate.path}"',
    );
  }

270 271 272 273 274 275 276 277 278 279 280
  @override
  void createSync({bool recursive = false}) {
    _runSync<void>(
      () => delegate.createSync(
        recursive: recursive,
      ),
      platform: _platform,
      failureMessage: 'Flutter failed to create file at "${delegate.path}"',
    );
  }

281 282 283 284 285 286 287 288 289 290 291
  @override
  RandomAccessFile openSync({FileMode mode = FileMode.read}) {
    return _runSync<RandomAccessFile>(
      () => delegate.openSync(
        mode: mode,
      ),
      platform: _platform,
      failureMessage: 'Flutter failed to open a file at "${delegate.path}"',
    );
  }

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  /// This copy method attempts to handle file system errors from both reading
  /// and writing the copied file.
  @override
  File copySync(String newPath) {
    final File resultFile = fileSystem.file(newPath);
    // First check if the source file can be read. If not, bail through error
    // handling.
    _runSync<void>(
      () => delegate.openSync(mode: FileMode.read).closeSync(),
      platform: _platform,
      failureMessage: 'Flutter failed to copy $path to $newPath due to source location error'
    );
    // Next check if the destination file can be written. If not, bail through
    // error handling.
    _runSync<void>(
307
      () => resultFile.createSync(recursive: true),
308
      platform: _platform,
Pierre-Louis's avatar
Pierre-Louis committed
309
      failureMessage: 'Flutter failed to copy $path to $newPath due to destination location error'
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
    );
    // If both of the above checks passed, attempt to copy the file and catch
    // any thrown errors.
    try {
      return wrapFile(delegate.copySync(newPath));
    } on FileSystemException {
      // Proceed below
    }
    // If the copy failed but both of the above checks passed, copy the bytes
    // directly.
    _runSync(() {
      RandomAccessFile source;
      RandomAccessFile sink;
      try {
        source = delegate.openSync(mode: FileMode.read);
        sink = resultFile.openSync(mode: FileMode.writeOnly);
        // 64k is the same sized buffer used by dart:io for `File.openRead`.
        final Uint8List buffer = Uint8List(64 * 1024);
        final int totalBytes = source.lengthSync();
        int bytes = 0;
        while (bytes < totalBytes) {
          final int chunkLength = source.readIntoSync(buffer);
          sink.writeFromSync(buffer, 0, chunkLength);
          bytes += chunkLength;
        }
      } catch (err) { // ignore: avoid_catches_without_on_clauses
        ErrorHandlingFileSystem.deleteIfExists(resultFile, recursive: true);
        rethrow;
      } finally {
        source?.closeSync();
        sink?.closeSync();
      }
    }, platform: _platform, failureMessage: 'Flutter failed to copy $path to $newPath due to unknown error');
    // The original copy failed, but the manual copy worked. Report an analytics event to
    // track this to determine if this code path is actually hit.
    ErrorHandlingEvent('copy-fallback').send();
    return wrapFile(resultFile);
  }

349 350
  @override
  String toString() => delegate.toString();
351 352 353 354 355
}

class ErrorHandlingDirectory
    extends ForwardingFileSystemEntity<Directory, io.Directory>
    with ForwardingDirectory<Directory> {
356 357 358 359 360 361 362 363 364
  ErrorHandlingDirectory({
    @required Platform platform,
    @required this.fileSystem,
    @required this.delegate,
  }) :
    assert(platform != null),
    assert(fileSystem != null),
    assert(delegate != null),
    _platform = platform;
365 366 367 368 369 370 371

  @override
  final io.Directory delegate;

  @override
  final FileSystem fileSystem;

372 373
  final Platform _platform;

374
  @override
375 376 377 378 379
  File wrapFile(io.File delegate) => ErrorHandlingFile(
    platform: _platform,
    fileSystem: fileSystem,
    delegate: delegate,
  );
380 381

  @override
382 383 384 385 386
  Directory wrapDirectory(io.Directory delegate) => ErrorHandlingDirectory(
    platform: _platform,
    fileSystem: fileSystem,
    delegate: delegate,
  );
387 388

  @override
389 390 391 392 393
  Link wrapLink(io.Link delegate) => ErrorHandlingLink(
    platform: _platform,
    fileSystem: fileSystem,
    delegate: delegate,
  );
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

  // For the childEntity methods, we first obtain an instance of the entity
  // from the underlying file system, then invoke childEntity() on it, then
  // wrap in the ErrorHandling version.
  @override
  Directory childDirectory(String basename) =>
    wrapDirectory(fileSystem.directory(delegate).childDirectory(basename));

  @override
  File childFile(String basename) =>
    wrapFile(fileSystem.directory(delegate).childFile(basename));

  @override
  Link childLink(String basename) =>
    wrapLink(fileSystem.directory(delegate).childLink(basename));
409

410 411 412 413 414 415 416 417 418 419
  @override
  void createSync({bool recursive = false}) {
    return _runSync<void>(
      () => delegate.createSync(recursive: recursive),
      platform: _platform,
      failureMessage:
        'Flutter failed to create a directory at "${delegate.path}"',
    );
  }

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
  @override
  Future<Directory> createTemp([String prefix]) {
    return _run<Directory>(
      () async => wrap(await delegate.createTemp(prefix)),
      platform: _platform,
      failureMessage:
        'Flutter failed to create a temporary directory with prefix "$prefix"',
    );
  }

  @override
  Directory createTempSync([String prefix]) {
    return _runSync<Directory>(
      () => wrap(delegate.createTempSync(prefix)),
      platform: _platform,
      failureMessage:
        'Flutter failed to create a temporary directory with prefix "$prefix"',
    );
  }

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
  @override
  Future<Directory> create({bool recursive = false}) {
    return _run<Directory>(
      () async => wrap(await delegate.create(recursive: recursive)),
      platform: _platform,
      failureMessage:
        'Flutter failed to create a directory at "${delegate.path}"',
    );
  }

  @override
  Future<Directory> delete({bool recursive = false}) {
    return _run<Directory>(
      () async => wrap(fileSystem.directory((await delegate.delete(recursive: recursive)).path)),
      platform: _platform,
      failureMessage:
        'Flutter failed to delete a directory at "${delegate.path}"',
    );
  }

  @override
  void deleteSync({bool recursive = false}) {
    return _runSync<void>(
      () => delegate.deleteSync(recursive: recursive),
      platform: _platform,
      failureMessage:
        'Flutter failed to delete a directory at "${delegate.path}"',
    );
  }

470 471 472 473 474 475 476 477 478 479
  @override
  bool existsSync() {
    return _runSync<bool>(
      () => delegate.existsSync(),
      platform: _platform,
      failureMessage:
        'Flutter failed to check for directory existence at "${delegate.path}"',
    );
  }

480 481
  @override
  String toString() => delegate.toString();
482 483 484 485 486
}

class ErrorHandlingLink
    extends ForwardingFileSystemEntity<Link, io.Link>
    with ForwardingLink {
487 488 489 490 491 492 493 494 495
  ErrorHandlingLink({
    @required Platform platform,
    @required this.fileSystem,
    @required this.delegate,
  }) :
    assert(platform != null),
    assert(fileSystem != null),
    assert(delegate != null),
    _platform = platform;
496 497 498 499 500 501 502

  @override
  final io.Link delegate;

  @override
  final FileSystem fileSystem;

503 504
  final Platform _platform;

505
  @override
506 507 508 509 510
  File wrapFile(io.File delegate) => ErrorHandlingFile(
    platform: _platform,
    fileSystem: fileSystem,
    delegate: delegate,
  );
511 512

  @override
513 514 515 516 517
  Directory wrapDirectory(io.Directory delegate) => ErrorHandlingDirectory(
    platform: _platform,
    fileSystem: fileSystem,
    delegate: delegate,
  );
518 519

  @override
520 521 522 523 524
  Link wrapLink(io.Link delegate) => ErrorHandlingLink(
    platform: _platform,
    fileSystem: fileSystem,
    delegate: delegate,
  );
525 526 527

  @override
  String toString() => delegate.toString();
528
}
529 530 531 532 533 534 535 536 537 538

Future<T> _run<T>(Future<T> Function() op, {
  @required Platform platform,
  String failureMessage,
}) async {
  assert(platform != null);
  try {
    return await op();
  } on FileSystemException catch (e) {
    if (platform.isWindows) {
539
      _handleWindowsException(e, failureMessage, e.osError?.errorCode ?? 0);
540 541
    } else if (platform.isLinux || platform.isMacOS) {
      _handlePosixException(e, failureMessage, e.osError?.errorCode ?? 0);
542 543 544 545 546
    }
    rethrow;
  } on io.ProcessException catch (e) {
    if (platform.isWindows) {
      _handleWindowsException(e, failureMessage, e.errorCode ?? 0);
547 548
    } else if (platform.isLinux || platform.isMacOS) {
      _handlePosixException(e, failureMessage, e.errorCode ?? 0);
549 550 551 552 553 554 555 556 557 558 559 560 561 562
    }
    rethrow;
  }
}

T _runSync<T>(T Function() op, {
  @required Platform platform,
  String failureMessage,
}) {
  assert(platform != null);
  try {
    return op();
  } on FileSystemException catch (e) {
    if (platform.isWindows) {
563
      _handleWindowsException(e, failureMessage, e.osError?.errorCode ?? 0);
564 565
    } else if (platform.isLinux || platform.isMacOS) {
      _handlePosixException(e, failureMessage, e.osError?.errorCode ?? 0);
566 567 568 569 570
    }
    rethrow;
  } on io.ProcessException catch (e) {
    if (platform.isWindows) {
      _handleWindowsException(e, failureMessage, e.errorCode ?? 0);
571 572
    } else if (platform.isLinux || platform.isMacOS) {
      _handlePosixException(e, failureMessage, e.errorCode ?? 0);
573 574 575 576 577
    }
    rethrow;
  }
}

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
class _ProcessDelegate {
  const _ProcessDelegate();

  Future<io.Process> start(
    List<String> command, {
    String workingDirectory,
    Map<String, String> environment,
    bool includeParentEnvironment = true,
    bool runInShell = false,
    io.ProcessStartMode mode = io.ProcessStartMode.normal,
  }) {
    return io.Process.start(
      command[0],
      command.skip(1).toList(),
      workingDirectory: workingDirectory,
      environment: environment,
      includeParentEnvironment: includeParentEnvironment,
      runInShell: runInShell,
    );
  }

  Future<io.ProcessResult> run(
    List<String> command, {
    String workingDirectory,
    Map<String, String> environment,
    bool includeParentEnvironment = true,
    bool runInShell = false,
    Encoding stdoutEncoding = io.systemEncoding,
    Encoding stderrEncoding = io.systemEncoding,
  }) {
    return io.Process.run(
      command[0],
      command.skip(1).toList(),
      workingDirectory: workingDirectory,
      environment: environment,
      includeParentEnvironment: includeParentEnvironment,
      runInShell: runInShell,
      stdoutEncoding: stdoutEncoding,
      stderrEncoding: stderrEncoding,
    );
  }

  io.ProcessResult runSync(
    List<String> command, {
    String workingDirectory,
    Map<String, String> environment,
    bool includeParentEnvironment = true,
    bool runInShell = false,
    Encoding stdoutEncoding = io.systemEncoding,
    Encoding stderrEncoding = io.systemEncoding,
  }) {
    return io.Process.runSync(
      command[0],
      command.skip(1).toList(),
      workingDirectory: workingDirectory,
      environment: environment,
      includeParentEnvironment: includeParentEnvironment,
      runInShell: runInShell,
      stdoutEncoding: stdoutEncoding,
      stderrEncoding: stderrEncoding,
    );
  }
}

642 643 644 645 646 647 648
/// A [ProcessManager] that throws a [ToolExit] on certain errors.
///
/// If a [ProcessException] is not caused by the Flutter tool, and can only be
/// addressed by the user, it should be caught by this [ProcessManager] and thrown
/// as a [ToolExit] using [throwToolExit].
///
/// See also:
649
///   * [ErrorHandlingFileSystem], for a similar file system strategy.
650
class ErrorHandlingProcessManager extends ProcessManager {
651
  ErrorHandlingProcessManager({
652
    @required ProcessManager delegate,
653
    @required Platform platform,
654 655
  }) : _delegate = delegate,
       _platform = platform;
656

657 658
  final ProcessManager _delegate;
  final Platform _platform;
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
  static const _ProcessDelegate _processDelegate = _ProcessDelegate();
  static bool _skipCommandLookup = false;

  /// Bypass package:process command lookup for all functions in this block.
  ///
  /// This required that the fully resolved executable path is provided.
  static Future<T> skipCommandLookup<T>(Future<T> Function() operation) async {
    final bool previousValue = ErrorHandlingProcessManager._skipCommandLookup;
    try {
      ErrorHandlingProcessManager._skipCommandLookup = true;
      return await operation();
    } finally {
      ErrorHandlingProcessManager._skipCommandLookup = previousValue;
    }
  }
674 675

  @override
676
  bool canRun(dynamic executable, {String workingDirectory}) {
677 678
    return _runSync(
      () => _delegate.canRun(executable, workingDirectory: workingDirectory),
679 680 681 682 683
      platform: _platform,
    );
  }

  @override
684
  bool killPid(int pid, [io.ProcessSignal signal = io.ProcessSignal.sigterm]) {
685 686
    return _runSync(
      () => _delegate.killPid(pid, signal),
687 688 689 690 691 692
      platform: _platform,
    );
  }

  @override
  Future<io.ProcessResult> run(
693
    List<dynamic> command, {
694 695 696 697 698 699 700
    String workingDirectory,
    Map<String, String> environment,
    bool includeParentEnvironment = true,
    bool runInShell = false,
    Encoding stdoutEncoding = io.systemEncoding,
    Encoding stderrEncoding = io.systemEncoding,
  }) {
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    return _run(() {
      if (_skipCommandLookup && _delegate is LocalProcessManager) {
       return _processDelegate.run(
          command.cast<String>(),
          workingDirectory: workingDirectory,
          environment: environment,
          includeParentEnvironment: includeParentEnvironment,
          runInShell: runInShell,
          stdoutEncoding: stdoutEncoding,
          stderrEncoding: stderrEncoding,
        );
      }
      return _delegate.run(
        command,
        workingDirectory: workingDirectory,
        environment: environment,
        includeParentEnvironment: includeParentEnvironment,
        runInShell: runInShell,
        stdoutEncoding: stdoutEncoding,
        stderrEncoding: stderrEncoding,
      );
    }, platform: _platform);
723 724 725 726
  }

  @override
  Future<io.Process> start(
727
    List<dynamic> command, {
728 729 730 731 732 733
    String workingDirectory,
    Map<String, String> environment,
    bool includeParentEnvironment = true,
    bool runInShell = false,
    io.ProcessStartMode mode = io.ProcessStartMode.normal,
  }) {
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
    return _run(() {
      if (_skipCommandLookup && _delegate is LocalProcessManager) {
        return _processDelegate.start(
          command.cast<String>(),
          workingDirectory: workingDirectory,
          environment: environment,
          includeParentEnvironment: includeParentEnvironment,
          runInShell: runInShell,
        );
      }
      return _delegate.start(
        command,
        workingDirectory: workingDirectory,
        environment: environment,
        includeParentEnvironment: includeParentEnvironment,
        runInShell: runInShell,
      );
    }, platform: _platform);
752 753 754 755
  }

  @override
  io.ProcessResult runSync(
756
    List<dynamic> command, {
757 758 759 760 761 762 763
    String workingDirectory,
    Map<String, String> environment,
    bool includeParentEnvironment = true,
    bool runInShell = false,
    Encoding stdoutEncoding = io.systemEncoding,
    Encoding stderrEncoding = io.systemEncoding,
  }) {
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
    return _runSync(() {
      if (_skipCommandLookup && _delegate is LocalProcessManager) {
        return _processDelegate.runSync(
          command.cast<String>(),
          workingDirectory: workingDirectory,
          environment: environment,
          includeParentEnvironment: includeParentEnvironment,
          runInShell: runInShell,
          stdoutEncoding: stdoutEncoding,
          stderrEncoding: stderrEncoding,
        );
      }
      return _delegate.runSync(
        command,
        workingDirectory: workingDirectory,
        environment: environment,
        includeParentEnvironment: includeParentEnvironment,
        runInShell: runInShell,
        stdoutEncoding: stdoutEncoding,
        stderrEncoding: stderrEncoding,
      );
    }, platform: _platform);
786 787 788
  }
}

789
void _handlePosixException(Exception e, String message, int errorCode) {
790 791 792
  // From:
  // https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/errno.h
  // https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/errno-base.h
793
  // https://github.com/apple/darwin-xnu/blob/master/bsd/dev/dtrace/scripts/errno.d
794
  const int eperm = 1;
795
  const int enospc = 28;
796
  const int eacces = 13;
797
  // Catch errors and bail when:
798
  String errorMessage;
799 800
  switch (errorCode) {
    case enospc:
801
      errorMessage =
802 803
        '$message. The target device is full.'
        '\n$e\n'
804
        'Free up space and try again.';
805
      break;
806
    case eperm:
807
    case eacces:
808
      errorMessage =
809
        '$message. The flutter tool cannot access the file or directory.\n'
810
        'Please ensure that the SDK and/or project is installed in a location '
811
        'that has read/write permissions for the current user.';
812
      break;
813 814 815 816
    default:
      // Caller must rethrow the exception.
      break;
  }
817
  _throwFileSystemException(errorMessage);
818 819
}

820
void _handleWindowsException(Exception e, String message, int errorCode) {
821 822 823 824
  // From:
  // https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes
  const int kDeviceFull = 112;
  const int kUserMappedSectionOpened = 1224;
825
  const int kAccessDenied = 5;
826 827
  const int kFatalDeviceHardwareError = 483;

828
  // Catch errors and bail when:
829
  String errorMessage;
830
  switch (errorCode) {
831
    case kAccessDenied:
832
      errorMessage =
833
        '$message. The flutter tool cannot access the file or directory.\n'
834
        'Please ensure that the SDK and/or project is installed in a location '
835
        'that has read/write permissions for the current user.';
836
      break;
837
    case kDeviceFull:
838
      errorMessage =
839 840
        '$message. The target device is full.'
        '\n$e\n'
841
        'Free up space and try again.';
842 843
      break;
    case kUserMappedSectionOpened:
844
      errorMessage =
845 846 847
        '$message. The file is being used by another program.'
        '\n$e\n'
        'Do you have an antivirus program running? '
848
        'Try disabling your antivirus program and try again.';
849
      break;
850 851 852 853 854
    case kFatalDeviceHardwareError:
      errorMessage =
        '$message. There is a problem with the device driver '
        'that this file or directory is stored on.';
      break;
855 856 857 858
    default:
      // Caller must rethrow the exception.
      break;
  }
859 860 861 862 863 864 865 866 867 868 869
  _throwFileSystemException(errorMessage);
}

void _throwFileSystemException(String errorMessage) {
  if (errorMessage == null) {
    return;
  }
  if (ErrorHandlingFileSystem._noExitOnFailure) {
    throw Exception(errorMessage);
  }
  throwToolExit(errorMessage);
870
}