summaryrefslogtreecommitdiff
path: root/binary/src/dactylUtils.cpp
blob: 86a4d46a5993a9f3cbc1c2584869aeb4653b0939 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Contributors, possibly:
 *   Kris Maglione <maglione.k at Gmail>
 *   Jeff Walden <jwalden@mit.edu>
 *   Mike Shaver <shaver@zeroknowledge.com>
 *   John Bandhauer <jband@netscape.com>
 *   Robert Ginda <rginda@netscape.com>
 *   Pierre Phaneuf <pp@ludusdesign.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK *****
 */

#include "dactylUtils.h"

#include "jsdbgapi.h"
#include "jsobj.h"

#include "nsIContent.h"
#include "nsIDOMXULElement.h"
#include "nsIXULTemplateBuilder.h"
#include "nsIObserverService.h"
#include "nsIScriptSecurityManager.h"
#include "nsIXPCScriptable.h"

#include "nsComponentManagerUtils.h"
#include "nsServiceManagerUtils.h"
#include "nsStringAPI.h"


class autoDropPrincipals {
public:
	autoDropPrincipals(JSContext *context, JSPrincipals *principals) : mContext(context), mJSPrincipals(principals) {}
	~autoDropPrincipals() {
        JSPRINCIPALS_DROP(mContext, mJSPrincipals);
    }

private:
    JSContext *mContext;
    JSPrincipals *mJSPrincipals;
};

static JSBool
Dump(JSContext *cx, uintN argc, jsval *vp)
{
    JSString *str;
    if (!argc)
        return JS_TRUE;

    str = JS_ValueToString(cx, JS_ARGV(cx, vp)[0]);
    if (!str)
        return JS_FALSE;

    size_t length;
    const jschar *chars = JS_GetStringCharsAndLength(cx, str, &length);
    if (!chars)
        return JS_FALSE;

    fputs(NS_ConvertUTF16toUTF8(reinterpret_cast<const PRUnichar*>(chars)).get(), stderr);
    return JS_TRUE;
}

static JSFunctionSpec gGlobalFun[] = {
    {"dump",    Dump,   1,0},
    {nsnull,nsnull,0,0}
};

static dactylUtils* gService = nsnull;

dactylUtils::dactylUtils()
	: mRuntime(nsnull)
{
	NS_ASSERTION(gService == nsnull, "Service already exists");
}

dactylUtils::~dactylUtils()
{
    mRuntimeService = nsnull;
    gService = nsnull;
}

nsresult
dactylUtils::Init()
{
	nsresult rv;
	NS_ENSURE_TRUE(!gService, NS_ERROR_UNEXPECTED);

    mRuntimeService = do_GetService("@mozilla.org/js/xpc/RuntimeService;1", &rv);
	NS_ENSURE_SUCCESS(rv, rv);

    rv = mRuntimeService->GetRuntime(&mRuntime);
	NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIScriptSecurityManager> secman =
        do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
    NS_ENSURE_TRUE(secman, NS_ERROR_FAILURE);

    rv = secman->GetSystemPrincipal(getter_AddRefs(mSystemPrincipal));
    NS_ENSURE_TRUE(rv, rv);
    NS_ENSURE_TRUE(mSystemPrincipal, NS_ERROR_FAILURE);

    return NS_OK;
}

NS_IMPL_ISUPPORTS1(dactylUtils,
                   dactylIUtils)

NS_IMETHODIMP
dactylUtils::CreateGlobal(JSContext *cx, jsval *out)
{
    nsresult rv;

    // JS::AutoPreserveCompartment pc(cx);

    nsCOMPtr<nsIXPCScriptable> backstagePass;
    rv = mRuntimeService->GetBackstagePass(getter_AddRefs(backstagePass));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIXPConnect> xpc =
        do_GetService("@mozilla.org/js/xpc/XPConnect;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Make sure InitClassesWithNewWrappedGlobal() installs the
    // backstage pass as the global in our compilation context.
    JS_SetGlobalObject(cx, nsnull);

    nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
    rv = xpc->InitClassesWithNewWrappedGlobal(cx, backstagePass,
                                              NS_GET_IID(nsISupports),
                                              mSystemPrincipal,
                                              nsnull,
                                              nsIXPConnect::
                                                  FLAG_SYSTEM_GLOBAL_OBJECT,
                                              getter_AddRefs(holder));
    NS_ENSURE_SUCCESS(rv, rv);

    JSObject *global;
    rv = holder->GetJSObject(&global);
    NS_ENSURE_SUCCESS(rv, rv);

    JSAutoEnterCompartment ac;
    NS_ENSURE_TRUE(ac.enter(cx, global), NS_ERROR_FAILURE);

    NS_ENSURE_TRUE(JS_DefineFunctions(cx, global, gGlobalFun),
                   NS_ERROR_FAILURE);
    NS_ENSURE_TRUE(JS_DefineProfilingFunctions(cx, global),
                   NS_ERROR_FAILURE);

    *out = OBJECT_TO_JSVAL(global);
    return NS_OK;
}

NS_IMETHODIMP
dactylUtils::EvalInContext(const nsAString &aSource,
                           const jsval &aTarget,
                           const nsACString &aFilename,
                           PRInt32 aLineNumber,
                           JSContext *cx,
                           jsval *rval)
{
    nsresult rv;

    nsCOMPtr<nsIXPConnect> xpc(do_GetService(nsIXPConnect::GetCID(), &rv));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCString filename;

    if (!aFilename.IsEmpty())
        filename.Assign(aFilename);
    else {
        nsCOMPtr<nsIStackFrame> frame;
        xpc->GetCurrentJSStack(getter_AddRefs(frame));
        NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
        frame->GetFilename(getter_Copies(filename));
        frame->GetLineNumber(&aLineNumber);
    }

    JSObject *target;
    NS_ENSURE_FALSE(JSVAL_IS_PRIMITIVE(aTarget), NS_ERROR_UNEXPECTED);
    target = JSVAL_TO_OBJECT(aTarget);


    JSObject *result = target;
    target = JS_FindCompilationScope(cx, target);
    NS_ENSURE_TRUE(target, NS_ERROR_FAILURE);


    nsCOMPtr<nsIScriptSecurityManager> secman =
        do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
    NS_ENSURE_TRUE(secman, NS_ERROR_FAILURE);

    nsCOMPtr<nsIPrincipal> principal;
    rv = secman->GetObjectPrincipal(cx, target, getter_AddRefs(principal));
    NS_ENSURE_SUCCESS(rv, rv);


    JSPrincipals *jsPrincipals;
    rv = principal->GetJSPrincipals(cx, &jsPrincipals);
    NS_ENSURE_SUCCESS(rv, rv);
    autoDropPrincipals adp(cx, jsPrincipals);

    JSObject *callingScope;
    {
        JSAutoRequest req(cx);

        callingScope = JS_GetScopeChain(cx);
        NS_ENSURE_TRUE(callingScope, NS_ERROR_FAILURE);
        callingScope = JS_GetGlobalForObject(cx, callingScope);
    }

    {
        JSAutoRequest req(cx);
        JSAutoEnterCompartment ac;
        jsval v;

        NS_ENSURE_TRUE(ac.enter(cx, target), NS_ERROR_FAILURE);

        JSBool ok =
            JS_EvaluateUCScriptForPrincipals(cx, target,
                                             jsPrincipals,
                                             reinterpret_cast<const jschar*>
                                                (PromiseFlatString(aSource).get()),
                                             aSource.Length(),
                                             filename.get(), aLineNumber, &v);

        if (!ok) {
            jsval exn;
            if (!JS_GetPendingException(cx, &exn))
                rv = NS_ERROR_FAILURE;
            else {
                JS_ClearPendingException(cx);

                if (JS_WrapValue(cx, &exn))
                    JS_SetPendingException(cx, exn);
            }
        }
        else {
            // Convert the result into something safe for our caller.
            JSAutoRequest req(cx);
            JSAutoEnterCompartment ac;

            if (!ac.enter(cx, callingScope) || !JS_WrapValue(cx, &v))
                rv = NS_ERROR_FAILURE;

            if (NS_SUCCEEDED(rv))
                *rval = v;
        }
    }

    return rv;
}

NS_IMETHODIMP
dactylUtils::CreateContents(nsIDOMElement *aElement)
{
    nsCOMPtr<nsIContent> content = do_QueryInterface(aElement);

    for (nsIContent *element = content;
         element;
         element = element->GetParent()) {

        nsCOMPtr<nsIDOMXULElement> xulelem = do_QueryInterface(element);
        if (xulelem) {
            nsCOMPtr<nsIXULTemplateBuilder> builder;
            xulelem->GetBuilder(getter_AddRefs(builder));
            if (builder) {
                builder->CreateContents(content, PR_TRUE);
                break;
            }
        }
    }
    return NS_OK;
}

NS_IMETHODIMP
dactylUtils::GetGlobalForObject(const jsval &aObject,
                                JSContext *cx,
                                jsval *rval)
{
    nsresult rv;

    NS_ENSURE_FALSE(JSVAL_IS_PRIMITIVE(aObject),
                    NS_ERROR_XPC_BAD_CONVERT_JS);

    JSObject *obj = JSVAL_TO_OBJECT(aObject);
#ifndef WIN32 /* Why? No idea. */
    if (obj->isProxy())
#endif
        obj = obj->unwrap();

    JSObject *global = JS_GetGlobalForObject(cx, obj);
    *rval = OBJECT_TO_JSVAL(global);

    // Outerize if necessary.
    if (JSObjectOp outerize = global->getClass()->ext.outerObject)
        *rval = OBJECT_TO_JSVAL(outerize(cx, global));

    return NS_OK;
}

/* vim:se sts=4 sw=4 et ft=cpp: */