• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 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 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6 
7 #include "fxjs/xfa/cfxjse_context.h"
8 
9 #include <utility>
10 
11 #include "fxjs/cfxjs_engine.h"
12 #include "fxjs/fxv8.h"
13 #include "fxjs/xfa/cfxjse_class.h"
14 #include "fxjs/xfa/cfxjse_isolatetracker.h"
15 #include "fxjs/xfa/cfxjse_runtimedata.h"
16 #include "fxjs/xfa/cfxjse_value.h"
17 #include "fxjs/xfa/cjx_object.h"
18 #include "third_party/base/check.h"
19 #include "third_party/base/check_op.h"
20 #include "third_party/base/ptr_util.h"
21 #include "v8/include/v8-exception.h"
22 #include "v8/include/v8-function.h"
23 #include "v8/include/v8-message.h"
24 #include "v8/include/v8-script.h"
25 #include "xfa/fxfa/parser/cxfa_thisproxy.h"
26 
27 namespace {
28 
29 const char szCompatibleModeScript[] =
30     "(function(global, list) {\n"
31     "  'use strict';\n"
32     "  var objname;\n"
33     "  for (objname in list) {\n"
34     "    var globalobj = global[objname];\n"
35     "    if (globalobj) {\n"
36     "      list[objname].forEach(function(name) {\n"
37     "        if (!globalobj[name]) {\n"
38     "          Object.defineProperty(globalobj, name, {\n"
39     "            writable: true,\n"
40     "            enumerable: false,\n"
41     "            value: (function(obj) {\n"
42     "              if (arguments.length === 0) {\n"
43     "                throw new TypeError('missing argument 0 when calling "
44     "                    function ' + objname + '.' + name);\n"
45     "              }\n"
46     "              return globalobj.prototype[name].apply(obj, "
47     "                  Array.prototype.slice.call(arguments, 1));\n"
48     "            })\n"
49     "          });\n"
50     "        }\n"
51     "      });\n"
52     "    }\n"
53     "  }\n"
54     "}(this, {String: ['substr', 'toUpperCase']}));";
55 
56 const char szConsoleScript[] =
57     "console.show = function() {};\n"
58     "\n"
59     "console.println = function(...args) {\n"
60     "  this.log(...args);\n"
61     "};";
62 
63 // Only address matters, values are for humans debuging here.  Keep these
64 // wchar_t to prevent the compiler from doing something clever, like
65 // aligning them on a byte boundary to save space, which would make them
66 // incompatible for use as V8 aligned pointers.
67 const wchar_t kFXJSEHostObjectTag[] = L"FXJSE Host Object";
68 const wchar_t kFXJSEProxyObjectTag[] = L"FXJSE Proxy Object";
69 
CreateReturnValue(v8::Isolate * pIsolate,v8::TryCatch * trycatch)70 v8::Local<v8::Object> CreateReturnValue(v8::Isolate* pIsolate,
71                                         v8::TryCatch* trycatch) {
72   v8::Local<v8::Object> hReturnValue = v8::Object::New(pIsolate);
73   if (!trycatch->HasCaught())
74     return hReturnValue;
75 
76   v8::Local<v8::Message> hMessage = trycatch->Message();
77   if (hMessage.IsEmpty())
78     return hReturnValue;
79 
80   v8::Local<v8::Context> context = pIsolate->GetCurrentContext();
81   v8::Local<v8::Value> hException = trycatch->Exception();
82   if (hException->IsObject()) {
83     v8::Local<v8::String> hNameStr = fxv8::NewStringHelper(pIsolate, "name");
84     v8::Local<v8::Value> hValue =
85         hException.As<v8::Object>()->Get(context, hNameStr).ToLocalChecked();
86     if (hValue->IsString() || hValue->IsStringObject()) {
87       hReturnValue->Set(context, 0, hValue).FromJust();
88     } else {
89       v8::Local<v8::String> hErrorStr =
90           fxv8::NewStringHelper(pIsolate, "Error");
91       hReturnValue->Set(context, 0, hErrorStr).FromJust();
92     }
93     v8::Local<v8::String> hMessageStr =
94         fxv8::NewStringHelper(pIsolate, "message");
95     hValue =
96         hException.As<v8::Object>()->Get(context, hMessageStr).ToLocalChecked();
97     if (hValue->IsString() || hValue->IsStringObject())
98       hReturnValue->Set(context, 1, hValue).FromJust();
99     else
100       hReturnValue->Set(context, 1, hMessage->Get()).FromJust();
101   } else {
102     v8::Local<v8::String> hErrorStr = fxv8::NewStringHelper(pIsolate, "Error");
103     hReturnValue->Set(context, 0, hErrorStr).FromJust();
104     hReturnValue->Set(context, 1, hMessage->Get()).FromJust();
105   }
106   hReturnValue->Set(context, 2, hException).FromJust();
107   int line = hMessage->GetLineNumber(context).FromMaybe(0);
108   hReturnValue->Set(context, 3, v8::Integer::New(pIsolate, line)).FromJust();
109   v8::Local<v8::String> source =
110       hMessage->GetSourceLine(context).FromMaybe(v8::Local<v8::String>());
111   hReturnValue->Set(context, 4, source).FromJust();
112   int column = hMessage->GetStartColumn(context).FromMaybe(0);
113   hReturnValue->Set(context, 5, v8::Integer::New(pIsolate, column)).FromJust();
114   column = hMessage->GetEndColumn(context).FromMaybe(0);
115   hReturnValue->Set(context, 6, v8::Integer::New(pIsolate, column)).FromJust();
116   return hReturnValue;
117 }
118 
FXJSE_UpdateProxyBinding(v8::Local<v8::Object> hObject)119 void FXJSE_UpdateProxyBinding(v8::Local<v8::Object> hObject) {
120   DCHECK(!hObject.IsEmpty());
121   DCHECK_EQ(hObject->InternalFieldCount(), 2);
122   hObject->SetAlignedPointerInInternalField(
123       0, const_cast<wchar_t*>(kFXJSEProxyObjectTag));
124   hObject->SetAlignedPointerInInternalField(1, nullptr);
125 }
126 
127 }  // namespace
128 
FXJSE_UpdateObjectBinding(v8::Local<v8::Object> hObject,CFXJSE_HostObject * pNewBinding)129 void FXJSE_UpdateObjectBinding(v8::Local<v8::Object> hObject,
130                                CFXJSE_HostObject* pNewBinding) {
131   DCHECK(!hObject.IsEmpty());
132   DCHECK_EQ(hObject->InternalFieldCount(), 2);
133   hObject->SetAlignedPointerInInternalField(
134       0, const_cast<wchar_t*>(kFXJSEHostObjectTag));
135   hObject->SetAlignedPointerInInternalField(1, pNewBinding);
136 }
137 
FXJSE_ClearObjectBinding(v8::Local<v8::Object> hObject)138 void FXJSE_ClearObjectBinding(v8::Local<v8::Object> hObject) {
139   DCHECK(!hObject.IsEmpty());
140   DCHECK_EQ(hObject->InternalFieldCount(), 2);
141   hObject->SetAlignedPointerInInternalField(0, nullptr);
142   hObject->SetAlignedPointerInInternalField(1, nullptr);
143 }
144 
FXJSE_RetrieveObjectBinding(v8::Local<v8::Value> hValue)145 CFXJSE_HostObject* FXJSE_RetrieveObjectBinding(v8::Local<v8::Value> hValue) {
146   if (!fxv8::IsObject(hValue))
147     return nullptr;
148 
149   v8::Local<v8::Object> hObject = hValue.As<v8::Object>();
150   if (hObject->InternalFieldCount() != 2 ||
151       hObject->GetAlignedPointerFromInternalField(0) == kFXJSEProxyObjectTag) {
152     v8::Local<v8::Value> hProtoObject = hObject->GetPrototype();
153     if (!fxv8::IsObject(hProtoObject))
154       return nullptr;
155 
156     hObject = hProtoObject.As<v8::Object>();
157     if (hObject->InternalFieldCount() != 2)
158       return nullptr;
159   }
160   if (hObject->GetAlignedPointerFromInternalField(0) != kFXJSEHostObjectTag)
161     return nullptr;
162 
163   return static_cast<CFXJSE_HostObject*>(
164       hObject->GetAlignedPointerFromInternalField(1));
165 }
166 
167 // static
Create(v8::Isolate * pIsolate,const FXJSE_CLASS_DESCRIPTOR * pGlobalClass,CFXJSE_HostObject * pGlobalObject,CXFA_ThisProxy * pProxy)168 std::unique_ptr<CFXJSE_Context> CFXJSE_Context::Create(
169     v8::Isolate* pIsolate,
170     const FXJSE_CLASS_DESCRIPTOR* pGlobalClass,
171     CFXJSE_HostObject* pGlobalObject,
172     CXFA_ThisProxy* pProxy) {
173   CFXJSE_ScopeUtil_IsolateHandle scope(pIsolate);
174 
175   // Private constructor.
176   auto pContext = pdfium::WrapUnique(new CFXJSE_Context(pIsolate, pProxy));
177   v8::Local<v8::ObjectTemplate> hObjectTemplate;
178   if (pGlobalClass) {
179     CFXJSE_Class* pGlobalClassObj =
180         CFXJSE_Class::Create(pContext.get(), pGlobalClass, true);
181     hObjectTemplate =
182         pGlobalClassObj->GetTemplate(pIsolate)->InstanceTemplate();
183   } else {
184     hObjectTemplate = v8::ObjectTemplate::New(pIsolate);
185     hObjectTemplate->SetInternalFieldCount(2);
186   }
187   hObjectTemplate->Set(v8::Symbol::GetToStringTag(pIsolate),
188                        fxv8::NewStringHelper(pIsolate, "global"));
189 
190   v8::Local<v8::Context> hNewContext =
191       v8::Context::New(pIsolate, nullptr, hObjectTemplate);
192   v8::Local<v8::Object> pThisProxy = hNewContext->Global();
193   FXJSE_UpdateProxyBinding(pThisProxy);
194 
195   v8::Local<v8::Object> pThis = pThisProxy->GetPrototype().As<v8::Object>();
196   FXJSE_UpdateObjectBinding(pThis, pGlobalObject);
197 
198   v8::Local<v8::Context> hRootContext = v8::Local<v8::Context>::New(
199       pIsolate, CFXJSE_RuntimeData::Get(pIsolate)->GetRootContext());
200   hNewContext->SetSecurityToken(hRootContext->GetSecurityToken());
201   pContext->m_hContext.Reset(pIsolate, hNewContext);
202   return pContext;
203 }
204 
CFXJSE_Context(v8::Isolate * pIsolate,CXFA_ThisProxy * pProxy)205 CFXJSE_Context::CFXJSE_Context(v8::Isolate* pIsolate, CXFA_ThisProxy* pProxy)
206     : m_pIsolate(pIsolate), m_pProxy(pProxy) {}
207 
208 CFXJSE_Context::~CFXJSE_Context() = default;
209 
GetGlobalObject()210 v8::Local<v8::Object> CFXJSE_Context::GetGlobalObject() {
211   v8::Isolate::Scope isolate_scope(GetIsolate());
212   v8::EscapableHandleScope handle_scope(GetIsolate());
213   v8::Local<v8::Context> hContext =
214       v8::Local<v8::Context>::New(GetIsolate(), m_hContext);
215   v8::Local<v8::Object> result =
216       hContext->Global()->GetPrototype().As<v8::Object>();
217   return handle_scope.Escape(result);
218 }
219 
GetContext()220 v8::Local<v8::Context> CFXJSE_Context::GetContext() {
221   return v8::Local<v8::Context>::New(GetIsolate(), m_hContext);
222 }
223 
AddClass(std::unique_ptr<CFXJSE_Class> pClass)224 void CFXJSE_Context::AddClass(std::unique_ptr<CFXJSE_Class> pClass) {
225   m_rgClasses.push_back(std::move(pClass));
226 }
227 
GetClassByName(ByteStringView szName) const228 CFXJSE_Class* CFXJSE_Context::GetClassByName(ByteStringView szName) const {
229   auto pClass =
230       std::find_if(m_rgClasses.begin(), m_rgClasses.end(),
231                    [szName](const std::unique_ptr<CFXJSE_Class>& item) {
232                      return item->IsName(szName);
233                    });
234   return pClass != m_rgClasses.end() ? pClass->get() : nullptr;
235 }
236 
EnableCompatibleMode()237 void CFXJSE_Context::EnableCompatibleMode() {
238   ExecuteScript(szCompatibleModeScript, nullptr, v8::Local<v8::Object>());
239   ExecuteScript(szConsoleScript, nullptr, v8::Local<v8::Object>());
240 }
241 
ExecuteScript(ByteStringView bsScript,CFXJSE_Value * pRetValue,v8::Local<v8::Object> hNewThis)242 bool CFXJSE_Context::ExecuteScript(ByteStringView bsScript,
243                                    CFXJSE_Value* pRetValue,
244                                    v8::Local<v8::Object> hNewThis) {
245   CFXJSE_ScopeUtil_IsolateHandleContext scope(this);
246   v8::Local<v8::Context> hContext = GetIsolate()->GetCurrentContext();
247   v8::TryCatch trycatch(GetIsolate());
248   v8::Local<v8::String> hScriptString =
249       fxv8::NewStringHelper(GetIsolate(), bsScript);
250   if (hNewThis.IsEmpty()) {
251     v8::Local<v8::Script> hScript;
252     if (v8::Script::Compile(hContext, hScriptString).ToLocal(&hScript)) {
253       CHECK(!trycatch.HasCaught());
254       v8::Local<v8::Value> hValue;
255       if (hScript->Run(hContext).ToLocal(&hValue)) {
256         CHECK(!trycatch.HasCaught());
257         if (pRetValue)
258           pRetValue->ForceSetValue(GetIsolate(), hValue);
259         return true;
260       }
261     }
262     if (pRetValue) {
263       pRetValue->ForceSetValue(GetIsolate(),
264                                CreateReturnValue(GetIsolate(), &trycatch));
265     }
266     return false;
267   }
268 
269   v8::Local<v8::String> hEval = fxv8::NewStringHelper(
270       GetIsolate(), "(function () { return eval(arguments[0]); })");
271   v8::Local<v8::Script> hWrapper =
272       v8::Script::Compile(hContext, hEval).ToLocalChecked();
273   v8::Local<v8::Value> hWrapperValue;
274   if (hWrapper->Run(hContext).ToLocal(&hWrapperValue)) {
275     CHECK(!trycatch.HasCaught());
276     CHECK(hWrapperValue->IsFunction());
277     v8::Local<v8::Function> hWrapperFn = hWrapperValue.As<v8::Function>();
278     v8::Local<v8::Value> rgArgs[] = {hScriptString};
279     v8::Local<v8::Value> hValue;
280     if (hWrapperFn->Call(hContext, hNewThis, 1, rgArgs).ToLocal(&hValue)) {
281       DCHECK(!trycatch.HasCaught());
282       if (pRetValue)
283         pRetValue->ForceSetValue(GetIsolate(), hValue);
284       return true;
285     }
286   }
287 
288 #ifndef NDEBUG
289   v8::String::Utf8Value error(GetIsolate(), trycatch.Exception());
290   fprintf(stderr, "JS Error: %s\n", *error);
291 
292   v8::Local<v8::Message> message = trycatch.Message();
293   if (!message.IsEmpty()) {
294     v8::Local<v8::Context> context(GetIsolate()->GetCurrentContext());
295     int linenum = message->GetLineNumber(context).FromJust();
296     v8::String::Utf8Value sourceline(
297         GetIsolate(), message->GetSourceLine(context).ToLocalChecked());
298     fprintf(stderr, "Line %d: %s\n", linenum, *sourceline);
299   }
300 #endif  // NDEBUG
301 
302   if (pRetValue) {
303     pRetValue->ForceSetValue(GetIsolate(),
304                              CreateReturnValue(GetIsolate(), &trycatch));
305   }
306   return false;
307 }
308