xref: /aosp_15_r20/external/pdfium/testing/v8_test_environment.cpp (revision 3ac0a46f773bac49fa9476ec2b1cf3f8da5ec3a4)
1 // Copyright 2020 The PDFium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "testing/v8_test_environment.h"
6 
7 #include <memory>
8 #include <string>
9 
10 #include "core/fxcrt/fx_system.h"
11 #include "testing/v8_initializer.h"
12 #include "third_party/base/check.h"
13 #include "v8/include/libplatform/libplatform.h"
14 #include "v8/include/v8-isolate.h"
15 #include "v8/include/v8-platform.h"
16 #include "v8/include/v8-snapshot.h"
17 
18 namespace {
19 
20 V8TestEnvironment* g_environment = nullptr;
21 
22 }  // namespace
23 
V8TestEnvironment(const char * exe_name)24 V8TestEnvironment::V8TestEnvironment(const char* exe_name)
25     : exe_path_(exe_name),
26       array_buffer_allocator_(std::make_unique<CFX_V8ArrayBufferAllocator>()) {
27   DCHECK(!g_environment);
28   g_environment = this;
29 }
30 
~V8TestEnvironment()31 V8TestEnvironment::~V8TestEnvironment() {
32   DCHECK(g_environment);
33 
34 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
35   if (startup_data_)
36     free(const_cast<char*>(startup_data_->data));
37 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
38 
39   g_environment = nullptr;
40 }
41 
42 // static
GetInstance()43 V8TestEnvironment* V8TestEnvironment::GetInstance() {
44   return g_environment;
45 }
46 
47 // static
PumpPlatformMessageLoop(v8::Isolate * isolate)48 void V8TestEnvironment::PumpPlatformMessageLoop(v8::Isolate* isolate) {
49   v8::Platform* platform = GetInstance()->platform();
50   while (v8::platform::PumpMessageLoop(platform, isolate))
51     continue;
52 }
53 
SetUp()54 void V8TestEnvironment::SetUp() {
55 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
56   if (startup_data_) {
57     platform_ = InitializeV8ForPDFiumWithStartupData(exe_path_, std::string(),
58                                                      std::string(), nullptr);
59   } else {
60     startup_data_ = std::make_unique<v8::StartupData>();
61     platform_ = InitializeV8ForPDFiumWithStartupData(
62         exe_path_, std::string(), std::string(), startup_data_.get());
63   }
64 #else
65   platform_ = InitializeV8ForPDFium(std::string(), exe_path_);
66 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
67 
68   v8::Isolate::CreateParams params;
69   params.array_buffer_allocator = array_buffer_allocator_.get();
70   isolate_.reset(v8::Isolate::New(params));
71 }
72 
TearDown()73 void V8TestEnvironment::TearDown() {
74   isolate_.reset();
75   ShutdownV8ForPDFium();
76 }
77