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
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "xpcprivate.h"
8 #include "XPCWrapper.h"
9 #include "WrapperFactory.h"
10 #include "AccessCheck.h"
11 
12 using namespace xpc;
13 using namespace mozilla;
14 using namespace JS;
15 
16 namespace XPCNativeWrapper {
17 
ThrowException(nsresult ex,JSContext * cx)18 static inline bool ThrowException(nsresult ex, JSContext* cx) {
19   XPCThrower::Throw(ex, cx);
20 
21   return false;
22 }
23 
UnwrapNW(JSContext * cx,unsigned argc,Value * vp)24 static bool UnwrapNW(JSContext* cx, unsigned argc, Value* vp) {
25   JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
26   if (args.length() != 1) {
27     return ThrowException(NS_ERROR_XPC_NOT_ENOUGH_ARGS, cx);
28   }
29 
30   JS::RootedValue v(cx, args[0]);
31   if (!v.isObject() || !js::IsCrossCompartmentWrapper(&v.toObject()) ||
32       !WrapperFactory::AllowWaiver(&v.toObject())) {
33     args.rval().set(v);
34     return true;
35   }
36 
37   bool ok = xpc::WrapperFactory::WaiveXrayAndWrap(cx, &v);
38   NS_ENSURE_TRUE(ok, false);
39   args.rval().set(v);
40   return true;
41 }
42 
XrayWrapperConstructor(JSContext * cx,unsigned argc,Value * vp)43 static bool XrayWrapperConstructor(JSContext* cx, unsigned argc, Value* vp) {
44   JS::CallArgs args = CallArgsFromVp(argc, vp);
45   if (args.length() == 0) {
46     return ThrowException(NS_ERROR_XPC_NOT_ENOUGH_ARGS, cx);
47   }
48 
49   if (!args[0].isObject()) {
50     args.rval().set(args[0]);
51     return true;
52   }
53 
54   args.rval().setObject(*js::UncheckedUnwrap(&args[0].toObject()));
55   return JS_WrapValue(cx, args.rval());
56 }
57 // static
AttachNewConstructorObject(JSContext * aCx,JS::HandleObject aGlobalObject)58 bool AttachNewConstructorObject(JSContext* aCx,
59                                 JS::HandleObject aGlobalObject) {
60   JSAutoRealm ar(aCx, aGlobalObject);
61   JSFunction* xpcnativewrapper = JS_DefineFunction(
62       aCx, aGlobalObject, "XPCNativeWrapper", XrayWrapperConstructor, 1,
63       JSPROP_READONLY | JSPROP_PERMANENT | JSFUN_CONSTRUCTOR);
64   if (!xpcnativewrapper) {
65     return false;
66   }
67   JS::RootedObject obj(aCx, JS_GetFunctionObject(xpcnativewrapper));
68   return JS_DefineFunction(aCx, obj, "unwrap", UnwrapNW, 1,
69                            JSPROP_READONLY | JSPROP_PERMANENT) != nullptr;
70 }
71 
72 }  // namespace XPCNativeWrapper
73 
74 namespace XPCWrapper {
75 
UnsafeUnwrapSecurityWrapper(JSObject * obj)76 JSObject* UnsafeUnwrapSecurityWrapper(JSObject* obj) {
77   if (js::IsProxy(obj)) {
78     return js::UncheckedUnwrap(obj);
79   }
80 
81   return obj;
82 }
83 
84 }  // namespace XPCWrapper
85