js/xpconnect/src/XPCShellImpl.cpp

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/js/xpconnect/src/XPCShellImpl.cpp	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,1756 @@
     1.4 +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
     1.5 +/* vim: set ts=8 sts=4 et sw=4 tw=99: */
     1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.9 +
    1.10 +#include "nsXULAppAPI.h"
    1.11 +#include "jsapi.h"
    1.12 +#include "jsfriendapi.h"
    1.13 +#include "jsprf.h"
    1.14 +#include "js/OldDebugAPI.h"
    1.15 +#include "nsServiceManagerUtils.h"
    1.16 +#include "nsComponentManagerUtils.h"
    1.17 +#include "nsIXPConnect.h"
    1.18 +#include "nsIJSNativeInitializer.h"
    1.19 +#include "nsIServiceManager.h"
    1.20 +#include "nsIFile.h"
    1.21 +#include "nsString.h"
    1.22 +#include "nsIDirectoryService.h"
    1.23 +#include "nsDirectoryServiceDefs.h"
    1.24 +#include "nsAppDirectoryServiceDefs.h"
    1.25 +#include "nscore.h"
    1.26 +#include "nsArrayEnumerator.h"
    1.27 +#include "nsCOMArray.h"
    1.28 +#include "nsDirectoryServiceUtils.h"
    1.29 +#include "nsIJSRuntimeService.h"
    1.30 +#include "nsCOMPtr.h"
    1.31 +#include "nsAutoPtr.h"
    1.32 +#include "nsJSPrincipals.h"
    1.33 +#include "xpcpublic.h"
    1.34 +#include "BackstagePass.h"
    1.35 +#include "nsCxPusher.h"
    1.36 +#include "nsIScriptSecurityManager.h"
    1.37 +#include "nsIPrincipal.h"
    1.38 +
    1.39 +#ifdef ANDROID
    1.40 +#include <android/log.h>
    1.41 +#endif
    1.42 +
    1.43 +#ifdef XP_WIN
    1.44 +#include <windows.h>
    1.45 +#endif
    1.46 +
    1.47 +// all this crap is needed to do the interactive shell stuff
    1.48 +#include <stdlib.h>
    1.49 +#include <errno.h>
    1.50 +#ifdef HAVE_IO_H
    1.51 +#include <io.h>     /* for isatty() */
    1.52 +#endif
    1.53 +#ifdef HAVE_UNISTD_H
    1.54 +#include <unistd.h>     /* for isatty() */
    1.55 +#endif
    1.56 +
    1.57 +#ifdef MOZ_CRASHREPORTER
    1.58 +#include "nsExceptionHandler.h"
    1.59 +#include "nsICrashReporter.h"
    1.60 +#endif
    1.61 +
    1.62 +using namespace mozilla;
    1.63 +using namespace JS;
    1.64 +
    1.65 +class XPCShellDirProvider : public nsIDirectoryServiceProvider2
    1.66 +{
    1.67 +public:
    1.68 +    NS_DECL_ISUPPORTS_INHERITED
    1.69 +    NS_DECL_NSIDIRECTORYSERVICEPROVIDER
    1.70 +    NS_DECL_NSIDIRECTORYSERVICEPROVIDER2
    1.71 +
    1.72 +    XPCShellDirProvider() { }
    1.73 +    ~XPCShellDirProvider() { }
    1.74 +
    1.75 +    // The platform resource folder
    1.76 +    void SetGREDir(nsIFile *greDir);
    1.77 +    void ClearGREDir() { mGREDir = nullptr; }
    1.78 +    // The application resource folder
    1.79 +    void SetAppDir(nsIFile *appFile);
    1.80 +    void ClearAppDir() { mAppDir = nullptr; }
    1.81 +    // The app executable
    1.82 +    void SetAppFile(nsIFile *appFile);
    1.83 +    void ClearAppFile() { mAppFile = nullptr; }
    1.84 +    // An additional custom plugin dir if specified
    1.85 +    void SetPluginDir(nsIFile* pluginDir);
    1.86 +    void ClearPluginDir() { mPluginDir = nullptr; }
    1.87 +
    1.88 +private:
    1.89 +    nsCOMPtr<nsIFile> mGREDir;
    1.90 +    nsCOMPtr<nsIFile> mAppDir;
    1.91 +    nsCOMPtr<nsIFile> mPluginDir;
    1.92 +    nsCOMPtr<nsIFile> mAppFile;
    1.93 +};
    1.94 +
    1.95 +#ifdef JS_THREADSAFE
    1.96 +#define DoBeginRequest(cx) JS_BeginRequest((cx))
    1.97 +#define DoEndRequest(cx)   JS_EndRequest((cx))
    1.98 +#else
    1.99 +#define DoBeginRequest(cx) ((void)0)
   1.100 +#define DoEndRequest(cx)   ((void)0)
   1.101 +#endif
   1.102 +
   1.103 +static const char kXPConnectServiceContractID[] = "@mozilla.org/js/xpc/XPConnect;1";
   1.104 +
   1.105 +#define EXITCODE_RUNTIME_ERROR 3
   1.106 +#define EXITCODE_FILE_NOT_FOUND 4
   1.107 +
   1.108 +static FILE *gOutFile = nullptr;
   1.109 +static FILE *gErrFile = nullptr;
   1.110 +static FILE *gInFile = nullptr;
   1.111 +
   1.112 +static int gExitCode = 0;
   1.113 +static bool gIgnoreReportedErrors = false;
   1.114 +static bool gQuitting = false;
   1.115 +static bool reportWarnings = true;
   1.116 +static bool compileOnly = false;
   1.117 +
   1.118 +static JSPrincipals *gJSPrincipals = nullptr;
   1.119 +static nsAutoString *gWorkingDirectory = nullptr;
   1.120 +
   1.121 +static bool
   1.122 +GetLocationProperty(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp)
   1.123 +{
   1.124 +#if !defined(XP_WIN) && !defined(XP_UNIX)
   1.125 +    //XXX: your platform should really implement this
   1.126 +    return false;
   1.127 +#else
   1.128 +    JS::AutoFilename filename;
   1.129 +    if (JS::DescribeScriptedCaller(cx, &filename) && filename.get()) {
   1.130 +        nsresult rv;
   1.131 +        nsCOMPtr<nsIXPConnect> xpc =
   1.132 +            do_GetService(kXPConnectServiceContractID, &rv);
   1.133 +
   1.134 +#if defined(XP_WIN)
   1.135 +        // convert from the system codepage to UTF-16
   1.136 +        int bufferSize = MultiByteToWideChar(CP_ACP, 0, filename.get(),
   1.137 +                                             -1, nullptr, 0);
   1.138 +        nsAutoString filenameString;
   1.139 +        filenameString.SetLength(bufferSize);
   1.140 +        MultiByteToWideChar(CP_ACP, 0, filename.get(),
   1.141 +                            -1, (LPWSTR)filenameString.BeginWriting(),
   1.142 +                            filenameString.Length());
   1.143 +        // remove the null terminator
   1.144 +        filenameString.SetLength(bufferSize - 1);
   1.145 +
   1.146 +        // replace forward slashes with backslashes,
   1.147 +        // since nsLocalFileWin chokes on them
   1.148 +        char16_t* start = filenameString.BeginWriting();
   1.149 +        char16_t* end = filenameString.EndWriting();
   1.150 +
   1.151 +        while (start != end) {
   1.152 +            if (*start == L'/')
   1.153 +                *start = L'\\';
   1.154 +            start++;
   1.155 +        }
   1.156 +#elif defined(XP_UNIX)
   1.157 +        NS_ConvertUTF8toUTF16 filenameString(filename.get());
   1.158 +#endif
   1.159 +
   1.160 +        nsCOMPtr<nsIFile> location;
   1.161 +        if (NS_SUCCEEDED(rv)) {
   1.162 +            rv = NS_NewLocalFile(filenameString,
   1.163 +                                 false, getter_AddRefs(location));
   1.164 +        }
   1.165 +
   1.166 +        if (!location && gWorkingDirectory) {
   1.167 +            // could be a relative path, try appending it to the cwd
   1.168 +            // and then normalize
   1.169 +            nsAutoString absolutePath(*gWorkingDirectory);
   1.170 +            absolutePath.Append(filenameString);
   1.171 +
   1.172 +            rv = NS_NewLocalFile(absolutePath,
   1.173 +                                 false, getter_AddRefs(location));
   1.174 +        }
   1.175 +
   1.176 +        if (location) {
   1.177 +            nsCOMPtr<nsIXPConnectJSObjectHolder> locationHolder;
   1.178 +
   1.179 +            bool symlink;
   1.180 +            // don't normalize symlinks, because that's kind of confusing
   1.181 +            if (NS_SUCCEEDED(location->IsSymlink(&symlink)) &&
   1.182 +                !symlink)
   1.183 +                location->Normalize();
   1.184 +            rv = xpc->WrapNative(cx, obj, location,
   1.185 +                                 NS_GET_IID(nsIFile),
   1.186 +                                 getter_AddRefs(locationHolder));
   1.187 +
   1.188 +            if (NS_SUCCEEDED(rv) &&
   1.189 +                locationHolder->GetJSObject()) {
   1.190 +                vp.set(OBJECT_TO_JSVAL(locationHolder->GetJSObject()));
   1.191 +            }
   1.192 +        }
   1.193 +    }
   1.194 +
   1.195 +    return true;
   1.196 +#endif
   1.197 +}
   1.198 +
   1.199 +static bool
   1.200 +GetLine(JSContext *cx, char *bufp, FILE *file, const char *prompt) {
   1.201 +    {
   1.202 +        char line[256] = { '\0' };
   1.203 +        fputs(prompt, gOutFile);
   1.204 +        fflush(gOutFile);
   1.205 +        if ((!fgets(line, sizeof line, file) && errno != EINTR) || feof(file))
   1.206 +            return false;
   1.207 +        strcpy(bufp, line);
   1.208 +    }
   1.209 +    return true;
   1.210 +}
   1.211 +
   1.212 +static bool
   1.213 +ReadLine(JSContext *cx, unsigned argc, jsval *vp)
   1.214 +{
   1.215 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.216 +
   1.217 +    // While 4096 might be quite arbitrary, this is something to be fixed in
   1.218 +    // bug 105707. It is also the same limit as in ProcessFile.
   1.219 +    char buf[4096];
   1.220 +    RootedString str(cx);
   1.221 +
   1.222 +    /* If a prompt was specified, construct the string */
   1.223 +    if (args.length() > 0) {
   1.224 +        str = JS::ToString(cx, args[0]);
   1.225 +        if (!str)
   1.226 +            return false;
   1.227 +    } else {
   1.228 +        str = JS_GetEmptyString(JS_GetRuntime(cx));
   1.229 +    }
   1.230 +
   1.231 +    /* Get a line from the infile */
   1.232 +    JSAutoByteString strBytes(cx, str);
   1.233 +    if (!strBytes || !GetLine(cx, buf, gInFile, strBytes.ptr()))
   1.234 +        return false;
   1.235 +
   1.236 +    /* Strip newline character added by GetLine() */
   1.237 +    unsigned int buflen = strlen(buf);
   1.238 +    if (buflen == 0) {
   1.239 +        if (feof(gInFile)) {
   1.240 +            args.rval().setNull();
   1.241 +            return true;
   1.242 +        }
   1.243 +    } else if (buf[buflen - 1] == '\n') {
   1.244 +        --buflen;
   1.245 +    }
   1.246 +
   1.247 +    /* Turn buf into a JSString */
   1.248 +    str = JS_NewStringCopyN(cx, buf, buflen);
   1.249 +    if (!str)
   1.250 +        return false;
   1.251 +
   1.252 +    args.rval().setString(str);
   1.253 +    return true;
   1.254 +}
   1.255 +
   1.256 +static bool
   1.257 +Print(JSContext *cx, unsigned argc, jsval *vp)
   1.258 +{
   1.259 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.260 +    args.rval().setUndefined();
   1.261 +
   1.262 +    RootedString str(cx);
   1.263 +    nsAutoCString utf8str;
   1.264 +    size_t length;
   1.265 +    const jschar *chars;
   1.266 +
   1.267 +    for (unsigned i = 0; i < args.length(); i++) {
   1.268 +        str = ToString(cx, args[i]);
   1.269 +        if (!str)
   1.270 +            return false;
   1.271 +        chars = JS_GetStringCharsAndLength(cx, str, &length);
   1.272 +        if (!chars)
   1.273 +            return false;
   1.274 +
   1.275 +        if (i)
   1.276 +            utf8str.Append(' ');
   1.277 +        AppendUTF16toUTF8(Substring(reinterpret_cast<const char16_t*>(chars),
   1.278 +                                    length),
   1.279 +                          utf8str);
   1.280 +    }
   1.281 +    utf8str.Append('\n');
   1.282 +    fputs(utf8str.get(), gOutFile);
   1.283 +    fflush(gOutFile);
   1.284 +    return true;
   1.285 +}
   1.286 +
   1.287 +static bool
   1.288 +Dump(JSContext *cx, unsigned argc, jsval *vp)
   1.289 +{
   1.290 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.291 +    args.rval().setUndefined();
   1.292 +
   1.293 +    if (!args.length())
   1.294 +         return true;
   1.295 +
   1.296 +    RootedString str(cx, ToString(cx, args[0]));
   1.297 +    if (!str)
   1.298 +        return false;
   1.299 +
   1.300 +    size_t length;
   1.301 +    const jschar *chars = JS_GetStringCharsAndLength(cx, str, &length);
   1.302 +    if (!chars)
   1.303 +        return false;
   1.304 +
   1.305 +    NS_ConvertUTF16toUTF8 utf8str(reinterpret_cast<const char16_t*>(chars),
   1.306 +                                  length);
   1.307 +#ifdef ANDROID
   1.308 +    __android_log_print(ANDROID_LOG_INFO, "Gecko", "%s", utf8str.get());
   1.309 +#endif
   1.310 +#ifdef XP_WIN
   1.311 +    if (IsDebuggerPresent()) {
   1.312 +      OutputDebugStringW(reinterpret_cast<const wchar_t*>(chars));
   1.313 +    }
   1.314 +#endif
   1.315 +    fputs(utf8str.get(), gOutFile);
   1.316 +    fflush(gOutFile);
   1.317 +    return true;
   1.318 +}
   1.319 +
   1.320 +static bool
   1.321 +Load(JSContext *cx, unsigned argc, jsval *vp)
   1.322 +{
   1.323 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.324 +
   1.325 +    JS::Rooted<JSObject*> obj(cx, JS_THIS_OBJECT(cx, vp));
   1.326 +    if (!obj)
   1.327 +        return false;
   1.328 +
   1.329 +    RootedString str(cx);
   1.330 +    for (unsigned i = 0; i < args.length(); i++) {
   1.331 +        str = ToString(cx, args[i]);
   1.332 +        if (!str)
   1.333 +            return false;
   1.334 +        JSAutoByteString filename(cx, str);
   1.335 +        if (!filename)
   1.336 +            return false;
   1.337 +        FILE *file = fopen(filename.ptr(), "r");
   1.338 +        if (!file) {
   1.339 +            JS_ReportError(cx, "cannot open file '%s' for reading",
   1.340 +                           filename.ptr());
   1.341 +            return false;
   1.342 +        }
   1.343 +        JS::CompileOptions options(cx);
   1.344 +        options.setUTF8(true)
   1.345 +               .setFileAndLine(filename.ptr(), 1);
   1.346 +        JS::Rooted<JSScript*> script(cx, JS::Compile(cx, obj, options, file));
   1.347 +        fclose(file);
   1.348 +        if (!script)
   1.349 +            return false;
   1.350 +
   1.351 +        if (!compileOnly && !JS_ExecuteScript(cx, obj, script))
   1.352 +            return false;
   1.353 +    }
   1.354 +    args.rval().setUndefined();
   1.355 +    return true;
   1.356 +}
   1.357 +
   1.358 +static bool
   1.359 +Version(JSContext *cx, unsigned argc, jsval *vp)
   1.360 +{
   1.361 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.362 +    args.rval().setInt32(JS_GetVersion(cx));
   1.363 +    if (args.get(0).isInt32())
   1.364 +        JS_SetVersionForCompartment(js::GetContextCompartment(cx),
   1.365 +                                    JSVersion(args[0].toInt32()));
   1.366 +    return true;
   1.367 +}
   1.368 +
   1.369 +static bool
   1.370 +BuildDate(JSContext *cx, unsigned argc, jsval *vp)
   1.371 +{
   1.372 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.373 +    fprintf(gOutFile, "built on %s at %s\n", __DATE__, __TIME__);
   1.374 +    args.rval().setUndefined();
   1.375 +    return true;
   1.376 +}
   1.377 +
   1.378 +static bool
   1.379 +Quit(JSContext *cx, unsigned argc, jsval *vp)
   1.380 +{
   1.381 +    gExitCode = 0;
   1.382 +    JS_ConvertArguments(cx, JS::CallArgsFromVp(argc, vp),"/ i", &gExitCode);
   1.383 +
   1.384 +    gQuitting = true;
   1.385 +//    exit(0);
   1.386 +    return false;
   1.387 +}
   1.388 +
   1.389 +// Provide script a way to disable the xpcshell error reporter, preventing
   1.390 +// reported errors from being logged to the console and also from affecting the
   1.391 +// exit code returned by the xpcshell binary.
   1.392 +static bool
   1.393 +IgnoreReportedErrors(JSContext *cx, unsigned argc, jsval *vp)
   1.394 +{
   1.395 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.396 +    if (args.length() != 1 || !args[0].isBoolean()) {
   1.397 +        JS_ReportError(cx, "Bad arguments");
   1.398 +        return false;
   1.399 +    }
   1.400 +    gIgnoreReportedErrors = args[0].toBoolean();
   1.401 +    return true;
   1.402 +}
   1.403 +
   1.404 +static bool
   1.405 +DumpXPC(JSContext *cx, unsigned argc, jsval *vp)
   1.406 +{
   1.407 +    JS::CallArgs args = CallArgsFromVp(argc, vp);
   1.408 +
   1.409 +    uint16_t depth = 2;
   1.410 +    if (args.length() > 0) {
   1.411 +        if (!JS::ToUint16(cx, args[0], &depth))
   1.412 +            return false;
   1.413 +    }
   1.414 +
   1.415 +    nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
   1.416 +    if (xpc)
   1.417 +        xpc->DebugDump(int16_t(depth));
   1.418 +    args.rval().setUndefined();
   1.419 +    return true;
   1.420 +}
   1.421 +
   1.422 +static bool
   1.423 +GC(JSContext *cx, unsigned argc, jsval *vp)
   1.424 +{
   1.425 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.426 +    JSRuntime *rt = JS_GetRuntime(cx);
   1.427 +    JS_GC(rt);
   1.428 +#ifdef JS_GCMETER
   1.429 +    js_DumpGCStats(rt, stdout);
   1.430 +#endif
   1.431 +    args.rval().setUndefined();
   1.432 +    return true;
   1.433 +}
   1.434 +
   1.435 +#ifdef JS_GC_ZEAL
   1.436 +static bool
   1.437 +GCZeal(JSContext *cx, unsigned argc, jsval *vp)
   1.438 +{
   1.439 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.440 +    uint32_t zeal;
   1.441 +    if (!ToUint32(cx, args.get(0), &zeal))
   1.442 +        return false;
   1.443 +
   1.444 +    JS_SetGCZeal(cx, uint8_t(zeal), JS_DEFAULT_ZEAL_FREQ);
   1.445 +    args.rval().setUndefined();
   1.446 +    return true;
   1.447 +}
   1.448 +#endif
   1.449 +
   1.450 +static bool
   1.451 +SendCommand(JSContext *cx, unsigned argc, Value *vp)
   1.452 +{
   1.453 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.454 +
   1.455 +    if (args.length() == 0) {
   1.456 +        JS_ReportError(cx, "Function takes at least one argument!");
   1.457 +        return false;
   1.458 +    }
   1.459 +
   1.460 +    JSString* str = ToString(cx, args[0]);
   1.461 +    if (!str) {
   1.462 +        JS_ReportError(cx, "Could not convert argument 1 to string!");
   1.463 +        return false;
   1.464 +    }
   1.465 +
   1.466 +    if (args.length() > 1 && JS_TypeOfValue(cx, args[1]) != JSTYPE_FUNCTION) {
   1.467 +        JS_ReportError(cx, "Could not convert argument 2 to function!");
   1.468 +        return false;
   1.469 +    }
   1.470 +
   1.471 +    if (!XRE_SendTestShellCommand(cx, str, args.length() > 1 ? args[1].address() : nullptr)) {
   1.472 +        JS_ReportError(cx, "Couldn't send command!");
   1.473 +        return false;
   1.474 +    }
   1.475 +
   1.476 +    args.rval().setUndefined();
   1.477 +    return true;
   1.478 +}
   1.479 +
   1.480 +static bool
   1.481 +Options(JSContext *cx, unsigned argc, jsval *vp)
   1.482 +{
   1.483 +    JS::CallArgs args = CallArgsFromVp(argc, vp);
   1.484 +    ContextOptions oldOptions = ContextOptionsRef(cx);
   1.485 +
   1.486 +    for (unsigned i = 0; i < args.length(); ++i) {
   1.487 +        JSString *str = ToString(cx, args[i]);
   1.488 +        if (!str)
   1.489 +            return false;
   1.490 +
   1.491 +        JSAutoByteString opt(cx, str);
   1.492 +        if (!opt)
   1.493 +            return false;
   1.494 +
   1.495 +        if (strcmp(opt.ptr(), "strict") == 0)
   1.496 +            ContextOptionsRef(cx).toggleExtraWarnings();
   1.497 +        else if (strcmp(opt.ptr(), "werror") == 0)
   1.498 +            ContextOptionsRef(cx).toggleWerror();
   1.499 +        else if (strcmp(opt.ptr(), "strict_mode") == 0)
   1.500 +            ContextOptionsRef(cx).toggleStrictMode();
   1.501 +        else {
   1.502 +            JS_ReportError(cx, "unknown option name '%s'. The valid names are "
   1.503 +                           "strict, werror, and strict_mode.", opt.ptr());
   1.504 +            return false;
   1.505 +        }
   1.506 +    }
   1.507 +
   1.508 +    char *names = nullptr;
   1.509 +    if (oldOptions.extraWarnings()) {
   1.510 +        names = JS_sprintf_append(names, "%s", "strict");
   1.511 +        if (!names) {
   1.512 +            JS_ReportOutOfMemory(cx);
   1.513 +            return false;
   1.514 +        }
   1.515 +    }
   1.516 +    if (oldOptions.werror()) {
   1.517 +        names = JS_sprintf_append(names, "%s%s", names ? "," : "", "werror");
   1.518 +        if (!names) {
   1.519 +            JS_ReportOutOfMemory(cx);
   1.520 +            return false;
   1.521 +        }
   1.522 +    }
   1.523 +    if (names && oldOptions.strictMode()) {
   1.524 +        names = JS_sprintf_append(names, "%s%s", names ? "," : "", "strict_mode");
   1.525 +        if (!names) {
   1.526 +            JS_ReportOutOfMemory(cx);
   1.527 +            return false;
   1.528 +        }
   1.529 +    }
   1.530 +
   1.531 +    JSString *str = JS_NewStringCopyZ(cx, names);
   1.532 +    free(names);
   1.533 +    if (!str)
   1.534 +        return false;
   1.535 +
   1.536 +    args.rval().setString(str);
   1.537 +    return true;
   1.538 +}
   1.539 +
   1.540 +static bool
   1.541 +Parent(JSContext *cx, unsigned argc, jsval *vp)
   1.542 +{
   1.543 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.544 +    if (args.length() != 1) {
   1.545 +        JS_ReportError(cx, "Wrong number of arguments");
   1.546 +        return false;
   1.547 +    }
   1.548 +
   1.549 +    Value v = args[0];
   1.550 +    if (JSVAL_IS_PRIMITIVE(v)) {
   1.551 +        JS_ReportError(cx, "Only objects have parents!");
   1.552 +        return false;
   1.553 +    }
   1.554 +
   1.555 +    args.rval().setObjectOrNull(JS_GetParent(&v.toObject()));
   1.556 +    return true;
   1.557 +}
   1.558 +
   1.559 +static bool
   1.560 +Atob(JSContext *cx, unsigned argc, Value *vp)
   1.561 +{
   1.562 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.563 +    if (!args.length())
   1.564 +        return true;
   1.565 +
   1.566 +    return xpc::Base64Decode(cx, args[0], args.rval());
   1.567 +}
   1.568 +
   1.569 +static bool
   1.570 +Btoa(JSContext *cx, unsigned argc, Value *vp)
   1.571 +{
   1.572 +    CallArgs args = CallArgsFromVp(argc, vp);
   1.573 +    if (!args.length())
   1.574 +        return true;
   1.575 +
   1.576 +  return xpc::Base64Encode(cx, args[0], args.rval());
   1.577 +}
   1.578 +
   1.579 +static bool
   1.580 +Blob(JSContext *cx, unsigned argc, Value *vp)
   1.581 +{
   1.582 +  JS::CallArgs args = CallArgsFromVp(argc, vp);
   1.583 +
   1.584 +  nsCOMPtr<nsISupports> native =
   1.585 +    do_CreateInstance("@mozilla.org/dom/multipart-blob;1");
   1.586 +  if (!native) {
   1.587 +    JS_ReportError(cx, "Could not create native object!");
   1.588 +    return false;
   1.589 +  }
   1.590 +
   1.591 +  nsCOMPtr<nsIJSNativeInitializer> initializer = do_QueryInterface(native);
   1.592 +  MOZ_ASSERT(initializer);
   1.593 +
   1.594 +  nsresult rv = initializer->Initialize(nullptr, cx, nullptr, args);
   1.595 +  if (NS_FAILED(rv)) {
   1.596 +    JS_ReportError(cx, "Could not initialize native object!");
   1.597 +    return false;
   1.598 +  }
   1.599 +
   1.600 +  nsCOMPtr<nsIXPConnect> xpc = do_GetService(kXPConnectServiceContractID, &rv);
   1.601 +  if (NS_FAILED(rv)) {
   1.602 +    JS_ReportError(cx, "Could not get XPConnent service!");
   1.603 +    return false;
   1.604 +  }
   1.605 +
   1.606 +  JSObject *global = JS::CurrentGlobalOrNull(cx);
   1.607 +  rv = xpc->WrapNativeToJSVal(cx, global, native, nullptr,
   1.608 +                              &NS_GET_IID(nsISupports), true,
   1.609 +                              args.rval());
   1.610 +  if (NS_FAILED(rv)) {
   1.611 +    JS_ReportError(cx, "Could not wrap native object!");
   1.612 +    return false;
   1.613 +  }
   1.614 +
   1.615 +  return true;
   1.616 +}
   1.617 +
   1.618 +static bool
   1.619 +File(JSContext *cx, unsigned argc, Value *vp)
   1.620 +{
   1.621 +  JS::CallArgs args = CallArgsFromVp(argc, vp);
   1.622 +
   1.623 +  nsCOMPtr<nsISupports> native =
   1.624 +    do_CreateInstance("@mozilla.org/dom/multipart-file;1");
   1.625 +  if (!native) {
   1.626 +    JS_ReportError(cx, "Could not create native object!");
   1.627 +    return false;
   1.628 +  }
   1.629 +
   1.630 +  nsCOMPtr<nsIJSNativeInitializer> initializer = do_QueryInterface(native);
   1.631 +  MOZ_ASSERT(initializer);
   1.632 +
   1.633 +  nsresult rv = initializer->Initialize(nullptr, cx, nullptr, args);
   1.634 +  if (NS_FAILED(rv)) {
   1.635 +    JS_ReportError(cx, "Could not initialize native object!");
   1.636 +    return false;
   1.637 +  }
   1.638 +
   1.639 +  nsCOMPtr<nsIXPConnect> xpc = do_GetService(kXPConnectServiceContractID, &rv);
   1.640 +  if (NS_FAILED(rv)) {
   1.641 +    JS_ReportError(cx, "Could not get XPConnent service!");
   1.642 +    return false;
   1.643 +  }
   1.644 +
   1.645 +  JSObject *global = JS::CurrentGlobalOrNull(cx);
   1.646 +  rv = xpc->WrapNativeToJSVal(cx, global, native, nullptr,
   1.647 +                              &NS_GET_IID(nsISupports), true,
   1.648 +                              args.rval());
   1.649 +  if (NS_FAILED(rv)) {
   1.650 +    JS_ReportError(cx, "Could not wrap native object!");
   1.651 +    return false;
   1.652 +  }
   1.653 +
   1.654 +  return true;
   1.655 +}
   1.656 +
   1.657 +static Maybe<PersistentRootedValue> sScriptedInterruptCallback;
   1.658 +
   1.659 +static bool
   1.660 +XPCShellInterruptCallback(JSContext *cx)
   1.661 +{
   1.662 +    MOZ_ASSERT(!sScriptedInterruptCallback.empty());
   1.663 +    RootedValue callback(cx, sScriptedInterruptCallback.ref());
   1.664 +
   1.665 +    // If no interrupt callback was set by script, no-op.
   1.666 +    if (callback.isUndefined())
   1.667 +        return true;
   1.668 +
   1.669 +    JSAutoCompartment ac(cx, &callback.toObject());
   1.670 +    RootedValue rv(cx);
   1.671 +    if (!JS_CallFunctionValue(cx, JS::NullPtr(), callback, JS::HandleValueArray::empty(), &rv) ||
   1.672 +        !rv.isBoolean())
   1.673 +    {
   1.674 +        NS_WARNING("Scripted interrupt callback failed! Terminating script.");
   1.675 +        JS_ClearPendingException(cx);
   1.676 +        return false;
   1.677 +    }
   1.678 +
   1.679 +    return rv.toBoolean();
   1.680 +}
   1.681 +
   1.682 +static bool
   1.683 +SetInterruptCallback(JSContext *cx, unsigned argc, jsval *vp)
   1.684 +{
   1.685 +    MOZ_ASSERT(!sScriptedInterruptCallback.empty());
   1.686 +
   1.687 +    // Sanity-check args.
   1.688 +    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
   1.689 +    if (args.length() != 1) {
   1.690 +        JS_ReportError(cx, "Wrong number of arguments");
   1.691 +        return false;
   1.692 +    }
   1.693 +
   1.694 +    // Allow callers to remove the interrupt callback by passing undefined.
   1.695 +    if (args[0].isUndefined()) {
   1.696 +        sScriptedInterruptCallback.ref() = UndefinedValue();
   1.697 +        return true;
   1.698 +    }
   1.699 +
   1.700 +    // Otherwise, we should have a callable object.
   1.701 +    if (!args[0].isObject() || !JS_ObjectIsCallable(cx, &args[0].toObject())) {
   1.702 +        JS_ReportError(cx, "Argument must be callable");
   1.703 +        return false;
   1.704 +    }
   1.705 +
   1.706 +    sScriptedInterruptCallback.ref() = args[0];
   1.707 +
   1.708 +    return true;
   1.709 +}
   1.710 +
   1.711 +static bool
   1.712 +SimulateActivityCallback(JSContext *cx, unsigned argc, jsval *vp)
   1.713 +{
   1.714 +    // Sanity-check args.
   1.715 +    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
   1.716 +    if (args.length() != 1 || !args[0].isBoolean()) {
   1.717 +        JS_ReportError(cx, "Wrong number of arguments");
   1.718 +        return false;
   1.719 +    }
   1.720 +    xpc::SimulateActivityCallback(args[0].toBoolean());
   1.721 +    return true;
   1.722 +}
   1.723 +
   1.724 +static const JSFunctionSpec glob_functions[] = {
   1.725 +    JS_FS("print",           Print,          0,0),
   1.726 +    JS_FS("readline",        ReadLine,       1,0),
   1.727 +    JS_FS("load",            Load,           1,0),
   1.728 +    JS_FS("quit",            Quit,           0,0),
   1.729 +    JS_FS("ignoreReportedErrors", IgnoreReportedErrors, 1,0),
   1.730 +    JS_FS("version",         Version,        1,0),
   1.731 +    JS_FS("build",           BuildDate,      0,0),
   1.732 +    JS_FS("dumpXPC",         DumpXPC,        1,0),
   1.733 +    JS_FS("dump",            Dump,           1,0),
   1.734 +    JS_FS("gc",              GC,             0,0),
   1.735 +#ifdef JS_GC_ZEAL
   1.736 +    JS_FS("gczeal",          GCZeal,         1,0),
   1.737 +#endif
   1.738 +    JS_FS("options",         Options,        0,0),
   1.739 +    JS_FN("parent",          Parent,         1,0),
   1.740 +    JS_FS("sendCommand",     SendCommand,    1,0),
   1.741 +    JS_FS("atob",            Atob,           1,0),
   1.742 +    JS_FS("btoa",            Btoa,           1,0),
   1.743 +    JS_FS("Blob",            Blob,           2,JSFUN_CONSTRUCTOR),
   1.744 +    JS_FS("File",            File,           2,JSFUN_CONSTRUCTOR),
   1.745 +    JS_FS("setInterruptCallback", SetInterruptCallback, 1,0),
   1.746 +    JS_FS("simulateActivityCallback", SimulateActivityCallback, 1,0),
   1.747 +    JS_FS_END
   1.748 +};
   1.749 +
   1.750 +static bool
   1.751 +env_setProperty(JSContext *cx, HandleObject obj, HandleId id, bool strict, MutableHandleValue vp)
   1.752 +{
   1.753 +/* XXX porting may be easy, but these don't seem to supply setenv by default */
   1.754 +#if !defined SOLARIS
   1.755 +    JSString *valstr;
   1.756 +    JS::Rooted<JSString*> idstr(cx);
   1.757 +    int rv;
   1.758 +
   1.759 +    RootedValue idval(cx);
   1.760 +    if (!JS_IdToValue(cx, id, &idval))
   1.761 +        return false;
   1.762 +
   1.763 +    idstr = ToString(cx, idval);
   1.764 +    valstr = ToString(cx, vp);
   1.765 +    if (!idstr || !valstr)
   1.766 +        return false;
   1.767 +    JSAutoByteString name(cx, idstr);
   1.768 +    if (!name)
   1.769 +        return false;
   1.770 +    JSAutoByteString value(cx, valstr);
   1.771 +    if (!value)
   1.772 +        return false;
   1.773 +#if defined XP_WIN || defined HPUX || defined OSF1 || defined SCO
   1.774 +    {
   1.775 +        char *waste = JS_smprintf("%s=%s", name.ptr(), value.ptr());
   1.776 +        if (!waste) {
   1.777 +            JS_ReportOutOfMemory(cx);
   1.778 +            return false;
   1.779 +        }
   1.780 +        rv = putenv(waste);
   1.781 +#ifdef XP_WIN
   1.782 +        /*
   1.783 +         * HPUX9 at least still has the bad old non-copying putenv.
   1.784 +         *
   1.785 +         * Per mail from <s.shanmuganathan@digital.com>, OSF1 also has a putenv
   1.786 +         * that will crash if you pass it an auto char array (so it must place
   1.787 +         * its argument directly in the char *environ[] array).
   1.788 +         */
   1.789 +        free(waste);
   1.790 +#endif
   1.791 +    }
   1.792 +#else
   1.793 +    rv = setenv(name.ptr(), value.ptr(), 1);
   1.794 +#endif
   1.795 +    if (rv < 0) {
   1.796 +        JS_ReportError(cx, "can't set envariable %s to %s", name.ptr(), value.ptr());
   1.797 +        return false;
   1.798 +    }
   1.799 +    vp.set(STRING_TO_JSVAL(valstr));
   1.800 +#endif /* !defined SOLARIS */
   1.801 +    return true;
   1.802 +}
   1.803 +
   1.804 +static bool
   1.805 +env_enumerate(JSContext *cx, HandleObject obj)
   1.806 +{
   1.807 +    static bool reflected;
   1.808 +    char **evp, *name, *value;
   1.809 +    RootedString valstr(cx);
   1.810 +    bool ok;
   1.811 +
   1.812 +    if (reflected)
   1.813 +        return true;
   1.814 +
   1.815 +    for (evp = (char **)JS_GetPrivate(obj); (name = *evp) != nullptr; evp++) {
   1.816 +        value = strchr(name, '=');
   1.817 +        if (!value)
   1.818 +            continue;
   1.819 +        *value++ = '\0';
   1.820 +        valstr = JS_NewStringCopyZ(cx, value);
   1.821 +        ok = valstr ? JS_DefineProperty(cx, obj, name, valstr, JSPROP_ENUMERATE) : false;
   1.822 +        value[-1] = '=';
   1.823 +        if (!ok)
   1.824 +            return false;
   1.825 +    }
   1.826 +
   1.827 +    reflected = true;
   1.828 +    return true;
   1.829 +}
   1.830 +
   1.831 +static bool
   1.832 +env_resolve(JSContext *cx, HandleObject obj, HandleId id,
   1.833 +            JS::MutableHandleObject objp)
   1.834 +{
   1.835 +    JSString *idstr, *valstr;
   1.836 +
   1.837 +    RootedValue idval(cx);
   1.838 +    if (!JS_IdToValue(cx, id, &idval))
   1.839 +        return false;
   1.840 +
   1.841 +    idstr = ToString(cx, idval);
   1.842 +    if (!idstr)
   1.843 +        return false;
   1.844 +    JSAutoByteString name(cx, idstr);
   1.845 +    if (!name)
   1.846 +        return false;
   1.847 +    const char *value = getenv(name.ptr());
   1.848 +    if (value) {
   1.849 +        valstr = JS_NewStringCopyZ(cx, value);
   1.850 +        if (!valstr)
   1.851 +            return false;
   1.852 +        if (!JS_DefinePropertyById(cx, obj, id, STRING_TO_JSVAL(valstr),
   1.853 +                                   nullptr, nullptr, JSPROP_ENUMERATE)) {
   1.854 +            return false;
   1.855 +        }
   1.856 +        objp.set(obj);
   1.857 +    }
   1.858 +    return true;
   1.859 +}
   1.860 +
   1.861 +static const JSClass env_class = {
   1.862 +    "environment", JSCLASS_HAS_PRIVATE | JSCLASS_NEW_RESOLVE,
   1.863 +    JS_PropertyStub,  JS_DeletePropertyStub,
   1.864 +    JS_PropertyStub,  env_setProperty,
   1.865 +    env_enumerate, (JSResolveOp) env_resolve,
   1.866 +    JS_ConvertStub,   nullptr
   1.867 +};
   1.868 +
   1.869 +/***************************************************************************/
   1.870 +
   1.871 +typedef enum JSShellErrNum {
   1.872 +#define MSG_DEF(name, number, count, exception, format) \
   1.873 +    name = number,
   1.874 +#include "jsshell.msg"
   1.875 +#undef MSG_DEF
   1.876 +    JSShellErr_Limit
   1.877 +} JSShellErrNum;
   1.878 +
   1.879 +static const JSErrorFormatString jsShell_ErrorFormatString[JSShellErr_Limit] = {
   1.880 +#define MSG_DEF(name, number, count, exception, format) \
   1.881 +    { format, count } ,
   1.882 +#include "jsshell.msg"
   1.883 +#undef MSG_DEF
   1.884 +};
   1.885 +
   1.886 +static const JSErrorFormatString *
   1.887 +my_GetErrorMessage(void *userRef, const char *locale, const unsigned errorNumber)
   1.888 +{
   1.889 +    if (errorNumber == 0 || errorNumber >= JSShellErr_Limit)
   1.890 +        return nullptr;
   1.891 +
   1.892 +    return &jsShell_ErrorFormatString[errorNumber];
   1.893 +}
   1.894 +
   1.895 +static void
   1.896 +ProcessFile(JSContext *cx, JS::Handle<JSObject*> obj, const char *filename, FILE *file,
   1.897 +            bool forceTTY)
   1.898 +{
   1.899 +    JS::RootedScript script(cx);
   1.900 +    JS::RootedValue result(cx);
   1.901 +    int lineno, startline;
   1.902 +    bool ok, hitEOF;
   1.903 +    char *bufp, buffer[4096];
   1.904 +    JSString *str;
   1.905 +
   1.906 +    if (forceTTY) {
   1.907 +        file = stdin;
   1.908 +    } else if (!isatty(fileno(file)))
   1.909 +    {
   1.910 +        /*
   1.911 +         * It's not interactive - just execute it.
   1.912 +         *
   1.913 +         * Support the UNIX #! shell hack; gobble the first line if it starts
   1.914 +         * with '#'.  TODO - this isn't quite compatible with sharp variables,
   1.915 +         * as a legal js program (using sharp variables) might start with '#'.
   1.916 +         * But that would require multi-character lookahead.
   1.917 +         */
   1.918 +        int ch = fgetc(file);
   1.919 +        if (ch == '#') {
   1.920 +            while ((ch = fgetc(file)) != EOF) {
   1.921 +                if (ch == '\n' || ch == '\r')
   1.922 +                    break;
   1.923 +            }
   1.924 +        }
   1.925 +        ungetc(ch, file);
   1.926 +        DoBeginRequest(cx);
   1.927 +
   1.928 +        JS::CompileOptions options(cx);
   1.929 +        options.setUTF8(true)
   1.930 +               .setFileAndLine(filename, 1);
   1.931 +        script = JS::Compile(cx, obj, options, file);
   1.932 +        if (script && !compileOnly)
   1.933 +            (void)JS_ExecuteScript(cx, obj, script, &result);
   1.934 +        DoEndRequest(cx);
   1.935 +
   1.936 +        return;
   1.937 +    }
   1.938 +
   1.939 +    /* It's an interactive filehandle; drop into read-eval-print loop. */
   1.940 +    lineno = 1;
   1.941 +    hitEOF = false;
   1.942 +    do {
   1.943 +        bufp = buffer;
   1.944 +        *bufp = '\0';
   1.945 +
   1.946 +        /*
   1.947 +         * Accumulate lines until we get a 'compilable unit' - one that either
   1.948 +         * generates an error (before running out of source) or that compiles
   1.949 +         * cleanly.  This should be whenever we get a complete statement that
   1.950 +         * coincides with the end of a line.
   1.951 +         */
   1.952 +        startline = lineno;
   1.953 +        do {
   1.954 +            if (!GetLine(cx, bufp, file, startline == lineno ? "js> " : "")) {
   1.955 +                hitEOF = true;
   1.956 +                break;
   1.957 +            }
   1.958 +            bufp += strlen(bufp);
   1.959 +            lineno++;
   1.960 +        } while (!JS_BufferIsCompilableUnit(cx, obj, buffer, strlen(buffer)));
   1.961 +
   1.962 +        DoBeginRequest(cx);
   1.963 +        /* Clear any pending exception from previous failed compiles.  */
   1.964 +        JS_ClearPendingException(cx);
   1.965 +        JS::CompileOptions options(cx);
   1.966 +        options.setFileAndLine("typein", startline);
   1.967 +        script = JS_CompileScript(cx, obj, buffer, strlen(buffer), options);
   1.968 +        if (script) {
   1.969 +            JSErrorReporter older;
   1.970 +
   1.971 +            if (!compileOnly) {
   1.972 +                ok = JS_ExecuteScript(cx, obj, script, &result);
   1.973 +                if (ok && result != JSVAL_VOID) {
   1.974 +                    /* Suppress error reports from JS::ToString(). */
   1.975 +                    older = JS_SetErrorReporter(cx, nullptr);
   1.976 +                    str = ToString(cx, result);
   1.977 +                    JS_SetErrorReporter(cx, older);
   1.978 +                    JSAutoByteString bytes;
   1.979 +                    if (str && bytes.encodeLatin1(cx, str))
   1.980 +                        fprintf(gOutFile, "%s\n", bytes.ptr());
   1.981 +                    else
   1.982 +                        ok = false;
   1.983 +                }
   1.984 +            }
   1.985 +        }
   1.986 +        DoEndRequest(cx);
   1.987 +    } while (!hitEOF && !gQuitting);
   1.988 +
   1.989 +    fprintf(gOutFile, "\n");
   1.990 +}
   1.991 +
   1.992 +static void
   1.993 +Process(JSContext *cx, JS::Handle<JSObject*> obj, const char *filename, bool forceTTY)
   1.994 +{
   1.995 +    FILE *file;
   1.996 +
   1.997 +    if (forceTTY || !filename || strcmp(filename, "-") == 0) {
   1.998 +        file = stdin;
   1.999 +    } else {
  1.1000 +        file = fopen(filename, "r");
  1.1001 +        if (!file) {
  1.1002 +            JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr,
  1.1003 +                                 JSSMSG_CANT_OPEN,
  1.1004 +                                 filename, strerror(errno));
  1.1005 +            gExitCode = EXITCODE_FILE_NOT_FOUND;
  1.1006 +            return;
  1.1007 +        }
  1.1008 +    }
  1.1009 +
  1.1010 +    ProcessFile(cx, obj, filename, file, forceTTY);
  1.1011 +    if (file != stdin)
  1.1012 +        fclose(file);
  1.1013 +}
  1.1014 +
  1.1015 +static int
  1.1016 +usage(void)
  1.1017 +{
  1.1018 +    fprintf(gErrFile, "%s\n", JS_GetImplementationVersion());
  1.1019 +    fprintf(gErrFile, "usage: xpcshell [-g gredir] [-a appdir] [-r manifest]... [-PsSwWCijmIn] [-v version] [-f scriptfile] [-e script] [scriptfile] [scriptarg...]\n");
  1.1020 +    return 2;
  1.1021 +}
  1.1022 +
  1.1023 +static void
  1.1024 +ProcessArgsForCompartment(JSContext *cx, char **argv, int argc)
  1.1025 +{
  1.1026 +    for (int i = 0; i < argc; i++) {
  1.1027 +        if (argv[i][0] != '-' || argv[i][1] == '\0')
  1.1028 +            break;
  1.1029 +
  1.1030 +        switch (argv[i][1]) {
  1.1031 +          case 'v':
  1.1032 +          case 'f':
  1.1033 +          case 'e':
  1.1034 +            if (++i == argc)
  1.1035 +                return;
  1.1036 +            break;
  1.1037 +        case 'S':
  1.1038 +            ContextOptionsRef(cx).toggleWerror();
  1.1039 +        case 's':
  1.1040 +            ContextOptionsRef(cx).toggleExtraWarnings();
  1.1041 +            break;
  1.1042 +        case 'I':
  1.1043 +            RuntimeOptionsRef(cx).toggleIon()
  1.1044 +                                 .toggleAsmJS();
  1.1045 +            break;
  1.1046 +        }
  1.1047 +    }
  1.1048 +}
  1.1049 +
  1.1050 +static int
  1.1051 +ProcessArgs(JSContext *cx, JS::Handle<JSObject*> obj, char **argv, int argc, XPCShellDirProvider* aDirProvider)
  1.1052 +{
  1.1053 +    const char rcfilename[] = "xpcshell.js";
  1.1054 +    FILE *rcfile;
  1.1055 +    int i;
  1.1056 +    JS::Rooted<JSObject*> argsObj(cx);
  1.1057 +    char *filename = nullptr;
  1.1058 +    bool isInteractive = true;
  1.1059 +    bool forceTTY = false;
  1.1060 +
  1.1061 +    rcfile = fopen(rcfilename, "r");
  1.1062 +    if (rcfile) {
  1.1063 +        printf("[loading '%s'...]\n", rcfilename);
  1.1064 +        ProcessFile(cx, obj, rcfilename, rcfile, false);
  1.1065 +        fclose(rcfile);
  1.1066 +    }
  1.1067 +
  1.1068 +    /*
  1.1069 +     * Scan past all optional arguments so we can create the arguments object
  1.1070 +     * before processing any -f options, which must interleave properly with
  1.1071 +     * -v and -w options.  This requires two passes, and without getopt, we'll
  1.1072 +     * have to keep the option logic here and in the second for loop in sync.
  1.1073 +     */
  1.1074 +    for (i = 0; i < argc; i++) {
  1.1075 +        if (argv[i][0] != '-' || argv[i][1] == '\0') {
  1.1076 +            ++i;
  1.1077 +            break;
  1.1078 +        }
  1.1079 +        switch (argv[i][1]) {
  1.1080 +          case 'v':
  1.1081 +          case 'f':
  1.1082 +          case 'e':
  1.1083 +            ++i;
  1.1084 +            break;
  1.1085 +          default:;
  1.1086 +        }
  1.1087 +    }
  1.1088 +
  1.1089 +    /*
  1.1090 +     * Create arguments early and define it to root it, so it's safe from any
  1.1091 +     * GC calls nested below, and so it is available to -f <file> arguments.
  1.1092 +     */
  1.1093 +    argsObj = JS_NewArrayObject(cx, 0);
  1.1094 +    if (!argsObj)
  1.1095 +        return 1;
  1.1096 +    if (!JS_DefineProperty(cx, obj, "arguments", argsObj, 0))
  1.1097 +        return 1;
  1.1098 +
  1.1099 +    for (size_t j = 0, length = argc - i; j < length; j++) {
  1.1100 +        JSString *str = JS_NewStringCopyZ(cx, argv[i++]);
  1.1101 +        if (!str)
  1.1102 +            return 1;
  1.1103 +        if (!JS_DefineElement(cx, argsObj, j, STRING_TO_JSVAL(str),
  1.1104 +                              nullptr, nullptr, JSPROP_ENUMERATE)) {
  1.1105 +            return 1;
  1.1106 +        }
  1.1107 +    }
  1.1108 +
  1.1109 +    for (i = 0; i < argc; i++) {
  1.1110 +        if (argv[i][0] != '-' || argv[i][1] == '\0') {
  1.1111 +            filename = argv[i++];
  1.1112 +            isInteractive = false;
  1.1113 +            break;
  1.1114 +        }
  1.1115 +        switch (argv[i][1]) {
  1.1116 +        case 'v':
  1.1117 +            if (++i == argc) {
  1.1118 +                return usage();
  1.1119 +            }
  1.1120 +            JS_SetVersionForCompartment(js::GetContextCompartment(cx),
  1.1121 +                                        JSVersion(atoi(argv[i])));
  1.1122 +            break;
  1.1123 +        case 'W':
  1.1124 +            reportWarnings = false;
  1.1125 +            break;
  1.1126 +        case 'w':
  1.1127 +            reportWarnings = true;
  1.1128 +            break;
  1.1129 +        case 'x':
  1.1130 +            break;
  1.1131 +        case 'd':
  1.1132 +            xpc_ActivateDebugMode();
  1.1133 +            break;
  1.1134 +        case 'f':
  1.1135 +            if (++i == argc) {
  1.1136 +                return usage();
  1.1137 +            }
  1.1138 +            Process(cx, obj, argv[i], false);
  1.1139 +            /*
  1.1140 +             * XXX: js -f foo.js should interpret foo.js and then
  1.1141 +             * drop into interactive mode, but that breaks test
  1.1142 +             * harness. Just execute foo.js for now.
  1.1143 +             */
  1.1144 +            isInteractive = false;
  1.1145 +            break;
  1.1146 +        case 'i':
  1.1147 +            isInteractive = forceTTY = true;
  1.1148 +            break;
  1.1149 +        case 'e':
  1.1150 +        {
  1.1151 +            RootedValue rval(cx);
  1.1152 +
  1.1153 +            if (++i == argc) {
  1.1154 +                return usage();
  1.1155 +            }
  1.1156 +
  1.1157 +            JS_EvaluateScript(cx, obj, argv[i], strlen(argv[i]), "-e", 1, &rval);
  1.1158 +
  1.1159 +            isInteractive = false;
  1.1160 +            break;
  1.1161 +        }
  1.1162 +        case 'C':
  1.1163 +            compileOnly = true;
  1.1164 +            isInteractive = false;
  1.1165 +            break;
  1.1166 +        case 'S':
  1.1167 +        case 's':
  1.1168 +        case 'm':
  1.1169 +        case 'I':
  1.1170 +            // These options are processed in ProcessArgsForCompartment.
  1.1171 +            break;
  1.1172 +        case 'p':
  1.1173 +        {
  1.1174 +          // plugins path
  1.1175 +          char *pluginPath = argv[++i];
  1.1176 +          nsCOMPtr<nsIFile> pluginsDir;
  1.1177 +          if (NS_FAILED(XRE_GetFileFromPath(pluginPath, getter_AddRefs(pluginsDir)))) {
  1.1178 +              fprintf(gErrFile, "Couldn't use given plugins dir.\n");
  1.1179 +              return usage();
  1.1180 +          }
  1.1181 +          aDirProvider->SetPluginDir(pluginsDir);
  1.1182 +          break;
  1.1183 +        }
  1.1184 +        default:
  1.1185 +            return usage();
  1.1186 +        }
  1.1187 +    }
  1.1188 +
  1.1189 +    if (filename || isInteractive)
  1.1190 +        Process(cx, obj, filename, forceTTY);
  1.1191 +
  1.1192 +    return gExitCode;
  1.1193 +}
  1.1194 +
  1.1195 +/***************************************************************************/
  1.1196 +
  1.1197 +// #define TEST_InitClassesWithNewWrappedGlobal
  1.1198 +
  1.1199 +#ifdef TEST_InitClassesWithNewWrappedGlobal
  1.1200 +// XXX hacky test code...
  1.1201 +#include "xpctest.h"
  1.1202 +
  1.1203 +class TestGlobal : public nsIXPCTestNoisy, public nsIXPCScriptable
  1.1204 +{
  1.1205 +public:
  1.1206 +    NS_DECL_ISUPPORTS
  1.1207 +    NS_DECL_NSIXPCTESTNOISY
  1.1208 +    NS_DECL_NSIXPCSCRIPTABLE
  1.1209 +
  1.1210 +    TestGlobal(){}
  1.1211 +};
  1.1212 +
  1.1213 +NS_IMPL_ISUPPORTS(TestGlobal, nsIXPCTestNoisy, nsIXPCScriptable)
  1.1214 +
  1.1215 +// The nsIXPCScriptable map declaration that will generate stubs for us...
  1.1216 +#define XPC_MAP_CLASSNAME           TestGlobal
  1.1217 +#define XPC_MAP_QUOTED_CLASSNAME   "TestGlobal"
  1.1218 +#define XPC_MAP_FLAGS               nsIXPCScriptable::USE_JSSTUB_FOR_ADDPROPERTY |\
  1.1219 +                                    nsIXPCScriptable::USE_JSSTUB_FOR_DELPROPERTY |\
  1.1220 +                                    nsIXPCScriptable::USE_JSSTUB_FOR_SETPROPERTY
  1.1221 +#include "xpc_map_end.h" /* This will #undef the above */
  1.1222 +
  1.1223 +NS_IMETHODIMP TestGlobal::Squawk() {return NS_OK;}
  1.1224 +
  1.1225 +#endif
  1.1226 +
  1.1227 +// uncomment to install the test 'this' translator
  1.1228 +// #define TEST_TranslateThis
  1.1229 +
  1.1230 +#ifdef TEST_TranslateThis
  1.1231 +
  1.1232 +#include "xpctest.h"
  1.1233 +
  1.1234 +class nsXPCFunctionThisTranslator : public nsIXPCFunctionThisTranslator
  1.1235 +{
  1.1236 +public:
  1.1237 +  NS_DECL_ISUPPORTS
  1.1238 +  NS_DECL_NSIXPCFUNCTIONTHISTRANSLATOR
  1.1239 +
  1.1240 +  nsXPCFunctionThisTranslator();
  1.1241 +  virtual ~nsXPCFunctionThisTranslator();
  1.1242 +  /* additional members */
  1.1243 +};
  1.1244 +
  1.1245 +/* Implementation file */
  1.1246 +NS_IMPL_ISUPPORTS(nsXPCFunctionThisTranslator, nsIXPCFunctionThisTranslator)
  1.1247 +
  1.1248 +nsXPCFunctionThisTranslator::nsXPCFunctionThisTranslator()
  1.1249 +{
  1.1250 +}
  1.1251 +
  1.1252 +nsXPCFunctionThisTranslator::~nsXPCFunctionThisTranslator()
  1.1253 +{
  1.1254 +}
  1.1255 +
  1.1256 +/* nsISupports TranslateThis (in nsISupports aInitialThis); */
  1.1257 +NS_IMETHODIMP
  1.1258 +nsXPCFunctionThisTranslator::TranslateThis(nsISupports *aInitialThis,
  1.1259 +                                           nsISupports **_retval)
  1.1260 +{
  1.1261 +    nsCOMPtr<nsISupports> temp = aInitialThis;
  1.1262 +    temp.forget(_retval);
  1.1263 +    return NS_OK;
  1.1264 +}
  1.1265 +
  1.1266 +#endif
  1.1267 +
  1.1268 +static void
  1.1269 +XPCShellErrorReporter(JSContext *cx, const char *message, JSErrorReport *rep)
  1.1270 +{
  1.1271 +    if (gIgnoreReportedErrors)
  1.1272 +        return;
  1.1273 +
  1.1274 +    if (!JSREPORT_IS_WARNING(rep->flags))
  1.1275 +        gExitCode = EXITCODE_RUNTIME_ERROR;
  1.1276 +
  1.1277 +    // Delegate to the system error reporter for heavy lifting.
  1.1278 +    xpc::SystemErrorReporter(cx, message, rep);
  1.1279 +}
  1.1280 +
  1.1281 +static bool
  1.1282 +ContextCallback(JSContext *cx, unsigned contextOp)
  1.1283 +{
  1.1284 +    if (contextOp == JSCONTEXT_NEW)
  1.1285 +        JS_SetErrorReporter(cx, XPCShellErrorReporter);
  1.1286 +    return true;
  1.1287 +}
  1.1288 +
  1.1289 +static bool
  1.1290 +GetCurrentWorkingDirectory(nsAString& workingDirectory)
  1.1291 +{
  1.1292 +#if !defined(XP_WIN) && !defined(XP_UNIX)
  1.1293 +    //XXX: your platform should really implement this
  1.1294 +    return false;
  1.1295 +#elif XP_WIN
  1.1296 +    DWORD requiredLength = GetCurrentDirectoryW(0, nullptr);
  1.1297 +    workingDirectory.SetLength(requiredLength);
  1.1298 +    GetCurrentDirectoryW(workingDirectory.Length(),
  1.1299 +                         (LPWSTR)workingDirectory.BeginWriting());
  1.1300 +    // we got a trailing null there
  1.1301 +    workingDirectory.SetLength(requiredLength);
  1.1302 +    workingDirectory.Replace(workingDirectory.Length() - 1, 1, L'\\');
  1.1303 +#elif defined(XP_UNIX)
  1.1304 +    nsAutoCString cwd;
  1.1305 +    // 1024 is just a guess at a sane starting value
  1.1306 +    size_t bufsize = 1024;
  1.1307 +    char* result = nullptr;
  1.1308 +    while (result == nullptr) {
  1.1309 +        cwd.SetLength(bufsize);
  1.1310 +        result = getcwd(cwd.BeginWriting(), cwd.Length());
  1.1311 +        if (!result) {
  1.1312 +            if (errno != ERANGE)
  1.1313 +                return false;
  1.1314 +            // need to make the buffer bigger
  1.1315 +            bufsize *= 2;
  1.1316 +        }
  1.1317 +    }
  1.1318 +    // size back down to the actual string length
  1.1319 +    cwd.SetLength(strlen(result) + 1);
  1.1320 +    cwd.Replace(cwd.Length() - 1, 1, '/');
  1.1321 +    workingDirectory = NS_ConvertUTF8toUTF16(cwd);
  1.1322 +#endif
  1.1323 +    return true;
  1.1324 +}
  1.1325 +
  1.1326 +static JSSecurityCallbacks shellSecurityCallbacks;
  1.1327 +
  1.1328 +int
  1.1329 +XRE_XPCShellMain(int argc, char **argv, char **envp)
  1.1330 +{
  1.1331 +    JSRuntime *rt;
  1.1332 +    JSContext *cx;
  1.1333 +    int result;
  1.1334 +    nsresult rv;
  1.1335 +
  1.1336 +    gErrFile = stderr;
  1.1337 +    gOutFile = stdout;
  1.1338 +    gInFile = stdin;
  1.1339 +
  1.1340 +    NS_LogInit();
  1.1341 +
  1.1342 +    nsCOMPtr<nsIFile> appFile;
  1.1343 +    rv = XRE_GetBinaryPath(argv[0], getter_AddRefs(appFile));
  1.1344 +    if (NS_FAILED(rv)) {
  1.1345 +        printf("Couldn't find application file.\n");
  1.1346 +        return 1;
  1.1347 +    }
  1.1348 +    nsCOMPtr<nsIFile> appDir;
  1.1349 +    rv = appFile->GetParent(getter_AddRefs(appDir));
  1.1350 +    if (NS_FAILED(rv)) {
  1.1351 +        printf("Couldn't get application directory.\n");
  1.1352 +        return 1;
  1.1353 +    }
  1.1354 +
  1.1355 +    XPCShellDirProvider dirprovider;
  1.1356 +
  1.1357 +    dirprovider.SetAppFile(appFile);
  1.1358 +
  1.1359 +    nsCOMPtr<nsIFile> greDir;
  1.1360 +    if (argc > 1 && !strcmp(argv[1], "-g")) {
  1.1361 +        if (argc < 3)
  1.1362 +            return usage();
  1.1363 +
  1.1364 +        rv = XRE_GetFileFromPath(argv[2], getter_AddRefs(greDir));
  1.1365 +        if (NS_FAILED(rv)) {
  1.1366 +            printf("Couldn't use given GRE dir.\n");
  1.1367 +            return 1;
  1.1368 +        }
  1.1369 +
  1.1370 +        dirprovider.SetGREDir(greDir);
  1.1371 +
  1.1372 +        argc -= 2;
  1.1373 +        argv += 2;
  1.1374 +    } else {
  1.1375 +        nsAutoString workingDir;
  1.1376 +        if (!GetCurrentWorkingDirectory(workingDir)) {
  1.1377 +            printf("GetCurrentWorkingDirectory failed.\n");
  1.1378 +            return 1;
  1.1379 +        }
  1.1380 +        rv = NS_NewLocalFile(workingDir, true, getter_AddRefs(greDir));
  1.1381 +        if (NS_FAILED(rv)) {
  1.1382 +            printf("NS_NewLocalFile failed.\n");
  1.1383 +            return 1;
  1.1384 +        }
  1.1385 +    }
  1.1386 +
  1.1387 +    if (argc > 1 && !strcmp(argv[1], "-a")) {
  1.1388 +        if (argc < 3)
  1.1389 +            return usage();
  1.1390 +
  1.1391 +        nsCOMPtr<nsIFile> dir;
  1.1392 +        rv = XRE_GetFileFromPath(argv[2], getter_AddRefs(dir));
  1.1393 +        if (NS_SUCCEEDED(rv)) {
  1.1394 +            appDir = do_QueryInterface(dir, &rv);
  1.1395 +            dirprovider.SetAppDir(appDir);
  1.1396 +        }
  1.1397 +        if (NS_FAILED(rv)) {
  1.1398 +            printf("Couldn't use given appdir.\n");
  1.1399 +            return 1;
  1.1400 +        }
  1.1401 +        argc -= 2;
  1.1402 +        argv += 2;
  1.1403 +    }
  1.1404 +
  1.1405 +    while (argc > 1 && !strcmp(argv[1], "-r")) {
  1.1406 +        if (argc < 3)
  1.1407 +            return usage();
  1.1408 +
  1.1409 +        nsCOMPtr<nsIFile> lf;
  1.1410 +        rv = XRE_GetFileFromPath(argv[2], getter_AddRefs(lf));
  1.1411 +        if (NS_FAILED(rv)) {
  1.1412 +            printf("Couldn't get manifest file.\n");
  1.1413 +            return 1;
  1.1414 +        }
  1.1415 +        XRE_AddManifestLocation(NS_COMPONENT_LOCATION, lf);
  1.1416 +
  1.1417 +        argc -= 2;
  1.1418 +        argv += 2;
  1.1419 +    }
  1.1420 +
  1.1421 +#ifdef MOZ_CRASHREPORTER
  1.1422 +    const char *val = getenv("MOZ_CRASHREPORTER");
  1.1423 +    if (val && *val) {
  1.1424 +        rv = CrashReporter::SetExceptionHandler(greDir, true);
  1.1425 +        if (NS_FAILED(rv)) {
  1.1426 +            printf("CrashReporter::SetExceptionHandler failed!\n");
  1.1427 +            return 1;
  1.1428 +        }
  1.1429 +        MOZ_ASSERT(CrashReporter::GetEnabled());
  1.1430 +    }
  1.1431 +#endif
  1.1432 +
  1.1433 +    {
  1.1434 +        if (argc > 1 && !strcmp(argv[1], "--greomni")) {
  1.1435 +            nsCOMPtr<nsIFile> greOmni;
  1.1436 +            nsCOMPtr<nsIFile> appOmni;
  1.1437 +            XRE_GetFileFromPath(argv[2], getter_AddRefs(greOmni));
  1.1438 +            if (argc > 3 && !strcmp(argv[3], "--appomni")) {
  1.1439 +                XRE_GetFileFromPath(argv[4], getter_AddRefs(appOmni));
  1.1440 +                argc-=2;
  1.1441 +                argv+=2;
  1.1442 +            } else {
  1.1443 +                appOmni = greOmni;
  1.1444 +            }
  1.1445 +
  1.1446 +            XRE_InitOmnijar(greOmni, appOmni);
  1.1447 +            argc-=2;
  1.1448 +            argv+=2;
  1.1449 +        }
  1.1450 +
  1.1451 +        nsCOMPtr<nsIServiceManager> servMan;
  1.1452 +        rv = NS_InitXPCOM2(getter_AddRefs(servMan), appDir, &dirprovider);
  1.1453 +        if (NS_FAILED(rv)) {
  1.1454 +            printf("NS_InitXPCOM2 failed!\n");
  1.1455 +            return 1;
  1.1456 +        }
  1.1457 +
  1.1458 +        nsCOMPtr<nsIJSRuntimeService> rtsvc = do_GetService("@mozilla.org/js/xpc/RuntimeService;1");
  1.1459 +        // get the JSRuntime from the runtime svc
  1.1460 +        if (!rtsvc) {
  1.1461 +            printf("failed to get nsJSRuntimeService!\n");
  1.1462 +            return 1;
  1.1463 +        }
  1.1464 +
  1.1465 +        if (NS_FAILED(rtsvc->GetRuntime(&rt)) || !rt) {
  1.1466 +            printf("failed to get JSRuntime from nsJSRuntimeService!\n");
  1.1467 +            return 1;
  1.1468 +        }
  1.1469 +
  1.1470 +        rtsvc->RegisterContextCallback(ContextCallback);
  1.1471 +
  1.1472 +        // Override the default XPConnect interrupt callback. We could store the
  1.1473 +        // old one and restore it before shutting down, but there's not really a
  1.1474 +        // reason to bother.
  1.1475 +        sScriptedInterruptCallback.construct(rt, UndefinedValue());
  1.1476 +        JS_SetInterruptCallback(rt, XPCShellInterruptCallback);
  1.1477 +
  1.1478 +        cx = JS_NewContext(rt, 8192);
  1.1479 +        if (!cx) {
  1.1480 +            printf("JS_NewContext failed!\n");
  1.1481 +            return 1;
  1.1482 +        }
  1.1483 +
  1.1484 +        argc--;
  1.1485 +        argv++;
  1.1486 +        ProcessArgsForCompartment(cx, argv, argc);
  1.1487 +
  1.1488 +        nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
  1.1489 +        if (!xpc) {
  1.1490 +            printf("failed to get nsXPConnect service!\n");
  1.1491 +            return 1;
  1.1492 +        }
  1.1493 +
  1.1494 +        nsCOMPtr<nsIPrincipal> systemprincipal;
  1.1495 +        // Fetch the system principal and store it away in a global, to use for
  1.1496 +        // script compilation in Load() and ProcessFile() (including interactive
  1.1497 +        // eval loop)
  1.1498 +        {
  1.1499 +
  1.1500 +            nsCOMPtr<nsIScriptSecurityManager> securityManager =
  1.1501 +                do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
  1.1502 +            if (NS_SUCCEEDED(rv) && securityManager) {
  1.1503 +                rv = securityManager->GetSystemPrincipal(getter_AddRefs(systemprincipal));
  1.1504 +                if (NS_FAILED(rv)) {
  1.1505 +                    fprintf(gErrFile, "+++ Failed to obtain SystemPrincipal from ScriptSecurityManager service.\n");
  1.1506 +                } else {
  1.1507 +                    // fetch the JS principals and stick in a global
  1.1508 +                    gJSPrincipals = nsJSPrincipals::get(systemprincipal);
  1.1509 +                    JS_HoldPrincipals(gJSPrincipals);
  1.1510 +                }
  1.1511 +            } else {
  1.1512 +                fprintf(gErrFile, "+++ Failed to get ScriptSecurityManager service, running without principals");
  1.1513 +            }
  1.1514 +        }
  1.1515 +
  1.1516 +        const JSSecurityCallbacks *scb = JS_GetSecurityCallbacks(rt);
  1.1517 +        MOZ_ASSERT(scb, "We are assuming that nsScriptSecurityManager::Init() has been run");
  1.1518 +        shellSecurityCallbacks = *scb;
  1.1519 +        JS_SetSecurityCallbacks(rt, &shellSecurityCallbacks);
  1.1520 +
  1.1521 +#ifdef TEST_TranslateThis
  1.1522 +        nsCOMPtr<nsIXPCFunctionThisTranslator>
  1.1523 +            translator(new nsXPCFunctionThisTranslator);
  1.1524 +        xpc->SetFunctionThisTranslator(NS_GET_IID(nsITestXPCFunctionCallback), translator);
  1.1525 +#endif
  1.1526 +
  1.1527 +        nsCxPusher pusher;
  1.1528 +        pusher.Push(cx);
  1.1529 +
  1.1530 +        nsRefPtr<BackstagePass> backstagePass;
  1.1531 +        rv = NS_NewBackstagePass(getter_AddRefs(backstagePass));
  1.1532 +        if (NS_FAILED(rv)) {
  1.1533 +            fprintf(gErrFile, "+++ Failed to create BackstagePass: %8x\n",
  1.1534 +                    static_cast<uint32_t>(rv));
  1.1535 +            return 1;
  1.1536 +        }
  1.1537 +
  1.1538 +        // Make the default XPCShell global use a fresh zone (rather than the
  1.1539 +        // System Zone) to improve cross-zone test coverage.
  1.1540 +        JS::CompartmentOptions options;
  1.1541 +        options.setZone(JS::FreshZone)
  1.1542 +               .setVersion(JSVERSION_LATEST);
  1.1543 +        nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
  1.1544 +        rv = xpc->InitClassesWithNewWrappedGlobal(cx,
  1.1545 +                                                  static_cast<nsIGlobalObject *>(backstagePass),
  1.1546 +                                                  systemprincipal,
  1.1547 +                                                  0,
  1.1548 +                                                  options,
  1.1549 +                                                  getter_AddRefs(holder));
  1.1550 +        if (NS_FAILED(rv))
  1.1551 +            return 1;
  1.1552 +
  1.1553 +        {
  1.1554 +            JS::Rooted<JSObject*> glob(cx, holder->GetJSObject());
  1.1555 +            if (!glob) {
  1.1556 +                return 1;
  1.1557 +            }
  1.1558 +
  1.1559 +            // Even if we're building in a configuration where source is
  1.1560 +            // discarded, there's no reason to do that on XPCShell, and doing so
  1.1561 +            // might break various automation scripts.
  1.1562 +            JS::CompartmentOptionsRef(glob).setDiscardSource(false);
  1.1563 +
  1.1564 +            backstagePass->SetGlobalObject(glob);
  1.1565 +
  1.1566 +            JSAutoCompartment ac(cx, glob);
  1.1567 +
  1.1568 +            if (!JS_InitReflect(cx, glob)) {
  1.1569 +                JS_EndRequest(cx);
  1.1570 +                return 1;
  1.1571 +            }
  1.1572 +
  1.1573 +            if (!JS_DefineFunctions(cx, glob, glob_functions) ||
  1.1574 +                !JS_DefineProfilingFunctions(cx, glob)) {
  1.1575 +                JS_EndRequest(cx);
  1.1576 +                return 1;
  1.1577 +            }
  1.1578 +
  1.1579 +            JS::Rooted<JSObject*> envobj(cx);
  1.1580 +            envobj = JS_DefineObject(cx, glob, "environment", &env_class, nullptr, 0);
  1.1581 +            if (!envobj) {
  1.1582 +                JS_EndRequest(cx);
  1.1583 +                return 1;
  1.1584 +            }
  1.1585 +
  1.1586 +            JS_SetPrivate(envobj, envp);
  1.1587 +
  1.1588 +            nsAutoString workingDirectory;
  1.1589 +            if (GetCurrentWorkingDirectory(workingDirectory))
  1.1590 +                gWorkingDirectory = &workingDirectory;
  1.1591 +
  1.1592 +            JS_DefineProperty(cx, glob, "__LOCATION__", JS::UndefinedHandleValue, 0,
  1.1593 +                              GetLocationProperty, nullptr);
  1.1594 +
  1.1595 +            result = ProcessArgs(cx, glob, argv, argc, &dirprovider);
  1.1596 +
  1.1597 +            JS_DropPrincipals(rt, gJSPrincipals);
  1.1598 +            JS_SetAllNonReservedSlotsToUndefined(cx, glob);
  1.1599 +            JS_GC(rt);
  1.1600 +        }
  1.1601 +        pusher.Pop();
  1.1602 +        JS_GC(rt);
  1.1603 +        JS_DestroyContext(cx);
  1.1604 +    } // this scopes the nsCOMPtrs
  1.1605 +
  1.1606 +    if (!XRE_ShutdownTestShell())
  1.1607 +        NS_ERROR("problem shutting down testshell");
  1.1608 +
  1.1609 +    // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
  1.1610 +    rv = NS_ShutdownXPCOM( nullptr );
  1.1611 +    MOZ_ASSERT(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");
  1.1612 +
  1.1613 +    sScriptedInterruptCallback.destroyIfConstructed();
  1.1614 +
  1.1615 +#ifdef TEST_CALL_ON_WRAPPED_JS_AFTER_SHUTDOWN
  1.1616 +    // test of late call and release (see above)
  1.1617 +    JSContext* bogusCX;
  1.1618 +    bogus->Peek(&bogusCX);
  1.1619 +    bogus = nullptr;
  1.1620 +#endif
  1.1621 +
  1.1622 +    appDir = nullptr;
  1.1623 +    appFile = nullptr;
  1.1624 +    dirprovider.ClearGREDir();
  1.1625 +    dirprovider.ClearAppDir();
  1.1626 +    dirprovider.ClearPluginDir();
  1.1627 +    dirprovider.ClearAppFile();
  1.1628 +
  1.1629 +#ifdef MOZ_CRASHREPORTER
  1.1630 +    // Shut down the crashreporter service to prevent leaking some strings it holds.
  1.1631 +    if (CrashReporter::GetEnabled())
  1.1632 +        CrashReporter::UnsetExceptionHandler();
  1.1633 +#endif
  1.1634 +
  1.1635 +    NS_LogTerm();
  1.1636 +
  1.1637 +    return result;
  1.1638 +}
  1.1639 +
  1.1640 +void
  1.1641 +XPCShellDirProvider::SetGREDir(nsIFile* greDir)
  1.1642 +{
  1.1643 +    mGREDir = greDir;
  1.1644 +}
  1.1645 +
  1.1646 +void
  1.1647 +XPCShellDirProvider::SetAppFile(nsIFile* appFile)
  1.1648 +{
  1.1649 +    mAppFile = appFile;
  1.1650 +}
  1.1651 +
  1.1652 +void
  1.1653 +XPCShellDirProvider::SetAppDir(nsIFile* appDir)
  1.1654 +{
  1.1655 +    mAppDir = appDir;
  1.1656 +}
  1.1657 +
  1.1658 +void
  1.1659 +XPCShellDirProvider::SetPluginDir(nsIFile* pluginDir)
  1.1660 +{
  1.1661 +    mPluginDir = pluginDir;
  1.1662 +}
  1.1663 +
  1.1664 +NS_IMETHODIMP_(MozExternalRefCountType)
  1.1665 +XPCShellDirProvider::AddRef()
  1.1666 +{
  1.1667 +    return 2;
  1.1668 +}
  1.1669 +
  1.1670 +NS_IMETHODIMP_(MozExternalRefCountType)
  1.1671 +XPCShellDirProvider::Release()
  1.1672 +{
  1.1673 +    return 1;
  1.1674 +}
  1.1675 +
  1.1676 +NS_IMPL_QUERY_INTERFACE(XPCShellDirProvider,
  1.1677 +                        nsIDirectoryServiceProvider,
  1.1678 +                        nsIDirectoryServiceProvider2)
  1.1679 +
  1.1680 +NS_IMETHODIMP
  1.1681 +XPCShellDirProvider::GetFile(const char *prop, bool *persistent,
  1.1682 +                             nsIFile* *result)
  1.1683 +{
  1.1684 +    if (mGREDir && !strcmp(prop, NS_GRE_DIR)) {
  1.1685 +        *persistent = true;
  1.1686 +        return mGREDir->Clone(result);
  1.1687 +    } else if (mAppFile && !strcmp(prop, XRE_EXECUTABLE_FILE)) {
  1.1688 +        *persistent = true;
  1.1689 +        return mAppFile->Clone(result);
  1.1690 +    } else if (mGREDir && !strcmp(prop, NS_APP_PREF_DEFAULTS_50_DIR)) {
  1.1691 +        nsCOMPtr<nsIFile> file;
  1.1692 +        *persistent = true;
  1.1693 +        if (NS_FAILED(mGREDir->Clone(getter_AddRefs(file))) ||
  1.1694 +            NS_FAILED(file->AppendNative(NS_LITERAL_CSTRING("defaults"))) ||
  1.1695 +            NS_FAILED(file->AppendNative(NS_LITERAL_CSTRING("pref"))))
  1.1696 +            return NS_ERROR_FAILURE;
  1.1697 +        file.forget(result);
  1.1698 +        return NS_OK;
  1.1699 +    }
  1.1700 +
  1.1701 +    return NS_ERROR_FAILURE;
  1.1702 +}
  1.1703 +
  1.1704 +NS_IMETHODIMP
  1.1705 +XPCShellDirProvider::GetFiles(const char *prop, nsISimpleEnumerator* *result)
  1.1706 +{
  1.1707 +    if (mGREDir && !strcmp(prop, "ChromeML")) {
  1.1708 +        nsCOMArray<nsIFile> dirs;
  1.1709 +
  1.1710 +        nsCOMPtr<nsIFile> file;
  1.1711 +        mGREDir->Clone(getter_AddRefs(file));
  1.1712 +        file->AppendNative(NS_LITERAL_CSTRING("chrome"));
  1.1713 +        dirs.AppendObject(file);
  1.1714 +
  1.1715 +        nsresult rv = NS_GetSpecialDirectory(NS_APP_CHROME_DIR,
  1.1716 +                                             getter_AddRefs(file));
  1.1717 +        if (NS_SUCCEEDED(rv))
  1.1718 +            dirs.AppendObject(file);
  1.1719 +
  1.1720 +        return NS_NewArrayEnumerator(result, dirs);
  1.1721 +    } else if (!strcmp(prop, NS_APP_PREFS_DEFAULTS_DIR_LIST)) {
  1.1722 +        nsCOMArray<nsIFile> dirs;
  1.1723 +        nsCOMPtr<nsIFile> appDir;
  1.1724 +        bool exists;
  1.1725 +        if (mAppDir &&
  1.1726 +            NS_SUCCEEDED(mAppDir->Clone(getter_AddRefs(appDir))) &&
  1.1727 +            NS_SUCCEEDED(appDir->AppendNative(NS_LITERAL_CSTRING("defaults"))) &&
  1.1728 +            NS_SUCCEEDED(appDir->AppendNative(NS_LITERAL_CSTRING("preferences"))) &&
  1.1729 +            NS_SUCCEEDED(appDir->Exists(&exists)) && exists) {
  1.1730 +            dirs.AppendObject(appDir);
  1.1731 +            return NS_NewArrayEnumerator(result, dirs);
  1.1732 +        }
  1.1733 +        return NS_ERROR_FAILURE;
  1.1734 +    } else if (!strcmp(prop, NS_APP_PLUGINS_DIR_LIST)) {
  1.1735 +        nsCOMArray<nsIFile> dirs;
  1.1736 +        // Add the test plugin location passed in by the caller or through
  1.1737 +        // runxpcshelltests.
  1.1738 +        if (mPluginDir) {
  1.1739 +            dirs.AppendObject(mPluginDir);
  1.1740 +        // If there was no path specified, default to the one set up by automation
  1.1741 +        } else {
  1.1742 +            nsCOMPtr<nsIFile> file;
  1.1743 +            bool exists;
  1.1744 +            // We have to add this path, buildbot copies the test plugin directory
  1.1745 +            // to (app)/bin when unpacking test zips.
  1.1746 +            if (mGREDir) {
  1.1747 +                mGREDir->Clone(getter_AddRefs(file));
  1.1748 +                if (NS_SUCCEEDED(mGREDir->Clone(getter_AddRefs(file)))) {
  1.1749 +                    file->AppendNative(NS_LITERAL_CSTRING("plugins"));
  1.1750 +                    if (NS_SUCCEEDED(file->Exists(&exists)) && exists) {
  1.1751 +                        dirs.AppendObject(file);
  1.1752 +                    }
  1.1753 +                }
  1.1754 +            }
  1.1755 +        }
  1.1756 +        return NS_NewArrayEnumerator(result, dirs);
  1.1757 +    }
  1.1758 +    return NS_ERROR_FAILURE;
  1.1759 +}

mercurial