Skip to content

[flutter_tools] Do not crash if buildXcodeProject temporary directory is deleted before cleanup - #195918

Open
bkonyi wants to merge 8 commits into
flutter:masterfrom
bkonyi:fix-xcode-build-temp-dir-delete
Open

bkonyi wants to merge 8 commits into
flutter:masterfrom
bkonyi:fix-xcode-build-temp-dir-delete

Conversation

@bkonyi

@bkonyi bkonyi commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

In buildXcodeProject, fs.systemTempDirectory.createTempSync('flutter_ios_build_temp_dir') creates a temporary directory under the per-invocation LocalFileSystem temp root. If that temporary directory is deleted before buildXcodeProject finishes (for example, by LocalFileSystem's fatal-signal temp cleanup on SIGINT/SIGTERM or external cleanup while xcodebuild is running), listenToScriptOutputLine(), scriptOutputPipeFile?.writeAsStringSync('all done'), and the finally block's tempDir.deleteSync(recursive: true) throw an unhandled PathNotFoundException or ToolExit.

This change:

  • Guards listenToScriptOutputLine() with if (!scriptOutputPipeFile!.existsSync()) { return; } before readAsLines() so the pipe listener exits cleanly if tempDir disappears while xcodebuild or xcode_backend is running.
  • Wraps if (scriptOutputPipeFile!.existsSync()) { scriptOutputPipeFile.writeAsStringSync('all done'); } in ErrorHandlingFileSystem.noExitOnFailure and try { ... } on FileSystemException so terminal sessions do not throw PathNotFoundException or ToolExit if the temporary directory was removed either before or after existsSync() (and File.writeAsStringSync does not recreate missing parent directories).
  • Uses ErrorHandlingFileSystem.deleteIfExists(tempDir, recursive: true) in buildXcodeProject's finally block so cleanup succeeds if tempDir was already removed and removes tempDir if only pipe_to_stdout was unlinked.
  • Threads FeatureFlags to buildXcodeProject, processPodsIfNeeded, BuildIOSCommand, BuildIOSArchiveCommand, BuildFrameworkCommand, and BuildSwiftPackageUtils (and resolves FlutterCommand.analytics lazily in BuildSwiftPackage.utils) so the new build_ios_test.dart regression tests run under testWithoutContext.

Fixes #195906

Previous output:

+35 -1: xcresults simulator Do not crash if temporary build directory is deleted before cleanup. [E]

  Expected: throws <Instance of 'ToolExit'> with `message`: contains 'Encountered error while building for simulator.'
    Actual: <Instance of 'Future<void>'>
     Which: threw FileSystemException:<FileSystemException: No such file or directory, path = '/.tmp_rand0/flutter_ios_build_temp_dirrand0' (OS Error: No such file or directory, errno = 2)>
            stack package:file/src/backends/memory/common.dart 13:5                                                                                                                              checkExists
                  package:file/src/backends/memory/memory_file_system_entity.dart 64:5                                                                                                           MemoryFileSystemEntity.backing
                  package:file/src/backends/memory/memory_file_system_entity.dart 292:17                                                                                                         MemoryFileSystemEntity.internalDeleteSync
                  package:file/src/backends/memory/memory_file_system_entity.dart 140:7                                                                                                          MemoryFileSystemEntity.deleteSync
                  package:flutter_tools/src/ios/mac.dart 637:13                                                                                                                                  buildXcodeProject
+35 -3: Some tests failed.

Current output:

+38: All tests passed!

Pre-launch Checklist

  • I read the [Contributor Guide] and followed the process outlined there for submitting PRs.
  • I read the [Tree Hygiene] wiki page, which explains my responsibilities.
  • I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement].
  • I signed the [CLA].
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///).
  • I added new tests to check the change I am making, or this PR is [test-exempt].
  • I followed the [breaking change policy] and added [Data Driven Fixes] where supported.
  • All existing and new tests are passing.

…leted before cleanup

During `buildXcodeProject`, `globals.fs.systemTempDirectory.createTempSync('flutter_ios_build_temp_dir.')` creates a temporary directory for the `xcresult` bundle and optional `pipe_to_stdout` FIFO. If `flutter` receives a termination signal (which triggers `LocalFileSystem.dispose()` and deletes the process-wide system temp directory) or external temp cleanup removes the directory while `xcodebuild` is running, `buildXcodeProject` previously crashed with an unhandled `PathNotFoundException` when writing to `scriptOutputPipeFile` or when calling `tempDir.deleteSync(recursive: true)` in the `finally` block (since `ErrorHandlingDirectory.deleteSync` passes `kSystemCodeCannotFindFile` in `ignoreErrorCodes`, causing `ENOENT` to be rethrown).

Guard `scriptOutputPipeFile.writeAsStringSync('all done')` with `scriptOutputPipeFile.existsSync()` and replace `tempDir.deleteSync(recursive: true)` with `ErrorHandlingFileSystem.deleteIfExists(tempDir, recursive: true)`.

Previous output:
```
+35 -1: xcresults simulator Do not crash if temporary build directory is deleted before cleanup. [E]

  Expected: throws <Instance of 'ToolExit'> with `message`: contains 'Encountered error while building for simulator.'
    Actual: <Instance of 'Future<void>'>
     Which: threw FileSystemException:<FileSystemException: No such file or directory, path = '/.tmp_rand0/flutter_ios_build_temp_dirrand0' (OS Error: No such file or directory, errno = 2)>
            stack package:file/src/backends/memory/common.dart 13:5                                                                                                                              checkExists
                  package:file/src/backends/memory/memory_file_system_entity.dart 64:5                                                                                                           MemoryFileSystemEntity.backing
                  package:file/src/backends/memory/memory_file_system_entity.dart 292:17                                                                                                         MemoryFileSystemEntity.internalDeleteSync
                  package:file/src/backends/memory/memory_file_system_entity.dart 140:7                                                                                                          MemoryFileSystemEntity.deleteSync
                  package:flutter_tools/src/ios/mac.dart 637:13                                                                                                                                  buildXcodeProject
+35 -2: Some tests failed.
```

Current output:
```
+37: All tests passed!
```
…eted after existsSync in buildXcodeProject

Wrap the terminal pipe 'all done' write in ErrorHandlingFileSystem.noExitOnFailure and catch FileSystemException so buildXcodeProject does not throw PathNotFoundException or ToolExit if the temporary build directory is removed between existsSync and writeAsStringSync. Because File.writeAsStringSync does not create missing parent directories, the deleted temporary directory is not recreated, and the finally block's ErrorHandlingFileSystem.deleteIfExists(tempDir, recursive: true) cleans up the directory if only the pipe file was removed.

Fixes flutter#195906

Previous output:
```text
+35 -1: xcresults simulator Do not crash if temporary build directory is deleted before cleanup. [E]

  Expected: throws <Instance of 'ToolExit'> with `message`: contains 'Encountered error while building for simulator.'
    Actual: <Instance of 'Future<void>'>
     Which: threw FileSystemException:<FileSystemException: No such file or directory, path = '/.tmp_rand0/flutter_ios_build_temp_dirrand0' (OS Error: No such file or directory, errno = 2)>
            stack package:file/src/backends/memory/common.dart 13:5                                                                                                                              checkExists
                  package:file/src/backends/memory/memory_file_system_entity.dart 64:5                                                                                                           MemoryFileSystemEntity.backing
                  package:file/src/backends/memory/memory_file_system_entity.dart 292:17                                                                                                         MemoryFileSystemEntity.internalDeleteSync
                  package:file/src/backends/memory/memory_file_system_entity.dart 140:7                                                                                                          MemoryFileSystemEntity.deleteSync
                  package:flutter_tools/src/ios/mac.dart 637:13                                                                                                                                  buildXcodeProject
+35 -3: Some tests failed.
```

Current output:
```text
+38: All tests passed!
```
@bkonyi bkonyi added the CICD Run CI/CD label Nov 3, 2026
@github-actions github-actions Bot added platform-ios iOS applications specifically tool Affects the "flutter" command-line tool. See also t: labels. team-ios Owned by iOS platform team labels Nov 3, 2026
…estWithoutContext

Convert the three temporary build directory deletion tests in `build_ios_test.dart` from `testUsingContext` to `testWithoutContext` using `createTestBuildCommand` and `createTestCommandRunner`.

Thread `FeatureFlags` explicitly through `buildXcodeProject`, `processPodsIfNeeded`, `BuildIOSCommand`, `BuildIOSArchiveCommand`, and `BuildFrameworkCommand`, and defer `FlutterCommand.analytics` access in `BuildSwiftPackage` so `BuildCommand` and `BuildIOSCommand` can be constructed and run without ambient `AppContext` lookups.
@github-actions github-actions Bot added platform-macos Building on or for macOS specifically a: desktop Running on desktop team-macos Owned by the macOS platform team labels Nov 3, 2026
…featureFlags imports

- Guard `listenToScriptOutputLine()` in `buildXcodeProject` with `if (!scriptOutputPipeFile!.existsSync()) { return; }` so the pipe listener exits cleanly if `tempDir` disappears while `xcodebuild` or `xcode_backend` is running.

- Wrap the terminal-session regression test in `ErrorHandlingFileSystem` and initialize an empty pipe file by default in `_PipeOperatingSystemUtils` so the test exercises `listenToScriptOutputLine()`.

- Restrict `features.dart` imports to `show FeatureFlags` in `build_ios_framework.dart`, `build_ios.dart`, `mac.dart`, and `cocoapod_utils.dart`, and privatize `_BuildIOSSubCommand._featureFlags`.
Replaces the ambient `featureFlags` getter reads in `IOSDevice` and `IOSSimulator` with constructor-injected `FeatureFlags` (`_featureFlags`), matching `MacOSDevice`.

Threads `required FeatureFlags featureFlags` through `XCDevice`, `IOSSimulatorUtils`, `ToolDependencies`, `context_runner.dart`, and unit test callers, and extracts `kEnoent` in `build_ios_test.dart`.
@bkonyi
bkonyi marked this pull request as ready for review November 12, 2026 03:22
@bkonyi
bkonyi requested review from a team as code owners November 12, 2026 03:22

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request threads FeatureFlags through various build commands, device classes, and utility methods (such as XCDevice, IOSSimulatorUtils, and processPodsIfNeeded) to avoid relying on global state. Additionally, it hardens the Xcode build process in mac.dart against crashes caused by the temporary build directory or pipe file being deleted mid-build, using ErrorHandlingFileSystem and existence checks. The review feedback highlights a potential TOCTOU race condition in listenToScriptOutputLine where readAsLines() is called after existsSync(), suggesting wrapping it in a try-catch block to prevent unhandled FileSystemException crashes.

@LouiseHsu
LouiseHsu requested a review from vashworth November 12, 2026 22:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

a: desktop Running on desktop CICD Run CI/CD platform-ios iOS applications specifically platform-macos Building on or for macOS specifically t: cp-candidate A PR that should be considered for a cherry-pick upon landing. team-ios Owned by iOS platform team team-macos Owned by the macOS platform team tool Affects the "flutter" command-line tool. See also t: labels.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[tool_crash] PathNotFoundException deleting temporary directory in buildXcodeProject on macOS

1 participant