Bug 1485800 - Rename SourceBufferHolder to SourceText, and add a <typename Unit> template parameter to it so it can hold putative UTF-8 or UTF-16 source text. r=tcampbell, r=fitzgen
authorJeff Walden <jwalden@mit.edu>
Thu, 08 Nov 2018 18:42:48 -0800
changeset 502944 56eaf6c976d377cba4e44a302bdeda9e7420bd94
parent 502943 422924c19ce5c0aa87174e713e3aa43564f1a4b3
child 502945 9d7d25507cacca3488f4efd3e4034d3a45d405eb
push id10290
push userffxbld-merge
push dateMon, 03 Dec 2018 16:23:23 +0000
treeherdermozilla-beta@700bed2445e6 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerstcampbell, fitzgen
bugs1485800
milestone65.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1485800 - Rename SourceBufferHolder to SourceText, and add a <typename Unit> template parameter to it so it can hold putative UTF-8 or UTF-16 source text. r=tcampbell, r=fitzgen
dom/base/nsFrameMessageManager.cpp
dom/base/nsJSUtils.cpp
dom/base/nsJSUtils.h
dom/script/ScriptLoader.cpp
dom/script/ScriptLoader.h
dom/workers/ScriptLoader.cpp
dom/workers/WorkerPrivate.cpp
dom/worklet/Worklet.cpp
dom/xul/XULDocument.cpp
dom/xul/nsXULContentSink.cpp
dom/xul/nsXULElement.cpp
dom/xul/nsXULElement.h
ipc/testshell/XPCShellEnvironment.cpp
js/public/CompilationAndEvaluation.h
js/public/OffThreadScriptCompilation.h
js/public/SourceBufferHolder.h
js/public/SourceText.h
js/rust/build.rs
js/rust/etc/wrapper.hpp
js/rust/src/rust.rs
js/src/NamespaceImports.h
js/src/builtin/Eval.cpp
js/src/builtin/TestingFunctions.cpp
js/src/frontend/BytecodeCompiler.cpp
js/src/frontend/BytecodeCompiler.h
js/src/jsapi-tests/testCompileNonSyntactic.cpp
js/src/jsapi-tests/testErrorLineOfContext.cpp
js/src/jsapi-tests/testJSEvaluateScript.cpp
js/src/jsapi-tests/testMutedErrors.cpp
js/src/jsapi-tests/testScriptObject.cpp
js/src/jsapi.cpp
js/src/jsapi.h
js/src/moz.build
js/src/shell/js.cpp
js/src/vm/CompilationAndEvaluation.cpp
js/src/vm/Debugger.cpp
js/src/vm/HelperThreads.cpp
js/src/vm/HelperThreads.h
js/src/vm/JSFunction.cpp
js/src/vm/JSScript.cpp
js/src/vm/JSScript.h
js/src/vm/OffThreadScriptCompilation.cpp
js/src/wasm/AsmJS.cpp
js/xpconnect/loader/ChromeScriptLoader.cpp
js/xpconnect/loader/mozJSSubScriptLoader.cpp
js/xpconnect/src/Sandbox.cpp
--- a/dom/base/nsFrameMessageManager.cpp
+++ b/dom/base/nsFrameMessageManager.cpp
@@ -26,17 +26,17 @@
 #include "nsIScriptError.h"
 #include "nsIConsoleService.h"
 #include "nsIMemoryReporter.h"
 #include "nsIProtocolHandler.h"
 #include "nsIScriptSecurityManager.h"
 #include "xpcpublic.h"
 #include "js/CompilationAndEvaluation.h"
 #include "js/JSON.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/CycleCollectedJSContext.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/ScriptPreloader.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/dom/ChildProcessMessageManager.h"
 #include "mozilla/dom/ChromeMessageBroadcaster.h"
 #include "mozilla/dom/File.h"
@@ -1392,17 +1392,17 @@ nsMessageManagerScriptExecutor::TryCache
     }
 
     if (!dataStringBuf || dataStringLength == 0) {
       return;
     }
 
     JS::UniqueTwoByteChars srcChars(dataStringBuf);
 
-    JS::SourceBufferHolder srcBuf;
+    JS::SourceText<char16_t> srcBuf;
     if (!srcBuf.init(cx, std::move(srcChars), dataStringLength)) {
       return;
     }
 
     JS::CompileOptions options(cx);
     options.setFileAndLine(url.get(), 1);
     options.setNoScriptRval(true);
 
--- a/dom/base/nsJSUtils.cpp
+++ b/dom/base/nsJSUtils.cpp
@@ -11,17 +11,17 @@
  * the generated code itself.
  */
 
 #include "nsJSUtils.h"
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "js/CompilationAndEvaluation.h"
 #include "js/OffThreadScriptCompilation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "nsIScriptContext.h"
 #include "nsIScriptElement.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIXPConnect.h"
 #include "nsCOMPtr.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsPIDOMWindow.h"
 #include "GeckoProfiler.h"
@@ -93,19 +93,19 @@ nsJSUtils::CompileFunction(AutoJSAPI& js
   // Do the junk Gecko is supposed to do before calling into JSAPI.
   for (size_t i = 0; i < aScopeChain.length(); ++i) {
     JS::ExposeObjectToActiveJS(aScopeChain[i]);
   }
 
   // Compile.
   const nsPromiseFlatString& flatBody = PromiseFlatString(aBody);
 
-  JS::SourceBufferHolder source;
+  JS::SourceText<char16_t> source;
   if (!source.init(cx, flatBody.get(), flatBody.Length(),
-                   JS::SourceBufferHolder::NoOwnership))
+                   JS::SourceOwnership::Borrowed))
   {
     return NS_ERROR_FAILURE;
   }
 
   JS::Rooted<JSFunction*> fun(cx);
   if (!JS::CompileFunction(cx, aScopeChain, aOptions,
                            PromiseFlatCString(aName).get(),
                            aArgCount, aArgArray,
@@ -219,17 +219,17 @@ nsJSUtils::ExecutionContext::JoinAndExec
     return mRv;
   }
 
   return NS_OK;
 }
 
 nsresult
 nsJSUtils::ExecutionContext::CompileAndExec(JS::CompileOptions& aCompileOptions,
-                                            JS::SourceBufferHolder& aSrcBuf,
+                                            JS::SourceText<char16_t>& aSrcBuf,
                                             JS::MutableHandle<JSScript*> aScript)
 {
   if (mSkip) {
     return mRv;
   }
 
   MOZ_ASSERT(aSrcBuf.get());
   MOZ_ASSERT(mRetValue.isUndefined());
@@ -272,19 +272,19 @@ nsJSUtils::ExecutionContext::CompileAndE
                                             const nsAString& aScript)
 {
   MOZ_ASSERT(!mEncodeBytecode, "A JSScript is needed for calling FinishIncrementalEncoding");
   if (mSkip) {
     return mRv;
   }
 
   const nsPromiseFlatString& flatScript = PromiseFlatString(aScript);
-  JS::SourceBufferHolder srcBuf;
+  JS::SourceText<char16_t> srcBuf;
   if (!srcBuf.init(mCx, flatScript.get(), flatScript.Length(),
-                   JS::SourceBufferHolder::NoOwnership))
+                   JS::SourceOwnership::Borrowed))
   {
     mSkip = true;
     mRv = EvaluationExceptionToNSResult(mCx);
     return mRv;
   }
 
   JS::Rooted<JSScript*> script(mCx);
   return CompileAndExec(aCompileOptions, srcBuf, &script);
@@ -482,17 +482,17 @@ nsJSUtils::ExecutionContext::ExtractRetu
   }
 
   aRetValue.set(mRetValue);
   return NS_OK;
 }
 
 nsresult
 nsJSUtils::CompileModule(JSContext* aCx,
-                       JS::SourceBufferHolder& aSrcBuf,
+                       JS::SourceText<char16_t>& aSrcBuf,
                        JS::Handle<JSObject*> aEvaluationGlobal,
                        JS::CompileOptions &aCompileOptions,
                        JS::MutableHandle<JSObject*> aModule)
 {
   AUTO_PROFILER_LABEL("nsJSUtils::CompileModule", JS);
 
   MOZ_ASSERT(aCx == nsContentUtils::GetCurrentJSContext());
   MOZ_ASSERT(aSrcBuf.get());
--- a/dom/base/nsJSUtils.h
+++ b/dom/base/nsJSUtils.h
@@ -15,16 +15,17 @@
  */
 
 #include "mozilla/Assertions.h"
 
 #include "GeckoProfiler.h"
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "js/Conversions.h"
+#include "js/SourceText.h"
 #include "js/StableStringChars.h"
 #include "nsString.h"
 
 class nsIScriptContext;
 class nsIScriptElement;
 class nsIScriptGlobalObject;
 class nsXBLPrototypeBinding;
 
@@ -152,19 +153,19 @@ public:
     // After getting a notification that an off-thread compilation terminated,
     // this function will take the result of the parser by moving it to the main
     // thread before starting the execution of the script.
     //
     // The compiled script would be returned in the |aScript| out-param.
     MOZ_MUST_USE nsresult JoinAndExec(JS::OffThreadToken** aOffThreadToken,
                                       JS::MutableHandle<JSScript*> aScript);
 
-    // Compile a script contained in a SourceBuffer, and execute it.
+    // Compile a script contained in a SourceText, and execute it.
     nsresult CompileAndExec(JS::CompileOptions& aCompileOptions,
-                            JS::SourceBufferHolder& aSrcBuf,
+                            JS::SourceText<char16_t>& aSrcBuf,
                             JS::MutableHandle<JSScript*> aScript);
 
     // Compile a script contained in a string, and execute it.
     nsresult CompileAndExec(JS::CompileOptions& aCompileOptions,
                             const nsAString& aScript);
 
     // Decode a script contained in a buffer, and execute it.
     MOZ_MUST_USE nsresult DecodeAndExec(JS::CompileOptions& aCompileOptions,
@@ -181,17 +182,17 @@ public:
 
     // Decode a BinAST encoded script contained in a buffer, and execute it.
     nsresult DecodeBinASTAndExec(JS::CompileOptions& aCompileOptions,
                                  const uint8_t* aBuf, size_t aLength,
                                  JS::MutableHandle<JSScript*> aScript);
   };
 
   static nsresult CompileModule(JSContext* aCx,
-                                JS::SourceBufferHolder& aSrcBuf,
+                                JS::SourceText<char16_t>& aSrcBuf,
                                 JS::Handle<JSObject*> aEvaluationGlobal,
                                 JS::CompileOptions &aCompileOptions,
                                 JS::MutableHandle<JSObject*> aModule);
 
   static nsresult InitModuleSourceElement(JSContext* aCx,
                                           JS::Handle<JSObject*> aModule,
                                           nsIScriptElement* aElement);
 
--- a/dom/script/ScriptLoader.cpp
+++ b/dom/script/ScriptLoader.cpp
@@ -11,17 +11,17 @@
 #include "ModuleLoadRequest.h"
 #include "ModuleScript.h"
 
 #include "prsystem.h"
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "js/CompilationAndEvaluation.h"
 #include "js/OffThreadScriptCompilation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/Utility.h"
 #include "xpcpublic.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIContent.h"
 #include "nsJSUtils.h"
 #include "mozilla/dom/DocGroup.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/ScriptSettings.h"
@@ -63,17 +63,17 @@
 #include "mozilla/AsyncEventDispatcher.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/Unused.h"
 #include "nsIScriptError.h"
 #include "nsIOutputStream.h"
 
-using JS::SourceBufferHolder;
+using JS::SourceText;
 
 using mozilla::Telemetry::LABELS_DOM_SCRIPT_PRELOAD_RESULT;
 
 namespace mozilla {
 namespace dom {
 
 LazyLogModule ScriptLoader::gCspPRLog("CSP");
 LazyLogModule ScriptLoader::gScriptLoaderLog("ScriptLoader");
@@ -1928,56 +1928,56 @@ ScriptLoader::CompileOffThreadOrProcessR
 
   if (couldCompile) {
     return NS_OK;
   }
 
   return ProcessRequest(aRequest);
 }
 
-mozilla::Maybe<SourceBufferHolder>
+mozilla::Maybe<SourceText<char16_t>>
 ScriptLoader::GetScriptSource(JSContext* aCx, ScriptLoadRequest* aRequest)
 {
-  // Return a SourceBufferHolder object holding the script's source text.
-  // Ownership of the buffer is transferred to the resulting SourceBufferHolder.
+  // Return a SourceText<char16_t> object holding the script's source text.
+  // Ownership of the buffer is transferred to the resulting holder.
 
   // If there's no script text, we try to get it from the element
   if (aRequest->mIsInline) {
     nsAutoString inlineData;
     aRequest->Element()->GetScriptText(inlineData);
 
     size_t nbytes = inlineData.Length() * sizeof(char16_t);
     JS::UniqueTwoByteChars chars(static_cast<char16_t*>(JS_malloc(aCx, nbytes)));
     if (!chars) {
       return Nothing();
     }
 
     memcpy(chars.get(), inlineData.get(), nbytes);
 
-    SourceBufferHolder srcBuf;
+    SourceText<char16_t> srcBuf;
     if (!srcBuf.init(aCx, std::move(chars), inlineData.Length())) {
       return Nothing();
     }
 
-    return Some(SourceBufferHolder(std::move(srcBuf)));
+    return Some(SourceText<char16_t>(std::move(srcBuf)));
   }
 
   size_t length = aRequest->ScriptText().length();
   JS::UniqueTwoByteChars chars(aRequest->ScriptText().extractOrCopyRawBuffer());
   if (!chars) {
     JS_ReportOutOfMemory(aCx);
     return Nothing();
   }
 
-  SourceBufferHolder srcBuf;
+  SourceText<char16_t> srcBuf;
   if (!srcBuf.init(aCx, std::move(chars), length)) {
     return Nothing();
   }
 
-  return Some(SourceBufferHolder(std::move(srcBuf)));
+  return Some(SourceText<char16_t>(std::move(srcBuf)));
 }
 
 nsresult
 ScriptLoader::ProcessRequest(ScriptLoadRequest* aRequest)
 {
   LOG(("ScriptLoadRequest (%p): Process request", aRequest));
 
   NS_ASSERTION(nsContentUtils::IsSafeToRunScript(),
--- a/dom/script/ScriptLoader.h
+++ b/dom/script/ScriptLoader.h
@@ -27,17 +27,19 @@
 #include "mozilla/MozPromise.h"
 #include "mozilla/net/ReferrerPolicy.h"
 #include "mozilla/StaticPrefs.h"
 #include "mozilla/Vector.h"
 
 class nsIURI;
 
 namespace JS {
-  class SourceBufferHolder;
+
+template<typename UnitT> class SourceText;
+
 } // namespace JS
 
 namespace mozilla {
 namespace dom {
 
 class AutoJSAPI;
 class ModuleLoadRequest;
 class ModuleScript;
@@ -502,18 +504,18 @@ private:
                                 nsresult aStatus);
 
   void AddDeferRequest(ScriptLoadRequest* aRequest);
   void AddAsyncRequest(ScriptLoadRequest* aRequest);
   bool MaybeRemovedDeferRequests();
 
   void MaybeMoveToLoadedList(ScriptLoadRequest* aRequest);
 
-  mozilla::Maybe<JS::SourceBufferHolder> GetScriptSource(JSContext* aCx,
-                                                         ScriptLoadRequest* aRequest);
+  mozilla::Maybe<JS::SourceText<char16_t>>
+  GetScriptSource(JSContext* aCx, ScriptLoadRequest* aRequest);
 
   void SetModuleFetchStarted(ModuleLoadRequest *aRequest);
   void SetModuleFetchFinishedAndResumeWaitingRequests(ModuleLoadRequest* aRequest,
                                                       nsresult aResult);
 
   bool IsFetchingModule(ModuleLoadRequest* aRequest) const;
 
   bool ModuleMapContainsURL(nsIURI* aURL) const;
--- a/dom/workers/ScriptLoader.cpp
+++ b/dom/workers/ScriptLoader.cpp
@@ -23,17 +23,17 @@
 #include "nsIStreamLoader.h"
 #include "nsIStreamListenerTee.h"
 #include "nsIThreadRetargetableRequest.h"
 #include "nsIURI.h"
 
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "nsError.h"
 #include "nsContentPolicyUtils.h"
 #include "nsContentUtils.h"
 #include "nsDocShellCID.h"
 #include "nsISupportsPrimitives.h"
 #include "nsNetUtil.h"
 #include "nsIPipe.h"
 #include "nsIOutputStream.h"
@@ -2129,17 +2129,17 @@ ScriptExecutorRunnable::WorkerRun(JSCont
     // Pass ownership of the data, first to local variables, then to the
     // UniqueTwoByteChars moved into the |init| function.
     size_t dataLength = 0;
     char16_t* data = nullptr;
 
     std::swap(dataLength, loadInfo.mScriptTextLength);
     std::swap(data, loadInfo.mScriptTextBuf);
 
-    JS::SourceBufferHolder srcBuf;
+    JS::SourceText<char16_t> srcBuf;
     if (!srcBuf.init(aCx, JS::UniqueTwoByteChars(data), dataLength)) {
       mScriptLoader.mRv.StealExceptionFromJSContext(aCx);
       return true;
     }
 
     // Our ErrorResult still shouldn't be a failure.
     MOZ_ASSERT(!mScriptLoader.mRv.Failed(), "Who failed it and why?");
     JS::Rooted<JS::Value> unused(aCx);
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -4,17 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "WorkerPrivate.h"
 
 #include "js/CompilationAndEvaluation.h"
 #include "js/LocaleSensitive.h"
 #include "js/MemoryMetrics.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "MessageEventRunnable.h"
 #include "mozilla/ScopeExit.h"
 #include "mozilla/StaticPrefs.h"
 #include "mozilla/dom/BlobURLProtocolHandler.h"
 #include "mozilla/dom/ClientManager.h"
 #include "mozilla/dom/ClientSource.h"
 #include "mozilla/dom/ClientState.h"
 #include "mozilla/dom/Console.h"
@@ -4897,19 +4897,19 @@ WorkerPrivate::RunExpiredTimeouts(JSCont
       uint32_t lineNo = 0, dummyColumn = 0;
       info->mHandler->GetLocation(&filename, &lineNo, &dummyColumn);
 
       JS::CompileOptions options(aes.cx());
       options.setFileAndLine(filename, lineNo).setNoScriptRval(true);
 
       JS::Rooted<JS::Value> unused(aes.cx());
 
-      JS::SourceBufferHolder srcBuf;
+      JS::SourceText<char16_t> srcBuf;
       if (!srcBuf.init(aes.cx(), script.BeginReading(), script.Length(),
-                       JS::SourceBufferHolder::NoOwnership) ||
+                       JS::SourceOwnership::Borrowed) ||
           !JS::Evaluate(aes.cx(), options, srcBuf, &unused))
       {
         if (!JS_IsExceptionPending(aCx)) {
           retval = false;
           break;
         }
       }
     } else {
--- a/dom/worklet/Worklet.cpp
+++ b/dom/worklet/Worklet.cpp
@@ -12,17 +12,17 @@
 #include "mozilla/dom/BlobBinding.h"
 #include "mozilla/dom/Fetch.h"
 #include "mozilla/dom/PromiseNativeHandler.h"
 #include "mozilla/dom/Response.h"
 #include "mozilla/dom/ScriptSettings.h"
 #include "mozilla/dom/ScriptLoader.h"
 #include "mozilla/dom/WorkletImpl.h"
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "nsIInputStreamPump.h"
 #include "nsIThreadRetargetableRequest.h"
 #include "nsNetUtil.h"
 #include "xpcprivate.h"
 
 namespace mozilla {
 namespace dom {
 
@@ -397,17 +397,17 @@ ExecutionRunnable::RunOnWorkletThread()
   compileOptions.setIntroductionType("Worklet");
   compileOptions.setFileAndLine(url.get(), 0);
   compileOptions.setIsRunOnce(true);
   compileOptions.setNoScriptRval(true);
 
   JSAutoRealm ar(cx, globalObj);
 
   JS::Rooted<JS::Value> unused(cx);
-  JS::SourceBufferHolder buffer;
+  JS::SourceText<char16_t> buffer;
   if (!buffer.init(cx, std::move(mScriptBuffer), mScriptLength) ||
       !JS::Evaluate(cx, compileOptions, buffer, &unused)) {
     ErrorResult error;
     error.MightThrowJSException();
     error.StealExceptionFromJSContext(cx);
     mResult = error.StealNSResult();
     return;
   }
--- a/dom/xul/XULDocument.cpp
+++ b/dom/xul/XULDocument.cpp
@@ -86,17 +86,17 @@
 #include "mozilla/dom/XULDocumentBinding.h"
 #include "mozilla/dom/XULPersist.h"
 #include "mozilla/EventDispatcher.h"
 #include "mozilla/LoadInfo.h"
 #include "mozilla/Preferences.h"
 #include "nsTextNode.h"
 #include "nsJSUtils.h"
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "mozilla/dom/URL.h"
 #include "nsIContentPolicy.h"
 #include "mozAutoDocUpdate.h"
 #include "xpcpublic.h"
 #include "mozilla/StyleSheet.h"
 #include "mozilla/StyleSheetInlines.h"
 #include "nsIConsoleService.h"
 
@@ -1290,17 +1290,17 @@ XULDocument::OnStreamComplete(nsIStreamL
             // below always takes ownership of the buffer.
             char16_t* units = nullptr;
             size_t unitsLength = 0;
 
             std::swap(units, mOffThreadCompileStringBuf);
             std::swap(unitsLength, mOffThreadCompileStringLength);
 
             rv = mCurrentScriptProto->Compile(units, unitsLength,
-                                              JS::SourceBufferHolder::GiveOwnership,
+                                              JS::SourceOwnership::TakeOwnership,
                                               uri, 1, this, this);
             if (NS_SUCCEEDED(rv) && !mCurrentScriptProto->HasScriptObject()) {
                 mOffThreadCompiling = true;
                 BlockOnload();
                 return NS_OK;
             }
         }
     }
--- a/dom/xul/nsXULContentSink.cpp
+++ b/dom/xul/nsXULContentSink.cpp
@@ -502,17 +502,17 @@ XULContentSinkImpl::HandleEndElement(con
 
         // If given a src= attribute, we must ignore script tag content.
         if (!script->mSrcURI && !script->HasScriptObject()) {
             nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocument);
 
             script->mOutOfLine = false;
             if (doc) {
                 script->Compile(mText, mTextLength,
-                                JS::SourceBufferHolder::NoOwnership, mDocumentURL,
+                                JS::SourceOwnership::Borrowed, mDocumentURL,
                                 script->mLineNo, doc);
             }
         }
 
         FlushText(false);
     }
     break;
 
--- a/dom/xul/nsXULElement.cpp
+++ b/dom/xul/nsXULElement.cpp
@@ -14,17 +14,17 @@
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDocument.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/EventListenerManager.h"
 #include "mozilla/EventStateManager.h"
 #include "mozilla/EventStates.h"
 #include "mozilla/DeclarationBlock.h"
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "nsFocusManager.h"
 #include "nsHTMLStyleSheet.h"
 #include "nsNameSpaceManager.h"
 #include "nsIObjectInputStream.h"
 #include "nsIObjectOutputStream.h"
 #include "nsIPresShell.h"
 #include "nsIPrincipal.h"
 #include "nsIScriptContext.h"
@@ -2275,35 +2275,35 @@ OffThreadScriptReceiverCallback(JS::OffT
     RefPtr<NotifyOffThreadScriptCompletedRunnable> notify =
         new NotifyOffThreadScriptCompletedRunnable(aReceiver, aToken);
     NS_DispatchToMainThread(notify);
 }
 
 nsresult
 nsXULPrototypeScript::Compile(const char16_t* aText,
                               size_t aTextLength,
-                              JS::SourceBufferHolder::Ownership aOwnership,
+                              JS::SourceOwnership aOwnership,
                               nsIURI* aURI, uint32_t aLineNo,
                               nsIDocument* aDocument,
                               nsIOffThreadScriptReceiver *aOffThreadReceiver /* = nullptr */)
 {
     // We'll compile the script in the compilation scope.
     AutoJSAPI jsapi;
     if (!jsapi.Init(xpc::CompilationScope())) {
-        if (aOwnership == JS::SourceBufferHolder::GiveOwnership) {
+        if (aOwnership == JS::SourceOwnership::TakeOwnership) {
             // In this early-exit case -- before the |srcBuf.init| call will
             // own |aText| -- we must relinquish ownership manually.
             js_free(const_cast<char16_t*>(aText));
         }
 
         return NS_ERROR_UNEXPECTED;
     }
     JSContext* cx = jsapi.cx();
 
-    JS::SourceBufferHolder srcBuf;
+    JS::SourceText<char16_t> srcBuf;
     if (NS_WARN_IF(!srcBuf.init(cx, aText, aTextLength, aOwnership))) {
         return NS_ERROR_FAILURE;
     }
 
     nsAutoCString urlspec;
     nsresult rv = aURI->GetSpec(urlspec);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
--- a/dom/xul/nsXULElement.h
+++ b/dom/xul/nsXULElement.h
@@ -7,17 +7,17 @@
 
   The base XUL element class and associates.
 
 */
 
 #ifndef nsXULElement_h__
 #define nsXULElement_h__
 
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/TracingAPI.h"
 #include "mozilla/Attributes.h"
 #include "nsIServiceManager.h"
 #include "nsAtom.h"
 #include "mozilla/dom/NodeInfo.h"
 #include "nsIControllers.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIURI.h"
@@ -211,17 +211,17 @@ public:
     virtual nsresult Deserialize(nsIObjectInputStream* aStream,
                                  nsXULPrototypeDocument* aProtoDoc,
                                  nsIURI* aDocumentURI,
                                  const nsTArray<RefPtr<mozilla::dom::NodeInfo>> *aNodeInfos) override;
     nsresult DeserializeOutOfLine(nsIObjectInputStream* aInput,
                                   nsXULPrototypeDocument* aProtoDoc);
 
     nsresult Compile(const char16_t* aText, size_t aTextLength,
-                     JS::SourceBufferHolder::Ownership aOwnership,
+                     JS::SourceOwnership aOwnership,
                      nsIURI* aURI, uint32_t aLineNo,
                      nsIDocument* aDocument,
                      nsIOffThreadScriptReceiver *aOffThreadReceiver = nullptr);
 
     void UnlinkJSObjects();
 
     void Set(JSScript* aObject);
 
--- a/ipc/testshell/XPCShellEnvironment.cpp
+++ b/ipc/testshell/XPCShellEnvironment.cpp
@@ -13,17 +13,17 @@
 #include <unistd.h>     /* for isatty() */
 #endif
 
 #include "base/basictypes.h"
 
 #include "jsapi.h"
 #include "js/CharacterEncoding.h"
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 
 #include "xpcpublic.h"
 
 #include "XPCShellEnvironment.h"
 
 #include "mozilla/XPCOM.h"
 
 #include "nsIChannel.h"
@@ -487,19 +487,19 @@ XPCShellEnvironment::EvaluateString(cons
 {
   AutoEntryScript aes(GetGlobalObject(),
                       "ipc XPCShellEnvironment::EvaluateString");
   JSContext* cx = aes.cx();
 
   JS::CompileOptions options(cx);
   options.setFileAndLine("typein", 0);
 
-  JS::SourceBufferHolder srcBuf;
+  JS::SourceText<char16_t> srcBuf;
   if (!srcBuf.init(cx, aString.get(), aString.Length(),
-                   JS::SourceBufferHolder::NoOwnership))
+                   JS::SourceOwnership::Borrowed))
   {
     return false;
   }
 
   JS::Rooted<JSScript*> script(cx);
   if (!JS::Compile(cx, options, srcBuf, &script))
   {
      return false;
--- a/js/public/CompilationAndEvaluation.h
+++ b/js/public/CompilationAndEvaluation.h
@@ -21,17 +21,17 @@ struct JSContext;
 class JSFunction;
 class JSObject;
 class JSScript;
 
 namespace JS {
 
 template<typename T> class AutoVector;
 
-class SourceBufferHolder;
+template<typename UnitT> class SourceText;
 
 } // namespace JS
 
 /**
  * Given a buffer, return false if the buffer might become a valid JavaScript
  * script with the addition of more lines, or true if the validity of such a
  * script is conclusively known (because it's the prefix of a valid script --
  * and possibly the entirety of such a script).
@@ -102,26 +102,26 @@ extern JS_PUBLIC_API(bool)
 CloneAndExecuteScript(JSContext* cx, AutoVector<JSObject*>& envChain, Handle<JSScript*> script,
                       MutableHandle<Value> rval);
 
 /**
  * Evaluate the given source buffer in the scope of the current global of cx.
  */
 extern JS_PUBLIC_API(bool)
 Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options,
-         SourceBufferHolder& srcBuf, MutableHandle<Value> rval);
+         SourceText<char16_t>& srcBuf, MutableHandle<Value> rval);
 
 /**
  * As above, but providing an explicit scope chain.  envChain must not include
  * the global object on it; that's implicit.  It needs to contain the other
  * objects that should end up on the script's scope chain.
  */
 extern JS_PUBLIC_API(bool)
 Evaluate(JSContext* cx, AutoVector<JSObject*>& envChain, const ReadOnlyCompileOptions& options,
-         SourceBufferHolder& srcBuf, MutableHandle<Value> rval);
+         SourceText<char16_t>& srcBuf, MutableHandle<Value> rval);
 
 /**
  * Evaluate the provided UTF-8 data in the scope of the current global of |cx|,
  * and return the completion value in |rval|.  If the data contains invalid
  * UTF-8, an error is reported.
  */
 extern JS_PUBLIC_API(bool)
 EvaluateUtf8(JSContext* cx, const ReadOnlyCompileOptions& options,
@@ -149,17 +149,17 @@ extern JS_PUBLIC_API(bool)
 EvaluateUtf8Path(JSContext* cx, const ReadOnlyCompileOptions& options,
                  const char* filename, MutableHandle<Value> rval);
 
 /**
  * |script| will always be set. On failure, it will be set to nullptr.
  */
 extern JS_PUBLIC_API(bool)
 Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
-        SourceBufferHolder& srcBuf, MutableHandle<JSScript*> script);
+        SourceText<char16_t>& srcBuf, MutableHandle<JSScript*> script);
 
 /**
  * Compile the provided UTF-8 data into a script.  If the data contains invalid
  * UTF-8, an error is reported.
  *
  * |script| is always set to the compiled script or to null in case of error.
  */
 extern JS_PUBLIC_API(bool)
@@ -197,17 +197,17 @@ CompileUtf8File(JSContext* cx, const Rea
  * |script| is always set to the compiled script or to null in case of error.
  */
 extern JS_PUBLIC_API(bool)
 CompileUtf8Path(JSContext* cx, const ReadOnlyCompileOptions& options,
                 const char* filename, MutableHandle<JSScript*> script);
 
 extern JS_PUBLIC_API(bool)
 CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options,
-                            SourceBufferHolder& srcBuf, MutableHandle<JSScript*> script);
+                            SourceText<char16_t>& srcBuf, MutableHandle<JSScript*> script);
 
 /**
  * Compile the given Latin-1 data for non-syntactic scope.
  *
  * There is no way to compile UTF-8 data for non-syntactic scope because no
  * user currently needs it.  Such way could be added in the future if it's ever
  * needed.
  */
@@ -222,17 +222,17 @@ CompileLatin1ForNonSyntacticScope(JSCont
  * scope chain used for the function will consist of With wrappers for those
  * objects, followed by the current global of the compartment cx is in.  This
  * global must not be explicitly included in the scope chain.
  */
 extern JS_PUBLIC_API(bool)
 CompileFunction(JSContext* cx, AutoVector<JSObject*>& envChain,
                 const ReadOnlyCompileOptions& options,
                 const char* name, unsigned nargs, const char* const* argnames,
-                SourceBufferHolder& srcBuf, MutableHandle<JSFunction*> fun);
+                SourceText<char16_t>& srcBuf, MutableHandle<JSFunction*> fun);
 
 /**
  * Same as above, but taking UTF-8 encoded const char* for the function body.
  */
 extern JS_PUBLIC_API(bool)
 CompileFunctionUtf8(JSContext* cx, AutoVector<JSObject*>& envChain,
                     const ReadOnlyCompileOptions& options,
                     const char* name, unsigned nargs, const char* const* argnames,
--- a/js/public/OffThreadScriptCompilation.h
+++ b/js/public/OffThreadScriptCompilation.h
@@ -22,17 +22,17 @@
 #include "js/GCVector.h" // JS::GCVector
 #include "js/Transcoding.h" // JS::TranscodeSource
 
 struct JSContext;
 class JSScript;
 
 namespace JS {
 
-class SourceBufferHolder;
+template<typename UnitT> class SourceText;
 
 } // namespace JS
 
 namespace JS {
 
 class OffThreadToken;
 
 using OffThreadCompileCallback = void (*)(OffThreadToken* token, void* callbackData);
@@ -56,28 +56,29 @@ CanDecodeOffThread(JSContext* cx, const 
  * - CancelOffThreadScript, to free the resources without creating a script.
  *
  * The characters passed in to CompileOffThread must remain live until the
  * callback is invoked, and the resulting script will be rooted until the call
  * to FinishOffThreadScript.
  */
 
 extern JS_PUBLIC_API(bool)
-CompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options, SourceBufferHolder& srcBuf,
-                 OffThreadCompileCallback callback, void* callbackData);
+CompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options,
+                 SourceText<char16_t>& srcBuf, OffThreadCompileCallback callback,
+                 void* callbackData);
 
 extern JS_PUBLIC_API(JSScript*)
 FinishOffThreadScript(JSContext* cx, OffThreadToken* token);
 
 extern JS_PUBLIC_API(void)
 CancelOffThreadScript(JSContext* cx, OffThreadToken* token);
 
 extern JS_PUBLIC_API(bool)
 CompileOffThreadModule(JSContext* cx, const ReadOnlyCompileOptions& options,
-                       SourceBufferHolder& srcBuf, OffThreadCompileCallback callback,
+                       SourceText<char16_t>& srcBuf, OffThreadCompileCallback callback,
                        void* callbackData);
 
 extern JS_PUBLIC_API(JSObject*)
 FinishOffThreadModule(JSContext* cx, OffThreadToken* token);
 
 extern JS_PUBLIC_API(void)
 CancelOffThreadModule(JSContext* cx, OffThreadToken* token);
 
rename from js/public/SourceBufferHolder.h
rename to js/public/SourceText.h
--- a/js/public/SourceBufferHolder.h
+++ b/js/public/SourceText.h
@@ -1,196 +1,282 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /*
- * SourceBufferHolder groups buffer and length values and provides a way to
- * optionally pass ownership of the buffer to the JS engine without copying.
+ * SourceText encapsulates a count of char16_t (UTF-16) or Utf8Unit (UTF-8)
+ * code units (note: code *units*, not bytes or code points) and those code
+ * units ("source units").  (Latin-1 is not supported: all places where Latin-1
+ * must be compiled first convert to a supported encoding.)
+ *
+ * A SourceText either observes without owning, or takes ownership of, source
+ * units passed to |SourceText::init|.  Thus SourceText can be used to
+ * efficiently avoid copying.
  *
  * Rules for use:
  *
- *  1) The data array must be allocated with js_malloc() or js_realloc() if
- *     ownership is being granted to the SourceBufferHolder.
- *  2) If ownership is not given to SourceBufferHolder::init, then the memory
- *     must be kept alive until the JS compilation is complete.  If ownership
- *     is given to SourceBufferHolder::init, it is given *even if that function
- *     fails*.
- *  3) Any code calling SourceBufferHolder::take() must guarantee to keep the
- *     memory alive until JS compilation completes.  Normally only the JS
- *     engine should be calling take().
+ *  1) The passed-in source units must be allocated with js_malloc(),
+ *     js_calloc(), or js_realloc() if |SourceText::init| is instructed to take
+ *     ownership of the source units.
+ *  2) If |SourceText::init| merely borrows the source units, the user must
+ *     keep them alive until associated JS compilation is complete.
+ *  3) Code that calls |SourceText::take{Chars,Units}()| must keep the source
+ *     units alive until JS compilation completes.  Normally only the JS engine
+ *     should call |SourceText::take{Chars,Units}()|.
+ *  4) Use the appropriate SourceText parameterization depending on the source
+ *     units encoding.
  *
  * Example use:
  *
  *    size_t length = 512;
  *    char16_t* chars = js_pod_malloc<char16_t>(length);
  *    if (!chars) {
  *        JS_ReportOutOfMemory(cx);
  *        return false;
  *    }
- *    JS::SourceBufferHolder srcBuf;
- *    if (!srcBuf.init(cx, chars, length, JS::SourceBufferHolder::GiveOwnership) ||
- *        !JS::Compile(cx, options, srcBuf))
- *    {
+ *    JS::SourceText<char16_t> srcBuf;
+ *    if (!srcBuf.init(cx, chars, length, JS::SourceOwnership::TakeOwnership)) {
+ *        return false;
+ *    }
+ *    JS::Rooted<JSScript*> script(cx);
+ *    if (!JS::Compile(cx, options, srcBuf, &script)) {
  *        return false;
  *    }
  */
 
-#ifndef js_SourceBufferHolder_h
-#define js_SourceBufferHolder_h
+#ifndef js_SourceText_h
+#define js_SourceText_h
 
 #include "mozilla/Assertions.h" // MOZ_ASSERT
-#include "mozilla/Attributes.h" // MOZ_IS_CLASS_INIT, MOZ_MUST_USE
+#include "mozilla/Attributes.h" // MOZ_COLD, MOZ_IS_CLASS_INIT, MOZ_MUST_USE
 #include "mozilla/Likely.h" // MOZ_UNLIKELY
+#include "mozilla/Utf8.h" // mozilla::Utf8Unit
 
 #include <stddef.h> // size_t
 #include <stdint.h> // UINT32_MAX
+#include <type_traits> // std::conditional, std::is_same
 
-#include "js/Utility.h" // JS::UniqueTwoByteChars
+#include "js/UniquePtr.h" // js::UniquePtr
+#include "js/Utility.h" // JS::FreePolicy
 
 namespace JS {
 
 namespace detail {
 
 MOZ_COLD extern JS_PUBLIC_API(void)
 ReportSourceTooLong(JSContext* cx);
 
-}
+} // namespace detail
 
-class SourceBufferHolder final
+enum class SourceOwnership
+{
+    Borrowed,
+    TakeOwnership,
+};
+
+template<typename Unit>
+class SourceText final
 {
   private:
-    const char16_t* data_ = nullptr;
-    size_t length_ = 0;
-    bool ownsChars_ = false;
+    static_assert(std::is_same<Unit, mozilla::Utf8Unit>::value ||
+                  std::is_same<Unit, char16_t>::value,
+                  "Unit must be either char16_t or Utf8Unit for "
+                  "SourceText<Unit>");
+
+    /** |char16_t| or |Utf8Unit| source units of uncertain validity. */
+    const Unit* units_ = nullptr;
+
+    /** The length in code units of |units_|. */
+    uint32_t length_ = 0;
+
+    /**
+     * Whether this owns |units_| or merely observes source units owned by some
+     * other object.
+     */
+    bool ownsUnits_ = false;
+
+  public:
+    // A C++ character type that can represent the source units -- suitable for
+    // passing to C++ string functions.
+    using CharT =
+        typename std::conditional<std::is_same<Unit, char16_t>::value,
+                                  char16_t,
+                                  char>::type;
 
   public:
     /**
-     * Construct a SourceBufferHolder.  It must be initialized using |init()|
-     * before it can be used as compilation source text.
+     * Construct a SourceText.  It must be initialized using |init()| before it
+     * can be used as compilation source text.
      */
-    SourceBufferHolder() = default;
+    SourceText() = default;
 
     /**
-     * Construct a SourceBufferHolder from contents extracted from |other|.
-     * This SourceBufferHolder will then act exactly as |other| would have
-     * acted, had it not been passed to this function.  |other| will return to
-     * its default-constructed state and must have |init()| called on it to use
-     * it.
+     * Construct a SourceText from contents extracted from |other|.  This
+     * SourceText will then act exactly as |other| would have acted, had it
+     * not been passed to this function.  |other| will return to its default-
+     * constructed state and must have |init()| called on it to use it.
      */
-    SourceBufferHolder(SourceBufferHolder&& other)
-      : data_(other.data_),
+    SourceText(SourceText&& other)
+      : units_(other.units_),
         length_(other.length_),
-        ownsChars_(other.ownsChars_)
+        ownsUnits_(other.ownsUnits_)
     {
-        other.data_ = nullptr;
+        other.units_ = nullptr;
         other.length_ = 0;
-        other.ownsChars_ = false;
+        other.ownsUnits_ = false;
     }
 
-    ~SourceBufferHolder() {
-        if (ownsChars_) {
-            js_free(const_cast<char16_t*>(data_));
+    ~SourceText() {
+        if (ownsUnits_) {
+            js_free(const_cast<Unit*>(units_));
         }
     }
 
-    enum Ownership {
-        NoOwnership,
-        GiveOwnership
-    };
-
     /**
-     * Initialize this with data.
+     * Initialize this with source unit data: |char16_t| for UTF-16 source
+     * units, or |Utf8Unit| for UTF-8 source units.
      *
-     * If |ownership == GiveOwnership|, *this function* takes ownership of
-     * |data|, *even if* this function fails.  You MUST NOT free |data| after
-     * this function takes ownership of it, REGARDLESS whether this function
-     * succeeds or fails.  This single-owner-friendly approach reduces risk of
-     * leaks on failure.
+     * If |ownership == TakeOwnership|, *this function* takes ownership of
+     * |units|, *even if* this function fails, and you MUST NOT free |units|
+     * yourself.  This single-owner-friendly approach reduces risk of leaks on
+     * failure.
      *
-     * |data| may be null if |dataLength == 0|; if so, this will silently be
-     * initialized using non-null, unowned data.
+     * |units| may be null if |unitsLength == 0|; if so, this will silently be
+     * initialized using non-null, unowned units.
      */
     MOZ_IS_CLASS_INIT MOZ_MUST_USE bool
-    init(JSContext* cx, const char16_t* data, size_t dataLength, Ownership ownership) {
-        MOZ_ASSERT_IF(data == nullptr, dataLength == 0);
+    init(JSContext* cx, const Unit* units, size_t unitsLength, SourceOwnership ownership) {
+        MOZ_ASSERT_IF(units == nullptr, unitsLength == 0);
 
-        static const char16_t nonNullData[] = u"";
+        // Ideally we'd use |Unit| and not cast below, but the risk of a static
+        // initializer is too great.
+        static const CharT emptyString[] = { '\0' };
 
         // Initialize all fields *before* checking length.  This ensures that
-        // if data ownership is being passed to SourceBufferHolder, a failure
-        // of length-checking will result in this class freeing the data on
-        // destruction.
-        if (data) {
-            data_ = data;
-            length_ = static_cast<uint32_t>(dataLength);
-            ownsChars_ = ownership == GiveOwnership;
+        // if |ownership == SourceOwnership::TakeOwnership|, |units| will be
+        // freed when |this|'s destructor is called.
+        if (units) {
+            units_ = units;
+            length_ = static_cast<uint32_t>(unitsLength);
+            ownsUnits_ = ownership == SourceOwnership::TakeOwnership;
         } else {
-            data_ = nonNullData;
+            units_ = reinterpret_cast<const Unit*>(emptyString);
             length_ = 0;
-            ownsChars_ = false;
+            ownsUnits_ = false;
         }
 
         // IMPLEMENTATION DETAIL, DO NOT RELY ON: This limit is used so we can
-        // store offsets in JSScripts as uint32_t.  It could be lifted fairly
-        // easily if desired as the compiler uses size_t internally.
-        if (MOZ_UNLIKELY(dataLength > UINT32_MAX)) {
+        // store offsets in |JSScript|s as |uint32_t|.  It could be lifted
+        // fairly easily if desired, as the compiler uses |size_t| internally.
+        if (MOZ_UNLIKELY(unitsLength > UINT32_MAX)) {
             detail::ReportSourceTooLong(cx);
             return false;
         }
 
         return true;
     }
 
     /**
-     * Initialize this from data with ownership transferred from the caller.
+     * Exactly identical to the |init()| overload above that accepts
+     * |const Unit*|, but instead takes character data: |const CharT*|.
+     *
+     * (We can't just write this to accept |const CharT*|, because then in the
+     * UTF-16 case this overload and the one above would be identical.  So we
+     * use SFINAE to expose the |CharT| overload only if it's different.)
      */
-    MOZ_IS_CLASS_INIT MOZ_MUST_USE
-    bool init(JSContext* cx, UniqueTwoByteChars data, size_t dataLength) {
-        return init(cx, data.release(), dataLength, GiveOwnership);
+    template<typename Char,
+             typename =
+                typename std::enable_if<std::is_same<Char, CharT>::value &&
+                                        !std::is_same<Char, Unit>::value>::type>
+    MOZ_IS_CLASS_INIT MOZ_MUST_USE bool
+    init(JSContext* cx, const Char* chars, size_t charsLength, SourceOwnership ownership) {
+        return init(cx, reinterpret_cast<const Unit*>(chars), charsLength, ownership);
+    }
+
+    /**
+     * Initialize this using source units transferred out of |data|.
+     */
+    MOZ_MUST_USE bool init(JSContext* cx,
+                           js::UniquePtr<CharT[], JS::FreePolicy> data,
+                           size_t dataLength)
+    {
+        return init(cx, data.release(), dataLength, SourceOwnership::TakeOwnership);
     }
 
-    /** Access the underlying source buffer without affecting ownership. */
-    const char16_t* get() const {
-        return data_;
+    /**
+     * Access the encapsulated data using a code unit type.
+     *
+     * This function is useful for code that wants to interact with source text
+     * as *code units*, not as string data.  This doesn't matter for UTF-16,
+     * but it's a crucial distinction for UTF-8.  When UTF-8 source text is
+     * encapsulated, |Unit| being |mozilla::Utf8Unit| unambiguously indicates
+     * that the code units are UTF-8.  In contrast |const char*| returned by
+     * |get()| below could hold UTF-8 (or its ASCII subset) or Latin-1 or (in
+     * particularly cursed embeddings) EBCDIC or some other legacy character
+     * set.  Prefer this function to |get()| wherever possible.
+     */
+    const Unit* units() const { return units_; }
+
+    /**
+     * Access the encapsulated data using a character type.
+     *
+     * This function is useful for interactions with character-centric actions
+     * like interacting with UniqueChars/UniqueTwoByteChars or printing out
+     * text in a debugger, that only work with |CharT|.  But as |CharT| loses
+     * encoding specificity when UTF-8 source text is encapsulated, prefer
+     * |units()| to this function.
+     */
+    const CharT* get() const { return reinterpret_cast<const CharT*>(units_); }
+
+    /**
+     * Returns true if this owns the source units and will free them on
+     * destruction.  If true, it is legal to call |take{Chars,Units}()|.
+     */
+    bool ownsUnits() const {
+        return ownsUnits_;
     }
 
-    /** Length of the source buffer in char16_t code units (not bytes). */
+    /**
+     * Count of the underlying source units -- code units, not bytes or code
+     * points -- in this.
+     */
     uint32_t length() const {
         return length_;
     }
 
     /**
-     * Returns true if the SourceBufferHolder owns the buffer and will free it
-     * upon destruction.  If true, it is legal to call take().
-     */
-    bool ownsChars() const {
-        return ownsChars_;
-    }
-
-    /**
-     * Retrieve and take ownership of the underlying data buffer.  The caller
+     * Retrieve and take ownership of the underlying source units.  The caller
      * is now responsible for calling js_free() on the returned value, *but
      * only after JS script compilation has completed*.
      *
-     * After the buffer has been taken, this will continue to refer to the same
-     * data -- it just won't own the data.  get() and length() will return the
-     * same values.  The taken buffer must be kept alive until after JS script
+     * After underlying source units have been taken, this will continue to
+     * refer to the same data -- it just won't own the data.  get() and
+     * length() will return the same values, but ownsUnits() will be false.
+     * The taken source units must be kept alive until after JS script
      * compilation completes, as noted above, for this to be safe.
      *
-     * The caller must check ownsChars() before attempting to take the buffer.
-     * Taking and then free'ing an unowned buffer will have dire consequences.
+     * The caller must check ownsUnits() before calling takeUnits().  Taking
+     * and then free'ing an unowned buffer will have dire consequences.
      */
-    char16_t* take() {
-        MOZ_ASSERT(ownsChars_);
-        ownsChars_ = false;
-        return const_cast<char16_t*>(data_);
+    Unit* takeUnits() {
+        MOZ_ASSERT(ownsUnits_);
+        ownsUnits_ = false;
+        return const_cast<Unit*>(units_);
+    }
+
+    /**
+     * Akin to |takeUnits()| in all respects, but returns characters rather
+     * than units.
+     */
+    CharT* takeChars() {
+        return reinterpret_cast<CharT*>(takeUnits());
     }
 
   private:
-    SourceBufferHolder(SourceBufferHolder&) = delete;
-    SourceBufferHolder& operator=(SourceBufferHolder&) = delete;
+    SourceText(const SourceText&) = delete;
+    void operator=(const SourceText&) = delete;
 };
 
 } // namespace JS
 
-#endif /* js_SourceBufferHolder_h */
+#endif /* js_SourceText_h */
--- a/js/rust/build.rs
+++ b/js/rust/build.rs
@@ -222,17 +222,17 @@ const WHITELIST_TYPES: &'static [&'stati
     "JS::Rooted",
     "JS::RootedObject",
     "JS::RootingContext",
     "JS::RootKind",
     "js::Scalar::Type",
     "JS::ServoSizes",
     "js::shadow::Object",
     "js::shadow::ObjectGroup",
-    "JS::SourceBufferHolder",
+    "JS::SourceText",
     "js::StackFormat",
     "JSStructuredCloneCallbacks",
     "JS::Symbol",
     "JS::SymbolCode",
     "JS::TraceKind",
     "JS::TransferableOwnership",
     "JS::Value",
     "JS::WarningReporter",
--- a/js/rust/etc/wrapper.hpp
+++ b/js/rust/etc/wrapper.hpp
@@ -13,16 +13,16 @@ typedef uint32_t HashNumber;
 
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "js/CompilationAndEvaluation.h"
 #include "js/CompileOptions.h"
 #include "js/Conversions.h"
 #include "js/Initialization.h"
 #include "js/MemoryMetrics.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/StructuredClone.h"
 
 // Replacements for types that are too difficult for rust-bindgen.
 
 /// <div rustbindgen replaces="JS::detail::MaybeWrapped" />
 template <typename T>
 using replaces_MaybeWrapped = T;
--- a/js/rust/src/rust.rs
+++ b/js/rust/src/rust.rs
@@ -227,20 +227,21 @@ impl Runtime {
         } else {
             (script_utf16.as_ptr(), script_utf16.len() as c_uint)
         };
         assert!(!ptr.is_null());
         unsafe {
             let _ar = AutoRealm::with_obj(self.cx(), glob.get());
             let options = CompileOptionsWrapper::new(self.cx(), filename_cstr.as_ptr(), line_num);
 
-            let mut srcBuf = JS::SourceBufferHolder {
-                data_: ptr,
+            let mut srcBuf = JS::SourceText {
+                units_: ptr,
                 length_: len as _,
-                ownsChars_: false
+                ownsUnits_: false,
+                _phantom_0: marker::PhantomData
             };
             if !JS::Evaluate(self.cx(), options.ptr, &mut srcBuf, rval) {
                 debug!("...err!");
                 panic::maybe_resume_unwind();
                 Err(())
             } else {
                 // we could return the script result but then we'd have
                 // to root it and so forth and, really, who cares?
--- a/js/src/NamespaceImports.h
+++ b/js/src/NamespaceImports.h
@@ -33,17 +33,17 @@ class UTF8CharsZ;
 using AutoValueVector = AutoVector<Value>;
 using AutoIdVector = AutoVector<jsid>;
 using AutoObjectVector = AutoVector<JSObject*>;
 
 using ValueVector = JS::GCVector<JS::Value>;
 using IdVector = JS::GCVector<jsid>;
 using ScriptVector = JS::GCVector<JSScript*>;
 
-class SourceBufferHolder;
+template<typename UnitT> class SourceText;
 
 class HandleValueArray;
 
 class ObjectOpResult;
 class PropertyResult;
 
 enum class SymbolCode: uint32_t;
 
--- a/js/src/builtin/Eval.cpp
+++ b/js/src/builtin/Eval.cpp
@@ -6,17 +6,17 @@
 
 #include "builtin/Eval.h"
 
 #include "mozilla/HashFunctions.h"
 #include "mozilla/Range.h"
 
 #include "frontend/BytecodeCompiler.h"
 #include "gc/HashUtil.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/StableStringChars.h"
 #include "vm/Debugger.h"
 #include "vm/GlobalObject.h"
 #include "vm/JSContext.h"
 #include "vm/JSONParser.h"
 
 #include "vm/Interpreter-inl.h"
 
@@ -24,17 +24,18 @@ using namespace js;
 
 using mozilla::AddToHash;
 using mozilla::HashString;
 using mozilla::RangedPtr;
 
 using JS::AutoCheckCannotGC;
 using JS::AutoStableStringChars;
 using JS::CompileOptions;
-using JS::SourceBufferHolder;
+using JS::SourceOwnership;
+using JS::SourceText;
 
 // We should be able to assert this for *any* fp->environmentChain().
 static void
 AssertInnerizedEnvironmentChain(JSContext* cx, JSObject& env)
 {
 #ifdef DEBUG
     RootedObject obj(cx);
     for (obj = &env; obj; obj = obj->enclosingEnvironment()) {
@@ -312,22 +313,22 @@ EvalKernel(JSContext* cx, HandleValue v,
             options.setIntroductionType("eval");
         }
 
         AutoStableStringChars linearChars(cx);
         if (!linearChars.initTwoByte(cx, linearStr)) {
             return false;
         }
 
-        SourceBufferHolder srcBuf;
+        SourceText<char16_t> srcBuf;
 
         const char16_t* chars = linearChars.twoByteRange().begin().get();
-        SourceBufferHolder::Ownership ownership = linearChars.maybeGiveOwnershipToCaller()
-                                                  ? SourceBufferHolder::GiveOwnership
-                                                  : SourceBufferHolder::NoOwnership;
+        SourceOwnership ownership = linearChars.maybeGiveOwnershipToCaller()
+                                    ? SourceOwnership::TakeOwnership
+                                    : SourceOwnership::Borrowed;
         if (!srcBuf.init(cx, chars, linearStr->length(), ownership)) {
             return false;
         }
 
         JSScript* compiled = frontend::CompileEvalScript(cx, env, enclosing, options, srcBuf);
         if (!compiled) {
             return false;
         }
@@ -401,22 +402,22 @@ js::DirectEvalStringFromIon(JSContext* c
             options.setIntroductionType("eval");
         }
 
         AutoStableStringChars linearChars(cx);
         if (!linearChars.initTwoByte(cx, linearStr)) {
             return false;
         }
 
-        SourceBufferHolder srcBuf;
+        SourceText<char16_t> srcBuf;
 
         const char16_t* chars = linearChars.twoByteRange().begin().get();
-        SourceBufferHolder::Ownership ownership = linearChars.maybeGiveOwnershipToCaller()
-                                                  ? SourceBufferHolder::GiveOwnership
-                                                  : SourceBufferHolder::NoOwnership;
+        SourceOwnership ownership = linearChars.maybeGiveOwnershipToCaller()
+                                    ? SourceOwnership::TakeOwnership
+                                    : SourceOwnership::Borrowed;
         if (!srcBuf.init(cx, chars, linearStr->length(), ownership)) {
             return false;
         }
 
         JSScript* compiled = frontend::CompileEvalScript(cx, env, enclosing, options, srcBuf);
         if (!compiled) {
             return false;
         }
--- a/js/src/builtin/TestingFunctions.cpp
+++ b/js/src/builtin/TestingFunctions.cpp
@@ -42,17 +42,17 @@
 #include "jit/InlinableNatives.h"
 #include "jit/JitRealm.h"
 #include "js/CharacterEncoding.h"
 #include "js/CompilationAndEvaluation.h"
 #include "js/CompileOptions.h"
 #include "js/Debug.h"
 #include "js/HashTable.h"
 #include "js/LocaleSensitive.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/StableStringChars.h"
 #include "js/StructuredClone.h"
 #include "js/UbiNode.h"
 #include "js/UbiNodeBreadthFirst.h"
 #include "js/UbiNodeShortestPaths.h"
 #include "js/UniquePtr.h"
 #include "js/Vector.h"
 #include "js/Wrapper.h"
@@ -88,17 +88,18 @@
 
 using namespace js;
 
 using mozilla::ArrayLength;
 using mozilla::Maybe;
 
 using JS::AutoStableStringChars;
 using JS::CompileOptions;
-using JS::SourceBufferHolder;
+using JS::SourceOwnership;
+using JS::SourceText;
 
 // If fuzzingSafe is set, remove functionality that could cause problems with
 // fuzzers. Set this via the environment variable MOZ_FUZZING_SAFE.
 mozilla::Atomic<bool> fuzzingSafe(false);
 
 // If disableOOMFunctions is set, disable functionality that causes artificial
 // OOM conditions.
 static mozilla::Atomic<bool> disableOOMFunctions(false);
@@ -4028,18 +4029,18 @@ EvalReturningScope(JSContext* cx, unsign
     unsigned lineno;
 
     JS::DescribeScriptedCaller(cx, &filename, &lineno);
 
     JS::CompileOptions options(cx);
     options.setFileAndLine(filename.get(), lineno);
     options.setNoScriptRval(true);
 
-    JS::SourceBufferHolder srcBuf;
-    if (!srcBuf.init(cx, src, srclen, JS::SourceBufferHolder::NoOwnership)) {
+    JS::SourceText<char16_t> srcBuf;
+    if (!srcBuf.init(cx, src, srclen, SourceOwnership::Borrowed)) {
         return false;
     }
 
     RootedScript script(cx);
     if (!JS::CompileForNonSyntacticScope(cx, options, srcBuf, &script)) {
         return false;
     }
 
@@ -4133,18 +4134,18 @@ ShellCloneAndExecuteScript(JSContext* cx
     unsigned lineno;
 
     JS::DescribeScriptedCaller(cx, &filename, &lineno);
 
     JS::CompileOptions options(cx);
     options.setFileAndLine(filename.get(), lineno);
     options.setNoScriptRval(true);
 
-    JS::SourceBufferHolder srcBuf;
-    if (!srcBuf.init(cx, src, srclen, JS::SourceBufferHolder::NoOwnership)) {
+    JS::SourceText<char16_t> srcBuf;
+    if (!srcBuf.init(cx, src, srclen, SourceOwnership::Borrowed)) {
         return false;
     }
 
     RootedScript script(cx);
     if (!JS::Compile(cx, options, srcBuf, &script)) {
         return false;
     }
 
@@ -5561,18 +5562,18 @@ js::TestingFunctionArgumentToScript(JSCo
         }
         size_t len = GetLinearStringLength(linearStr);
         AutoStableStringChars linearChars(cx);
         if (!linearChars.initTwoByte(cx, linearStr)) {
             return nullptr;
         }
         const char16_t* chars = linearChars.twoByteRange().begin().get();
 
-        SourceBufferHolder source;
-        if (!source.init(cx, chars, len, SourceBufferHolder::NoOwnership)) {
+        SourceText<char16_t> source;
+        if (!source.init(cx, chars, len, SourceOwnership::Borrowed)) {
             return nullptr;
         }
 
         RootedScript script(cx);
         CompileOptions options(cx);
         if (!JS::Compile(cx, options, source, &script)) {
             return nullptr;
         }
--- a/js/src/frontend/BytecodeCompiler.cpp
+++ b/js/src/frontend/BytecodeCompiler.cpp
@@ -14,17 +14,17 @@
 #if defined(JS_BUILD_BINAST)
 # include "frontend/BinSource.h"
 #endif // JS_BUILD_BINAST
 #include "frontend/BytecodeEmitter.h"
 #include "frontend/EitherParser.h"
 #include "frontend/ErrorReporter.h"
 #include "frontend/FoldConstants.h"
 #include "frontend/Parser.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "vm/GlobalObject.h"
 #include "vm/JSContext.h"
 #include "vm/JSScript.h"
 #include "vm/TraceLogging.h"
 #include "wasm/AsmJS.h"
 
 #include "vm/EnvironmentObject-inl.h"
 #include "vm/GeckoProfiler-inl.h"
@@ -33,17 +33,17 @@
 using namespace js;
 using namespace js::frontend;
 
 using mozilla::Maybe;
 using mozilla::Nothing;
 
 using JS::CompileOptions;
 using JS::ReadOnlyCompileOptions;
-using JS::SourceBufferHolder;
+using JS::SourceText;
 
 template<typename Unit> class SourceAwareCompiler;
 template<typename Unit> class ScriptCompiler;
 template<typename Unit> class ModuleCompiler;
 template<typename Unit> class StandaloneFunctionCompiler;
 
 // The BytecodeCompiler class contains resources common to compiling scripts and
 // function bodies.
@@ -92,40 +92,40 @@ class MOZ_STACK_CLASS BytecodeCompiler
     // Create a script for source of the given length, using the explicitly-
     // provided toString offsets as the created script's offsets in the source.
     MOZ_MUST_USE bool internalCreateScript(uint32_t toStringStart, uint32_t toStringEnd,
                                            uint32_t sourceBufferLength);
 
     MOZ_MUST_USE bool emplaceEmitter(Maybe<BytecodeEmitter>& emitter,
                                      const EitherParser& parser, SharedContext* sharedContext);
 
-    // This function will eventually be templated on source-units type.  It
-    // lives here, not in SourceAwareCompiler, because it mostly uses fields in
-    // *this* class.
-    MOZ_MUST_USE bool assignSource(SourceBufferHolder& sourceBuffer);
+    // This function lives here, not in SourceAwareCompiler, because it mostly
+    // uses fields in *this* class.
+    template<typename Unit>
+    MOZ_MUST_USE bool assignSource(SourceText<Unit>& sourceBuffer);
 
     bool canLazilyParse() const;
 
     MOZ_MUST_USE bool
     deoptimizeArgumentsInEnclosingScripts(JSContext* cx, HandleObject environment);
 };
 
 template<typename Unit>
 class MOZ_STACK_CLASS SourceAwareCompiler
 {
   protected:
-    SourceBufferHolder& sourceBuffer_;
+    SourceText<Unit>& sourceBuffer_;
 
     Maybe<Parser<SyntaxParseHandler, Unit>> syntaxParser;
     Maybe<Parser<FullParseHandler, Unit>> parser;
 
     using TokenStreamPosition = frontend::TokenStreamPosition<Unit>;
 
   protected:
-    explicit SourceAwareCompiler(SourceBufferHolder& sourceBuffer)
+    explicit SourceAwareCompiler(SourceText<Unit>& sourceBuffer)
       : sourceBuffer_(sourceBuffer)
     {
         MOZ_ASSERT(sourceBuffer_.get() != nullptr);
     }
 
     // Call this before calling compile{Global,Eval}Script.
     MOZ_MUST_USE bool prepareScriptParse(BytecodeCompiler& info) {
         return createSourceAndParser(info, ParseGoal::Script) && createCompleteScript(info);
@@ -212,17 +212,17 @@ class MOZ_STACK_CLASS GlobalScriptCompil
   : public ScriptCompiler<Unit>
 {
     using Base = ScriptCompiler<Unit>;
 
     using Base::compileScript;
     using Base::prepareScriptParse;
 
   public:
-    explicit GlobalScriptCompiler(SourceBufferHolder& srcBuf)
+    explicit GlobalScriptCompiler(SourceText<Unit>& srcBuf)
       : Base(srcBuf)
     {}
 
     JSScript* compile(GlobalScriptInfo& info) {
         if (!prepareScriptParse(info)) {
             return nullptr;
         }
         return compileScript(info, nullptr, info.sharedContext());
@@ -257,17 +257,17 @@ class MOZ_STACK_CLASS EvalScriptCompiler
   : public ScriptCompiler<Unit>
 {
     using Base = ScriptCompiler<Unit>;
 
     using Base::compileScript;
     using Base::prepareScriptParse;
 
   public:
-    explicit EvalScriptCompiler(SourceBufferHolder& srcBuf)
+    explicit EvalScriptCompiler(SourceText<Unit>& srcBuf)
       : Base(srcBuf)
     {}
 
     JSScript* compile(EvalScriptInfo& info) {
         if (!prepareScriptParse(info)) {
             return nullptr;
         }
         return compileScript(info, info.environment(), info.sharedContext());
@@ -291,17 +291,17 @@ class MOZ_STACK_CLASS ModuleCompiler fin
 
     using Base::assertSourceParserAndScriptCreated;
     using Base::createCompleteScript;
     using Base::createSourceAndParser;
     using Base::emplaceEmitter;
     using Base::parser;
 
   public:
-    explicit ModuleCompiler(SourceBufferHolder& srcBuf)
+    explicit ModuleCompiler(SourceText<Unit>& srcBuf)
       : Base(srcBuf)
     {}
 
     ModuleObject* compile(ModuleInfo& info);
 };
 
 class MOZ_STACK_CLASS StandaloneFunctionInfo final
   : public BytecodeCompiler
@@ -323,17 +323,17 @@ class MOZ_STACK_CLASS StandaloneFunction
     using Base::emplaceEmitter;
     using Base::handleParseFailure;
     using Base::parser;
     using Base::sourceBuffer_;
 
     using typename Base::TokenStreamPosition;
 
   public:
-    explicit StandaloneFunctionCompiler(SourceBufferHolder& srcBuf)
+    explicit StandaloneFunctionCompiler(SourceText<Unit>& srcBuf)
       : Base(srcBuf)
     {}
 
     MOZ_MUST_USE bool prepare(StandaloneFunctionInfo& info,
                               const Maybe<uint32_t>& parameterListEnd)
     {
         return createSourceAndParser(info, ParseGoal::Script, parameterListEnd);
     }
@@ -423,18 +423,19 @@ BytecodeCompiler::createScriptSource(con
     if (!sourceObject) {
         return false;
     }
 
     scriptSource = sourceObject->source();
     return true;
 }
 
+template<typename Unit>
 bool
-BytecodeCompiler::assignSource(SourceBufferHolder& sourceBuffer)
+BytecodeCompiler::assignSource(SourceText<Unit>& sourceBuffer)
 {
     if (!cx->realm()->behaviors().discardSource()) {
         if (options.sourceIsLazy) {
             scriptSource->setSourceRetrievable();
         } else if (!scriptSource->setSourceCopy(cx, sourceBuffer)) {
             return false;
         }
     }
@@ -849,17 +850,17 @@ class MOZ_RAII AutoAssertReportedExcepti
     explicit AutoAssertReportedException(JSContext*) {}
     void reset() {}
 #endif
 };
 
 JSScript*
 frontend::CompileGlobalScript(JSContext* cx, ScopeKind scopeKind,
                               const ReadOnlyCompileOptions& options,
-                              SourceBufferHolder& srcBuf,
+                              SourceText<char16_t>& srcBuf,
                               ScriptSourceObject** sourceObjectOut)
 {
     MOZ_ASSERT(scopeKind == ScopeKind::Global || scopeKind == ScopeKind::NonSyntactic);
 
     AutoAssertReportedException assertException(cx);
 
     GlobalScriptInfo info(cx, options, scopeKind);
     AutoInitializeSourceObject autoSSO(info, sourceObjectOut);
@@ -936,17 +937,17 @@ frontend::CompileGlobalBinASTScript(JSCo
 }
 
 #endif // JS_BUILD_BINAST
 
 JSScript*
 frontend::CompileEvalScript(JSContext* cx, HandleObject environment,
                             HandleScope enclosingScope,
                             const ReadOnlyCompileOptions& options,
-                            SourceBufferHolder& srcBuf,
+                            SourceText<char16_t>& srcBuf,
                             ScriptSourceObject** sourceObjectOut)
 {
     AutoAssertReportedException assertException(cx);
 
     EvalScriptInfo info(cx, options, environment, enclosingScope);
     AutoInitializeSourceObject autoSSO(info, sourceObjectOut);
 
     EvalScriptCompiler<char16_t> compiler(srcBuf);
@@ -957,17 +958,17 @@ frontend::CompileEvalScript(JSContext* c
 
     assertException.reset();
     return script;
 
 }
 
 ModuleObject*
 frontend::CompileModule(JSContext* cx, const ReadOnlyCompileOptions& optionsInput,
-                        SourceBufferHolder& srcBuf,
+                        SourceText<char16_t>& srcBuf,
                         ScriptSourceObject** sourceObjectOut)
 {
     MOZ_ASSERT(srcBuf.get());
     MOZ_ASSERT_IF(sourceObjectOut, *sourceObjectOut == nullptr);
 
     AutoAssertReportedException assertException(cx);
 
     CompileOptions options(cx, optionsInput);
@@ -985,17 +986,17 @@ frontend::CompileModule(JSContext* cx, c
     }
 
     assertException.reset();
     return module;
 }
 
 ModuleObject*
 frontend::CompileModule(JSContext* cx, const JS::ReadOnlyCompileOptions& options,
-                        SourceBufferHolder& srcBuf)
+                        SourceText<char16_t>& srcBuf)
 {
     AutoAssertReportedException assertException(cx);
 
     if (!GlobalObject::ensureModulePrototypesCreated(cx, cx->global())) {
         return nullptr;
     }
 
     RootedModuleObject module(cx, CompileModule(cx, options, srcBuf, nullptr));
@@ -1213,17 +1214,17 @@ frontend::CompileLazyBinASTFunction(JSCo
     return script;
 }
 
 #endif // JS_BUILD_BINAST
 
 bool
 frontend::CompileStandaloneFunction(JSContext* cx, MutableHandleFunction fun,
                                     const JS::ReadOnlyCompileOptions& options,
-                                    JS::SourceBufferHolder& srcBuf,
+                                    JS::SourceText<char16_t>& srcBuf,
                                     const Maybe<uint32_t>& parameterListEnd,
                                     HandleScope enclosingScope /* = nullptr */)
 {
     AutoAssertReportedException assertException(cx);
 
     StandaloneFunctionInfo info(cx, options);
 
     StandaloneFunctionCompiler<char16_t> compiler(srcBuf);
@@ -1244,17 +1245,17 @@ frontend::CompileStandaloneFunction(JSCo
 
     assertException.reset();
     return true;
 }
 
 bool
 frontend::CompileStandaloneGenerator(JSContext* cx, MutableHandleFunction fun,
                                      const JS::ReadOnlyCompileOptions& options,
-                                     JS::SourceBufferHolder& srcBuf,
+                                     JS::SourceText<char16_t>& srcBuf,
                                      const Maybe<uint32_t>& parameterListEnd)
 {
     AutoAssertReportedException assertException(cx);
 
     StandaloneFunctionInfo info(cx, options);
 
     StandaloneFunctionCompiler<char16_t> compiler(srcBuf);
     if (!compiler.prepare(info, parameterListEnd)) {
@@ -1271,17 +1272,17 @@ frontend::CompileStandaloneGenerator(JSC
 
     assertException.reset();
     return true;
 }
 
 bool
 frontend::CompileStandaloneAsyncFunction(JSContext* cx, MutableHandleFunction fun,
                                          const ReadOnlyCompileOptions& options,
-                                         JS::SourceBufferHolder& srcBuf,
+                                         JS::SourceText<char16_t>& srcBuf,
                                          const Maybe<uint32_t>& parameterListEnd)
 {
     AutoAssertReportedException assertException(cx);
 
     StandaloneFunctionInfo info(cx, options);
 
     StandaloneFunctionCompiler<char16_t> compiler(srcBuf);
     if (!compiler.prepare(info, parameterListEnd)) {
@@ -1298,17 +1299,17 @@ frontend::CompileStandaloneAsyncFunction
 
     assertException.reset();
     return true;
 }
 
 bool
 frontend::CompileStandaloneAsyncGenerator(JSContext* cx, MutableHandleFunction fun,
                                           const ReadOnlyCompileOptions& options,
-                                          JS::SourceBufferHolder& srcBuf,
+                                          JS::SourceText<char16_t>& srcBuf,
                                           const Maybe<uint32_t>& parameterListEnd)
 {
     AutoAssertReportedException assertException(cx);
 
     StandaloneFunctionInfo info(cx, options);
 
     StandaloneFunctionCompiler<char16_t> compiler(srcBuf);
     if (!compiler.prepare(info, parameterListEnd)) {
--- a/js/src/frontend/BytecodeCompiler.h
+++ b/js/src/frontend/BytecodeCompiler.h
@@ -7,16 +7,17 @@
 #ifndef frontend_BytecodeCompiler_h
 #define frontend_BytecodeCompiler_h
 
 #include "mozilla/Maybe.h"
 
 #include "NamespaceImports.h"
 
 #include "js/CompileOptions.h"
+#include "js/SourceText.h"
 #include "vm/Scope.h"
 #include "vm/TraceLogging.h"
 
 class JSLinearString;
 
 namespace js {
 
 class LazyScript;
@@ -27,17 +28,17 @@ namespace frontend {
 
 class ErrorReporter;
 class FunctionBox;
 class ParseNode;
 
 JSScript*
 CompileGlobalScript(JSContext* cx, ScopeKind scopeKind,
                     const JS::ReadOnlyCompileOptions& options,
-                    JS::SourceBufferHolder& srcBuf,
+                    JS::SourceText<char16_t>& srcBuf,
                     ScriptSourceObject** sourceObjectOut = nullptr);
 
 #if defined(JS_BUILD_BINAST)
 
 JSScript*
 CompileGlobalBinASTScript(JSContext *cx, LifoAlloc& alloc,
                           const JS::ReadOnlyCompileOptions& options,
                           const uint8_t* src, size_t len,
@@ -47,26 +48,26 @@ MOZ_MUST_USE bool
 CompileLazyBinASTFunction(JSContext* cx, Handle<LazyScript*> lazy, const uint8_t* buf, size_t length);
 
 #endif // JS_BUILD_BINAST
 
 JSScript*
 CompileEvalScript(JSContext* cx, HandleObject environment,
                   HandleScope enclosingScope,
                   const JS::ReadOnlyCompileOptions& options,
-                  JS::SourceBufferHolder& srcBuf,
+                  JS::SourceText<char16_t>& srcBuf,
                   ScriptSourceObject** sourceObjectOut = nullptr);
 
 ModuleObject*
 CompileModule(JSContext* cx, const JS::ReadOnlyCompileOptions& options,
-              JS::SourceBufferHolder& srcBuf);
+              JS::SourceText<char16_t>& srcBuf);
 
 ModuleObject*
 CompileModule(JSContext* cx, const JS::ReadOnlyCompileOptions& options,
-              JS::SourceBufferHolder& srcBuf,
+              JS::SourceText<char16_t>& srcBuf,
               ScriptSourceObject** sourceObjectOut);
 
 MOZ_MUST_USE bool
 CompileLazyFunction(JSContext* cx, Handle<LazyScript*> lazy, const char16_t* chars, size_t length);
 
 //
 // Compile a single function. The source in srcBuf must match the ECMA-262
 // FunctionExpression production.
@@ -77,36 +78,36 @@ CompileLazyFunction(JSContext* cx, Handl
 // it's how we detect that these weird cases are SyntaxErrors:
 //
 //     Function("/*", "*/x) {")
 //     Function("x){ if (3", "return x;}")
 //
 MOZ_MUST_USE bool
 CompileStandaloneFunction(JSContext* cx, MutableHandleFunction fun,
                           const JS::ReadOnlyCompileOptions& options,
-                          JS::SourceBufferHolder& srcBuf,
+                          JS::SourceText<char16_t>& srcBuf,
                           const mozilla::Maybe<uint32_t>& parameterListEnd,
                           HandleScope enclosingScope = nullptr);
 
 MOZ_MUST_USE bool
 CompileStandaloneGenerator(JSContext* cx, MutableHandleFunction fun,
                            const JS::ReadOnlyCompileOptions& options,
-                           JS::SourceBufferHolder& srcBuf,
+                           JS::SourceText<char16_t>& srcBuf,
                            const mozilla::Maybe<uint32_t>& parameterListEnd);
 
 MOZ_MUST_USE bool
 CompileStandaloneAsyncFunction(JSContext* cx, MutableHandleFunction fun,
                                const JS::ReadOnlyCompileOptions& options,
-                               JS::SourceBufferHolder& srcBuf,
+                               JS::SourceText<char16_t>& srcBuf,
                                const mozilla::Maybe<uint32_t>& parameterListEnd);
 
 MOZ_MUST_USE bool
 CompileStandaloneAsyncGenerator(JSContext* cx, MutableHandleFunction fun,
                                 const JS::ReadOnlyCompileOptions& options,
-                                JS::SourceBufferHolder& srcBuf,
+                                JS::SourceText<char16_t>& srcBuf,
                                 const mozilla::Maybe<uint32_t>& parameterListEnd);
 
 ScriptSourceObject*
 CreateScriptSourceObject(JSContext* cx, const JS::ReadOnlyCompileOptions& options,
                          const mozilla::Maybe<uint32_t>& parameterListEnd = mozilla::Nothing());
 
 /*
  * True if str consists of an IdentifierStart character, followed by one or
--- a/js/src/jsapi-tests/testCompileNonSyntactic.cpp
+++ b/js/src/jsapi-tests/testCompileNonSyntactic.cpp
@@ -1,15 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "gc/GCInternals.h"
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "jsapi-tests/tests.h"
 #include "vm/Monitor.h"
 #include "vm/MutexIDs.h"
 
 using namespace JS;
 using js::AutoLockMonitor;
 
 struct OffThreadTask
@@ -69,59 +69,59 @@ testCompile(bool nonSyntactic)
 
     constexpr size_t length = sizeof(src) - 1;
     static_assert(sizeof(src_16) / sizeof(*src_16) - 1 == length,
                   "Source buffers must be same length");
 
     JS::CompileOptions options(cx);
     options.setNonSyntacticScope(nonSyntactic);
 
-    JS::SourceBufferHolder buf;
-    CHECK(buf.init(cx, src_16, length, JS::SourceBufferHolder::NoOwnership));
+    JS::SourceText<char16_t> buf;
+    CHECK(buf.init(cx, src_16, length, JS::SourceOwnership::Borrowed));
 
     JS::RootedScript script(cx);
 
     // Check explicit non-syntactic compilation first to make sure it doesn't
     // modify our options object.
     CHECK(CompileForNonSyntacticScope(cx, options, buf, &script));
     CHECK_EQUAL(script->hasNonSyntacticScope(), true);
 
     CHECK(CompileLatin1ForNonSyntacticScope(cx, options, src, length, &script));
     CHECK_EQUAL(script->hasNonSyntacticScope(), true);
 
     {
-        JS::SourceBufferHolder srcBuf;
-        CHECK(srcBuf.init(cx, src_16, length, JS::SourceBufferHolder::NoOwnership));
+        JS::SourceText<char16_t> srcBuf;
+        CHECK(srcBuf.init(cx, src_16, length, JS::SourceOwnership::Borrowed));
 
         CHECK(CompileForNonSyntacticScope(cx, options, srcBuf, &script));
         CHECK_EQUAL(script->hasNonSyntacticScope(), true);
     }
 
 
     CHECK(Compile(cx, options, buf, &script));
     CHECK_EQUAL(script->hasNonSyntacticScope(), nonSyntactic);
 
     CHECK(CompileLatin1(cx, options, src, length, &script));
     CHECK_EQUAL(script->hasNonSyntacticScope(), nonSyntactic);
 
     {
-        JS::SourceBufferHolder srcBuf;
-        CHECK(srcBuf.init(cx, src_16, length, JS::SourceBufferHolder::NoOwnership));
+        JS::SourceText<char16_t> srcBuf;
+        CHECK(srcBuf.init(cx, src_16, length, JS::SourceOwnership::Borrowed));
 
         CHECK(Compile(cx, options, srcBuf, &script));
         CHECK_EQUAL(script->hasNonSyntacticScope(), nonSyntactic);
     }
 
 
     options.forceAsync = true;
     OffThreadTask task;
     OffThreadToken* token;
 
-    JS::SourceBufferHolder srcBuf;
-    CHECK(srcBuf.init(cx, src_16, length, JS::SourceBufferHolder::NoOwnership));
+    JS::SourceText<char16_t> srcBuf;
+    CHECK(srcBuf.init(cx, src_16, length, JS::SourceOwnership::Borrowed));
 
     CHECK(CompileOffThread(cx, options, srcBuf, task.OffThreadCallback, &task));
     CHECK(token = task.waitUntilDone(cx));
     CHECK(script = FinishOffThreadScript(cx, token));
     CHECK_EQUAL(script->hasNonSyntacticScope(), nonSyntactic);
 
     return true;
 }
--- a/js/src/jsapi-tests/testErrorLineOfContext.cpp
+++ b/js/src/jsapi-tests/testErrorLineOfContext.cpp
@@ -1,16 +1,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jsfriendapi.h"
 
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "jsapi-tests/tests.h"
 #include "vm/ErrorReporting.h"
 
 BEGIN_TEST(testErrorLineOfContext)
 {
     static const char16_t fullLineR[] = u"\n  var x = @;  \r  ";
     CHECK(testLineOfContextHasNoLineTerminator(fullLineR, ' '));
 
@@ -38,18 +38,18 @@ eval(const char16_t* chars, size_t len, 
 {
     JS::RealmOptions globalOptions;
     JS::RootedObject global(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr,
 						   JS::FireOnNewGlobalHook, globalOptions));
     CHECK(global);
 
     JSAutoRealm ar(cx, global);
 
-    JS::SourceBufferHolder srcBuf;
-    CHECK(srcBuf.init(cx, chars, len, JS::SourceBufferHolder::NoOwnership));
+    JS::SourceText<char16_t> srcBuf;
+    CHECK(srcBuf.init(cx, chars, len, JS::SourceOwnership::Borrowed));
 
     JS::CompileOptions options(cx);
     return JS::Evaluate(cx, options, srcBuf, rval);
 }
 
 template<size_t N>
 bool
 testLineOfContextHasNoLineTerminator(const char16_t (&chars)[N], char16_t expectedLast)
--- a/js/src/jsapi-tests/testJSEvaluateScript.cpp
+++ b/js/src/jsapi-tests/testJSEvaluateScript.cpp
@@ -1,32 +1,32 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  */
 
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "jsapi-tests/tests.h"
 
 using mozilla::ArrayLength;
 
 BEGIN_TEST(testJSEvaluateScript)
 {
     JS::RootedObject obj(cx, JS_NewPlainObject(cx));
     CHECK(obj);
 
     static const char16_t src[] = u"var x = 5;";
 
     JS::RootedValue retval(cx);
     JS::CompileOptions opts(cx);
     JS::AutoObjectVector scopeChain(cx);
     CHECK(scopeChain.append(obj));
 
-    JS::SourceBufferHolder srcBuf;
-    CHECK(srcBuf.init(cx, src, ArrayLength(src) - 1, JS::SourceBufferHolder::NoOwnership));
+    JS::SourceText<char16_t> srcBuf;
+    CHECK(srcBuf.init(cx, src, ArrayLength(src) - 1, JS::SourceOwnership::Borrowed));
 
     CHECK(JS::Evaluate(cx, scopeChain, opts.setFileAndLine(__FILE__, __LINE__),
                        srcBuf, &retval));
 
     bool hasProp = true;
     CHECK(JS_AlreadyHasOwnProperty(cx, obj, "x", &hasProp));
     CHECK(hasProp);
 
--- a/js/src/jsapi-tests/testMutedErrors.cpp
+++ b/js/src/jsapi-tests/testMutedErrors.cpp
@@ -1,15 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jsfriendapi.h"
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "jsapi-tests/tests.h"
 
 BEGIN_TEST(testMutedErrors)
 {
     CHECK(testOuter("function f() {return 1}; f;"));
     CHECK(testOuter("function outer() { return (function () {return 2}); }; outer();"));
     CHECK(testOuter("eval('(function() {return 3})');"));
     CHECK(testOuter("(function (){ return eval('(function() {return 4})'); })()"));
@@ -52,18 +52,18 @@ eval(const char* asciiChars, bool mutedE
     JSAutoRealm ar(cx, global);
     CHECK(JS::InitRealmStandardClasses(cx));
 
 
     JS::CompileOptions options(cx);
     options.setMutedErrors(mutedErrors)
            .setFileAndLine("", 0);
 
-    JS::SourceBufferHolder srcBuf;
-    CHECK(srcBuf.init(cx, chars.get(), len, JS::SourceBufferHolder::NoOwnership));
+    JS::SourceText<char16_t> srcBuf;
+    CHECK(srcBuf.init(cx, chars.get(), len, JS::SourceOwnership::Borrowed));
 
     return JS::Evaluate(cx, options, srcBuf, rval);
 }
 
 bool
 testOuter(const char* asciiChars)
 {
     CHECK(testInner(asciiChars, false));
--- a/js/src/jsapi-tests/testScriptObject.cpp
+++ b/js/src/jsapi-tests/testScriptObject.cpp
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "jsapi-tests/tests.h"
 
 struct ScriptObjectFixture : public JSAPITest {
     static const int code_size;
     static const char code[];
     static char16_t uc_code[];
 
     ScriptObjectFixture()
@@ -76,48 +76,48 @@ BEGIN_FIXTURE_TEST(ScriptObjectFixture, 
 }
 END_FIXTURE_TEST(ScriptObjectFixture, bug438633_CompileScriptForPrincipals)
 
 BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileUCScript)
 {
     JS::CompileOptions options(cx);
     options.setFileAndLine(__FILE__, __LINE__);
 
-    JS::SourceBufferHolder srcBuf;
-    CHECK(srcBuf.init(cx, uc_code, code_size, JS::SourceBufferHolder::NoOwnership));
+    JS::SourceText<char16_t> srcBuf;
+    CHECK(srcBuf.init(cx, uc_code, code_size, JS::SourceOwnership::Borrowed));
 
     JS::RootedScript script(cx);
     CHECK(JS::Compile(cx, options, srcBuf, &script));
 
     return tryScript(script);
 }
 END_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileUCScript)
 
 BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileUCScript_empty)
 {
     JS::CompileOptions options(cx);
     options.setFileAndLine(__FILE__, __LINE__);
 
-    JS::SourceBufferHolder srcBuf;
-    CHECK(srcBuf.init(cx, uc_code, 0, JS::SourceBufferHolder::NoOwnership));
+    JS::SourceText<char16_t> srcBuf;
+    CHECK(srcBuf.init(cx, uc_code, 0, JS::SourceOwnership::Borrowed));
 
     JS::RootedScript script(cx);
     CHECK(JS::Compile(cx, options, srcBuf, &script));
 
     return tryScript(script);
 }
 END_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileUCScript_empty)
 
 BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileUCScriptForPrincipals)
 {
     JS::CompileOptions options(cx);
     options.setFileAndLine(__FILE__, __LINE__);
 
-    JS::SourceBufferHolder srcBuf;
-    CHECK(srcBuf.init(cx, uc_code, code_size, JS::SourceBufferHolder::NoOwnership));
+    JS::SourceText<char16_t> srcBuf;
+    CHECK(srcBuf.init(cx, uc_code, code_size, JS::SourceOwnership::Borrowed));
 
     JS::RootedScript script(cx);
     CHECK(JS::Compile(cx, options, srcBuf, &script));
 
     return tryScript(script);
 }
 END_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileUCScriptForPrincipals)
 
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -57,17 +57,17 @@
 #include "js/CompileOptions.h"
 #include "js/Conversions.h"
 #include "js/Date.h"
 #include "js/Initialization.h"
 #include "js/JSON.h"
 #include "js/LocaleSensitive.h"
 #include "js/Proxy.h"
 #include "js/SliceBudget.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/StableStringChars.h"
 #include "js/StructuredClone.h"
 #include "js/Utility.h"
 #include "js/Wrapper.h"
 #include "util/CompleteFile.h"
 #include "util/StringBuffer.h"
 #include "util/Text.h"
 #include "vm/AsyncFunction.h"
@@ -109,17 +109,17 @@ using namespace js;
 
 using mozilla::Maybe;
 using mozilla::PodCopy;
 using mozilla::Some;
 
 using JS::AutoStableStringChars;
 using JS::CompileOptions;
 using JS::ReadOnlyCompileOptions;
-using JS::SourceBufferHolder;
+using JS::SourceText;
 
 #ifdef HAVE_VA_LIST_AS_ARRAY
 #define JS_ADDRESSOF_VA_LIST(ap) ((va_list*)(ap))
 #else
 #define JS_ADDRESSOF_VA_LIST(ap) (&(ap))
 #endif
 
 JS_PUBLIC_API(bool)
@@ -4157,17 +4157,17 @@ JS::FinishDynamicModuleImport(JSContext*
     CHECK_THREAD(cx);
     cx->check(referencingPrivate, promise);
 
     return js::FinishDynamicModuleImport(cx, referencingPrivate, specifier, promise);
 }
 
 JS_PUBLIC_API(bool)
 JS::CompileModule(JSContext* cx, const ReadOnlyCompileOptions& options,
-                  SourceBufferHolder& srcBuf, JS::MutableHandleObject module)
+                  SourceText<char16_t>& srcBuf, JS::MutableHandleObject module)
 {
     MOZ_ASSERT(!cx->zone()->isAtomsZone());
     AssertHeapIsIdle();
     CHECK_THREAD(cx);
 
     module.set(frontend::CompileModule(cx, options, srcBuf));
     return !!module;
 }
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -10,16 +10,17 @@
 #define jsapi_h
 
 #include "mozilla/AlreadyAddRefed.h"
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/Range.h"
 #include "mozilla/RangedPtr.h"
 #include "mozilla/RefPtr.h"
+#include "mozilla/Utf8.h"
 #include "mozilla/Variant.h"
 
 #include <stdarg.h>
 #include <stddef.h>
 #include <stdint.h>
 #include <stdio.h>
 
 #include "jspubtd.h"
@@ -46,17 +47,18 @@
 #include "js/Utility.h"
 #include "js/Value.h"
 #include "js/Vector.h"
 
 /************************************************************************/
 
 namespace JS {
 
-class SourceBufferHolder;
+template<typename UnitT> class SourceText;
+
 class TwoByteChars;
 
 /** AutoValueArray roots an internal fixed-size array of Values. */
 template <size_t N>
 class MOZ_RAII AutoValueArray : public AutoGCRooter
 {
     const size_t length_;
     Value elements_[N];
@@ -3120,17 +3122,17 @@ FinishDynamicModuleImport(JSContext* cx,
                           HandleObject promise);
 
 /**
  * Parse the given source buffer as a module in the scope of the current global
  * of cx and return a source text module record.
  */
 extern JS_PUBLIC_API(bool)
 CompileModule(JSContext* cx, const ReadOnlyCompileOptions& options,
-              SourceBufferHolder& srcBuf, JS::MutableHandleObject moduleRecord);
+              SourceText<char16_t>& srcBuf, JS::MutableHandleObject moduleRecord);
 
 /**
  * Set a private value associated with a source text module record.
  */
 extern JS_PUBLIC_API(void)
 SetModulePrivate(JSObject* module, const JS::Value& value);
 
 /**
--- a/js/src/moz.build
+++ b/js/src/moz.build
@@ -146,17 +146,17 @@ EXPORTS.js += [
     '../public/Proxy.h',
     '../public/Realm.h',
     '../public/RefCounted.h',
     '../public/RequiredDefines.h',
     '../public/Result.h',
     '../public/RootingAPI.h',
     '../public/SavedFrameAPI.h',
     '../public/SliceBudget.h',
-    '../public/SourceBufferHolder.h',
+    '../public/SourceText.h',
     '../public/StableStringChars.h',
     '../public/Stream.h',
     '../public/StructuredClone.h',
     '../public/SweepingAPI.h',
     '../public/TraceKind.h',
     '../public/TraceLoggerAPI.h',
     '../public/TracingAPI.h',
     '../public/TrackedOptimizationInfo.h',
--- a/js/src/shell/js.cpp
+++ b/js/src/shell/js.cpp
@@ -81,17 +81,17 @@
 #include "js/CharacterEncoding.h"
 #include "js/CompilationAndEvaluation.h"
 #include "js/CompileOptions.h"
 #include "js/Debug.h"
 #include "js/GCVector.h"
 #include "js/Initialization.h"
 #include "js/JSON.h"
 #include "js/Printf.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/StableStringChars.h"
 #include "js/StructuredClone.h"
 #include "js/SweepingAPI.h"
 #include "js/Wrapper.h"
 #include "perf/jsperf.h"
 #include "shell/jsoptparse.h"
 #include "shell/jsshell.h"
 #include "shell/OSObject.h"
@@ -2136,19 +2136,19 @@ Evaluate(JSContext* cx, unsigned argc, V
 
             if (loadBytecode) {
                 JS::TranscodeResult rv = JS::DecodeScript(cx, loadBuffer, &script);
                 if (!ConvertTranscodeResultToJSException(cx, rv)) {
                     return false;
                 }
             } else {
                 mozilla::Range<const char16_t> chars = codeChars.twoByteRange();
-                JS::SourceBufferHolder srcBuf;
+                JS::SourceText<char16_t> srcBuf;
                 if (!srcBuf.init(cx, chars.begin().get(), chars.length(),
-                                 JS::SourceBufferHolder::NoOwnership))
+                                 JS::SourceOwnership::Borrowed))
                 {
                     return false;
                 }
 
                 if (envChain.length() == 0) {
                     (void) JS::Compile(cx, options, srcBuf, &script);
                 } else {
                     (void) JS::CompileForNonSyntacticScope(cx, options, srcBuf, &script);
@@ -2383,19 +2383,19 @@ Run(JSContext* cx, unsigned argc, Value*
         return false;
     }
 
     AutoStableStringChars chars(cx);
     if (!chars.initTwoByte(cx, str)) {
         return false;
     }
 
-    JS::SourceBufferHolder srcBuf;
+    JS::SourceText<char16_t> srcBuf;
     if (!srcBuf.init(cx, chars.twoByteRange().begin().get(), str->length(),
-                     JS::SourceBufferHolder::NoOwnership))
+                     JS::SourceOwnership::Borrowed))
     {
         return false;
     }
 
     RootedScript script(cx);
     int64_t startClock = PRMJ_Now();
     {
         /* FIXME: This should use UTF-8 (bug 987069). */
@@ -3867,20 +3867,22 @@ EvalInContext(JSContext* cx, unsigned ar
         }
 
         sobj = ToWindowIfWindowProxy(sobj);
 
         if (!(sobj->getClass()->flags & JSCLASS_IS_GLOBAL)) {
             JS_ReportErrorASCII(cx, "Invalid scope argument to evalcx");
             return false;
         }
+
         JS::CompileOptions opts(cx);
         opts.setFileAndLine(filename.get(), lineno);
-        JS::SourceBufferHolder srcBuf;
-        if (!srcBuf.init(cx, src, srclen, JS::SourceBufferHolder::NoOwnership) ||
+
+        JS::SourceText<char16_t> srcBuf;
+        if (!srcBuf.init(cx, src, srclen, JS::SourceOwnership::Borrowed) ||
             !JS::Evaluate(cx, opts, srcBuf, args.rval()))
         {
             return false;
         }
     }
 
     if (!cx->compartment()->wrap(cx, args.rval())) {
         return false;
@@ -3985,19 +3987,19 @@ WorkerMain(WorkerInput* input)
         JSAutoRealm ar(cx, global);
 
         JS::CompileOptions options(cx);
         options.setFileAndLine("<string>", 1)
                .setIsRunOnce(true);
 
         AutoReportException are(cx);
         RootedScript script(cx);
-        JS::SourceBufferHolder srcBuf;
+        JS::SourceText<char16_t> srcBuf;
         if (!srcBuf.init(cx, input->chars.get(), input->length,
-                         JS::SourceBufferHolder::NoOwnership) ||
+                         JS::SourceOwnership::Borrowed) ||
             !JS::Compile(cx, options, srcBuf, &script))
         {
             break;
         }
         RootedValue result(cx);
         JS_ExecuteScript(cx, script, &result);
     } while (0);
 
@@ -4665,19 +4667,19 @@ Compile(JSContext* cx, unsigned argc, Va
     }
 
     JS::CompileOptions options(cx);
     options.setIntroductionType("js shell compile")
            .setFileAndLine("<string>", 1)
            .setIsRunOnce(true)
            .setNoScriptRval(true);
 
-    JS::SourceBufferHolder srcBuf;
+    JS::SourceText<char16_t> srcBuf;
     if (!srcBuf.init(cx, stableChars.twoByteRange().begin().get(), scriptContents->length(),
-                     JS::SourceBufferHolder::NoOwnership))
+                     JS::SourceOwnership::Borrowed))
     {
         return false;
     }
 
     RootedScript script(cx);
     if (!JS::Compile(cx, options, srcBuf, &script)) {
         return false;
     }
@@ -4740,18 +4742,18 @@ ParseModule(JSContext* cx, unsigned argc
     }
 
     AutoStableStringChars stableChars(cx);
     if (!stableChars.initTwoByte(cx, scriptContents)) {
         return false;
     }
 
     const char16_t* chars = stableChars.twoByteRange().begin().get();
-    JS::SourceBufferHolder srcBuf;
-    if (!srcBuf.init(cx, chars, scriptContents->length(), JS::SourceBufferHolder::NoOwnership)) {
+    JS::SourceText<char16_t> srcBuf;
+    if (!srcBuf.init(cx, chars, scriptContents->length(), JS::SourceOwnership::Borrowed)) {
         return false;
     }
 
     RootedObject module(cx, frontend::CompileModule(cx, options, srcBuf));
     if (!module) {
         return false;
     }
 
@@ -5454,18 +5456,18 @@ OffThreadCompileScript(JSContext* cx, un
     }
 
     OffThreadJob* job = NewOffThreadJob(cx, ScriptKind::Script,
                                         OffThreadJob::Source(std::move(ownedChars)));
     if (!job) {
         return false;
     }
 
-    JS::SourceBufferHolder srcBuf;
-    if (!srcBuf.init(cx, job->sourceChars(), length, JS::SourceBufferHolder::NoOwnership) ||
+    JS::SourceText<char16_t> srcBuf;
+    if (!srcBuf.init(cx, job->sourceChars(), length, JS::SourceOwnership::Borrowed) ||
         !JS::CompileOffThread(cx, options, srcBuf, OffThreadCompileScriptCallback, job))
     {
         job->cancel();
         DeleteOffThreadJob(cx, job);
         return false;
     }
 
     args.rval().setInt32(job->id);
@@ -5547,18 +5549,18 @@ OffThreadCompileModule(JSContext* cx, un
     }
 
     OffThreadJob* job = NewOffThreadJob(cx, ScriptKind::Module,
                                         OffThreadJob::Source(std::move(ownedChars)));
     if (!job) {
         return false;
     }
 
-    JS::SourceBufferHolder srcBuf;
-    if (!srcBuf.init(cx, job->sourceChars(), length, JS::SourceBufferHolder::NoOwnership) ||
+    JS::SourceText<char16_t> srcBuf;
+    if (!srcBuf.init(cx, job->sourceChars(), length, JS::SourceOwnership::Borrowed) ||
         !JS::CompileOffThreadModule(cx, options, srcBuf, OffThreadCompileScriptCallback, job))
     {
         job->cancel();
         DeleteOffThreadJob(cx, job);
         return false;
     }
 
     args.rval().setInt32(job->id);
@@ -8227,19 +8229,19 @@ EntryPoints(JSContext* cx, unsigned argc
             if (!codeString || !codeString->ensureFlat(cx)) {
                 return false;
             }
 
             AutoStableStringChars stableChars(cx);
             if (!stableChars.initTwoByte(cx, codeString)) {
                 return false;
             }
-            JS::SourceBufferHolder srcBuf;
+            JS::SourceText<char16_t> srcBuf;
             if (!srcBuf.init(cx, stableChars.twoByteRange().begin().get(), codeString->length(),
-                             JS::SourceBufferHolder::NoOwnership))
+                             JS::SourceOwnership::Borrowed))
             {
                 return false;
             }
 
             CompileOptions options(cx);
             options.setIntroductionType("entryPoint eval")
                    .setFileAndLine("entryPoint eval", 1);
 
--- a/js/src/vm/CompilationAndEvaluation.cpp
+++ b/js/src/vm/CompilationAndEvaluation.cpp
@@ -16,48 +16,49 @@
 #include "jsfriendapi.h" // js::GetErrorMessage
 #include "jstypes.h" // JS_PUBLIC_API
 
 #include "frontend/FullParseHandler.h" // frontend::FullParseHandler
 #include "frontend/ParseContext.h" // frontend::UsedNameTracker
 #include "frontend/Parser.h" // frontend::Parser, frontend::ParseGoal
 #include "js/CharacterEncoding.h" // JS::UTF8Chars, JS::UTF8CharsToNewTwoByteCharsZ
 #include "js/RootingAPI.h" // JS::Rooted
-#include "js/SourceBufferHolder.h" // JS::SourceBufferHolder
+#include "js/SourceText.h" // JS::SourceText
 #include "js/TypeDecls.h" // JS::HandleObject, JS::MutableHandleScript
 #include "js/Utility.h" // JS::UniqueTwoByteChars
 #include "js/Value.h" // JS::Value
 #include "util/CompleteFile.h" // js::FileContents, js::ReadCompleteFile
 #include "util/StringBuffer.h" // js::StringBuffer
 #include "vm/Debugger.h" // js::Debugger
 #include "vm/EnvironmentObject.h" // js::CreateNonSyntacticEnvironmentChain
 #include "vm/Interpreter.h" // js::Execute
 #include "vm/JSContext.h" // JSContext
 
 #include "vm/JSContext-inl.h" // JSContext::check
 
 using JS::CompileOptions;
 using JS::HandleObject;
 using JS::ReadOnlyCompileOptions;
-using JS::SourceBufferHolder;
+using JS::SourceOwnership;
+using JS::SourceText;
 using JS::UniqueTwoByteChars;
 using JS::UTF8Chars;
 using JS::UTF8CharsToNewTwoByteCharsZ;
 
 using namespace js;
 
 JS_PUBLIC_API(void)
 JS::detail::ReportSourceTooLong(JSContext* cx)
 {
     JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_SOURCE_TOO_LONG);
 }
 
 static bool
 CompileSourceBuffer(JSContext* cx, const ReadOnlyCompileOptions& options,
-                    SourceBufferHolder& srcBuf, JS::MutableHandleScript script)
+                    SourceText<char16_t>& srcBuf, JS::MutableHandleScript script)
 {
     ScopeKind scopeKind = options.nonSyntacticScope ? ScopeKind::NonSyntactic : ScopeKind::Global;
 
     MOZ_ASSERT(!cx->zone()->isAtomsZone());
     AssertHeapIsIdle();
     CHECK_THREAD(cx);
 
     script.set(frontend::CompileGlobalScript(cx, scopeKind, options, srcBuf));
@@ -68,17 +69,17 @@ static bool
 CompileLatin1(JSContext* cx, const ReadOnlyCompileOptions& options,
               const char* bytes, size_t length, JS::MutableHandleScript script)
 {
     auto chars = UniqueTwoByteChars(InflateString(cx, bytes, length));
     if (!chars) {
         return false;
     }
 
-    SourceBufferHolder source;
+    SourceText<char16_t> source;
     if (!source.init(cx, std::move(chars), length)) {
         return false;
     }
 
     return CompileSourceBuffer(cx, options, source, script);
 }
 
 static bool
@@ -86,27 +87,27 @@ CompileUtf8(JSContext* cx, const ReadOnl
             const char* bytes, size_t length, JS::MutableHandleScript script)
 {
     auto chars = UniqueTwoByteChars(UTF8CharsToNewTwoByteCharsZ(cx, UTF8Chars(bytes, length),
                                                                 &length).get());
     if (!chars) {
         return false;
     }
 
-    SourceBufferHolder source;
+    SourceText<char16_t> source;
     if (!source.init(cx, std::move(chars), length)) {
         return false;
     }
 
     return CompileSourceBuffer(cx, options, source, script);
 }
 
 bool
 JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
-            SourceBufferHolder& srcBuf, JS::MutableHandleScript script)
+            SourceText<char16_t>& srcBuf, JS::MutableHandleScript script)
 {
     return CompileSourceBuffer(cx, options, srcBuf, script);
 }
 
 bool
 JS::CompileLatin1(JSContext* cx, const ReadOnlyCompileOptions& options,
                   const char* bytes, size_t length, JS::MutableHandleScript script)
 {
@@ -144,17 +145,17 @@ JS::CompileUtf8Path(JSContext* cx, const
 
     CompileOptions options(cx, optionsArg);
     options.setFileAndLine(filename, 1);
     return CompileUtf8File(cx, options, file.fp(), script);
 }
 
 bool
 JS::CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
-                                SourceBufferHolder& srcBuf, JS::MutableHandleScript script)
+                                SourceText<char16_t>& srcBuf, JS::MutableHandleScript script)
 {
     CompileOptions options(cx, optionsArg);
     options.setNonSyntacticScope(true);
     return CompileSourceBuffer(cx, options, srcBuf, script);
 }
 
 bool
 JS::CompileLatin1ForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
@@ -225,17 +226,17 @@ JS_Utf8BufferIsCompilableUnit(JSContext*
  * enclosingScope is a scope, if any (e.g. a WithScope).  If the scope is the
  * global scope, this must be null.
  *
  * enclosingEnv is an environment to use, if it's not the global.
  */
 static bool
 CompileFunction(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
                 HandleAtom name, bool isInvalidName,
-                SourceBufferHolder& srcBuf, uint32_t parameterListEnd,
+                SourceText<char16_t>& srcBuf, uint32_t parameterListEnd,
                 HandleObject enclosingEnv, HandleScope enclosingScope,
                 MutableHandleFunction fun)
 {
     MOZ_ASSERT(!cx->zone()->isAtomsZone());
     AssertHeapIsIdle();
     CHECK_THREAD(cx);
     cx->check(enclosingEnv);
     RootedAtom funAtom(cx);
@@ -267,17 +268,17 @@ CompileFunction(JSContext* cx, const Rea
     }
 
     return true;
 }
 
 static MOZ_MUST_USE bool
 BuildFunctionString(const char* name, size_t nameLen,
                     unsigned nargs, const char* const* argnames,
-                    const SourceBufferHolder& srcBuf, StringBuffer* out,
+                    const SourceText<char16_t>& srcBuf, StringBuffer* out,
                     uint32_t* parameterListEnd)
 {
     MOZ_ASSERT(out);
     MOZ_ASSERT(parameterListEnd);
 
     if (!out->ensureTwoByteChars()) {
        return false;
     }
@@ -319,17 +320,17 @@ BuildFunctionString(const char* name, si
 
     return true;
 }
 
 JS_PUBLIC_API(bool)
 JS::CompileFunction(JSContext* cx, AutoObjectVector& envChain,
                     const ReadOnlyCompileOptions& options,
                     const char* name, unsigned nargs, const char* const* argnames,
-                    SourceBufferHolder& srcBuf, MutableHandleFunction fun)
+                    SourceText<char16_t>& srcBuf, MutableHandleFunction fun)
 {
     RootedObject env(cx);
     RootedScope scope(cx);
     if (!CreateNonSyntacticEnvironmentChain(cx, envChain, &env, &scope)) {
         return false;
     }
 
     size_t nameLen = 0;
@@ -357,17 +358,17 @@ JS::CompileFunction(JSContext* cx, AutoO
     }
 
     size_t newLen = funStr.length();
     UniqueTwoByteChars stolen(funStr.stealChars());
     if (!stolen) {
         return false;
     }
 
-    SourceBufferHolder newSrcBuf;
+    SourceText<char16_t> newSrcBuf;
     if (!newSrcBuf.init(cx, std::move(stolen), newLen)) {
         return false;
     }
 
     return CompileFunction(cx, options, nameAtom, isInvalidName, newSrcBuf, parameterListEnd, env,
                            scope, fun);
 }
 
@@ -378,17 +379,17 @@ JS::CompileFunctionUtf8(JSContext* cx, A
                         const char* bytes, size_t length, MutableHandleFunction fun)
 {
     auto chars = UniqueTwoByteChars(UTF8CharsToNewTwoByteCharsZ(cx, UTF8Chars(bytes, length),
                                                                 &length).get());
     if (!chars) {
         return false;
     }
 
-    SourceBufferHolder source;
+    SourceText<char16_t> source;
     if (!source.init(cx, std::move(chars), length)) {
         return false;
     }
 
     return CompileFunction(cx, envChain, options, name, nargs, argnames,
                            source, fun);
 }
 
@@ -507,17 +508,17 @@ JS::CloneAndExecuteScript(JSContext* cx,
         js::Debugger::onNewScript(cx, script);
     }
     return ExecuteScript(cx, envChain, script, rval.address());
 }
 
 static bool
 Evaluate(JSContext* cx, ScopeKind scopeKind, HandleObject env,
          const ReadOnlyCompileOptions& optionsArg,
-         SourceBufferHolder& srcBuf, MutableHandleValue rval)
+         SourceText<char16_t>& srcBuf, MutableHandleValue rval)
 {
     CompileOptions options(cx, optionsArg);
     MOZ_ASSERT(!cx->zone()->isAtomsZone());
     AssertHeapIsIdle();
     CHECK_THREAD(cx);
     cx->check(env);
     MOZ_ASSERT_IF(!IsGlobalLexicalEnvironment(env), scopeKind == ScopeKind::NonSyntactic);
 
@@ -530,17 +531,17 @@ Evaluate(JSContext* cx, ScopeKind scopeK
     bool result = Execute(cx, script, *env,
                           options.noScriptRval ? nullptr : rval.address());
 
     return result;
 }
 
 static bool
 Evaluate(JSContext* cx, AutoObjectVector& envChain, const ReadOnlyCompileOptions& optionsArg,
-         SourceBufferHolder& srcBuf, MutableHandleValue rval)
+         SourceText<char16_t>& srcBuf, MutableHandleValue rval)
 {
     RootedObject env(cx);
     RootedScope scope(cx);
     if (!CreateNonSyntacticEnvironmentChain(cx, envChain, &env, &scope)) {
         return false;
     }
     return ::Evaluate(cx, scope->kind(), env, optionsArg, srcBuf, rval);
 }
@@ -550,17 +551,17 @@ JS::EvaluateUtf8(JSContext* cx, const Re
                  const char* bytes, size_t length, MutableHandle<Value> rval)
 {
     auto chars = UniqueTwoByteChars(UTF8CharsToNewTwoByteCharsZ(cx, UTF8Chars(bytes, length),
                                                                 &length).get());
     if (!chars) {
         return false;
     }
 
-    SourceBufferHolder srcBuf;
+    SourceText<char16_t> srcBuf;
     if (!srcBuf.init(cx, std::move(chars), length)) {
         return false;
     }
 
     RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
     return ::Evaluate(cx, ScopeKind::Global, globalLexical, options, srcBuf, rval);
 }
 
@@ -568,36 +569,36 @@ extern JS_PUBLIC_API(bool)
 JS::EvaluateLatin1(JSContext* cx, const ReadOnlyCompileOptions& options,
                    const char* bytes, size_t length, MutableHandle<Value> rval)
 {
     auto chars = UniqueTwoByteChars(InflateString(cx, bytes, length));
     if (!chars) {
         return false;
     }
 
-    SourceBufferHolder srcBuf;
+    SourceText<char16_t> srcBuf;
     if (!srcBuf.init(cx, std::move(chars), length)) {
         return false;
     }
 
     RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
     return ::Evaluate(cx, ScopeKind::Global, globalLexical, options, srcBuf, rval);
 }
 
 JS_PUBLIC_API(bool)
 JS::Evaluate(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
-             SourceBufferHolder& srcBuf, MutableHandleValue rval)
+             SourceText<char16_t>& srcBuf, MutableHandleValue rval)
 {
     RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
     return ::Evaluate(cx, ScopeKind::Global, globalLexical, optionsArg, srcBuf, rval);
 }
 
 JS_PUBLIC_API(bool)
 JS::Evaluate(JSContext* cx, AutoObjectVector& envChain, const ReadOnlyCompileOptions& optionsArg,
-             SourceBufferHolder& srcBuf, MutableHandleValue rval)
+             SourceText<char16_t>& srcBuf, MutableHandleValue rval)
 {
     return ::Evaluate(cx, envChain, optionsArg, srcBuf, rval);
 }
 
 JS_PUBLIC_API(bool)
 JS::EvaluateUtf8Path(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
                      const char* filename, MutableHandleValue rval)
 {
--- a/js/src/vm/Debugger.cpp
+++ b/js/src/vm/Debugger.cpp
@@ -22,17 +22,17 @@
 #include "gc/HashUtil.h"
 #include "gc/Marking.h"
 #include "gc/Policy.h"
 #include "gc/PublicIterators.h"
 #include "jit/BaselineDebugModeOSR.h"
 #include "jit/BaselineJIT.h"
 #include "js/CharacterEncoding.h"
 #include "js/Date.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/StableStringChars.h"
 #include "js/UbiNodeBreadthFirst.h"
 #include "js/Vector.h"
 #include "js/Wrapper.h"
 #include "proxy/ScriptedProxyHandler.h"
 #include "util/Text.h"
 #include "vm/ArgumentsObject.h"
 #include "vm/AsyncFunction.h"
@@ -58,17 +58,18 @@
 
 using namespace js;
 
 using JS::AutoStableStringChars;
 using JS::CompileOptions;
 using JS::dbg::AutoEntryMonitor;
 using JS::dbg::Builder;
 using js::frontend::IsIdentifier;
-using JS::SourceBufferHolder;
+using JS::SourceOwnership;
+using JS::SourceText;
 using mozilla::DebugOnly;
 using mozilla::MakeScopeExit;
 using mozilla::Maybe;
 using mozilla::Some;
 using mozilla::Nothing;
 using mozilla::AsVariant;
 using mozilla::TimeDuration;
 using mozilla::TimeStamp;
@@ -8899,18 +8900,18 @@ EvaluateInEnv(JSContext* cx, Handle<Env*
 
     CompileOptions options(cx);
     options.setIsRunOnce(true)
            .setNoScriptRval(false)
            .setFileAndLine(filename, lineno)
            .setIntroductionType("debugger eval")
            .maybeMakeStrictMode(frame && frame.hasScript() ? frame.script()->strict() : false);
 
-    SourceBufferHolder srcBuf;
-    if (!srcBuf.init(cx, chars.begin().get(), chars.length(), SourceBufferHolder::NoOwnership)) {
+    SourceText<char16_t> srcBuf;
+    if (!srcBuf.init(cx, chars.begin().get(), chars.length(), SourceOwnership::Borrowed)) {
         return false;
     }
 
     RootedScript callerScript(cx, frame && frame.hasScript() ? frame.script() : nullptr);
     RootedScript script(cx);
 
     ScopeKind scopeKind;
     if (IsGlobalLexicalEnvironment(env)) {
--- a/js/src/vm/HelperThreads.cpp
+++ b/js/src/vm/HelperThreads.cpp
@@ -9,16 +9,17 @@
 #include "mozilla/Maybe.h"
 #include "mozilla/ScopeExit.h"
 #include "mozilla/Unused.h"
 
 #include "builtin/Promise.h"
 #include "frontend/BytecodeCompiler.h"
 #include "gc/GCInternals.h"
 #include "jit/IonBuilder.h"
+#include "js/SourceText.h"
 #include "js/UniquePtr.h"
 #include "js/Utility.h"
 #include "threading/CpuCount.h"
 #include "util/NativeStack.h"
 #include "vm/Debugger.h"
 #include "vm/ErrorReporting.h"
 #include "vm/SharedImmutableStringsCache.h"
 #include "vm/Time.h"
@@ -497,17 +498,17 @@ ParseTask::trace(JSTracer* trc)
 
 size_t
 ParseTask::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const
 {
     return options.sizeOfExcludingThis(mallocSizeOf) +
            errors.sizeOfExcludingThis(mallocSizeOf);
 }
 
-ScriptParseTask::ScriptParseTask(JSContext* cx, JS::SourceBufferHolder& srcBuf,
+ScriptParseTask::ScriptParseTask(JSContext* cx, JS::SourceText<char16_t>& srcBuf,
                                  JS::OffThreadCompileCallback callback, void* callbackData)
   : ParseTask(ParseTaskKind::Script, cx, callback, callbackData),
     data(std::move(srcBuf))
 {}
 
 void
 ScriptParseTask::parse(JSContext* cx)
 {
@@ -522,17 +523,17 @@ ScriptParseTask::parse(JSContext* cx)
     if (script) {
         scripts.infallibleAppend(script);
     }
     if (sourceObject) {
         sourceObjects.infallibleAppend(sourceObject);
     }
 }
 
-ModuleParseTask::ModuleParseTask(JSContext* cx, JS::SourceBufferHolder& srcBuf,
+ModuleParseTask::ModuleParseTask(JSContext* cx, JS::SourceText<char16_t>& srcBuf,
                                  JS::OffThreadCompileCallback callback, void* callbackData)
   : ParseTask(ParseTaskKind::Module, cx, callback, callbackData),
     data(std::move(srcBuf))
 {}
 
 void
 ModuleParseTask::parse(JSContext* cx)
 {
@@ -862,31 +863,31 @@ StartOffThreadParseTask(JSContext* cx, P
     }
 
     createdForHelper.forget();
     return true;
 }
 
 bool
 js::StartOffThreadParseScript(JSContext* cx, const ReadOnlyCompileOptions& options,
-                              JS::SourceBufferHolder& srcBuf,
+                              JS::SourceText<char16_t>& srcBuf,
                               JS::OffThreadCompileCallback callback, void* callbackData)
 {
     auto task = cx->make_unique<ScriptParseTask>(cx, srcBuf, callback, callbackData);
     if (!task || !StartOffThreadParseTask(cx, task.get(), options)) {
         return false;
     }
 
     Unused << task.release();
     return true;
 }
 
 bool
 js::StartOffThreadParseModule(JSContext* cx, const ReadOnlyCompileOptions& options,
-                              JS::SourceBufferHolder& srcBuf,
+                              JS::SourceText<char16_t>& srcBuf,
                               JS::OffThreadCompileCallback callback, void* callbackData)
 {
     auto task = cx->make_unique<ModuleParseTask>(cx, srcBuf, callback, callbackData);
     if (!task || !StartOffThreadParseTask(cx, task.get(), options)) {
         return false;
     }
 
     Unused << task.release();
--- a/js/src/vm/HelperThreads.h
+++ b/js/src/vm/HelperThreads.h
@@ -20,17 +20,17 @@
 #include "mozilla/TypeTraits.h"
 #include "mozilla/Variant.h"
 
 #include "jsapi.h"
 
 #include "ds/Fifo.h"
 #include "jit/Ion.h"
 #include "js/CompileOptions.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/TypeDecls.h"
 #include "threading/ConditionVariable.h"
 #include "vm/JSContext.h"
 #include "vm/MutexIDs.h"
 
 namespace JS {
 class OffThreadToken {};
 } // namespace JS
@@ -603,22 +603,22 @@ void
 CancelOffThreadParses(JSRuntime* runtime);
 
 /*
  * Start a parse/emit cycle for a stream of source. The characters must stay
  * alive until the compilation finishes.
  */
 bool
 StartOffThreadParseScript(JSContext* cx, const JS::ReadOnlyCompileOptions& options,
-                          JS::SourceBufferHolder& srcBuf,
+                          JS::SourceText<char16_t>& srcBuf,
                           JS::OffThreadCompileCallback callback, void* callbackData);
 
 bool
 StartOffThreadParseModule(JSContext* cx, const JS::ReadOnlyCompileOptions& options,
-                          JS::SourceBufferHolder& srcBuf,
+                          JS::SourceText<char16_t>& srcBuf,
                           JS::OffThreadCompileCallback callback, void* callbackData);
 
 bool
 StartOffThreadDecodeScript(JSContext* cx, const JS::ReadOnlyCompileOptions& options,
                            const JS::TranscodeRange& range,
                            JS::OffThreadCompileCallback callback, void* callbackData);
 
 #if defined(JS_BUILD_BINAST)
@@ -731,28 +731,28 @@ struct ParseTask : public mozilla::Linke
     size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
     size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
         return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
     }
 };
 
 struct ScriptParseTask : public ParseTask
 {
-    JS::SourceBufferHolder data;
+    JS::SourceText<char16_t> data;
 
-    ScriptParseTask(JSContext* cx, JS::SourceBufferHolder& srcBuf,
+    ScriptParseTask(JSContext* cx, JS::SourceText<char16_t>& srcBuf,
                     JS::OffThreadCompileCallback callback, void* callbackData);
     void parse(JSContext* cx) override;
 };
 
 struct ModuleParseTask : public ParseTask
 {
-    JS::SourceBufferHolder data;
+    JS::SourceText<char16_t> data;
 
-    ModuleParseTask(JSContext* cx, JS::SourceBufferHolder& srcBuf,
+    ModuleParseTask(JSContext* cx, JS::SourceText<char16_t>& srcBuf,
                     JS::OffThreadCompileCallback callback, void* callbackData);
     void parse(JSContext* cx) override;
 };
 
 struct ScriptDecodeTask : public ParseTask
 {
     const JS::TranscodeRange range;
 
--- a/js/src/vm/JSFunction.cpp
+++ b/js/src/vm/JSFunction.cpp
@@ -30,18 +30,17 @@
 #include "frontend/TokenStream.h"
 #include "gc/Marking.h"
 #include "gc/Policy.h"
 #include "jit/InlinableNatives.h"
 #include "jit/Ion.h"
 #include "js/CallNonGenericMethod.h"
 #include "js/CompileOptions.h"
 #include "js/Proxy.h"
-
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/StableStringChars.h"
 #include "js/Wrapper.h"
 #include "util/StringBuffer.h"
 #include "vm/AsyncFunction.h"
 #include "vm/AsyncIteration.h"
 #include "vm/Debugger.h"
 #include "vm/GlobalObject.h"
 #include "vm/Interpreter.h"
@@ -65,17 +64,18 @@ using namespace js;
 using mozilla::ArrayLength;
 using mozilla::CheckedInt;
 using mozilla::Maybe;
 using mozilla::Some;
 using mozilla::Utf8Unit;
 
 using JS::AutoStableStringChars;
 using JS::CompileOptions;
-using JS::SourceBufferHolder;
+using JS::SourceOwnership;
+using JS::SourceText;
 
 static bool
 fun_enumerate(JSContext* cx, HandleObject obj)
 {
     MOZ_ASSERT(obj->is<JSFunction>());
 
     RootedId id(cx);
     bool found;
@@ -2110,20 +2110,20 @@ CreateDynamicFunction(JSContext* cx, con
 
     // Steps 7.a-b, 8.a-b, 9.a-b, 16-28.
     AutoStableStringChars stableChars(cx);
     if (!stableChars.initTwoByte(cx, functionText)) {
         return false;
     }
 
     mozilla::Range<const char16_t> chars = stableChars.twoByteRange();
-    SourceBufferHolder::Ownership ownership = stableChars.maybeGiveOwnershipToCaller()
-                                              ? SourceBufferHolder::GiveOwnership
-                                              : SourceBufferHolder::NoOwnership;
-    SourceBufferHolder srcBuf;
+    SourceOwnership ownership = stableChars.maybeGiveOwnershipToCaller()
+                                ? SourceOwnership::TakeOwnership
+                                : SourceOwnership::Borrowed;
+    SourceText<char16_t> srcBuf;
     if (!srcBuf.init(cx, chars.begin().get(), chars.length(), ownership)) {
         return false;
     }
 
     if (isAsync) {
         if (isGenerator) {
             if (!CompileStandaloneAsyncGenerator(cx, &fun, options, srcBuf, parameterListEnd)) {
                 return false;
--- a/js/src/vm/JSScript.cpp
+++ b/js/src/vm/JSScript.cpp
@@ -35,17 +35,17 @@
 #include "gc/FreeOp.h"
 #include "jit/BaselineJIT.h"
 #include "jit/Ion.h"
 #include "jit/IonCode.h"
 #include "jit/JitRealm.h"
 #include "js/CompileOptions.h"
 #include "js/MemoryMetrics.h"
 #include "js/Printf.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/UniquePtr.h"
 #include "js/Utility.h"
 #include "js/Wrapper.h"
 #include "util/StringBuffer.h"
 #include "util/Text.h"
 #include "vm/ArgumentsObject.h"
 #include "vm/BytecodeIterator.h"
 #include "vm/BytecodeLocation.h"
@@ -79,17 +79,17 @@ using namespace js;
 using mozilla::Maybe;
 using mozilla::PodCopy;
 using mozilla::PointerRangeSize;
 using mozilla::Utf8AsUnsignedChars;
 using mozilla::Utf8Unit;
 
 using JS::CompileOptions;
 using JS::ReadOnlyCompileOptions;
-using JS::SourceBufferHolder;
+using JS::SourceText;
 
 template<XDRMode mode>
 XDRResult
 js::XDRScriptConst(XDRState<mode>* xdr, MutableHandleValue vp)
 {
     JSContext* cx = xdr->cx();
 
     enum ConstTag {
@@ -1997,25 +1997,25 @@ ScriptSource::setCompressedSource(JSCont
         return false;
     }
 
     setCompressedSource<Unit>(std::move(*deduped), sourceLength);
     return true;
 }
 
 bool
-ScriptSource::setSourceCopy(JSContext* cx, SourceBufferHolder& srcBuf)
+ScriptSource::setSourceCopy(JSContext* cx, SourceText<char16_t>& srcBuf)
 {
     MOZ_ASSERT(!hasSourceText());
 
     JSRuntime* runtime = cx->zone()->runtimeFromAnyThread();
     auto& cache = runtime->sharedImmutableStrings();
     auto deduped = cache.getOrCreate(srcBuf.get(), srcBuf.length(), [&srcBuf]() {
-        return srcBuf.ownsChars()
-               ? UniqueTwoByteChars(srcBuf.take())
+        return srcBuf.ownsUnits()
+               ? UniqueTwoByteChars(srcBuf.takeChars())
                : DuplicateString(srcBuf.get(), srcBuf.length());
     });
     if (!deduped) {
         ReportOutOfMemory(cx);
         return false;
     }
 
     setSource<char16_t>(std::move(*deduped));
--- a/js/src/vm/JSScript.h
+++ b/js/src/vm/JSScript.h
@@ -40,16 +40,17 @@
 #include "vm/NativeObject.h"
 #include "vm/Scope.h"
 #include "vm/Shape.h"
 #include "vm/SharedImmutableStringsCache.h"
 #include "vm/Time.h"
 
 namespace JS {
 struct ScriptSourceInfo;
+template<typename UnitT> class SourceText;
 } // namespace JS
 
 namespace js {
 
 namespace jit {
     struct BaselineScript;
     struct IonScriptCounts;
 } // namespace jit
@@ -665,17 +666,17 @@ class ScriptSource
         MOZ_ASSERT(refs != 0);
         if (--refs == 0) {
             js_delete(this);
         }
     }
     MOZ_MUST_USE bool initFromOptions(JSContext* cx,
                                       const JS::ReadOnlyCompileOptions& options,
                                       const mozilla::Maybe<uint32_t>& parameterListEnd = mozilla::Nothing());
-    MOZ_MUST_USE bool setSourceCopy(JSContext* cx, JS::SourceBufferHolder& srcBuf);
+    MOZ_MUST_USE bool setSourceCopy(JSContext* cx, JS::SourceText<char16_t>& srcBuf);
     void setSourceRetrievable() { sourceRetrievable_ = true; }
     bool sourceRetrievable() const { return sourceRetrievable_; }
     bool hasSourceText() const { return hasUncompressedSource() || hasCompressedSource(); }
     bool hasBinASTSource() const { return data.is<BinAST>(); }
 
     void setBinASTSourceMetadata(frontend::BinASTSourceMetadata* metadata) {
         MOZ_ASSERT(hasBinASTSource());
         binASTMetadata_.reset(metadata);
--- a/js/src/vm/OffThreadScriptCompilation.cpp
+++ b/js/src/vm/OffThreadScriptCompilation.cpp
@@ -84,17 +84,17 @@ JS_PUBLIC_API(bool)
 JS::CanDecodeBinASTOffThread(JSContext* cx, const ReadOnlyCompileOptions& options, size_t length)
 {
     return CanDoOffThread(cx, options, length, OffThread::DecodeBinAST);
 }
 #endif
 
 JS_PUBLIC_API(bool)
 JS::CompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options,
-                     JS::SourceBufferHolder& srcBuf,
+                     JS::SourceText<char16_t>& srcBuf,
                      OffThreadCompileCallback callback, void* callbackData)
 {
     MOZ_ASSERT(CanCompileOffThread(cx, options, srcBuf.length()));
     return StartOffThreadParseScript(cx, options, srcBuf, callback, callbackData);
 }
 
 JS_PUBLIC_API(JSScript*)
 JS::FinishOffThreadScript(JSContext* cx, JS::OffThreadToken* token)
@@ -109,17 +109,17 @@ JS::CancelOffThreadScript(JSContext* cx,
 {
     MOZ_ASSERT(cx);
     MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
     HelperThreadState().cancelParseTask(cx->runtime(), ParseTaskKind::Script, token);
 }
 
 JS_PUBLIC_API(bool)
 JS::CompileOffThreadModule(JSContext* cx, const ReadOnlyCompileOptions& options,
-                           JS::SourceBufferHolder& srcBuf,
+                           JS::SourceText<char16_t>& srcBuf,
                            OffThreadCompileCallback callback, void* callbackData)
 {
     MOZ_ASSERT(CanCompileOffThread(cx, options, srcBuf.length()));
     return StartOffThreadParseModule(cx, options, srcBuf, callback, callbackData);
 }
 
 JS_PUBLIC_API(JSObject*)
 JS::FinishOffThreadModule(JSContext* cx, JS::OffThreadToken* token)
--- a/js/src/wasm/AsmJS.cpp
+++ b/js/src/wasm/AsmJS.cpp
@@ -31,17 +31,17 @@
 #include "jsutil.h"
 
 #include "builtin/String.h"
 #include "frontend/ParseNode.h"
 #include "frontend/Parser.h"
 #include "gc/Policy.h"
 #include "js/MemoryMetrics.h"
 #include "js/Printf.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/StableStringChars.h"
 #include "js/Wrapper.h"
 #include "util/StringBuffer.h"
 #include "util/Text.h"
 #include "vm/ErrorReporting.h"
 #include "vm/SelfHosting.h"
 #include "vm/Time.h"
 #include "vm/TypedArrayObject.h"
@@ -71,17 +71,18 @@ using mozilla::IsNegativeZero;
 using mozilla::IsPositiveZero;
 using mozilla::IsPowerOfTwo;
 using mozilla::PodZero;
 using mozilla::PositiveInfinity;
 using mozilla::Unused;
 using JS::AsmJSOption;
 using JS::AutoStableStringChars;
 using JS::GenericNaN;
-using JS::SourceBufferHolder;
+using JS::SourceOwnership;
+using JS::SourceText;
 
 /*****************************************************************************/
 
 // The asm.js valid heap lengths are precisely the WASM valid heap lengths for ARM
 // greater or equal to MinHeapLength
 static const size_t MinHeapLength = PageSize;
 
 static uint32_t
@@ -6711,22 +6712,22 @@ HandleInstantiationFailure(JSContext* cx
         options.strictOption = true;
     }
 
     AutoStableStringChars stableChars(cx);
     if (!stableChars.initTwoByte(cx, src)) {
         return false;
     }
 
-    SourceBufferHolder srcBuf;
+    SourceText<char16_t> srcBuf;
 
     const char16_t* chars = stableChars.twoByteRange().begin().get();
-    SourceBufferHolder::Ownership ownership = stableChars.maybeGiveOwnershipToCaller()
-                                              ? SourceBufferHolder::GiveOwnership
-                                              : SourceBufferHolder::NoOwnership;
+    SourceOwnership ownership = stableChars.maybeGiveOwnershipToCaller()
+                                ? SourceOwnership::TakeOwnership
+                                : SourceOwnership::Borrowed;
     if (!srcBuf.init(cx, chars, end - begin, ownership)) {
         return false;
     }
 
     if (!frontend::CompileStandaloneFunction(cx, &fun, options, srcBuf, Nothing())) {
         return false;
     }
 
--- a/js/xpconnect/loader/ChromeScriptLoader.cpp
+++ b/js/xpconnect/loader/ChromeScriptLoader.cpp
@@ -9,17 +9,17 @@
 #include "nsIURI.h"
 #include "nsIChannel.h"
 #include "nsNetUtil.h"
 #include "nsThreadUtils.h"
 
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/Utility.h"
 
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/ChromeUtils.h"
 #include "mozilla/dom/Promise.h"
 #include "mozilla/dom/ScriptLoader.h"
 #include "mozilla/HoldDropJSObjects.h"
 #include "mozilla/SystemGroup.h"
@@ -136,17 +136,17 @@ OffThreadScriptLoaderCallback(JS::OffThr
     SystemGroup::Dispatch(TaskCategory::Other, scriptCompiler.forget());
 }
 
 bool
 AsyncScriptCompiler::StartCompile(JSContext* aCx)
 {
     Rooted<JSObject*> global(aCx, mGlobalObject->GetGlobalJSObject());
 
-    JS::SourceBufferHolder srcBuf;
+    JS::SourceText<char16_t> srcBuf;
     if (!srcBuf.init(aCx, std::move(mScriptText), mScriptLength)) {
         return false;
     }
 
     if (JS::CanCompileOffThread(aCx, mOptions, mScriptLength)) {
         if (!JS::CompileOffThread(aCx, mOptions, srcBuf,
                                   OffThreadScriptLoaderCallback,
                                   static_cast<void*>(this))) {
--- a/js/xpconnect/loader/mozJSSubScriptLoader.cpp
+++ b/js/xpconnect/loader/mozJSSubScriptLoader.cpp
@@ -15,17 +15,17 @@
 #include "nsNetCID.h"
 #include "nsNetUtil.h"
 #include "nsIFileURL.h"
 
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "xpcprivate.h" // For xpc::OptionsBase
 #include "js/CompilationAndEvaluation.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/Wrapper.h"
 
 #include "mozilla/ContentPrincipal.h"
 #include "mozilla/dom/Promise.h"
 #include "mozilla/dom/ToJSValue.h"
 #include "mozilla/dom/ScriptLoader.h"
 #include "mozilla/HoldDropJSObjects.h"
 #include "mozilla/ScriptPreloader.h"
@@ -160,17 +160,17 @@ PrepareScript(nsIURI* uri,
         nsresult rv =
             ScriptLoader::ConvertToUTF16(nullptr, reinterpret_cast<const uint8_t*>(buf), len,
                                          charset, nullptr, scriptBuf, scriptLength);
         if (NS_FAILED(rv)) {
             ReportError(cx, LOAD_ERROR_BADCHARSET, uri);
             return false;
         }
 
-        JS::SourceBufferHolder srcBuf;
+        JS::SourceText<char16_t> srcBuf;
         if (!srcBuf.init(cx, JS::UniqueTwoByteChars(scriptBuf), scriptLength)) {
             return false;
         }
 
         if (wantGlobalScript) {
             return JS::Compile(cx, options, srcBuf, script);
         }
         return JS::CompileForNonSyntacticScope(cx, options, srcBuf, script);
--- a/js/xpconnect/src/Sandbox.cpp
+++ b/js/xpconnect/src/Sandbox.cpp
@@ -8,17 +8,17 @@
  * The Components.Sandbox object.
  */
 
 #include "AccessCheck.h"
 #include "jsfriendapi.h"
 #include "js/CharacterEncoding.h"
 #include "js/CompilationAndEvaluation.h"
 #include "js/Proxy.h"
-#include "js/SourceBufferHolder.h"
+#include "js/SourceText.h"
 #include "js/StructuredClone.h"
 #include "nsContentUtils.h"
 #include "nsGlobalWindow.h"
 #include "nsIException.h" // for nsIStackFrame
 #include "nsIScriptContext.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsIURI.h"
 #include "nsJSUtils.h"
@@ -1922,18 +1922,18 @@ xpc::EvalInSandbox(JSContext* cx, Handle
         JSAutoRealm ar(sandcx, sandbox);
 
         JS::CompileOptions options(sandcx);
         options.setFileAndLine(filenameBuf.get(), lineNo);
         MOZ_ASSERT(JS_IsGlobalObject(sandbox));
 
         const nsPromiseFlatString& flat = PromiseFlatString(source);
 
-        JS::SourceBufferHolder buffer;
-        ok = buffer.init(sandcx, flat.get(), flat.Length(), JS::SourceBufferHolder::NoOwnership) &&
+        JS::SourceText<char16_t> buffer;
+        ok = buffer.init(sandcx, flat.get(), flat.Length(), JS::SourceOwnership::Borrowed) &&
              JS::Evaluate(sandcx, options, buffer, &v);
 
         // If the sandbox threw an exception, grab it off the context.
         if (aes.HasException()) {
             if (!aes.StealException(&exn)) {
                 return NS_ERROR_OUT_OF_MEMORY;
             }
         }