#include <string_view>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/files/file_util.h"
#include "base/task/single_thread_task_executor.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "gin/v8_initializer.h"
#include "mojo/core/embedder/embedder.h"
#include "mojo/public/cpp/bindings/binder_map.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_v8_context_snapshot.h"
#include "v8/include/v8.h"
namespace {
class SnapshotPlatform final : public blink::Platform {
public:
bool IsTakingV8ContextSnapshot() override { return true; }
};
}
int main(int argc, char** argv) {
base::AtExitManager at_exit;
const bool kRemoveRecognizedFlags = true;
v8::V8::SetFlagsFromCommandLine(&argc, argv, kRemoveRecognizedFlags);
base::CommandLine::Init(argc, argv);
auto early_access_feature_list = std::make_unique<base::FeatureList>();
base::FeatureList::SetInstance(std::move(early_access_feature_list));
#ifdef V8_USE_EXTERNAL_STARTUP_DATA
static constexpr std::string_view kSnapshotBlobFlag("snapshot_blob");
if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSnapshotBlobFlag)) {
base::File file(base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
kSnapshotBlobFlag),
base::File::FLAG_OPEN | base::File::FLAG_READ);
CHECK(file.IsValid());
gin::V8Initializer::LoadV8SnapshotFromFile(
std::move(file), nullptr, gin::V8SnapshotFileType::kDefault);
} else {
gin::V8Initializer::LoadV8Snapshot(gin::V8SnapshotFileType::kDefault);
}
#endif
base::SingleThreadTaskExecutor main_thread_task_executor;
base::ThreadPoolInstance::CreateAndStartWithDefaultParams("TakeSnapshot");
mojo::core::Init();
static constexpr char kPredictableFlag[] = "--predictable";
v8::V8::SetFlagsFromString(kPredictableFlag, sizeof(kPredictableFlag) - 1);
SnapshotPlatform platform;
mojo::BinderMap binders;
blink::CreateMainThreadAndInitialize(&platform, &binders);
auto* isolate = blink::CreateMainThreadIsolate();
v8::StartupData blob = blink::WebV8ContextSnapshot::TakeSnapshot(isolate);
base::FilePath file_path =
base::CommandLine::ForCurrentProcess()->GetSwitchValuePath("output_file");
CHECK(!file_path.empty());
int error_code = 0;
if (!base::WriteFile(file_path,
base::as_bytes(base::span(
blob.data, static_cast<size_t>(blob.raw_size))))) {
fprintf(stderr, "Error: WriteFile of %d snapshot has failed.\n",
blob.raw_size);
error_code = 1;
}
delete[] blob.data;
_exit(error_code);
}