dart_vm.cc 16.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// Copyright 2017 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.

#include "flutter/runtime/dart_vm.h"

#include <sys/stat.h>

#include <mutex>
#include <vector>

#include "flutter/common/settings.h"
13 14 15 16 17
#include "flutter/fml/arraysize.h"
#include "flutter/fml/compiler_specific.h"
#include "flutter/fml/file.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/time/time_delta.h"
18 19 20 21 22 23 24 25
#include "flutter/fml/trace_event.h"
#include "flutter/lib/io/dart_io.h"
#include "flutter/lib/ui/dart_runtime_hooks.h"
#include "flutter/lib/ui/dart_ui.h"
#include "flutter/runtime/dart_isolate.h"
#include "flutter/runtime/dart_service_isolate.h"
#include "flutter/runtime/start_up.h"
#include "third_party/dart/runtime/bin/embedded_dart_io.h"
26 27 28 29 30 31 32 33
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_class_library.h"
#include "third_party/tonic/dart_class_provider.h"
#include "third_party/tonic/dart_sticky_error.h"
#include "third_party/tonic/file_loader/file_loader.h"
#include "third_party/tonic/logging/dart_error.h"
#include "third_party/tonic/scopes/dart_api_scope.h"
#include "third_party/tonic/typed_data/uint8_list.h"
34 35 36 37 38 39 40 41

#ifdef ERROR
#undef ERROR
#endif

namespace dart {
namespace observatory {

42 43
#if !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_RELEASE) && \
    (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DYNAMIC_RELEASE)
44 45 46 47 48 49 50 51

// These two symbols are defined in |observatory_archive.cc| which is generated
// by the |//third_party/dart/runtime/observatory:archive_observatory| rule.
// Both of these symbols will be part of the data segment and therefore are read
// only.
extern unsigned int observatory_assets_archive_len;
extern const uint8_t* observatory_assets_archive;

J
Jason Simmons 已提交
52
#endif  // !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE !=
53 54
        // FLUTTER_RUNTIME_MODE_RELEASE) && (FLUTTER_RUNTIME_MODE !=
        // FLUTTER_RUNTIME_MODE_DYNAMIC_RELEASE)
55 56 57 58 59 60 61 62

}  // namespace observatory
}  // namespace dart

namespace blink {

// Arguments passed to the Dart VM in all configurations.
static const char* kDartLanguageArgs[] = {
63 64 65 66 67 68
    // clang-format off
    "--enable_mirrors=false",
    "--background_compilation",
    "--await_is_keyword",
    "--causal_async_stacks",
    // clang-format on
69 70 71 72 73 74
};

static const char* kDartPrecompilationArgs[] = {
    "--precompilation",
};

75
FML_ALLOW_UNUSED_TYPE
76 77 78 79 80 81 82 83 84 85
static const char* kDartWriteProtectCodeArgs[] = {
    "--no_write_protect_code",
};

static const char* kDartAssertArgs[] = {
    // clang-format off
    "--enable_asserts",
    // clang-format on
};

86 87 88 89 90 91 92 93
static const char* kDartCheckedModeArgs[] = {
    // clang-format off
    "--enable_type_checks",
    "--error_on_bad_type",
    "--error_on_bad_override",
    // clang-format on
};

94 95 96 97
static const char* kDartStrongModeArgs[] = {
    // clang-format off
    "--strong",
    "--reify_generic_functions",
A
Alexander Aprelev 已提交
98
    "--sync_async",
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    // clang-format on
};

static const char* kDartStartPausedArgs[]{
    "--pause_isolates_on_start",
};

static const char* kDartTraceStartupArgs[]{
    "--timeline_streams=Compiler,Dart,Debugger,Embedder,GC,Isolate,VM",
};

static const char* kDartEndlessTraceBufferArgs[]{
    "--timeline_recorder=endless",
};

114
static const char* kDartFuchsiaTraceArgs[] FML_ALLOW_UNUSED_TYPE = {
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    "--systrace_timeline",
    "--timeline_streams=Compiler,Dart,Debugger,Embedder,GC,Isolate,VM",
};

constexpr char kFileUriPrefix[] = "file://";
constexpr size_t kFileUriPrefixLength = sizeof(kFileUriPrefix) - 1;

bool DartFileModifiedCallback(const char* source_url, int64_t since_ms) {
  if (strncmp(source_url, kFileUriPrefix, kFileUriPrefixLength) != 0u) {
    // Assume modified.
    return true;
  }

  const char* path = source_url + kFileUriPrefixLength;
  struct stat info;
  if (stat(path, &info) < 0)
    return true;

  // If st_mtime is zero, it's more likely that the file system doesn't support
  // mtime than that the file was actually modified in the 1970s.
  if (!info.st_mtime)
    return true;

  // It's very unclear what time bases we're with here. The Dart API doesn't
  // document the time base for since_ms. Reading the code, the value varies by
  // platform, with a typical source being something like gettimeofday.
  //
  // We add one to st_mtime because st_mtime has less precision than since_ms
  // and we want to treat the file as modified if the since time is between
  // ticks of the mtime.
145 146
  fml::TimeDelta mtime = fml::TimeDelta::FromSeconds(info.st_mtime + 1);
  fml::TimeDelta since = fml::TimeDelta::FromMilliseconds(since_ms);
147 148 149 150 151 152 153

  return mtime > since;
}

void ThreadExitCallback() {}

Dart_Handle GetVMServiceAssetsArchiveCallback() {
154 155
#if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_RELEASE) || \
    (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DYNAMIC_RELEASE)
156
  return nullptr;
J
Jason Simmons 已提交
157
#elif OS_FUCHSIA
158 159 160
  std::vector<uint8_t> observatory_assets_archive;
  if (!files::ReadFileToVector("pkg/data/observatory.tar",
                               &observatory_assets_archive)) {
161
    FML_LOG(ERROR) << "Fail to load Observatory archive";
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    return nullptr;
  }
  return tonic::DartConverter<tonic::Uint8List>::ToDart(
      observatory_assets_archive.data(), observatory_assets_archive.size());
#else
  return tonic::DartConverter<tonic::Uint8List>::ToDart(
      ::dart::observatory::observatory_assets_archive,
      ::dart::observatory::observatory_assets_archive_len);
#endif
}

static const char kStdoutStreamId[] = "Stdout";
static const char kStderrStreamId[] = "Stderr";

static bool ServiceStreamListenCallback(const char* stream_id) {
  if (strcmp(stream_id, kStdoutStreamId) == 0) {
    dart::bin::SetCaptureStdout(true);
    return true;
  } else if (strcmp(stream_id, kStderrStreamId) == 0) {
    dart::bin::SetCaptureStderr(true);
    return true;
  }
  return false;
}

static void ServiceStreamCancelCallback(const char* stream_id) {
  if (strcmp(stream_id, kStdoutStreamId) == 0) {
    dart::bin::SetCaptureStdout(false);
  } else if (strcmp(stream_id, kStderrStreamId) == 0) {
    dart::bin::SetCaptureStderr(false);
  }
}

bool DartVM::IsRunningPrecompiledCode() {
  return Dart_IsPrecompiledRuntime();
}

static std::vector<const char*> ProfilingFlags(bool enable_profiling) {
// Disable Dart's built in profiler when building a debug build. This
// works around a race condition that would sometimes stop a crash's
// stack trace from being printed on Android.
#ifndef NDEBUG
  enable_profiling = false;
#endif

  // We want to disable profiling by default because it overwhelms LLDB. But
  // the VM enables the same by default. In either case, we have some profiling
  // flags.
  if (enable_profiling) {
    return {// This is the default. But just be explicit.
            "--profiler",
            // This instructs the profiler to walk C++ frames, and to include
            // them in the profile.
            "--profile-vm"};
  } else {
    return {"--no-profiler"};
  }
}

void PushBackAll(std::vector<const char*>* args,
                 const char** argv,
                 size_t argc) {
  for (size_t i = 0; i < argc; ++i) {
    args->push_back(argv[i]);
  }
}

static void EmbedderInformationCallback(Dart_EmbedderInformation* info) {
  info->version = DART_EMBEDDER_INFORMATION_CURRENT_VERSION;
  dart::bin::GetIOEmbedderInformation(info);
  info->name = "Flutter";
}

235
fml::RefPtr<DartVM> DartVM::ForProcess(Settings settings) {
236
  return ForProcess(settings, nullptr, nullptr, nullptr);
237 238 239
}

static std::once_flag gVMInitialization;
240
static fml::RefPtr<DartVM> gVM;
241

242
fml::RefPtr<DartVM> DartVM::ForProcess(
243
    Settings settings,
244 245 246
    fml::RefPtr<DartSnapshot> vm_snapshot,
    fml::RefPtr<DartSnapshot> isolate_snapshot,
    fml::RefPtr<DartSnapshot> shared_snapshot) {
247 248 249 250
  std::call_once(gVMInitialization, [settings,          //
                                     vm_snapshot,       //
                                     isolate_snapshot,  //
                                     shared_snapshot    //
251 252 253 254
  ]() mutable {
    if (!vm_snapshot) {
      vm_snapshot = DartSnapshot::VMSnapshotFromSettings(settings);
    }
255
    if (!(vm_snapshot && vm_snapshot->IsValid())) {
256
      FML_LOG(ERROR) << "VM snapshot must be valid.";
257 258
      return;
    }
259 260 261
    if (!isolate_snapshot) {
      isolate_snapshot = DartSnapshot::IsolateSnapshotFromSettings(settings);
    }
262
    if (!(isolate_snapshot && isolate_snapshot->IsValid())) {
263
      FML_LOG(ERROR) << "Isolate snapshot must be valid.";
264 265
      return;
    }
266 267 268
    if (!shared_snapshot) {
      shared_snapshot = DartSnapshot::Empty();
    }
269
    gVM = fml::MakeRefCounted<DartVM>(settings,                     //
270 271 272
                                      std::move(vm_snapshot),       //
                                      std::move(isolate_snapshot),  //
                                      std::move(shared_snapshot)    //
273 274 275 276 277
    );
  });
  return gVM;
}

278
fml::RefPtr<DartVM> DartVM::ForProcessIfInitialized() {
279 280 281 282
  return gVM;
}

DartVM::DartVM(const Settings& settings,
283 284 285
               fml::RefPtr<DartSnapshot> vm_snapshot,
               fml::RefPtr<DartSnapshot> isolate_snapshot,
               fml::RefPtr<DartSnapshot> shared_snapshot)
286 287 288
    : settings_(settings),
      vm_snapshot_(std::move(vm_snapshot)),
      isolate_snapshot_(std::move(isolate_snapshot)),
289
      shared_snapshot_(std::move(shared_snapshot)),
290
      platform_kernel_mapping_(
291
          std::make_unique<fml::FileMapping>(settings.platform_kernel_path)),
292 293
      weak_factory_(this) {
  TRACE_EVENT0("flutter", "DartVMInitializer");
294
  FML_DLOG(INFO) << "Attempting Dart VM launch for mode: "
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
                 << (IsRunningPrecompiledCode() ? "AOT" : "Interpreter");

  {
    TRACE_EVENT0("flutter", "dart::bin::BootstrapDartIo");
    dart::bin::BootstrapDartIo();

    if (!settings.temp_directory_path.empty()) {
      dart::bin::SetSystemTempDirectory(settings.temp_directory_path.c_str());
    }
  }

  std::vector<const char*> args;

  // Instruct the VM to ignore unrecognized flags.
  // There is a lot of diversity in a lot of combinations when it
  // comes to the arguments the VM supports. And, if the VM comes across a flag
  // it does not recognize, it exits immediately.
  args.push_back("--ignore-unrecognized-flags");

  for (const auto& profiler_flag :
       ProfilingFlags(settings.enable_dart_profiling)) {
    args.push_back(profiler_flag);
  }

  PushBackAll(&args, kDartLanguageArgs, arraysize(kDartLanguageArgs));

  if (IsRunningPrecompiledCode()) {
    PushBackAll(&args, kDartPrecompilationArgs,
                arraysize(kDartPrecompilationArgs));
  }

326
  // Enable checked mode if we are not running precompiled code. We run non-
327
  // precompiled code only in the debug product mode.
328
  bool use_checked_mode = !settings.dart_non_checked_mode;
329

330 331
#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DYNAMIC_PROFILE || \
    FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DYNAMIC_RELEASE
332
  use_checked_mode = false;
333 334
#endif

J
Jason Simmons 已提交
335
#if !OS_FUCHSIA
336
  if (IsRunningPrecompiledCode()) {
337
    use_checked_mode = false;
338
  }
J
Jason Simmons 已提交
339
#endif  // !OS_FUCHSIA
340 341 342 343 344 345 346 347

#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
  // Debug mode uses the JIT, disable code page write protection to avoid
  // memory page protection changes before and after every compilation.
  PushBackAll(&args, kDartWriteProtectCodeArgs,
              arraysize(kDartWriteProtectCodeArgs));
#endif

348 349
  const bool isolate_snapshot_is_dart_2 =
      Dart_IsDart2Snapshot(isolate_snapshot_->GetData()->GetSnapshotPointer());
350

351 352 353
  const bool is_preview_dart2 =
      (platform_kernel_mapping_->GetSize() > 0) || isolate_snapshot_is_dart_2;

354
  FML_DLOG(INFO) << "Dart 2 " << (is_preview_dart2 ? "is" : "is NOT")
355 356 357 358 359 360 361 362 363 364 365
                 << " enabled. Platform kernel: "
                 << static_cast<bool>(platform_kernel_mapping_->GetSize() > 0)
                 << " Isolate Snapshot is Dart 2: "
                 << isolate_snapshot_is_dart_2;

  if (is_preview_dart2) {
    PushBackAll(&args, kDartStrongModeArgs, arraysize(kDartStrongModeArgs));
    if (use_checked_mode) {
      PushBackAll(&args, kDartAssertArgs, arraysize(kDartAssertArgs));
    }
  } else if (use_checked_mode) {
366
    FML_DLOG(INFO) << "Checked mode is ON";
367
    PushBackAll(&args, kDartAssertArgs, arraysize(kDartAssertArgs));
368 369
    PushBackAll(&args, kDartCheckedModeArgs, arraysize(kDartCheckedModeArgs));
  } else {
370
    FML_DLOG(INFO) << "Is not Dart 2 and Checked mode is OFF";
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
  }

  if (settings.start_paused) {
    PushBackAll(&args, kDartStartPausedArgs, arraysize(kDartStartPausedArgs));
  }

  if (settings.endless_trace_buffer || settings.trace_startup) {
    // If we are tracing startup, make sure the trace buffer is endless so we
    // don't lose early traces.
    PushBackAll(&args, kDartEndlessTraceBufferArgs,
                arraysize(kDartEndlessTraceBufferArgs));
  }

  if (settings.trace_startup) {
    PushBackAll(&args, kDartTraceStartupArgs, arraysize(kDartTraceStartupArgs));
  }

#if defined(OS_FUCHSIA)
  PushBackAll(&args, kDartFuchsiaTraceArgs, arraysize(kDartFuchsiaTraceArgs));
#endif

  for (size_t i = 0; i < settings.dart_flags.size(); i++)
    args.push_back(settings.dart_flags[i].c_str());

395 396
  char* flags_error = Dart_SetVMFlags(args.size(), args.data());
  if (flags_error) {
397
    FML_LOG(FATAL) << "Error while setting Dart VM flags: " << flags_error;
398 399
    ::free(flags_error);
  }
400 401 402

  DartUI::InitForGlobal();

403 404
  Dart_SetFileModifiedCallback(&DartFileModifiedCallback);

405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
  {
    TRACE_EVENT0("flutter", "Dart_Initialize");
    Dart_InitializeParams params = {};
    params.version = DART_INITIALIZE_PARAMS_CURRENT_VERSION;
    params.vm_snapshot_data = vm_snapshot_->GetData()->GetSnapshotPointer();
    params.vm_snapshot_instructions = vm_snapshot_->GetInstructionsIfPresent();
    params.create = reinterpret_cast<decltype(params.create)>(
        DartIsolate::DartIsolateCreateCallback);
    params.shutdown = reinterpret_cast<decltype(params.shutdown)>(
        DartIsolate::DartIsolateShutdownCallback);
    params.cleanup = reinterpret_cast<decltype(params.cleanup)>(
        DartIsolate::DartIsolateCleanupCallback);
    params.thread_exit = ThreadExitCallback;
    params.get_service_assets = GetVMServiceAssetsArchiveCallback;
    params.entropy_source = DartIO::EntropySource;
    char* init_error = Dart_Initialize(&params);
    if (init_error) {
422
      FML_LOG(FATAL) << "Error while initializing the Dart VM: " << init_error;
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
      ::free(init_error);
    }
    // Send the earliest available timestamp in the application lifecycle to
    // timeline. The difference between this timestamp and the time we render
    // the very first frame gives us a good idea about Flutter's startup time.
    // Use a duration event so about:tracing will consider this event when
    // deciding the earliest event to use as time 0.
    if (blink::engine_main_enter_ts != 0) {
      Dart_TimelineEvent("FlutterEngineMainEnter",     // label
                         blink::engine_main_enter_ts,  // timestamp0
                         blink::engine_main_enter_ts,  // timestamp1_or_async_id
                         Dart_Timeline_Event_Duration,  // event type
                         0,                             // argument_count
                         nullptr,                       // argument_names
                         nullptr                        // argument_values
      );
    }
  }

  // Allow streaming of stdout and stderr by the Dart vm.
  Dart_SetServiceStreamCallbacks(&ServiceStreamListenCallback,
                                 &ServiceStreamCancelCallback);

  Dart_SetEmbedderInformationCallback(&EmbedderInformationCallback);
}

DartVM::~DartVM() {
  if (Dart_CurrentIsolate() != nullptr) {
    Dart_ExitIsolate();
  }
  char* result = Dart_Cleanup();
  if (result != nullptr) {
455
    FML_LOG(ERROR) << "Could not cleanly shut down the Dart VM. Message: \""
456 457 458 459 460 461 462 463 464
                   << result << "\".";
    free(result);
  }
}

const Settings& DartVM::GetSettings() const {
  return settings_;
}

465 466
const fml::Mapping& DartVM::GetPlatformKernel() const {
  return *platform_kernel_mapping_.get();
467 468 469 470 471 472
}

const DartSnapshot& DartVM::GetVMSnapshot() const {
  return *vm_snapshot_.get();
}

B
Ben Konyi 已提交
473 474 475 476
IsolateNameServer* DartVM::GetIsolateNameServer() {
  return &isolate_name_server_;
}

477
fml::RefPtr<DartSnapshot> DartVM::GetIsolateSnapshot() const {
478 479 480
  return isolate_snapshot_;
}

481
fml::RefPtr<DartSnapshot> DartVM::GetSharedSnapshot() const {
482 483 484
  return shared_snapshot_;
}

485 486 487 488
ServiceProtocol& DartVM::GetServiceProtocol() {
  return service_protocol_;
}

489
fml::WeakPtr<DartVM> DartVM::GetWeakPtr() {
490 491 492 493
  return weak_factory_.GetWeakPtr();
}

}  // namespace blink