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 "js/Transcoding.h"
8 #include "mozilla/scache/StartupCache.h"
9
10 #include "jsapi.h"
11 #include "jsfriendapi.h"
12
13 #include "mozilla/BasePrincipal.h"
14
15 using namespace JS;
16 using namespace mozilla::scache;
17 using mozilla::UniquePtr;
18
HandleTranscodeResult(JSContext * cx,JS::TranscodeResult result)19 static nsresult HandleTranscodeResult(JSContext* cx,
20 JS::TranscodeResult result) {
21 if (result == JS::TranscodeResult::Ok) {
22 return NS_OK;
23 }
24
25 if (result == JS::TranscodeResult::Throw) {
26 JS_ClearPendingException(cx);
27 return NS_ERROR_OUT_OF_MEMORY;
28 }
29
30 MOZ_ASSERT(IsTranscodeFailureResult(result));
31 return NS_ERROR_FAILURE;
32 }
33
34 // We only serialize scripts with system principals. So we don't serialize the
35 // principals when writing a script. Instead, when reading it back, we set the
36 // principals to the system principals.
ReadCachedScript(StartupCache * cache,nsACString & uri,JSContext * cx,const JS::ReadOnlyCompileOptions & options,MutableHandleScript scriptp)37 nsresult ReadCachedScript(StartupCache* cache, nsACString& uri, JSContext* cx,
38 const JS::ReadOnlyCompileOptions& options,
39 MutableHandleScript scriptp) {
40 const char* buf;
41 uint32_t len;
42 nsresult rv = cache->GetBuffer(PromiseFlatCString(uri).get(), &buf, &len);
43 if (NS_FAILED(rv)) {
44 return rv; // don't warn since NOT_AVAILABLE is an ok error
45 }
46 void* copy = malloc(len);
47 if (!copy) {
48 return NS_ERROR_OUT_OF_MEMORY;
49 }
50 memcpy(copy, buf, len);
51 JS::TranscodeBuffer buffer;
52 buffer.replaceRawBuffer(reinterpret_cast<uint8_t*>(copy), len);
53 JS::TranscodeResult code = JS::DecodeScript(cx, options, buffer, scriptp);
54 return HandleTranscodeResult(cx, code);
55 }
56
WriteCachedScript(StartupCache * cache,nsACString & uri,JSContext * cx,HandleScript script)57 nsresult WriteCachedScript(StartupCache* cache, nsACString& uri, JSContext* cx,
58 HandleScript script) {
59 MOZ_ASSERT(
60 nsJSPrincipals::get(JS_GetScriptPrincipals(script))->IsSystemPrincipal());
61
62 JS::TranscodeBuffer buffer;
63 JS::TranscodeResult code = JS::EncodeScript(cx, buffer, script);
64 if (code != JS::TranscodeResult::Ok) {
65 return HandleTranscodeResult(cx, code);
66 }
67
68 size_t size = buffer.length();
69 if (size > UINT32_MAX) {
70 return NS_ERROR_FAILURE;
71 }
72
73 // Move the vector buffer into a unique pointer buffer.
74 UniquePtr<char[]> buf(
75 reinterpret_cast<char*>(buffer.extractOrCopyRawBuffer()));
76 nsresult rv =
77 cache->PutBuffer(PromiseFlatCString(uri).get(), std::move(buf), size);
78 return rv;
79 }
80