[ VM / CLI ] Fix issue where trying to snapshot a non-existent script would cause an assertion failure

Passing --snapshot should result in the CLI being bypassed (`dart compile`
should be used otherwise). Check to see if this option is provided when
attempting to parse the script name and always populate script_name in
that case.

Fixes https://github.com/dart-lang/sdk/issues/43785

TEST=Added regression test to the CLI package to exercise this path.

Fixed: 43785
Change-Id: Ifb67a5880f6b83c54e6deb6b0785b61fdcfc0ada
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/172820
Reviewed-by: Alexander Aprelev <aam@google.com>
Commit-Queue: Ben Konyi <bkonyi@google.com>
diff --git a/pkg/dartdev/test/no_such_file_test.dart b/pkg/dartdev/test/no_such_file_test.dart
index 5a1469e..1641dfc 100644
--- a/pkg/dartdev/test/no_such_file_test.dart
+++ b/pkg/dartdev/test/no_such_file_test.dart
@@ -24,4 +24,16 @@
     expect(argsResult.stdout, isEmpty);
     expect(argsResult.exitCode, 64);
   });
+
+  test('Providing --snapshot VM option with invalid script fails gracefully',
+      () {
+    // Regression test for https://github.com/dart-lang/sdk/issues/43785
+    p = project();
+    final result = p.runSync('--snapshot=abc', ['foo.dart']);
+    expect(result.stderr, isNotEmpty);
+    expect(result.stderr,
+        contains("Error when reading 'foo.dart': No such file or directory"));
+    expect(result.stdout, isEmpty);
+    expect(result.exitCode, 254);
+  });
 }
diff --git a/runtime/bin/main_options.cc b/runtime/bin/main_options.cc
index 452346f..2e962c1 100644
--- a/runtime/bin/main_options.cc
+++ b/runtime/bin/main_options.cc
@@ -478,6 +478,7 @@
     bool is_potential_file_path = true;
 #endif  // !defined(DART_PRECOMPILED_RUNTIME)
     if (Options::disable_dart_dev() ||
+        (Options::snapshot_filename() != nullptr) ||
         (is_potential_file_path && !enable_vm_service_)) {
       *script_name = Utils::StrDup(argv[i]);
       run_script = true;