Fix physical path leakage in dart_plugin_registrant URI (#192218)

When obtaining the `dart_plugin_registrant` URI in
`KernelCompiler.compile`, the code was passing the `_fileSystemScheme`
and `_fileSystemRoots` class fields, which are always empty, to
`toMultiRootPath` to obtain virtual path, but fails quickly if they are
empty, returning the physical path instead.

This fix adds an `org-dartlang-plugin-registrant` scheme and sets the
root to the plugin source code's parent directory if these parameters
are not provided by the caller of the `compile` method.

Fixes #148461

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [AI contribution guidelines] and understand my
responsibilities, or I am not using AI tools.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant in-code documentation (doc comments with
`///`).
- [x] If this PR introduces a new feature or capability, I created and
linked a website documentation issue or PR in [flutter/website] (or
verified none is needed).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel
on [Discord].

If this change needs to override an active code freeze, provide a
comment explaining why. The code freeze workflow can be overridden by
code reviewers. See pinned issues for any active code freezes with
guidance.

**Note**: The Flutter team is currently trialing the use of [Gemini Code
Assist for
GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code).
Comments from the `gemini-code-assist` bot should not be taken as
authoritative feedback from the Flutter team. If you find its comments
useful you can update your code accordingly, but if you are unsure or
disagree with the feedback, please feel free to wait for a Flutter team
member's review for guidance on which automated comments should be
addressed.

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview
[AI contribution guidelines]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines
[Tree Hygiene]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md
[test-exempt]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md
[Features we expect every widget to implement]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[flutter/website]: https://github.com/flutter/website
[breaking change policy]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes
[Discord]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md
[Data Driven Fixes]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
diff --git a/packages/flutter_tools/lib/src/compile.dart b/packages/flutter_tools/lib/src/compile.dart
index fe457df..2d2e5a2 100644
--- a/packages/flutter_tools/lib/src/compile.dart
+++ b/packages/flutter_tools/lib/src/compile.dart
@@ -27,6 +27,9 @@
 /// Opt-in changes to the dart compilers.
 const kDartCompilerExperiments = <String>[];
 
+/// Keeps absolute paths to the dart_plugin_registrant out of compiled output.
+const kDartPluginRegistrantScheme = 'org-dartlang-plugin-registrant';
+
 /// Whether DDC canary features are enabled.
 ///
 /// This is the single source of truth for DDC canary mode. It controls both
@@ -330,6 +333,11 @@
       _fileSystem.file(outputFilePath).createSync(recursive: true);
     }
 
+    // Check before adding the plugin registrant root below so it doesn't disable --depfile.
+    if (fileSystemRoots != null && fileSystemRoots.isNotEmpty) {
+      depFilePath = null;
+    }
+
     // Check if there's a Dart plugin registrant.
     // This is contained in the file `dart_plugin_registrant.dart` under `.dart_tools/flutter_build/`.
     final File? dartPluginRegistrant = checkDartPluginRegistry
@@ -339,14 +347,16 @@
     String? dartPluginRegistrantUri;
     if (dartPluginRegistrant != null && dartPluginRegistrant.existsSync()) {
       final Uri dartPluginRegistrantFileUri = dartPluginRegistrant.uri;
-      dartPluginRegistrantUri =
-          packageConfig.toPackageUriForWorkspace(dartPluginRegistrantFileUri)?.toString() ??
-          toMultiRootPath(
-            dartPluginRegistrantFileUri,
-            _fileSystemScheme,
-            _fileSystemRoots,
-            _fileSystem.path.separator == r'\',
-          );
+
+      dartPluginRegistrantUri = packageConfig
+          .toPackageUriForWorkspace(dartPluginRegistrantFileUri)
+          ?.toString();
+
+      if (dartPluginRegistrantUri == null) {
+        fileSystemScheme ??= kDartPluginRegistrantScheme;
+        fileSystemRoots = <String>[...?fileSystemRoots, dartPluginRegistrant.parent.path];
+        dartPluginRegistrantUri = '$fileSystemScheme:///${dartPluginRegistrant.basename}';
+      }
     }
 
     final List<String> commandToStartFrontendServer = _commandToStartFrontendServer(
@@ -375,11 +385,7 @@
           ],
           if (packagesPath != null) ...<String>['--packages', packagesPath],
           if (outputFilePath != null) ...<String>['--output-dill', outputFilePath],
-          if (depFilePath != null &&
-              (fileSystemRoots == null || fileSystemRoots.isEmpty)) ...<String>[
-            '--depfile',
-            depFilePath,
-          ],
+          if (depFilePath != null) ...<String>['--depfile', depFilePath],
           if (fileSystemRoots != null)
             for (final String root in fileSystemRoots) ...<String>['--filesystem-root', root],
           if (fileSystemScheme != null) ...<String>['--filesystem-scheme', fileSystemScheme],
diff --git a/packages/flutter_tools/test/general.shard/compile_batch_test.dart b/packages/flutter_tools/test/general.shard/compile_batch_test.dart
index ef8486f..0243bad 100644
--- a/packages/flutter_tools/test/general.shard/compile_batch_test.dart
+++ b/packages/flutter_tools/test/general.shard/compile_batch_test.dart
@@ -484,6 +484,85 @@
     expect((await output)?.outputFilename, '');
   });
 
+  for (final style in <FileSystemStyle>[FileSystemStyle.posix, FileSystemStyle.windows]) {
+    final styleName = style == FileSystemStyle.windows ? 'windows' : 'posix';
+
+    test(
+      'KernelCompiler converts dart_plugin_registrant physical path to virtual URI ($styleName)',
+      () async {
+        final logger = BufferLogger.test();
+        final fileSystem = MemoryFileSystem.test(style: style);
+        final stdoutHandler = StdoutHandler(logger: logger, fileSystem: fileSystem);
+
+        final projectRoot = style == FileSystemStyle.windows ? r'C:\project' : '/project';
+        final String fileSystemRoot = fileSystem.path.join(
+          projectRoot,
+          '.dart_tool',
+          'flutter_build',
+        );
+        final String depFilePath = fileSystem.path.join(projectRoot, 'build', 'kernel_snapshot.d');
+        final Directory registrantDirectory = fileSystem.directory(fileSystemRoot)
+          ..createSync(recursive: true);
+        registrantDirectory.childFile('dart_plugin_registrant.dart').createSync();
+
+        final processManager = FakeProcessManager.list([
+          FakeCommand(
+            command: <String>[
+              'Artifact.engineDartAotRuntime',
+              'Artifact.frontendServerSnapshotForEngineDartSdk',
+              '--sdk-root',
+              'sdkroot/',
+              '--target=flutter',
+              '--no-print-incremental-dependencies',
+              '-Ddart.vm.profile=false',
+              '-Ddart.vm.product=false',
+              '--enable-asserts',
+              '--no-link-platform',
+              '--depfile',
+              depFilePath,
+              '--filesystem-root',
+              fileSystemRoot,
+              '--filesystem-scheme',
+              'org-dartlang-plugin-registrant',
+              '--source',
+              'org-dartlang-plugin-registrant:///dart_plugin_registrant.dart',
+              '--source',
+              'package:flutter/src/dart_plugin_registrant.dart',
+              '-Dflutter.dart_plugin_registrant=org-dartlang-plugin-registrant:///dart_plugin_registrant.dart',
+              '--verbosity=error',
+              '--native-assets-only',
+            ],
+          ),
+        ]);
+
+        final kernelCompiler = KernelCompiler(
+          fileSystem: fileSystem,
+          logger: logger,
+          processManager: processManager,
+          artifacts: Artifacts.test(),
+          fileSystemRoots: <String>[],
+          stdoutHandler: stdoutHandler,
+        );
+        final Future<CompilerOutput?> output = kernelCompiler.compile(
+          sdkRoot: 'sdkroot',
+          buildDir: registrantDirectory.childDirectory('somehash'),
+          checkDartPluginRegistry: true,
+          packagesPath: null,
+          depFilePath: depFilePath,
+          buildMode: .debug,
+          trackWidgetCreation: false,
+          dartDefines: const <String>[],
+          packageConfig: PackageConfig.empty,
+        );
+
+        stdoutHandler.compilerOutput?.complete(const CompilerOutput('', 0, <Uri>[]));
+        await output;
+
+        expect(processManager, hasNoRemainingExpectations);
+      },
+    );
+  }
+
   test('KernelCompiler uses generated entrypoint', () async {
     final logger = BufferLogger.test();
     final stdoutHandler = StdoutHandler(logger: logger, fileSystem: MemoryFileSystem.test());
@@ -510,11 +589,15 @@
             '--no-link-platform',
             '--packages',
             '.dart_tool/package_config.json',
+            '--filesystem-root',
+            '.dart_tools/flutter_build',
+            '--filesystem-scheme',
+            'org-dartlang-plugin-registrant',
             '--source',
-            '.dart_tools/flutter_build/dart_plugin_registrant.dart',
+            'org-dartlang-plugin-registrant:///dart_plugin_registrant.dart',
             '--source',
             'package:flutter/src/dart_plugin_registrant.dart',
-            '-Dflutter.dart_plugin_registrant=.dart_tools/flutter_build/dart_plugin_registrant.dart',
+            '-Dflutter.dart_plugin_registrant=org-dartlang-plugin-registrant:///dart_plugin_registrant.dart',
             '--verbosity=error',
             'scheme:///main.dart',
           ],