1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5  * You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef mozilla_dom_ToJSValue_h
8 #define mozilla_dom_ToJSValue_h
9 
10 #include <cstddef>  // for size_t
11 #include <cstdint>  // for int32_t, int64_t, uint32_t, uint64_t
12 #include <type_traits>  // for is_base_of, enable_if_t, enable_if, is_pointer, is_same, void_t
13 #include <utility>          // for forward
14 #include "ErrorList.h"      // for nsresult
15 #include "js/Array.h"       // for NewArrayObject
16 #include "js/GCVector.h"    // for RootedVector, MutableWrappedPtrOperations
17 #include "js/RootingAPI.h"  // for MutableHandle, Rooted, Handle, Heap
18 #include "js/Value.h"       // for Value
19 #include "js/ValueArray.h"  // for HandleValueArray
20 #include "jsapi.h"          // for CurrentGlobalOrNull
21 #include "mozilla/Assertions.h"  // for AssertionConditionType, MOZ_ASSERT, MOZ_ASSERT_HELPER1
22 #include "mozilla/UniquePtr.h"         // for UniquePtr
23 #include "mozilla/Unused.h"            // for Unused
24 #include "mozilla/dom/BindingUtils.h"  // for MaybeWrapValue, MaybeWrapObjectOrNullValue, XPCOMObjectToJsval, GetOrCreateDOMReflector
25 #include "mozilla/dom/CallbackObject.h"  // for CallbackObject
26 #include "mozilla/dom/Record.h"
27 #include "nsID.h"         // for NS_GET_TEMPLATE_IID, nsIID
28 #include "nsISupports.h"  // for nsISupports
29 #include "nsStringFwd.h"  // for nsAString
30 #include "nsTArrayForwardDeclare.h"
31 #include "xpcObjectHelper.h"  // for xpcObjectHelper
32 
33 namespace mozilla {
34 namespace dom {
35 
36 class CallbackObject;
37 class Promise;
38 class WindowProxyHolder;
39 template <typename TypedArrayType>
40 class TypedArrayCreator;
41 
42 // If ToJSValue returns false, it must set an exception on the
43 // JSContext.
44 
45 // Accept strings.
46 [[nodiscard]] bool ToJSValue(JSContext* aCx, const nsAString& aArgument,
47                              JS::MutableHandle<JS::Value> aValue);
48 
49 // Treats the input as UTF-8, and throws otherwise.
50 [[nodiscard]] bool ToJSValue(JSContext* aCx, const nsACString& aArgument,
51                              JS::MutableHandle<JS::Value> aValue);
52 
53 // Accept booleans.  But be careful here: if we just have a function that takes
54 // a boolean argument, then any pointer that doesn't match one of our other
55 // signatures/templates will get treated as a boolean, which is clearly not
56 // desirable.  So make this a template that only gets used if the argument type
57 // is actually boolean
58 template <typename T>
ToJSValue(JSContext * aCx,T aArgument,JS::MutableHandle<JS::Value> aValue)59 [[nodiscard]] std::enable_if_t<std::is_same<T, bool>::value, bool> ToJSValue(
60     JSContext* aCx, T aArgument, JS::MutableHandle<JS::Value> aValue) {
61   // Make sure we're called in a compartment
62   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
63 
64   aValue.setBoolean(aArgument);
65   return true;
66 }
67 
68 // Accept integer types
ToJSValue(JSContext * aCx,int32_t aArgument,JS::MutableHandle<JS::Value> aValue)69 inline bool ToJSValue(JSContext* aCx, int32_t aArgument,
70                       JS::MutableHandle<JS::Value> aValue) {
71   // Make sure we're called in a compartment
72   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
73 
74   aValue.setInt32(aArgument);
75   return true;
76 }
77 
ToJSValue(JSContext * aCx,uint32_t aArgument,JS::MutableHandle<JS::Value> aValue)78 inline bool ToJSValue(JSContext* aCx, uint32_t aArgument,
79                       JS::MutableHandle<JS::Value> aValue) {
80   // Make sure we're called in a compartment
81   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
82 
83   aValue.setNumber(aArgument);
84   return true;
85 }
86 
ToJSValue(JSContext * aCx,int64_t aArgument,JS::MutableHandle<JS::Value> aValue)87 inline bool ToJSValue(JSContext* aCx, int64_t aArgument,
88                       JS::MutableHandle<JS::Value> aValue) {
89   // Make sure we're called in a compartment
90   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
91 
92   aValue.setNumber(double(aArgument));
93   return true;
94 }
95 
ToJSValue(JSContext * aCx,uint64_t aArgument,JS::MutableHandle<JS::Value> aValue)96 inline bool ToJSValue(JSContext* aCx, uint64_t aArgument,
97                       JS::MutableHandle<JS::Value> aValue) {
98   // Make sure we're called in a compartment
99   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
100 
101   aValue.setNumber(double(aArgument));
102   return true;
103 }
104 
105 // accept floating point types
ToJSValue(JSContext * aCx,float aArgument,JS::MutableHandle<JS::Value> aValue)106 inline bool ToJSValue(JSContext* aCx, float aArgument,
107                       JS::MutableHandle<JS::Value> aValue) {
108   // Make sure we're called in a compartment
109   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
110 
111   aValue.setNumber(aArgument);
112   return true;
113 }
114 
ToJSValue(JSContext * aCx,double aArgument,JS::MutableHandle<JS::Value> aValue)115 inline bool ToJSValue(JSContext* aCx, double aArgument,
116                       JS::MutableHandle<JS::Value> aValue) {
117   // Make sure we're called in a compartment
118   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
119 
120   aValue.setNumber(aArgument);
121   return true;
122 }
123 
124 // Accept CallbackObjects
ToJSValue(JSContext * aCx,CallbackObject & aArgument,JS::MutableHandle<JS::Value> aValue)125 [[nodiscard]] inline bool ToJSValue(JSContext* aCx, CallbackObject& aArgument,
126                                     JS::MutableHandle<JS::Value> aValue) {
127   // Make sure we're called in a compartment
128   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
129 
130   aValue.setObjectOrNull(aArgument.Callback(aCx));
131 
132   return MaybeWrapValue(aCx, aValue);
133 }
134 
135 // Accept objects that inherit from nsWrapperCache (e.g. most
136 // DOM objects).
137 template <class T>
138 [[nodiscard]] std::enable_if_t<std::is_base_of<nsWrapperCache, T>::value, bool>
ToJSValue(JSContext * aCx,T & aArgument,JS::MutableHandle<JS::Value> aValue)139 ToJSValue(JSContext* aCx, T& aArgument, JS::MutableHandle<JS::Value> aValue) {
140   // Make sure we're called in a compartment
141   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
142 
143   return GetOrCreateDOMReflector(aCx, aArgument, aValue);
144 }
145 
146 // Accept non-refcounted DOM objects that do not inherit from
147 // nsWrapperCache.  Refcounted ones would be too much of a footgun:
148 // you could convert them to JS twice and get two different objects.
149 namespace binding_detail {
150 template <class T>
151 [[nodiscard]] std::enable_if_t<
152     std::is_base_of<NonRefcountedDOMObject, T>::value, bool>
ToJSValueFromPointerHelper(JSContext * aCx,T * aArgument,JS::MutableHandle<JS::Value> aValue)153 ToJSValueFromPointerHelper(JSContext* aCx, T* aArgument,
154                            JS::MutableHandle<JS::Value> aValue) {
155   // Make sure we're called in a compartment
156   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
157 
158   // This is a cut-down version of
159   // WrapNewBindingNonWrapperCachedObject that doesn't need to deal
160   // with nearly as many cases.
161   if (!aArgument) {
162     aValue.setNull();
163     return true;
164   }
165 
166   JS::Rooted<JSObject*> obj(aCx);
167   if (!aArgument->WrapObject(aCx, nullptr, &obj)) {
168     return false;
169   }
170 
171   aValue.setObject(*obj);
172   return true;
173 }
174 }  // namespace binding_detail
175 
176 // We can take a non-refcounted non-wrapper-cached DOM object that lives in a
177 // UniquePtr.
178 template <class T>
179 [[nodiscard]] std::enable_if_t<
180     std::is_base_of<NonRefcountedDOMObject, T>::value, bool>
ToJSValue(JSContext * aCx,UniquePtr<T> && aArgument,JS::MutableHandle<JS::Value> aValue)181 ToJSValue(JSContext* aCx, UniquePtr<T>&& aArgument,
182           JS::MutableHandle<JS::Value> aValue) {
183   if (!binding_detail::ToJSValueFromPointerHelper(aCx, aArgument.get(),
184                                                   aValue)) {
185     return false;
186   }
187 
188   // JS object took ownership
189   Unused << aArgument.release();
190   return true;
191 }
192 
193 // Accept typed arrays built from appropriate nsTArray values
194 template <typename T>
195 [[nodiscard]]
196 typename std::enable_if<std::is_base_of<AllTypedArraysBase, T>::value,
197                         bool>::type
ToJSValue(JSContext * aCx,const TypedArrayCreator<T> & aArgument,JS::MutableHandle<JS::Value> aValue)198 ToJSValue(JSContext* aCx, const TypedArrayCreator<T>& aArgument,
199           JS::MutableHandle<JS::Value> aValue) {
200   // Make sure we're called in a compartment
201   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
202 
203   JSObject* obj = aArgument.Create(aCx);
204   if (!obj) {
205     return false;
206   }
207   aValue.setObject(*obj);
208   return true;
209 }
210 
211 namespace binding_detail {
212 // Helper type alias for picking a script-exposable non-wrappercached XPIDL
213 // interface to expose to JS code. Falls back to `nsISupports` if the specific
214 // interface type is ambiguous.
215 template <typename T, typename = void>
216 struct GetScriptableInterfaceType {
217   using Type = nsISupports;
218 
219   static_assert(std::is_base_of_v<nsISupports, T>,
220                 "T must inherit from nsISupports");
221 };
222 template <typename T>
223 struct GetScriptableInterfaceType<
224     T, std::void_t<typename T::ScriptableInterfaceType>> {
225   using Type = typename T::ScriptableInterfaceType;
226 
227   static_assert(std::is_base_of_v<Type, T>,
228                 "T must inherit from ScriptableInterfaceType");
229   static_assert(std::is_base_of_v<nsISupports, Type>,
230                 "ScriptableInterfaceType must inherit from nsISupports");
231 };
232 
233 template <typename T>
234 using ScriptableInterfaceType = typename GetScriptableInterfaceType<T>::Type;
235 }  // namespace binding_detail
236 
237 // Accept objects that inherit from nsISupports but not nsWrapperCache (e.g.
238 // DOM File).
239 template <class T>
240 [[nodiscard]] std::enable_if_t<!std::is_base_of<nsWrapperCache, T>::value &&
241                                    !std::is_base_of<CallbackObject, T>::value &&
242                                    std::is_base_of<nsISupports, T>::value,
243                                bool>
244 ToJSValue(JSContext* aCx, T& aArgument, JS::MutableHandle<JS::Value> aValue) {
245   // Make sure we're called in a compartment
246   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
247 
248   xpcObjectHelper helper(ToSupports(&aArgument));
249   JS::Rooted<JSObject*> scope(aCx, JS::CurrentGlobalOrNull(aCx));
250   const nsIID& iid =
251       NS_GET_TEMPLATE_IID(binding_detail::ScriptableInterfaceType<T>);
252   return XPCOMObjectToJsval(aCx, scope, helper, &iid, true, aValue);
253 }
254 
255 [[nodiscard]] bool ToJSValue(JSContext* aCx, const WindowProxyHolder& aArgument,
256                              JS::MutableHandle<JS::Value> aValue);
257 
258 // Accept nsRefPtr/nsCOMPtr
259 template <typename T>
260 [[nodiscard]] bool ToJSValue(JSContext* aCx, const nsCOMPtr<T>& aArgument,
261                              JS::MutableHandle<JS::Value> aValue) {
262   return ToJSValue(aCx, *aArgument.get(), aValue);
263 }
264 
265 template <typename T>
266 [[nodiscard]] bool ToJSValue(JSContext* aCx, const RefPtr<T>& aArgument,
267                              JS::MutableHandle<JS::Value> aValue) {
268   return ToJSValue(aCx, *aArgument.get(), aValue);
269 }
270 
271 template <typename T>
272 [[nodiscard]] bool ToJSValue(JSContext* aCx, const NonNull<T>& aArgument,
273                              JS::MutableHandle<JS::Value> aValue) {
274   return ToJSValue(aCx, *aArgument.get(), aValue);
275 }
276 
277 // Accept WebIDL dictionaries
278 template <class T>
279 [[nodiscard]] std::enable_if_t<std::is_base_of<DictionaryBase, T>::value, bool>
280 ToJSValue(JSContext* aCx, const T& aArgument,
281           JS::MutableHandle<JS::Value> aValue) {
282   return aArgument.ToObjectInternal(aCx, aValue);
283 }
284 
285 // Accept existing JS values (which may not be same-compartment with us
286 [[nodiscard]] inline bool ToJSValue(JSContext* aCx, const JS::Value& aArgument,
287                                     JS::MutableHandle<JS::Value> aValue) {
288   aValue.set(aArgument);
289   return MaybeWrapValue(aCx, aValue);
290 }
291 [[nodiscard]] inline bool ToJSValue(JSContext* aCx,
292                                     JS::Handle<JS::Value> aArgument,
293                                     JS::MutableHandle<JS::Value> aValue) {
294   aValue.set(aArgument);
295   return MaybeWrapValue(aCx, aValue);
296 }
297 
298 // Accept existing JS values on the Heap (which may not be same-compartment with
299 // us
300 [[nodiscard]] inline bool ToJSValue(JSContext* aCx,
301                                     const JS::Heap<JS::Value>& aArgument,
302                                     JS::MutableHandle<JS::Value> aValue) {
303   aValue.set(aArgument);
304   return MaybeWrapValue(aCx, aValue);
305 }
306 
307 // Accept existing rooted JS values (which may not be same-compartment with us
308 [[nodiscard]] inline bool ToJSValue(JSContext* aCx,
309                                     const JS::Rooted<JS::Value>& aArgument,
310                                     JS::MutableHandle<JS::Value> aValue) {
311   aValue.set(aArgument);
312   return MaybeWrapValue(aCx, aValue);
313 }
314 
315 // Accept existing rooted JS objects (which may not be same-compartment with
316 // us).
317 [[nodiscard]] inline bool ToJSValue(JSContext* aCx,
318                                     const JS::Rooted<JSObject*>& aArgument,
319                                     JS::MutableHandle<JS::Value> aValue) {
320   aValue.setObjectOrNull(aArgument);
321   return MaybeWrapObjectOrNullValue(aCx, aValue);
322 }
323 
324 // Accept nsresult, for use in rejections, and create an XPCOM
325 // exception object representing that nsresult.
326 [[nodiscard]] bool ToJSValue(JSContext* aCx, nsresult aArgument,
327                              JS::MutableHandle<JS::Value> aValue);
328 
329 // Accept ErrorResult, for use in rejections, and create an exception
330 // representing the failure.  Note, the ErrorResult must indicate a failure
331 // with aArgument.Failure() returning true.
332 [[nodiscard]] bool ToJSValue(JSContext* aCx, ErrorResult&& aArgument,
333                              JS::MutableHandle<JS::Value> aValue);
334 
335 // Accept owning WebIDL unions.
336 template <typename T>
337 [[nodiscard]] std::enable_if_t<std::is_base_of<AllOwningUnionBase, T>::value,
338                                bool>
339 ToJSValue(JSContext* aCx, const T& aArgument,
340           JS::MutableHandle<JS::Value> aValue) {
341   JS::Rooted<JSObject*> global(aCx, JS::CurrentGlobalOrNull(aCx));
342   return aArgument.ToJSVal(aCx, global, aValue);
343 }
344 
345 // Accept pointers to other things we accept
346 template <typename T>
347 [[nodiscard]] std::enable_if_t<std::is_pointer<T>::value, bool> ToJSValue(
348     JSContext* aCx, T aArgument, JS::MutableHandle<JS::Value> aValue) {
349   return ToJSValue(aCx, *aArgument, aValue);
350 }
351 
352 // Accept Promise objects, which need special handling.
353 [[nodiscard]] bool ToJSValue(JSContext* aCx, Promise& aArgument,
354                              JS::MutableHandle<JS::Value> aValue);
355 
356 // Accept arrays (and nested arrays) of other things we accept
357 template <typename T>
358 [[nodiscard]] bool ToJSValue(JSContext* aCx, T* aArguments, size_t aLength,
359                              JS::MutableHandle<JS::Value> aValue);
360 
361 template <typename T>
362 [[nodiscard]] bool ToJSValue(JSContext* aCx, const nsTArray<T>& aArgument,
363                              JS::MutableHandle<JS::Value> aValue) {
364   return ToJSValue(aCx, aArgument.Elements(), aArgument.Length(), aValue);
365 }
366 
367 template <typename T>
368 [[nodiscard]] bool ToJSValue(JSContext* aCx, const FallibleTArray<T>& aArgument,
369                              JS::MutableHandle<JS::Value> aValue) {
370   return ToJSValue(aCx, aArgument.Elements(), aArgument.Length(), aValue);
371 }
372 
373 template <typename T, int N>
374 [[nodiscard]] bool ToJSValue(JSContext* aCx, const T (&aArgument)[N],
375                              JS::MutableHandle<JS::Value> aValue) {
376   return ToJSValue(aCx, aArgument, N, aValue);
377 }
378 
379 // Accept arrays of other things we accept
380 template <typename T>
381 [[nodiscard]] bool ToJSValue(JSContext* aCx, T* aArguments, size_t aLength,
382                              JS::MutableHandle<JS::Value> aValue) {
383   // Make sure we're called in a compartment
384   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
385 
386   JS::RootedVector<JS::Value> v(aCx);
387   if (!v.resize(aLength)) {
388     return false;
389   }
390   for (size_t i = 0; i < aLength; ++i) {
391     if (!ToJSValue(aCx, aArguments[i], v[i])) {
392       return false;
393     }
394   }
395   JSObject* arrayObj = JS::NewArrayObject(aCx, v);
396   if (!arrayObj) {
397     return false;
398   }
399   aValue.setObject(*arrayObj);
400   return true;
401 }
402 
403 // Accept records of other things we accept. N.B. This assumes that
404 // keys are either UTF-8 or UTF-16-ish. See Bug 1706058.
405 template <typename K, typename V>
406 [[nodiscard]] bool ToJSValue(JSContext* aCx, const Record<K, V>& aArgument,
407                              JS::MutableHandle<JS::Value> aValue) {
408   JS::RootedObject recordObj(aCx, JS_NewPlainObject(aCx));
409   if (!recordObj) {
410     return false;
411   }
412 
413   for (auto& entry : aArgument.Entries()) {
414     JS::Rooted<JS::Value> value(aCx);
415     if (!ToJSValue(aCx, entry.mValue, &value)) {
416       return false;
417     }
418 
419     if constexpr (std::is_same_v<nsCString, decltype(entry.mKey)>) {
420       NS_ConvertUTF8toUTF16 expandedKey(entry.mKey);
421       if (!JS_DefineUCProperty(aCx, recordObj, expandedKey.BeginReading(),
422                                expandedKey.Length(), value, JSPROP_ENUMERATE)) {
423         return false;
424       }
425     } else {
426       if (!JS_DefineUCProperty(aCx, recordObj, entry.mKey.BeginReading(),
427                                entry.mKey.Length(), value, JSPROP_ENUMERATE)) {
428         return false;
429       }
430     }
431   }
432 
433   aValue.setObject(*recordObj);
434   return true;
435 }
436 
437 }  // namespace dom
438 }  // namespace mozilla
439 
440 #endif /* mozilla_dom_ToJSValue_h */
441