• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6 
7 #include "fxjs/cfxjs_engine.h"
8 
9 #include <memory>
10 #include <utility>
11 #include <vector>
12 
13 #include "core/fxcrt/unowned_ptr.h"
14 #include "fxjs/cjs_object.h"
15 #include "fxjs/xfa/cfxjse_runtimedata.h"
16 #include "third_party/base/ptr_util.h"
17 #include "third_party/base/stl_util.h"
18 #include "v8/include/v8-util.h"
19 
20 class CFXJS_PerObjectData;
21 
22 namespace {
23 
24 unsigned int g_embedderDataSlot = 1u;
25 v8::Isolate* g_isolate = nullptr;
26 size_t g_isolate_ref_count = 0;
27 CFX_V8ArrayBufferAllocator* g_arrayBufferAllocator = nullptr;
28 v8::Global<v8::ObjectTemplate>* g_DefaultGlobalObjectTemplate = nullptr;
29 const wchar_t kPerObjectDataTag[] = L"CFXJS_PerObjectData";
30 
GetAlignedPointerForPerObjectDataTag()31 void* GetAlignedPointerForPerObjectDataTag() {
32   return const_cast<void*>(static_cast<const void*>(kPerObjectDataTag));
33 }
34 
GetLineAndColumnFromError(v8::Local<v8::Message> message,v8::Local<v8::Context> context)35 std::pair<int, int> GetLineAndColumnFromError(v8::Local<v8::Message> message,
36                                               v8::Local<v8::Context> context) {
37   if (message.IsEmpty())
38     return std::make_pair(-1, -1);
39   return std::make_pair(message->GetLineNumber(context).FromMaybe(-1),
40                         message->GetStartColumn());
41 }
42 
43 }  // namespace
44 
45 // Global weak map to save dynamic objects.
46 class V8TemplateMapTraits final
47     : public v8::StdMapTraits<CFXJS_PerObjectData*, v8::Object> {
48  public:
49   using WeakCallbackDataType = CFXJS_PerObjectData;
50   using MapType = v8::
51       GlobalValueMap<WeakCallbackDataType*, v8::Object, V8TemplateMapTraits>;
52 
53   static const v8::PersistentContainerCallbackType kCallbackType =
54       v8::kWeakWithInternalFields;
55 
WeakCallbackParameter(MapType * map,WeakCallbackDataType * key,v8::Local<v8::Object> value)56   static WeakCallbackDataType* WeakCallbackParameter(
57       MapType* map,
58       WeakCallbackDataType* key,
59       v8::Local<v8::Object> value) {
60     return key;
61   }
62   static MapType* MapFromWeakCallbackInfo(
63       const v8::WeakCallbackInfo<WeakCallbackDataType>&);
KeyFromWeakCallbackInfo(const v8::WeakCallbackInfo<WeakCallbackDataType> & data)64   static WeakCallbackDataType* KeyFromWeakCallbackInfo(
65       const v8::WeakCallbackInfo<WeakCallbackDataType>& data) {
66     return data.GetParameter();
67   }
OnWeakCallback(const v8::WeakCallbackInfo<WeakCallbackDataType> & data)68   static void OnWeakCallback(
69       const v8::WeakCallbackInfo<WeakCallbackDataType>& data) {}
70   static void DisposeWeak(
71       const v8::WeakCallbackInfo<WeakCallbackDataType>& data);
72   static void Dispose(v8::Isolate* isolate,
73                       v8::Global<v8::Object> value,
74                       WeakCallbackDataType* key);
DisposeCallbackData(WeakCallbackDataType * callbackData)75   static void DisposeCallbackData(WeakCallbackDataType* callbackData) {}
76 };
77 
78 class V8TemplateMap {
79  public:
80   using WeakCallbackDataType = CFXJS_PerObjectData;
81   using MapType = v8::
82       GlobalValueMap<WeakCallbackDataType*, v8::Object, V8TemplateMapTraits>;
83 
V8TemplateMap(v8::Isolate * isolate)84   explicit V8TemplateMap(v8::Isolate* isolate) : m_map(isolate) {}
85   ~V8TemplateMap() = default;
86 
SetAndMakeWeak(WeakCallbackDataType * key,v8::Local<v8::Object> handle)87   void SetAndMakeWeak(WeakCallbackDataType* key, v8::Local<v8::Object> handle) {
88     ASSERT(!m_map.Contains(key));
89 
90     // Inserting an object into a GlobalValueMap with the appropriate traits
91     // has the side-effect of making the object weak deep in the guts of V8,
92     // and arranges for it to be cleaned up by the methods in the traits.
93     m_map.Set(key, handle);
94   }
95 
96   friend class V8TemplateMapTraits;
97 
98  private:
99   MapType m_map;
100 };
101 
102 class CFXJS_PerObjectData {
103  public:
CFXJS_PerObjectData(int nObjDefID)104   explicit CFXJS_PerObjectData(int nObjDefID) : m_ObjDefID(nObjDefID) {}
105 
106   ~CFXJS_PerObjectData() = default;
107 
SetInObject(CFXJS_PerObjectData * pData,v8::Local<v8::Object> pObj)108   static void SetInObject(CFXJS_PerObjectData* pData,
109                           v8::Local<v8::Object> pObj) {
110     if (pObj->InternalFieldCount() == 2) {
111       pObj->SetAlignedPointerInInternalField(
112           0, GetAlignedPointerForPerObjectDataTag());
113       pObj->SetAlignedPointerInInternalField(1, pData);
114     }
115   }
116 
GetFromObject(v8::Local<v8::Object> pObj)117   static CFXJS_PerObjectData* GetFromObject(v8::Local<v8::Object> pObj) {
118     if (pObj.IsEmpty() || pObj->InternalFieldCount() != 2 ||
119         pObj->GetAlignedPointerFromInternalField(0) !=
120             GetAlignedPointerForPerObjectDataTag()) {
121       return nullptr;
122     }
123     return static_cast<CFXJS_PerObjectData*>(
124         pObj->GetAlignedPointerFromInternalField(1));
125   }
126 
127   const int m_ObjDefID;
128   std::unique_ptr<CJS_Object> m_pPrivate;
129 };
130 
131 class CFXJS_ObjDefinition {
132  public:
CFXJS_ObjDefinition(v8::Isolate * isolate,const char * sObjName,FXJSOBJTYPE eObjType,CFXJS_Engine::Constructor pConstructor,CFXJS_Engine::Destructor pDestructor)133   CFXJS_ObjDefinition(v8::Isolate* isolate,
134                       const char* sObjName,
135                       FXJSOBJTYPE eObjType,
136                       CFXJS_Engine::Constructor pConstructor,
137                       CFXJS_Engine::Destructor pDestructor)
138       : m_ObjName(sObjName),
139         m_ObjType(eObjType),
140         m_pConstructor(pConstructor),
141         m_pDestructor(pDestructor),
142         m_pIsolate(isolate) {
143     v8::Isolate::Scope isolate_scope(isolate);
144     v8::HandleScope handle_scope(isolate);
145     v8::Local<v8::FunctionTemplate> fun = v8::FunctionTemplate::New(isolate);
146     fun->InstanceTemplate()->SetInternalFieldCount(2);
147     fun->SetCallHandler(CallHandler, v8::Number::New(isolate, eObjType));
148     if (eObjType == FXJSOBJTYPE_GLOBAL) {
149       fun->InstanceTemplate()->Set(
150           v8::Symbol::GetToStringTag(isolate),
151           v8::String::NewFromUtf8(isolate, "global", v8::NewStringType::kNormal)
152               .ToLocalChecked());
153     }
154     m_FunctionTemplate.Reset(isolate, fun);
155     m_Signature.Reset(isolate, v8::Signature::New(isolate, fun));
156   }
157 
CallHandler(const v8::FunctionCallbackInfo<v8::Value> & info)158   static void CallHandler(const v8::FunctionCallbackInfo<v8::Value>& info) {
159     v8::Isolate* isolate = info.GetIsolate();
160     if (!info.IsConstructCall()) {
161       isolate->ThrowException(
162           v8::String::NewFromUtf8(isolate, "illegal constructor",
163                                   v8::NewStringType::kNormal)
164               .ToLocalChecked());
165       return;
166     }
167     if (info.Data().As<v8::Int32>()->Value() != FXJSOBJTYPE_DYNAMIC) {
168       isolate->ThrowException(
169           v8::String::NewFromUtf8(isolate, "not a dynamic object",
170                                   v8::NewStringType::kNormal)
171               .ToLocalChecked());
172       return;
173     }
174     v8::Local<v8::Object> holder = info.Holder();
175     ASSERT(holder->InternalFieldCount() == 2);
176     holder->SetAlignedPointerInInternalField(0, nullptr);
177     holder->SetAlignedPointerInInternalField(1, nullptr);
178   }
179 
GetIsolate() const180   v8::Isolate* GetIsolate() const { return m_pIsolate.Get(); }
181 
DefineConst(const char * sConstName,v8::Local<v8::Value> pDefault)182   void DefineConst(const char* sConstName, v8::Local<v8::Value> pDefault) {
183     GetInstanceTemplate()->Set(GetIsolate(), sConstName, pDefault);
184   }
185 
DefineProperty(v8::Local<v8::String> sPropName,v8::AccessorGetterCallback pPropGet,v8::AccessorSetterCallback pPropPut)186   void DefineProperty(v8::Local<v8::String> sPropName,
187                       v8::AccessorGetterCallback pPropGet,
188                       v8::AccessorSetterCallback pPropPut) {
189     GetInstanceTemplate()->SetAccessor(sPropName, pPropGet, pPropPut);
190   }
191 
DefineMethod(v8::Local<v8::String> sMethodName,v8::FunctionCallback pMethodCall)192   void DefineMethod(v8::Local<v8::String> sMethodName,
193                     v8::FunctionCallback pMethodCall) {
194     v8::Local<v8::FunctionTemplate> fun = v8::FunctionTemplate::New(
195         GetIsolate(), pMethodCall, v8::Local<v8::Value>(), GetSignature());
196     fun->RemovePrototype();
197     GetInstanceTemplate()->Set(sMethodName, fun, v8::ReadOnly);
198   }
199 
DefineAllProperties(v8::GenericNamedPropertyQueryCallback pPropQurey,v8::GenericNamedPropertyGetterCallback pPropGet,v8::GenericNamedPropertySetterCallback pPropPut,v8::GenericNamedPropertyDeleterCallback pPropDel)200   void DefineAllProperties(v8::GenericNamedPropertyQueryCallback pPropQurey,
201                            v8::GenericNamedPropertyGetterCallback pPropGet,
202                            v8::GenericNamedPropertySetterCallback pPropPut,
203                            v8::GenericNamedPropertyDeleterCallback pPropDel) {
204     GetInstanceTemplate()->SetHandler(v8::NamedPropertyHandlerConfiguration(
205         pPropGet, pPropPut, pPropQurey, pPropDel, nullptr,
206         v8::Local<v8::Value>(),
207         v8::PropertyHandlerFlags::kOnlyInterceptStrings));
208   }
209 
GetInstanceTemplate()210   v8::Local<v8::ObjectTemplate> GetInstanceTemplate() {
211     v8::EscapableHandleScope scope(GetIsolate());
212     v8::Local<v8::FunctionTemplate> function =
213         m_FunctionTemplate.Get(GetIsolate());
214     return scope.Escape(function->InstanceTemplate());
215   }
216 
GetSignature()217   v8::Local<v8::Signature> GetSignature() {
218     v8::EscapableHandleScope scope(GetIsolate());
219     return scope.Escape(m_Signature.Get(GetIsolate()));
220   }
221 
222   const char* const m_ObjName;
223   const FXJSOBJTYPE m_ObjType;
224   const CFXJS_Engine::Constructor m_pConstructor;
225   const CFXJS_Engine::Destructor m_pDestructor;
226   UnownedPtr<v8::Isolate> m_pIsolate;
227   v8::Global<v8::FunctionTemplate> m_FunctionTemplate;
228   v8::Global<v8::Signature> m_Signature;
229 };
230 
GetGlobalObjectTemplate(v8::Isolate * pIsolate)231 static v8::Local<v8::ObjectTemplate> GetGlobalObjectTemplate(
232     v8::Isolate* pIsolate) {
233   FXJS_PerIsolateData* pIsolateData = FXJS_PerIsolateData::Get(pIsolate);
234   for (int i = 0; i < pIsolateData->MaxObjDefinitionID(); ++i) {
235     CFXJS_ObjDefinition* pObjDef = pIsolateData->ObjDefinitionForID(i);
236     if (pObjDef->m_ObjType == FXJSOBJTYPE_GLOBAL)
237       return pObjDef->GetInstanceTemplate();
238   }
239   if (!g_DefaultGlobalObjectTemplate) {
240     v8::Local<v8::ObjectTemplate> hGlobalTemplate =
241         v8::ObjectTemplate::New(pIsolate);
242     hGlobalTemplate->Set(
243         v8::Symbol::GetToStringTag(pIsolate),
244         v8::String::NewFromUtf8(pIsolate, "global", v8::NewStringType::kNormal)
245             .ToLocalChecked());
246     g_DefaultGlobalObjectTemplate =
247         new v8::Global<v8::ObjectTemplate>(pIsolate, hGlobalTemplate);
248   }
249   return g_DefaultGlobalObjectTemplate->Get(pIsolate);
250 }
251 
Dispose(v8::Isolate * isolate,v8::Global<v8::Object> value,WeakCallbackDataType * key)252 void V8TemplateMapTraits::Dispose(v8::Isolate* isolate,
253                                   v8::Global<v8::Object> value,
254                                   WeakCallbackDataType* key) {
255   v8::Local<v8::Object> obj = value.Get(isolate);
256   if (obj.IsEmpty())
257     return;
258   int id = CFXJS_Engine::GetObjDefnID(obj);
259   if (id == -1)
260     return;
261   FXJS_PerIsolateData* pIsolateData = FXJS_PerIsolateData::Get(isolate);
262   CFXJS_ObjDefinition* pObjDef = pIsolateData->ObjDefinitionForID(id);
263   if (!pObjDef)
264     return;
265   if (pObjDef->m_pDestructor)
266     pObjDef->m_pDestructor(obj);
267   CFXJS_Engine::FreeObjectPrivate(obj);
268 }
269 
DisposeWeak(const v8::WeakCallbackInfo<WeakCallbackDataType> & data)270 void V8TemplateMapTraits::DisposeWeak(
271     const v8::WeakCallbackInfo<WeakCallbackDataType>& data) {
272   // TODO(tsepez): this is expected be called during GC.
273 }
274 
MapFromWeakCallbackInfo(const v8::WeakCallbackInfo<WeakCallbackDataType> & data)275 V8TemplateMapTraits::MapType* V8TemplateMapTraits::MapFromWeakCallbackInfo(
276     const v8::WeakCallbackInfo<WeakCallbackDataType>& data) {
277   V8TemplateMap* pMap =
278       FXJS_PerIsolateData::Get(data.GetIsolate())->m_pDynamicObjsMap.get();
279   return pMap ? &pMap->m_map : nullptr;
280 }
281 
FXJS_Initialize(unsigned int embedderDataSlot,v8::Isolate * pIsolate)282 void FXJS_Initialize(unsigned int embedderDataSlot, v8::Isolate* pIsolate) {
283   if (g_isolate) {
284     ASSERT(g_embedderDataSlot == embedderDataSlot);
285     ASSERT(g_isolate == pIsolate);
286     return;
287   }
288   g_embedderDataSlot = embedderDataSlot;
289   g_isolate = pIsolate;
290 }
291 
FXJS_Release()292 void FXJS_Release() {
293   ASSERT(!g_isolate || g_isolate_ref_count == 0);
294   delete g_DefaultGlobalObjectTemplate;
295   g_DefaultGlobalObjectTemplate = nullptr;
296   g_isolate = nullptr;
297 
298   delete g_arrayBufferAllocator;
299   g_arrayBufferAllocator = nullptr;
300 }
301 
FXJS_GetIsolate(v8::Isolate ** pResultIsolate)302 bool FXJS_GetIsolate(v8::Isolate** pResultIsolate) {
303   if (g_isolate) {
304     *pResultIsolate = g_isolate;
305     return false;
306   }
307   // Provide backwards compatibility when no external isolate.
308   if (!g_arrayBufferAllocator)
309     g_arrayBufferAllocator = new CFX_V8ArrayBufferAllocator();
310   v8::Isolate::CreateParams params;
311   params.array_buffer_allocator = g_arrayBufferAllocator;
312   *pResultIsolate = v8::Isolate::New(params);
313   return true;
314 }
315 
FXJS_GlobalIsolateRefCount()316 size_t FXJS_GlobalIsolateRefCount() {
317   return g_isolate_ref_count;
318 }
319 
~FXJS_PerIsolateData()320 FXJS_PerIsolateData::~FXJS_PerIsolateData() {}
321 
322 // static
SetUp(v8::Isolate * pIsolate)323 void FXJS_PerIsolateData::SetUp(v8::Isolate* pIsolate) {
324   if (!pIsolate->GetData(g_embedderDataSlot))
325     pIsolate->SetData(g_embedderDataSlot, new FXJS_PerIsolateData(pIsolate));
326 }
327 
328 // static
Get(v8::Isolate * pIsolate)329 FXJS_PerIsolateData* FXJS_PerIsolateData::Get(v8::Isolate* pIsolate) {
330   return static_cast<FXJS_PerIsolateData*>(
331       pIsolate->GetData(g_embedderDataSlot));
332 }
333 
MaxObjDefinitionID() const334 int FXJS_PerIsolateData::MaxObjDefinitionID() const {
335   return pdfium::CollectionSize<int>(m_ObjectDefnArray);
336 }
337 
FXJS_PerIsolateData(v8::Isolate * pIsolate)338 FXJS_PerIsolateData::FXJS_PerIsolateData(v8::Isolate* pIsolate)
339     : m_pDynamicObjsMap(new V8TemplateMap(pIsolate)) {}
340 
ObjDefinitionForID(int id) const341 CFXJS_ObjDefinition* FXJS_PerIsolateData::ObjDefinitionForID(int id) const {
342   return (id >= 0 && id < MaxObjDefinitionID()) ? m_ObjectDefnArray[id].get()
343                                                 : nullptr;
344 }
345 
AssignIDForObjDefinition(std::unique_ptr<CFXJS_ObjDefinition> pDefn)346 int FXJS_PerIsolateData::AssignIDForObjDefinition(
347     std::unique_ptr<CFXJS_ObjDefinition> pDefn) {
348   m_ObjectDefnArray.push_back(std::move(pDefn));
349   return m_ObjectDefnArray.size() - 1;
350 }
351 
CFXJS_Engine()352 CFXJS_Engine::CFXJS_Engine() : CFX_V8(nullptr) {}
353 
CFXJS_Engine(v8::Isolate * pIsolate)354 CFXJS_Engine::CFXJS_Engine(v8::Isolate* pIsolate) : CFX_V8(pIsolate) {}
355 
356 CFXJS_Engine::~CFXJS_Engine() = default;
357 
358 // static
GetObjDefnID(v8::Local<v8::Object> pObj)359 int CFXJS_Engine::GetObjDefnID(v8::Local<v8::Object> pObj) {
360   CFXJS_PerObjectData* pData = CFXJS_PerObjectData::GetFromObject(pObj);
361   return pData ? pData->m_ObjDefID : -1;
362 }
363 
364 // static
SetObjectPrivate(v8::Local<v8::Object> pObj,std::unique_ptr<CJS_Object> p)365 void CFXJS_Engine::SetObjectPrivate(v8::Local<v8::Object> pObj,
366                                     std::unique_ptr<CJS_Object> p) {
367   CFXJS_PerObjectData* pPerObjectData =
368       CFXJS_PerObjectData::GetFromObject(pObj);
369   if (!pPerObjectData)
370     return;
371   pPerObjectData->m_pPrivate = std::move(p);
372 }
373 
374 // static
FreeObjectPrivate(v8::Local<v8::Object> pObj)375 void CFXJS_Engine::FreeObjectPrivate(v8::Local<v8::Object> pObj) {
376   CFXJS_PerObjectData* pData = CFXJS_PerObjectData::GetFromObject(pObj);
377   pObj->SetAlignedPointerInInternalField(0, nullptr);
378   pObj->SetAlignedPointerInInternalField(1, nullptr);
379   delete pData;
380 }
381 
DefineObj(const char * sObjName,FXJSOBJTYPE eObjType,CFXJS_Engine::Constructor pConstructor,CFXJS_Engine::Destructor pDestructor)382 int CFXJS_Engine::DefineObj(const char* sObjName,
383                             FXJSOBJTYPE eObjType,
384                             CFXJS_Engine::Constructor pConstructor,
385                             CFXJS_Engine::Destructor pDestructor) {
386   v8::Isolate::Scope isolate_scope(GetIsolate());
387   v8::HandleScope handle_scope(GetIsolate());
388   FXJS_PerIsolateData::SetUp(GetIsolate());
389   FXJS_PerIsolateData* pIsolateData = FXJS_PerIsolateData::Get(GetIsolate());
390   return pIsolateData->AssignIDForObjDefinition(
391       pdfium::MakeUnique<CFXJS_ObjDefinition>(GetIsolate(), sObjName, eObjType,
392                                               pConstructor, pDestructor));
393 }
394 
DefineObjMethod(int nObjDefnID,const char * sMethodName,v8::FunctionCallback pMethodCall)395 void CFXJS_Engine::DefineObjMethod(int nObjDefnID,
396                                    const char* sMethodName,
397                                    v8::FunctionCallback pMethodCall) {
398   v8::Isolate::Scope isolate_scope(GetIsolate());
399   v8::HandleScope handle_scope(GetIsolate());
400   FXJS_PerIsolateData* pIsolateData = FXJS_PerIsolateData::Get(GetIsolate());
401   CFXJS_ObjDefinition* pObjDef = pIsolateData->ObjDefinitionForID(nObjDefnID);
402   pObjDef->DefineMethod(NewString(sMethodName), pMethodCall);
403 }
404 
DefineObjProperty(int nObjDefnID,const char * sPropName,v8::AccessorGetterCallback pPropGet,v8::AccessorSetterCallback pPropPut)405 void CFXJS_Engine::DefineObjProperty(int nObjDefnID,
406                                      const char* sPropName,
407                                      v8::AccessorGetterCallback pPropGet,
408                                      v8::AccessorSetterCallback pPropPut) {
409   v8::Isolate::Scope isolate_scope(GetIsolate());
410   v8::HandleScope handle_scope(GetIsolate());
411   FXJS_PerIsolateData* pIsolateData = FXJS_PerIsolateData::Get(GetIsolate());
412   CFXJS_ObjDefinition* pObjDef = pIsolateData->ObjDefinitionForID(nObjDefnID);
413   pObjDef->DefineProperty(NewString(sPropName), pPropGet, pPropPut);
414 }
415 
DefineObjAllProperties(int nObjDefnID,v8::GenericNamedPropertyQueryCallback pPropQurey,v8::GenericNamedPropertyGetterCallback pPropGet,v8::GenericNamedPropertySetterCallback pPropPut,v8::GenericNamedPropertyDeleterCallback pPropDel)416 void CFXJS_Engine::DefineObjAllProperties(
417     int nObjDefnID,
418     v8::GenericNamedPropertyQueryCallback pPropQurey,
419     v8::GenericNamedPropertyGetterCallback pPropGet,
420     v8::GenericNamedPropertySetterCallback pPropPut,
421     v8::GenericNamedPropertyDeleterCallback pPropDel) {
422   v8::Isolate::Scope isolate_scope(GetIsolate());
423   v8::HandleScope handle_scope(GetIsolate());
424   FXJS_PerIsolateData* pIsolateData = FXJS_PerIsolateData::Get(GetIsolate());
425   CFXJS_ObjDefinition* pObjDef = pIsolateData->ObjDefinitionForID(nObjDefnID);
426   pObjDef->DefineAllProperties(pPropQurey, pPropGet, pPropPut, pPropDel);
427 }
428 
DefineObjConst(int nObjDefnID,const char * sConstName,v8::Local<v8::Value> pDefault)429 void CFXJS_Engine::DefineObjConst(int nObjDefnID,
430                                   const char* sConstName,
431                                   v8::Local<v8::Value> pDefault) {
432   v8::Isolate::Scope isolate_scope(GetIsolate());
433   v8::HandleScope handle_scope(GetIsolate());
434   FXJS_PerIsolateData* pIsolateData = FXJS_PerIsolateData::Get(GetIsolate());
435   CFXJS_ObjDefinition* pObjDef = pIsolateData->ObjDefinitionForID(nObjDefnID);
436   pObjDef->DefineConst(sConstName, pDefault);
437 }
438 
DefineGlobalMethod(const char * sMethodName,v8::FunctionCallback pMethodCall)439 void CFXJS_Engine::DefineGlobalMethod(const char* sMethodName,
440                                       v8::FunctionCallback pMethodCall) {
441   v8::Isolate::Scope isolate_scope(GetIsolate());
442   v8::HandleScope handle_scope(GetIsolate());
443   v8::Local<v8::FunctionTemplate> fun =
444       v8::FunctionTemplate::New(GetIsolate(), pMethodCall);
445   fun->RemovePrototype();
446   GetGlobalObjectTemplate(GetIsolate())
447       ->Set(NewString(sMethodName), fun, v8::ReadOnly);
448 }
449 
DefineGlobalConst(const wchar_t * sConstName,v8::FunctionCallback pConstGetter)450 void CFXJS_Engine::DefineGlobalConst(const wchar_t* sConstName,
451                                      v8::FunctionCallback pConstGetter) {
452   v8::Isolate::Scope isolate_scope(GetIsolate());
453   v8::HandleScope handle_scope(GetIsolate());
454   v8::Local<v8::FunctionTemplate> fun =
455       v8::FunctionTemplate::New(GetIsolate(), pConstGetter);
456   fun->RemovePrototype();
457   GetGlobalObjectTemplate(GetIsolate())
458       ->SetAccessorProperty(NewString(sConstName), fun);
459 }
460 
InitializeEngine()461 void CFXJS_Engine::InitializeEngine() {
462   if (GetIsolate() == g_isolate)
463     ++g_isolate_ref_count;
464 
465   v8::Isolate::Scope isolate_scope(GetIsolate());
466   v8::HandleScope handle_scope(GetIsolate());
467 
468   // This has to happen before we call GetGlobalObjectTemplate because that
469   // method gets the PerIsolateData from GetIsolate().
470   FXJS_PerIsolateData::SetUp(GetIsolate());
471 
472   v8::Local<v8::Context> v8Context = v8::Context::New(
473       GetIsolate(), nullptr, GetGlobalObjectTemplate(GetIsolate()));
474 
475   // May not have the internal fields when called from tests.
476   v8::Local<v8::Object> pThisProxy = v8Context->Global();
477   if (pThisProxy->InternalFieldCount() == 2) {
478     pThisProxy->SetAlignedPointerInInternalField(0, nullptr);
479     pThisProxy->SetAlignedPointerInInternalField(1, nullptr);
480   }
481   v8::Local<v8::Object> pThis = pThisProxy->GetPrototype().As<v8::Object>();
482   if (pThis->InternalFieldCount() == 2) {
483     pThis->SetAlignedPointerInInternalField(0, nullptr);
484     pThis->SetAlignedPointerInInternalField(1, nullptr);
485   }
486 
487   v8::Context::Scope context_scope(v8Context);
488   FXJS_PerIsolateData* pIsolateData = FXJS_PerIsolateData::Get(GetIsolate());
489   int maxID = pIsolateData->MaxObjDefinitionID();
490   m_StaticObjects.resize(maxID + 1);
491   for (int i = 0; i < maxID; ++i) {
492     CFXJS_ObjDefinition* pObjDef = pIsolateData->ObjDefinitionForID(i);
493     if (pObjDef->m_ObjType == FXJSOBJTYPE_GLOBAL) {
494       CFXJS_PerObjectData::SetInObject(new CFXJS_PerObjectData(i),
495                                        v8Context->Global()
496                                            ->GetPrototype()
497                                            ->ToObject(v8Context)
498                                            .ToLocalChecked());
499       if (pObjDef->m_pConstructor) {
500         pObjDef->m_pConstructor(this, v8Context->Global()
501                                           ->GetPrototype()
502                                           ->ToObject(v8Context)
503                                           .ToLocalChecked());
504       }
505     } else if (pObjDef->m_ObjType == FXJSOBJTYPE_STATIC) {
506       v8::Local<v8::String> pObjName = NewString(pObjDef->m_ObjName);
507       v8::Local<v8::Object> obj = NewFXJSBoundObject(i, FXJSOBJTYPE_STATIC);
508       if (!obj.IsEmpty()) {
509         v8Context->Global()->Set(v8Context, pObjName, obj).FromJust();
510         m_StaticObjects[i] = v8::Global<v8::Object>(GetIsolate(), obj);
511       }
512     }
513   }
514   m_V8Context.Reset(GetIsolate(), v8Context);
515 }
516 
ReleaseEngine()517 void CFXJS_Engine::ReleaseEngine() {
518   v8::Isolate::Scope isolate_scope(GetIsolate());
519   v8::HandleScope handle_scope(GetIsolate());
520   v8::Local<v8::Context> context = GetV8Context();
521   v8::Context::Scope context_scope(context);
522   FXJS_PerIsolateData* pIsolateData = FXJS_PerIsolateData::Get(GetIsolate());
523   if (!pIsolateData)
524     return;
525 
526   m_ConstArrays.clear();
527 
528   for (int i = 0; i < pIsolateData->MaxObjDefinitionID(); ++i) {
529     CFXJS_ObjDefinition* pObjDef = pIsolateData->ObjDefinitionForID(i);
530     v8::Local<v8::Object> pObj;
531     if (pObjDef->m_ObjType == FXJSOBJTYPE_GLOBAL) {
532       pObj =
533           context->Global()->GetPrototype()->ToObject(context).ToLocalChecked();
534     } else if (!m_StaticObjects[i].IsEmpty()) {
535       pObj = v8::Local<v8::Object>::New(GetIsolate(), m_StaticObjects[i]);
536       m_StaticObjects[i].Reset();
537     }
538     if (!pObj.IsEmpty()) {
539       if (pObjDef->m_pDestructor)
540         pObjDef->m_pDestructor(pObj);
541       FreeObjectPrivate(pObj);
542     }
543   }
544 
545   m_V8Context.Reset();
546 
547   if (GetIsolate() == g_isolate && --g_isolate_ref_count > 0)
548     return;
549 
550   delete pIsolateData;
551   GetIsolate()->SetData(g_embedderDataSlot, nullptr);
552 }
553 
Execute(const WideString & script)554 Optional<IJS_Runtime::JS_Error> CFXJS_Engine::Execute(
555     const WideString& script) {
556   v8::Isolate::Scope isolate_scope(GetIsolate());
557   v8::TryCatch try_catch(GetIsolate());
558   v8::Local<v8::Context> context = GetIsolate()->GetCurrentContext();
559   v8::Local<v8::Script> compiled_script;
560   if (!v8::Script::Compile(context, NewString(script.AsStringView()))
561            .ToLocal(&compiled_script)) {
562     v8::String::Utf8Value error(GetIsolate(), try_catch.Exception());
563     v8::Local<v8::Message> msg = try_catch.Message();
564     int line = -1;
565     int column = -1;
566     std::tie(line, column) = GetLineAndColumnFromError(msg, context);
567     return IJS_Runtime::JS_Error(line, column, WideString::FromUTF8(*error));
568   }
569 
570   v8::Local<v8::Value> result;
571   if (!compiled_script->Run(context).ToLocal(&result)) {
572     v8::String::Utf8Value error(GetIsolate(), try_catch.Exception());
573     auto msg = try_catch.Message();
574     int line = -1;
575     int column = -1;
576     std::tie(line, column) = GetLineAndColumnFromError(msg, context);
577     return IJS_Runtime::JS_Error(line, column, WideString::FromUTF8(*error));
578   }
579   return pdfium::nullopt;
580 }
581 
NewFXJSBoundObject(int nObjDefnID,FXJSOBJTYPE type)582 v8::Local<v8::Object> CFXJS_Engine::NewFXJSBoundObject(int nObjDefnID,
583                                                        FXJSOBJTYPE type) {
584   v8::Isolate::Scope isolate_scope(GetIsolate());
585   v8::Local<v8::Context> context = GetIsolate()->GetCurrentContext();
586   FXJS_PerIsolateData* pData = FXJS_PerIsolateData::Get(GetIsolate());
587   if (!pData)
588     return v8::Local<v8::Object>();
589 
590   CFXJS_ObjDefinition* pObjDef = pData->ObjDefinitionForID(nObjDefnID);
591   if (!pObjDef)
592     return v8::Local<v8::Object>();
593 
594   v8::Local<v8::Object> obj;
595   if (!pObjDef->GetInstanceTemplate()->NewInstance(context).ToLocal(&obj))
596     return v8::Local<v8::Object>();
597 
598   CFXJS_PerObjectData* pObjData = new CFXJS_PerObjectData(nObjDefnID);
599   CFXJS_PerObjectData::SetInObject(pObjData, obj);
600   if (pObjDef->m_pConstructor)
601     pObjDef->m_pConstructor(this, obj);
602 
603   if (type == FXJSOBJTYPE_DYNAMIC) {
604     auto* pIsolateData = FXJS_PerIsolateData::Get(GetIsolate());
605     if (pIsolateData->m_pDynamicObjsMap)
606       pIsolateData->m_pDynamicObjsMap->SetAndMakeWeak(pObjData, obj);
607   }
608   return obj;
609 }
610 
GetThisObj()611 v8::Local<v8::Object> CFXJS_Engine::GetThisObj() {
612   v8::Isolate::Scope isolate_scope(GetIsolate());
613   if (!FXJS_PerIsolateData::Get(GetIsolate()))
614     return v8::Local<v8::Object>();
615 
616   // Return the global object.
617   v8::Local<v8::Context> context = GetIsolate()->GetCurrentContext();
618   return context->Global()->GetPrototype()->ToObject(context).ToLocalChecked();
619 }
620 
Error(const WideString & message)621 void CFXJS_Engine::Error(const WideString& message) {
622   GetIsolate()->ThrowException(NewString(message.AsStringView()));
623 }
624 
GetV8Context()625 v8::Local<v8::Context> CFXJS_Engine::GetV8Context() {
626   return v8::Local<v8::Context>::New(GetIsolate(), m_V8Context);
627 }
628 
629 // static
GetObjectPrivate(v8::Local<v8::Object> pObj)630 CJS_Object* CFXJS_Engine::GetObjectPrivate(v8::Local<v8::Object> pObj) {
631   auto* pData = CFXJS_PerObjectData::GetFromObject(pObj);
632   if (pData)
633     return pData->m_pPrivate.get();
634 
635   if (pObj.IsEmpty())
636     return nullptr;
637 
638   // It could be a global proxy object, in which case the prototype holds
639   // the actual bound object.
640   v8::Local<v8::Value> val = pObj->GetPrototype();
641   if (!val->IsObject())
642     return nullptr;
643 
644   auto* pProtoData = CFXJS_PerObjectData::GetFromObject(val.As<v8::Object>());
645   if (!pProtoData)
646     return nullptr;
647 
648   auto* pIsolateData = FXJS_PerIsolateData::Get(v8::Isolate::GetCurrent());
649   if (!pIsolateData)
650     return nullptr;
651 
652   CFXJS_ObjDefinition* pObjDef =
653       pIsolateData->ObjDefinitionForID(pProtoData->m_ObjDefID);
654   if (!pObjDef || pObjDef->m_ObjType != FXJSOBJTYPE_GLOBAL)
655     return nullptr;
656 
657   return pProtoData->m_pPrivate.get();
658 }
659 
GetConstArray(const WideString & name)660 v8::Local<v8::Array> CFXJS_Engine::GetConstArray(const WideString& name) {
661   return v8::Local<v8::Array>::New(GetIsolate(), m_ConstArrays[name]);
662 }
663 
SetConstArray(const WideString & name,v8::Local<v8::Array> array)664 void CFXJS_Engine::SetConstArray(const WideString& name,
665                                  v8::Local<v8::Array> array) {
666   m_ConstArrays[name] = v8::Global<v8::Array>(GetIsolate(), array);
667 }
668