Make v8 embedder data slot configurable
[pdfium.git] / fpdfsdk / src / jsapi / fxjs_v8.cpp
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 "../../../core/include/fxcrt/fx_basic.h"
8 #include "../../../core/include/fxcrt/fx_ext.h"
9 #include "../../include/jsapi/fxjs_v8.h"
10 #include "../../include/fsdk_define.h"
11 #include "time.h"
12 #include <cmath>
13 #include <limits>
14
15 #define VALUE_NAME_STRING               L"string"
16 #define VALUE_NAME_NUMBER               L"number"
17 #define VALUE_NAME_BOOLEAN              L"boolean"
18 #define VALUE_NAME_DATE                 L"date"
19 #define VALUE_NAME_OBJECT               L"object"
20 #define VALUE_NAME_FXOBJ                L"fxobj"
21 #define VALUE_NAME_NULL                 L"null"
22 #define VALUE_NAME_UNDEFINED    L"undefined"
23
24 const static FX_DWORD g_nan[2] = {0,0x7FF80000 };
25 static double GetNan()
26 {
27   return *(double*)g_nan;
28 }
29 static unsigned int g_embedderDataSlot = 0u;
30
31
32 class CJS_PrivateData
33 {
34 public:
35         CJS_PrivateData():ObjDefID(-1), pPrivate(NULL) {}
36         int ObjDefID;
37         void*   pPrivate;
38 };
39
40
41 class CJS_ObjDefintion
42 {
43 public:
44         CJS_ObjDefintion(v8::Isolate* isolate, const wchar_t* sObjName, FXJSOBJTYPE eObjType, LP_CONSTRUCTOR pConstructor, LP_DESTRUCTOR pDestructor, unsigned bApplyNew):
45           objName(sObjName), objType(eObjType), m_pConstructor(pConstructor), m_pDestructor(pDestructor),m_bApplyNew(bApplyNew),m_bSetAsGlobalObject(FALSE)
46           {
47                   v8::Isolate::Scope isolate_scope(isolate);
48                   v8::HandleScope handle_scope(isolate);
49
50                   v8::Local<v8::ObjectTemplate> objTemplate = v8::ObjectTemplate::New(isolate);
51                   objTemplate->SetInternalFieldCount(2);
52                   m_objTemplate.Reset(isolate, objTemplate);
53
54                  //Document as the global object.
55                   if(FXSYS_wcscmp(sObjName, L"Document") == 0)
56                   {
57                          m_bSetAsGlobalObject = TRUE;
58                   }
59
60           }
61           ~CJS_ObjDefintion()
62           {
63                   m_objTemplate.Reset();
64                   m_StaticObj.Reset();
65           }
66 public:
67         const wchar_t* objName;
68         FXJSOBJTYPE objType;
69         LP_CONSTRUCTOR m_pConstructor;
70         LP_DESTRUCTOR m_pDestructor;
71         unsigned m_bApplyNew;
72         FX_BOOL m_bSetAsGlobalObject;
73
74         v8::Global<v8::ObjectTemplate> m_objTemplate;
75         v8::Global<v8::Object> m_StaticObj;
76 };
77
78 int JS_DefineObj(IJS_Runtime* pJSRuntime, const wchar_t* sObjName, FXJSOBJTYPE eObjType, LP_CONSTRUCTOR pConstructor, LP_DESTRUCTOR pDestructor, unsigned bApplyNew)
79 {
80         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
81         v8::Isolate::Scope isolate_scope(isolate);
82         v8::HandleScope handle_scope(isolate);
83         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
84         if(!pArray)
85         {
86                 pArray = new CFX_PtrArray();
87                 isolate->SetData(g_embedderDataSlot, pArray);
88         }
89         CJS_ObjDefintion* pObjDef = new CJS_ObjDefintion(isolate, sObjName, eObjType, pConstructor, pDestructor, bApplyNew);
90         pArray->Add(pObjDef);
91         return pArray->GetSize()-1;
92 }
93
94 int JS_DefineObjMethod(IJS_Runtime* pJSRuntime, int nObjDefnID, const wchar_t* sMethodName, v8::FunctionCallback pMethodCall)
95 {
96         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
97         v8::Isolate::Scope isolate_scope(isolate);
98         v8::HandleScope handle_scope(isolate);
99
100         CFX_WideString ws = CFX_WideString(sMethodName);
101         CFX_ByteString bsMethodName = ws.UTF8Encode();
102
103         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
104         if(!pArray) return 0;
105
106         if(nObjDefnID<0 || nObjDefnID>= pArray->GetSize()) return 0;
107         CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(nObjDefnID);
108         v8::Local<v8::ObjectTemplate> objTemp = v8::Local<v8::ObjectTemplate>::New(isolate, pObjDef->m_objTemplate);
109         objTemp->Set(v8::String::NewFromUtf8(isolate, bsMethodName.c_str(), v8::NewStringType::kNormal).ToLocalChecked(), v8::FunctionTemplate::New(isolate, pMethodCall), v8::ReadOnly);
110         pObjDef->m_objTemplate.Reset(isolate,objTemp);
111         return 0;
112 }
113
114 int JS_DefineObjProperty(IJS_Runtime* pJSRuntime, int nObjDefnID, const wchar_t* sPropName, v8::AccessorGetterCallback pPropGet, v8::AccessorSetterCallback pPropPut)
115 {
116         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
117         v8::Isolate::Scope isolate_scope(isolate);
118         v8::HandleScope handle_scope(isolate);
119
120         CFX_WideString ws = CFX_WideString(sPropName);
121         CFX_ByteString bsPropertyName = ws.UTF8Encode();
122
123         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
124         if(!pArray) return 0;
125
126         if(nObjDefnID<0 || nObjDefnID>= pArray->GetSize()) return 0;
127         CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(nObjDefnID);
128         v8::Local<v8::ObjectTemplate> objTemp = v8::Local<v8::ObjectTemplate>::New(isolate, pObjDef->m_objTemplate);
129         objTemp->SetAccessor(v8::String::NewFromUtf8(isolate, bsPropertyName.c_str(), v8::NewStringType::kNormal).ToLocalChecked(), pPropGet, pPropPut);
130         pObjDef->m_objTemplate.Reset(isolate,objTemp);
131         return 0;
132 }
133
134 int     JS_DefineObjAllProperties(IJS_Runtime* pJSRuntime, int nObjDefnID, v8::NamedPropertyQueryCallback pPropQurey, v8::NamedPropertyGetterCallback pPropGet, v8::NamedPropertySetterCallback pPropPut, v8::NamedPropertyDeleterCallback pPropDel)
135 {
136         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
137         v8::Isolate::Scope isolate_scope(isolate);
138         v8::HandleScope handle_scope(isolate);
139
140         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
141         if(!pArray) return 0;
142
143         if(nObjDefnID<0 || nObjDefnID>= pArray->GetSize()) return 0;
144         CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(nObjDefnID);
145         v8::Local<v8::ObjectTemplate> objTemp = v8::Local<v8::ObjectTemplate>::New(isolate, pObjDef->m_objTemplate);
146         objTemp->SetNamedPropertyHandler(pPropGet, pPropPut, pPropQurey, pPropDel);
147         pObjDef->m_objTemplate.Reset(isolate,objTemp);
148         return 0;
149 }
150
151 int JS_DefineObjConst(IJS_Runtime* pJSRuntime, int nObjDefnID, const wchar_t* sConstName, v8::Local<v8::Value> pDefault)
152 {
153         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
154         v8::Isolate::Scope isolate_scope(isolate);
155         v8::HandleScope handle_scope(isolate);
156
157         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
158         if(!pArray) return 0;
159
160         CFX_WideString ws = CFX_WideString(sConstName);
161         CFX_ByteString bsConstName = ws.UTF8Encode();
162
163         if(nObjDefnID<0 || nObjDefnID>= pArray->GetSize()) return 0;
164         CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(nObjDefnID);
165         v8::Local<v8::ObjectTemplate> objTemp = v8::Local<v8::ObjectTemplate>::New(isolate, pObjDef->m_objTemplate);
166         objTemp->Set(isolate, bsConstName.c_str(), pDefault);
167         pObjDef->m_objTemplate.Reset(isolate,objTemp);
168         return 0;
169 }
170
171 static v8::Global<v8::ObjectTemplate>& _getGlobalObjectTemplate(IJS_Runtime* pJSRuntime)
172 {
173         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
174         v8::Isolate::Scope isolate_scope(isolate);
175         v8::HandleScope handle_scope(isolate);
176
177         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
178         ASSERT(pArray != NULL);
179         for(int i=0; i<pArray->GetSize(); i++)
180         {
181                 CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(i);
182                 if(pObjDef->m_bSetAsGlobalObject)
183                         return pObjDef->m_objTemplate;
184         }
185         static v8::Global<v8::ObjectTemplate> gloabalObjectTemplate;
186         return gloabalObjectTemplate;
187 }
188
189 int JS_DefineGlobalMethod(IJS_Runtime* pJSRuntime, const wchar_t* sMethodName, v8::FunctionCallback pMethodCall)
190 {
191         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
192         v8::Isolate::Scope isolate_scope(isolate);
193         v8::HandleScope handle_scope(isolate);
194
195         CFX_WideString ws = CFX_WideString(sMethodName);
196         CFX_ByteString bsMethodName = ws.UTF8Encode();
197
198         v8::Local<v8::FunctionTemplate> funTempl = v8::FunctionTemplate::New(isolate, pMethodCall);
199         v8::Local<v8::ObjectTemplate> objTemp;
200
201         v8::Global<v8::ObjectTemplate>& globalObjTemp = _getGlobalObjectTemplate(pJSRuntime);
202         if(globalObjTemp.IsEmpty())
203                 objTemp = v8::ObjectTemplate::New(isolate);
204         else
205                 objTemp = v8::Local<v8::ObjectTemplate>::New(isolate, globalObjTemp);
206         objTemp->Set(v8::String::NewFromUtf8(isolate, bsMethodName.c_str(), v8::NewStringType::kNormal).ToLocalChecked(), funTempl, v8::ReadOnly);
207
208         globalObjTemp.Reset(isolate,objTemp);
209
210         return 0;
211 }
212
213 int JS_DefineGlobalConst(IJS_Runtime* pJSRuntime, const wchar_t* sConstName, v8::Local<v8::Value> pDefault)
214 {
215         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
216         v8::Isolate::Scope isolate_scope(isolate);
217         v8::HandleScope handle_scope(isolate);
218
219         CFX_WideString ws = CFX_WideString(sConstName);
220         CFX_ByteString bsConst= ws.UTF8Encode();
221
222         v8::Local<v8::ObjectTemplate> objTemp;
223
224         v8::Global<v8::ObjectTemplate>& globalObjTemp = _getGlobalObjectTemplate(pJSRuntime);
225         if(globalObjTemp.IsEmpty())
226                 objTemp = v8::ObjectTemplate::New(isolate);
227         else
228                 objTemp = v8::Local<v8::ObjectTemplate>::New(isolate, globalObjTemp);
229         objTemp->Set(v8::String::NewFromUtf8(isolate, bsConst.c_str(), v8::NewStringType::kNormal).ToLocalChecked(), pDefault, v8::ReadOnly);
230
231         globalObjTemp.Reset(isolate,objTemp);
232
233         return 0;
234 }
235
236
237 void JS_InitialRuntime(IJS_Runtime* pJSRuntime,IFXJS_Runtime* pFXRuntime, IFXJS_Context* context, v8::Global<v8::Context>& v8PersistentContext)
238 {
239         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
240         v8::Isolate::Scope isolate_scope(isolate);
241         v8::HandleScope handle_scope(isolate);
242
243         v8::Global<v8::ObjectTemplate>& globalObjTemp = _getGlobalObjectTemplate(pJSRuntime);
244         v8::Local<v8::Context> v8Context = v8::Context::New(isolate, NULL, v8::Local<v8::ObjectTemplate>::New(isolate, globalObjTemp));
245         v8::Context::Scope context_scope(v8Context);
246
247         v8::Local<v8::External> ptr = v8::External::New(isolate, pFXRuntime);
248         v8Context->SetEmbedderData(1, ptr);
249
250         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
251         if(!pArray) return;
252
253         for(int i=0; i<pArray->GetSize(); i++)
254         {
255                 CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(i);
256                 CFX_WideString ws = CFX_WideString(pObjDef->objName);
257                 CFX_ByteString bs = ws.UTF8Encode();
258                 v8::Local<v8::String> objName = v8::String::NewFromUtf8(isolate, bs.c_str(), v8::NewStringType::kNormal, bs.GetLength()).ToLocalChecked();
259
260
261                 if(pObjDef->objType == JS_DYNAMIC)
262                 {
263                         //Document is set as global object, need to construct it first.
264                         if(ws.Equal(L"Document"))
265                         {
266
267                                 CJS_PrivateData* pPrivateData = new CJS_PrivateData;
268                                 pPrivateData->ObjDefID = i;
269
270                                 v8Context->Global()->GetPrototype()->ToObject(v8Context).ToLocalChecked()->SetAlignedPointerInInternalField(0, pPrivateData);
271
272                                 if(pObjDef->m_pConstructor)
273                                         pObjDef->m_pConstructor(context, v8Context->Global()->GetPrototype()->ToObject(v8Context).ToLocalChecked(), v8Context->Global()->GetPrototype()->ToObject(v8Context).ToLocalChecked());
274                         }
275                 }
276                 else
277                 {
278                         v8::Local<v8::Object> obj = JS_NewFxDynamicObj(pJSRuntime, context, i);
279                         v8Context->Global()->Set(v8Context, objName, obj).FromJust();
280                         pObjDef->m_StaticObj.Reset(isolate, obj);
281                 }
282         }
283         v8PersistentContext.Reset(isolate, v8Context);
284 }
285
286 void JS_ReleaseRuntime(IJS_Runtime* pJSRuntime, v8::Global<v8::Context>& v8PersistentContext)
287 {
288         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
289         v8::Isolate::Scope isolate_scope(isolate);
290         v8::HandleScope handle_scope(isolate);
291         v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, v8PersistentContext);
292         v8::Context::Scope context_scope(context);
293
294         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
295         if(!pArray) return ;
296
297         for(int i=0; i<pArray->GetSize(); i++)
298         {
299                 CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(i);
300                 if(!pObjDef->m_StaticObj.IsEmpty())
301                 {
302                         v8::Local<v8::Object> pObj = v8::Local<v8::Object>::New(isolate, pObjDef->m_StaticObj);
303                         if(pObjDef->m_pDestructor)
304                                 pObjDef->m_pDestructor(pObj);
305                         JS_FreePrivate(pObj);
306                 }
307                 delete pObjDef;
308         }
309         delete pArray;
310         isolate->SetData(g_embedderDataSlot,NULL);
311 }
312
313 void JS_Initial(unsigned int embedderDataSlot)
314 {
315         g_embedderDataSlot = embedderDataSlot;
316 }
317 void JS_Release()
318 {
319
320 }
321 int JS_Parse(IJS_Runtime* pJSRuntime, IFXJS_Context* pJSContext, const wchar_t* script, long length, FXJSErr* perror)
322 {
323         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
324         v8::Isolate::Scope isolate_scope(isolate);
325         v8::TryCatch try_catch(isolate);
326
327         CFX_WideString wsScript(script);
328         CFX_ByteString bsScript = wsScript.UTF8Encode();
329
330
331         v8::Local<v8::Context> context = isolate->GetCurrentContext();
332         v8::Local<v8::Script> compiled_script;
333         if (!v8::Script::Compile(context, v8::String::NewFromUtf8(isolate, bsScript.c_str(), v8::NewStringType::kNormal, bsScript.GetLength()).ToLocalChecked()).ToLocal(&compiled_script)) {
334                 v8::String::Utf8Value error(try_catch.Exception());
335                 return -1;
336         }
337         return 0;
338 }
339
340 int JS_Execute(IJS_Runtime* pJSRuntime, IFXJS_Context* pJSContext, const wchar_t* script, long length, FXJSErr* perror)
341 {
342         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
343         v8::Isolate::Scope isolate_scope(isolate);
344         v8::TryCatch try_catch(isolate);
345
346         CFX_WideString wsScript(script);
347         CFX_ByteString bsScript = wsScript.UTF8Encode();
348
349         v8::Local<v8::Context> context = isolate->GetCurrentContext();
350         v8::Local<v8::Script> compiled_script;
351         if (!v8::Script::Compile(context, v8::String::NewFromUtf8(isolate, bsScript.c_str(), v8::NewStringType::kNormal, bsScript.GetLength()).ToLocalChecked()).ToLocal(&compiled_script)) {
352                 v8::String::Utf8Value error(try_catch.Exception());
353                 return -1;
354         }
355
356         v8::Local<v8::Value> result;
357         if (!compiled_script->Run(context).ToLocal(&result)) {
358                 v8::String::Utf8Value error(try_catch.Exception());
359                 return -1;
360         }
361         return 0;
362 }
363
364 v8::Local<v8::Object> JS_NewFxDynamicObj(IJS_Runtime* pJSRuntime, IFXJS_Context* pJSContext, int nObjDefnID)
365 {
366         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
367         v8::Isolate::Scope isolate_scope(isolate);
368         v8::Local<v8::Context> context = isolate->GetCurrentContext();
369         if(-1 == nObjDefnID)
370         {
371                 v8::Local<v8::ObjectTemplate> objTempl = v8::ObjectTemplate::New(isolate);
372                 v8::Local<v8::Object> obj;
373                 if (objTempl->NewInstance(context).ToLocal(&obj)) return obj;
374                 return v8::Local<v8::Object>();
375         }
376
377         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
378         if(!pArray) return v8::Local<v8::Object>();
379
380
381         if(nObjDefnID<0 || nObjDefnID>= pArray->GetSize()) return v8::Local<v8::Object>();
382         CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(nObjDefnID);
383
384         v8::Local<v8::ObjectTemplate> objTemp = v8::Local<v8::ObjectTemplate>::New(isolate, pObjDef->m_objTemplate);
385         v8::Local<v8::Object> obj;
386         if (!objTemp->NewInstance(context).ToLocal(&obj)) return v8::Local<v8::Object>();
387
388         CJS_PrivateData* pPrivateData = new CJS_PrivateData;
389         pPrivateData->ObjDefID = nObjDefnID;
390
391         obj->SetAlignedPointerInInternalField(0, pPrivateData);
392         if(pObjDef->m_pConstructor)
393                 pObjDef->m_pConstructor(pJSContext, obj, context->Global()->GetPrototype()->ToObject(context).ToLocalChecked());
394
395         return obj;
396 }
397
398 v8::Local<v8::Object> JS_GetStaticObj(IJS_Runtime* pJSRuntime, int nObjDefnID)
399 {
400         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
401         v8::Isolate::Scope isolate_scope(isolate);
402
403         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
404         if(!pArray) return v8::Local<v8::Object>();
405
406         if(nObjDefnID<0 || nObjDefnID>= pArray->GetSize()) return v8::Local<v8::Object>();
407         CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(nObjDefnID);
408         v8::Local<v8::Object> obj = v8::Local<v8::Object>::New(isolate,pObjDef->m_StaticObj);
409         return obj;
410 }
411
412 void JS_SetThisObj(IJS_Runtime* pJSRuntime, int nThisObjID)
413 {
414         //Do nothing.
415 }
416 v8::Local<v8::Object>   JS_GetThisObj(IJS_Runtime * pJSRuntime)
417 {
418         //Return the global object.
419         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
420         v8::Isolate::Scope isolate_scope(isolate);
421
422         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
423         if(!pArray) return v8::Local<v8::Object>();
424
425         v8::Local<v8::Context> context = isolate->GetCurrentContext();
426         return context->Global()->GetPrototype()->ToObject(context).ToLocalChecked();
427 }
428
429 int     JS_GetObjDefnID(v8::Local<v8::Object> pObj)
430 {
431         if(pObj.IsEmpty() || !pObj->InternalFieldCount()) return -1;
432         CJS_PrivateData* pPrivateData = (CJS_PrivateData*)pObj->GetAlignedPointerFromInternalField(0);
433         if(pPrivateData)
434                 return pPrivateData->ObjDefID;
435         return -1;
436 }
437
438 IJS_Runtime* JS_GetRuntime(v8::Local<v8::Object> pObj)
439 {
440         if(pObj.IsEmpty()) return NULL;
441         v8::Local<v8::Context> context = pObj->CreationContext();
442         if(context.IsEmpty()) return NULL;
443         return context->GetIsolate();
444 }
445
446 int JS_GetObjDefnID(IJS_Runtime * pJSRuntime, const wchar_t* pObjName)
447 {
448         v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
449         v8::Isolate::Scope isolate_scope(isolate);
450
451         CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(g_embedderDataSlot);
452         if(!pArray) return -1;
453
454         for(int i=0; i<pArray->GetSize(); i++)
455         {
456                 CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(i);
457                 if(FXSYS_wcscmp(pObjDef->objName, pObjName) == 0)
458                         return i;
459         }
460         return -1;
461 }
462
463 void JS_Error(v8::Isolate* isolate, const CFX_WideString& message)
464 {
465     // Conversion from pdfium's wchar_t wide-strings to v8's uint16_t
466     // wide-strings isn't handled by v8, so use UTF8 as a common
467     // intermediate format.
468     CFX_ByteString utf8_message = message.UTF8Encode();
469     isolate->ThrowException(v8::String::NewFromUtf8(isolate,
470                                                     utf8_message.c_str(),
471                                                     v8::NewStringType::kNormal).ToLocalChecked());
472 }
473
474 unsigned JS_CalcHash(const wchar_t* main, unsigned nLen)
475 {
476         return (unsigned)FX_HashCode_String_GetW(main, nLen);
477 }
478
479 unsigned JS_CalcHash(const wchar_t* main)
480 {
481         return (unsigned)FX_HashCode_String_GetW(main, FXSYS_wcslen(main));
482 }
483 const wchar_t*  JS_GetTypeof(v8::Local<v8::Value> pObj)
484 {
485         if(pObj.IsEmpty()) return NULL;
486         if(pObj->IsString())
487                 return VALUE_NAME_STRING;
488         if(pObj->IsNumber())
489                 return VALUE_NAME_NUMBER;
490         if(pObj->IsBoolean())
491                 return VALUE_NAME_BOOLEAN;
492         if(pObj->IsDate())
493                 return VALUE_NAME_DATE;
494         if(pObj->IsObject())
495                 return VALUE_NAME_OBJECT;
496         if(pObj->IsNull())
497                 return VALUE_NAME_NULL;
498         if(pObj->IsUndefined())
499                 return VALUE_NAME_UNDEFINED;
500         return NULL;
501
502 }
503 void JS_SetPrivate(v8::Local<v8::Object> pObj, void* p)
504 {
505         JS_SetPrivate(NULL, pObj, p);
506 }
507
508 void* JS_GetPrivate(v8::Local<v8::Object> pObj)
509 {
510         return JS_GetPrivate(NULL,pObj);
511 }
512
513 void JS_SetPrivate(IJS_Runtime* pJSRuntime, v8::Local<v8::Object> pObj, void* p)
514 {
515         if(pObj.IsEmpty() || !pObj->InternalFieldCount()) return;
516         CJS_PrivateData* pPrivateData  = (CJS_PrivateData*)pObj->GetAlignedPointerFromInternalField(0);
517         if(!pPrivateData) return;
518         pPrivateData->pPrivate = p;
519 }
520
521 void* JS_GetPrivate(IJS_Runtime* pJSRuntime, v8::Local<v8::Object> pObj)
522 {
523         if(pObj.IsEmpty()) return NULL;
524         CJS_PrivateData* pPrivateData  = NULL;
525         if(pObj->InternalFieldCount())
526                 pPrivateData = (CJS_PrivateData*)pObj->GetAlignedPointerFromInternalField(0);
527         else
528         {
529                 //It could be a global proxy object.
530                 v8::Local<v8::Value> v = pObj->GetPrototype();
531                 v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
532                 v8::Local<v8::Context> context = isolate->GetCurrentContext();
533                 if(v->IsObject())
534                         pPrivateData = (CJS_PrivateData*)v->ToObject(context).ToLocalChecked()->GetAlignedPointerFromInternalField(0);
535         }
536         if(!pPrivateData) return NULL;
537         return pPrivateData->pPrivate;
538 }
539
540 void JS_FreePrivate(void* pPrivateData)
541 {
542         delete (CJS_PrivateData*)pPrivateData;
543 }
544
545 void JS_FreePrivate(v8::Local<v8::Object> pObj)
546 {
547         if(pObj.IsEmpty() || !pObj->InternalFieldCount()) return;
548         JS_FreePrivate(pObj->GetAlignedPointerFromInternalField(0));
549         pObj->SetAlignedPointerInInternalField(0, NULL);
550 }
551
552
553 v8::Local<v8::Value> JS_GetObjectValue(v8::Local<v8::Object> pObj)
554 {
555         return pObj;
556 }
557
558 v8::Local<v8::String> WSToJSString(IJS_Runtime* pJSRuntime, const wchar_t* PropertyName, int Len = -1)
559 {
560         CFX_WideString ws = CFX_WideString(PropertyName,Len);
561         CFX_ByteString bs = ws.UTF8Encode();
562         if(!pJSRuntime) pJSRuntime = v8::Isolate::GetCurrent();
563         return v8::String::NewFromUtf8(pJSRuntime, bs.c_str(), v8::NewStringType::kNormal).ToLocalChecked();
564 }
565
566 v8::Local<v8::Value> JS_GetObjectElement(IJS_Runtime* pJSRuntime, v8::Local<v8::Object> pObj,const wchar_t* PropertyName)
567 {
568         if(pObj.IsEmpty()) return v8::Local<v8::Value>();
569         v8::Local<v8::Value> val;
570         if (!pObj->Get(pJSRuntime->GetCurrentContext(), WSToJSString(pJSRuntime,PropertyName)).ToLocal(&val)) return v8::Local<v8::Value>();
571         return val;
572 }
573
574 v8::Local<v8::Array> JS_GetObjectElementNames(IJS_Runtime* pJSRuntime, v8::Local<v8::Object> pObj)
575 {
576         if(pObj.IsEmpty()) return v8::Local<v8::Array>();
577         v8::Local<v8::Array> val;
578         if (!pObj->GetPropertyNames(pJSRuntime->GetCurrentContext()).ToLocal(&val)) return v8::Local<v8::Array>();
579         return val;
580 }
581
582 void JS_PutObjectString(IJS_Runtime* pJSRuntime,v8::Local<v8::Object> pObj, const wchar_t* PropertyName, const wchar_t* sValue) //VT_string
583 {
584         if(pObj.IsEmpty()) return;
585         pObj->Set(pJSRuntime->GetCurrentContext(), WSToJSString(pJSRuntime, PropertyName), WSToJSString(pJSRuntime, sValue)).FromJust();
586 }
587
588 void JS_PutObjectNumber(IJS_Runtime* pJSRuntime,v8::Local<v8::Object> pObj, const wchar_t* PropertyName, int nValue)
589 {
590         if(pObj.IsEmpty()) return;
591         pObj->Set(pJSRuntime->GetCurrentContext(), WSToJSString(pJSRuntime,PropertyName),v8::Int32::New(pJSRuntime, nValue)).FromJust();
592 }
593
594 void JS_PutObjectNumber(IJS_Runtime* pJSRuntime,v8::Local<v8::Object> pObj, const wchar_t* PropertyName, float fValue)
595 {
596         if(pObj.IsEmpty()) return;
597         pObj->Set(pJSRuntime->GetCurrentContext(), WSToJSString(pJSRuntime,PropertyName),v8::Number::New(pJSRuntime, (double)fValue)).FromJust();
598 }
599
600 void JS_PutObjectNumber(IJS_Runtime* pJSRuntime,v8::Local<v8::Object> pObj, const wchar_t* PropertyName, double dValue)
601 {
602         if(pObj.IsEmpty()) return;
603         pObj->Set(pJSRuntime->GetCurrentContext(), WSToJSString(pJSRuntime,PropertyName),v8::Number::New(pJSRuntime, (double)dValue)).FromJust();
604 }
605
606 void JS_PutObjectBoolean(IJS_Runtime* pJSRuntime,v8::Local<v8::Object> pObj, const wchar_t* PropertyName, bool bValue)
607 {
608         if(pObj.IsEmpty()) return;
609         pObj->Set(pJSRuntime->GetCurrentContext(), WSToJSString(pJSRuntime,PropertyName),v8::Boolean::New(pJSRuntime, bValue)).FromJust();
610 }
611
612 void JS_PutObjectObject(IJS_Runtime* pJSRuntime,v8::Local<v8::Object> pObj, const wchar_t* PropertyName, v8::Local<v8::Object> pPut)
613 {
614         if(pObj.IsEmpty()) return;
615         pObj->Set(pJSRuntime->GetCurrentContext(), WSToJSString(pJSRuntime,PropertyName),pPut).FromJust();
616 }
617
618 void JS_PutObjectNull(IJS_Runtime* pJSRuntime,v8::Local<v8::Object> pObj, const wchar_t* PropertyName)
619 {
620         if(pObj.IsEmpty()) return;
621         pObj->Set(pJSRuntime->GetCurrentContext(), WSToJSString(pJSRuntime,PropertyName),v8::Local<v8::Object>()).FromJust();
622 }
623
624 v8::Local<v8::Array> JS_NewArray(IJS_Runtime* pJSRuntime)
625 {
626         return v8::Array::New(pJSRuntime);
627 }
628
629 unsigned JS_PutArrayElement(IJS_Runtime* pJSRuntime, v8::Local<v8::Array> pArray,unsigned index,v8::Local<v8::Value> pValue,FXJSVALUETYPE eType)
630 {
631         if(pArray.IsEmpty()) return 0;
632         if (pArray->Set(pJSRuntime->GetCurrentContext(), index, pValue).IsNothing()) return 0;
633         return 1;
634 }
635
636 v8::Local<v8::Value> JS_GetArrayElement(IJS_Runtime* pJSRuntime, v8::Local<v8::Array> pArray,unsigned index)
637 {
638         if(pArray.IsEmpty()) return v8::Local<v8::Value>();
639         v8::Local<v8::Value> val;
640         if (pArray->Get(pJSRuntime->GetCurrentContext(), index).ToLocal(&val)) return v8::Local<v8::Value>();
641         return val;
642 }
643
644 unsigned JS_GetArrayLength(v8::Local<v8::Array> pArray)
645 {
646         if(pArray.IsEmpty()) return 0;
647         return pArray->Length();
648 }
649
650 v8::Local<v8::Value> JS_NewNumber(IJS_Runtime* pJSRuntime,int number)
651 {
652         return v8::Int32::New(pJSRuntime, number);
653 }
654
655 v8::Local<v8::Value> JS_NewNumber(IJS_Runtime* pJSRuntime,double number)
656 {
657         return v8::Number::New(pJSRuntime, number);
658 }
659
660 v8::Local<v8::Value> JS_NewNumber(IJS_Runtime* pJSRuntime,float number)
661 {
662         return v8::Number::New(pJSRuntime, (float)number);
663 }
664
665 v8::Local<v8::Value> JS_NewBoolean(IJS_Runtime* pJSRuntime,bool b)
666 {
667         return v8::Boolean::New(pJSRuntime, b);
668 }
669
670 v8::Local<v8::Value> JS_NewObject(IJS_Runtime* pJSRuntime,v8::Local<v8::Object> pObj)
671 {
672         if(pObj.IsEmpty()) return v8::Local<v8::Value>();
673         return pObj->Clone();
674 }
675
676 v8::Local<v8::Value> JS_NewObject2(IJS_Runtime* pJSRuntime,v8::Local<v8::Array> pObj)
677 {
678         if(pObj.IsEmpty()) return v8::Local<v8::Value>();
679         return pObj->Clone();
680 }
681
682
683 v8::Local<v8::Value> JS_NewString(IJS_Runtime* pJSRuntime,const wchar_t* string)
684 {
685         return WSToJSString(pJSRuntime, string);
686 }
687
688 v8::Local<v8::Value> JS_NewString(IJS_Runtime* pJSRuntime,const wchar_t* string, unsigned nLen)
689 {
690         return WSToJSString(pJSRuntime, string, nLen);
691 }
692
693 v8::Local<v8::Value> JS_NewNull()
694 {
695         return v8::Local<v8::Value>();
696 }
697
698 v8::Local<v8::Value> JS_NewDate(IJS_Runtime* pJSRuntime,double d)
699 {
700         return v8::Date::New(pJSRuntime->GetCurrentContext(), d).ToLocalChecked();
701 }
702
703 v8::Local<v8::Value> JS_NewValue(IJS_Runtime* pJSRuntime)
704 {
705         return v8::Local<v8::Value>();
706 }
707
708 v8::Local<v8::Value> JS_GetListValue(IJS_Runtime* pJSRuntime, v8::Local<v8::Value> pList, int index)
709 {
710
711         v8::Local<v8::Context> context = pJSRuntime->GetCurrentContext();
712         if(!pList.IsEmpty() && pList->IsObject())
713         {
714                 v8::Local<v8::Object> obj;
715                 if (pList->ToObject(context).ToLocal(&obj))
716                 {
717                         v8::Local<v8::Value> val;
718                         if (obj->Get(context, index).ToLocal(&val)) return val;
719                 }
720         }
721         return v8::Local<v8::Value>();
722 }
723
724 int     JS_ToInt32(IJS_Runtime* pJSRuntime, v8::Local<v8::Value> pValue)
725 {
726         if(pValue.IsEmpty()) return 0;
727         v8::Local<v8::Context> context = pJSRuntime->GetCurrentContext();
728         return pValue->ToInt32(context).ToLocalChecked()->Value();
729 }
730
731 bool JS_ToBoolean(IJS_Runtime* pJSRuntime, v8::Local<v8::Value> pValue)
732 {
733         if(pValue.IsEmpty()) return false;
734         v8::Local<v8::Context> context = pJSRuntime->GetCurrentContext();
735         return pValue->ToBoolean(context).ToLocalChecked()->Value();
736 }
737
738 double JS_ToNumber(IJS_Runtime* pJSRuntime, v8::Local<v8::Value> pValue)
739 {
740         if(pValue.IsEmpty()) return 0.0;
741         v8::Local<v8::Context> context = pJSRuntime->GetCurrentContext();
742         return pValue->ToNumber(context).ToLocalChecked()->Value();
743 }
744
745 v8::Local<v8::Object> JS_ToObject(IJS_Runtime* pJSRuntime, v8::Local<v8::Value> pValue)
746 {
747         if(pValue.IsEmpty()) return v8::Local<v8::Object>();
748         v8::Local<v8::Context> context = pJSRuntime->GetCurrentContext();
749         return pValue->ToObject(context).ToLocalChecked();
750 }
751
752 CFX_WideString  JS_ToString(IJS_Runtime* pJSRuntime, v8::Local<v8::Value> pValue)
753 {
754         if(pValue.IsEmpty()) return L"";
755         v8::Local<v8::Context> context = pJSRuntime->GetCurrentContext();
756         v8::String::Utf8Value s(pValue->ToString(context).ToLocalChecked());
757         return CFX_WideString::FromUTF8(*s, s.length());
758 }
759
760 v8::Local<v8::Array> JS_ToArray(IJS_Runtime* pJSRuntime, v8::Local<v8::Value> pValue)
761 {
762         if(pValue.IsEmpty()) return v8::Local<v8::Array>();
763         v8::Local<v8::Context> context = pJSRuntime->GetCurrentContext();
764         return v8::Local<v8::Array>::Cast(pValue->ToObject(context).ToLocalChecked());
765 }
766
767 void JS_ValueCopy(v8::Local<v8::Value>& pTo, v8::Local<v8::Value> pFrom)
768 {
769         pTo = pFrom;
770 }
771
772
773 //JavaScript time implement begin.
774
775 double _getLocalTZA()
776 {
777         if(!FSDK_IsSandBoxPolicyEnabled(FPDF_POLICY_MACHINETIME_ACCESS))
778                 return 0;
779         time_t t = 0;
780         time(&t);
781         localtime(&t);
782 #if _MSC_VER >= 1900
783   // In gcc and in Visual Studio prior to VS 2015 'timezone' is a global
784   // variable declared in time.h. That variable was deprecated and in VS 2015
785   // is removed, with _get_timezone replacing it.
786   long timezone = 0;
787   _get_timezone(&timezone);
788 #endif
789         return (double)(-(timezone * 1000));
790 }
791
792 int _getDaylightSavingTA(double d)
793 {
794         if(!FSDK_IsSandBoxPolicyEnabled(FPDF_POLICY_MACHINETIME_ACCESS))
795                 return 0;
796         time_t t = (time_t)(d/1000);
797         struct tm * tmp = localtime(&t);
798         if (tmp == NULL)
799                 return 0;
800         if (tmp->tm_isdst > 0)
801                 //One hour.
802                 return (int)60*60*1000;
803         return 0;
804 }
805
806 double _Mod(double x, double y)
807 {
808         double r = fmod(x, y);
809         if (r < 0) r += y;
810         return r;
811 }
812
813 int _isfinite(double v)
814 {
815 #if _MSC_VER
816         return ::_finite(v);
817 #else
818         return std::fabs(v) < std::numeric_limits<double>::max();
819 #endif
820 }
821
822 double _toInteger(double n)
823 {
824         return (n >= 0)? FXSYS_floor(n): -FXSYS_floor(-n);
825 }
826
827 bool _isLeapYear(int year)
828 {
829         return (year%4==0)&&((year%100!=0)||(year%400!=0));
830 }
831
832 int _DayFromYear(int y)
833 {
834         return (int)(365*(y - 1970.0) + FXSYS_floor((y - 1969.0)/4) - FXSYS_floor((y - 1901.0)/100)+FXSYS_floor((y - 1601.0)/400));
835 }
836
837 double _TimeFromYear(int y)
838 {
839         return  ((double)86400000) * _DayFromYear(y);
840 }
841
842 double _TimeFromYearMonth(int y, int m)
843 {
844         static int daysMonth[12] ={ 0,31,59,90,120,151,181,212,243,273,304,334};
845         static int leapDaysMonth[12] = { 0,31,60,91,121,152,182,213,244,274,305,335};
846         int* pMonth = daysMonth;
847         if(_isLeapYear(y))
848                 pMonth = leapDaysMonth;
849         return _TimeFromYear(y) + ((double)pMonth[m])*86400000;
850 }
851
852 int _Day(double t)
853 {
854         return (int)FXSYS_floor(t / 86400000);
855 }
856
857 int _YearFromTime(double t)
858 {
859         //estimate the time.
860         int y = 1970 +(int)(t/(365.0*86400000));
861         if (_TimeFromYear(y) <= t)
862         {
863                 while(_TimeFromYear(y+1) <= t) y++;
864         }
865         else
866                 while(_TimeFromYear(y-1) > t) y--;
867         return y;
868 }
869
870 int _DayWithinYear(double t)
871 {
872         int year = _YearFromTime(t);
873         int day = _Day(t);
874         return day-_DayFromYear(year);
875 }
876
877 int _MonthFromTime(double t)
878 {
879         int day = _DayWithinYear(t);
880         int year = _YearFromTime(t);
881         if(0<=day && day <31)
882                 return 0;
883         if(31<=day && day< 59+_isLeapYear(year))
884                 return 1;
885         if((59+_isLeapYear(year))<=day && day<(90+_isLeapYear(year)))
886                 return 2;
887         if((90+_isLeapYear(year))<=day && day<(120+_isLeapYear(year)))
888                 return 3;
889         if((120+_isLeapYear(year))<=day && day<(151+_isLeapYear(year)))
890                 return 4;
891         if((151+_isLeapYear(year))<=day && day<(181+_isLeapYear(year)))
892                 return 5;
893         if((181+_isLeapYear(year))<=day && day<(212+_isLeapYear(year)))
894                 return 6;
895         if((212+_isLeapYear(year))<=day && day<(243+_isLeapYear(year)))
896                 return 7;
897         if((243+_isLeapYear(year))<=day && day<(273+_isLeapYear(year)))
898                 return 8;
899         if((273+_isLeapYear(year))<=day && day<(304+_isLeapYear(year)))
900                 return 9;
901         if((304+_isLeapYear(year))<=day && day<(334+_isLeapYear(year)))
902                 return 10;
903         if((334+_isLeapYear(year))<=day && day<(365+_isLeapYear(year)))
904                 return 11;
905
906         return -1;
907 }
908
909 int _DateFromTime(double t)
910 {
911         int day = _DayWithinYear(t);
912         int year = _YearFromTime(t);
913         bool leap = _isLeapYear(year);
914         int month = _MonthFromTime(t);
915         switch (month)
916         {
917         case 0:
918                 return day+1;
919         case 1:
920                 return day-30;
921         case 2:
922                 return day-58-leap;
923         case 3:
924                 return day-89-leap;
925         case 4:
926                 return day-119-leap;
927         case 5:
928                 return day-150-leap;
929         case 6:
930                 return day-180-leap;
931         case 7:
932                 return day-211-leap;
933         case 8:
934                 return day-242-leap;
935         case 9:
936                 return day-272-leap;
937         case 10:
938                 return day-303-leap;
939         case 11:
940                 return day-333-leap;
941         default:
942                 return 0;
943         }
944 }
945
946 double JS_GetDateTime()
947 {
948         if(!FSDK_IsSandBoxPolicyEnabled(FPDF_POLICY_MACHINETIME_ACCESS))
949                 return 0;
950         time_t t = time(NULL);
951         struct tm* pTm = localtime(&t);
952
953         int year = pTm->tm_year+1900;
954         double t1 = _TimeFromYear(year);
955
956         return t1 + pTm->tm_yday*86400000.0 + pTm->tm_hour*3600000.0+pTm->tm_min*60000.0+pTm->tm_sec*1000.0;
957 }
958
959 int JS_GetYearFromTime(double dt)
960 {
961         return _YearFromTime(dt);
962 }
963
964 int JS_GetMonthFromTime(double dt)
965 {
966         return _MonthFromTime(dt);
967 }
968
969 int JS_GetDayFromTime(double dt)
970 {
971         return _DateFromTime(dt);
972 }
973
974 int JS_GetHourFromTime(double dt)
975 {
976         return (int)_Mod(FXSYS_floor((double)(dt/(60*60*1000))), 24);
977 }
978
979 int JS_GetMinFromTime(double dt)
980 {
981         return (int)_Mod(FXSYS_floor((double)(dt/(60*1000))), 60);
982 }
983
984 int JS_GetSecFromTime(double dt)
985 {
986         return (int)_Mod(FXSYS_floor((double)(dt/1000)), 60);
987 }
988
989 double JS_DateParse(const wchar_t* string)
990 {
991         v8::Isolate* pIsolate = v8::Isolate::GetCurrent();
992         v8::Isolate::Scope isolate_scope(pIsolate);
993         v8::HandleScope scope(pIsolate);
994
995         v8::Local<v8::Context> context = pIsolate->GetCurrentContext();
996
997         //Use the built-in object method.
998         v8::Local<v8::Value> v = context->Global()->Get(context, v8::String::NewFromUtf8(pIsolate, "Date", v8::NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();
999         if(v->IsObject())
1000         {
1001                 v8::Local<v8::Object> o = v->ToObject(context).ToLocalChecked();
1002                 v = o->Get(context,v8::String::NewFromUtf8(pIsolate, "parse", v8::NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();
1003                 if(v->IsFunction())
1004                 {
1005                         v8::Local<v8::Function> funC = v8::Local<v8::Function>::Cast(v);
1006
1007                         const int argc = 1;
1008                         v8::Local<v8::String> timeStr = WSToJSString(pIsolate, string);
1009                         v8::Local<v8::Value> argv[argc] = {timeStr};
1010                         v = funC->Call(context, context->Global(), argc, argv).ToLocalChecked();
1011                         if(v->IsNumber())
1012                         {
1013                                 double date =  v->ToNumber(context).ToLocalChecked()->Value();
1014                                 if(!_isfinite(date)) return date;
1015                                 return date + _getLocalTZA() + _getDaylightSavingTA(date);
1016                         }
1017
1018                 }
1019         }
1020         return 0;
1021 }
1022
1023 double JS_MakeDay(int nYear, int nMonth, int nDate)
1024 {
1025         if (!_isfinite(nYear) || !_isfinite(nMonth) ||!_isfinite(nDate))
1026                 return GetNan();
1027         double y = _toInteger(nYear);
1028         double m = _toInteger(nMonth);
1029         double dt = _toInteger(nDate);
1030         double ym = y + FXSYS_floor((double)m/12);
1031         double mn = _Mod(m ,12);
1032
1033         double t = _TimeFromYearMonth((int)ym,(int)mn);
1034
1035         if (_YearFromTime(t) != ym || _MonthFromTime(t) != mn ||_DateFromTime(t) != 1)
1036                 return GetNan();
1037         return _Day(t)+dt-1;
1038 }
1039
1040 double JS_MakeTime(int nHour, int nMin, int nSec, int nMs)
1041 {
1042         if (!_isfinite(nHour) ||!_isfinite(nMin) ||!_isfinite(nSec) ||!_isfinite(nMs))
1043                 return GetNan();
1044
1045         double h = _toInteger(nHour);
1046         double m = _toInteger(nMin);
1047         double s = _toInteger(nSec);
1048         double milli = _toInteger(nMs);
1049
1050         return h * 3600000 + m * 60000 + s * 1000 + milli;
1051 }
1052
1053 double JS_MakeDate(double day, double time)
1054 {
1055         if (!_isfinite(day) ||!_isfinite(time))
1056                 return GetNan();
1057
1058         return day * 86400000 + time;
1059 }
1060
1061 bool JS_PortIsNan(double d)
1062 {
1063         return d != d;
1064 }
1065
1066 double JS_LocalTime(double d)
1067 {
1068         return JS_GetDateTime() + _getDaylightSavingTA(d);
1069 }
1070
1071 //JavaScript time implement End.