Bug 1663365 - Create a new js/public/String.h header seeded with the inline string functions previously found in jsfriendapi.h. (More functions ought be added/moved here, but these make a good start.) r=jandem,geckoview-reviewers,agi
authorJeff Walden <jwalden@mit.edu>
Tue, 08 Sep 2020 22:50:52 +0000
changeset 547929 d77193517dc56d7c5c6b897e66708e48d8f944db
parent 547928 ea452bb92e6aa1f39f99125c93a6f038b199d765
child 547930 1b452e9cdd96346be4004e9c3744b19196e6365e
push id37767
push userdluca@mozilla.com
push dateWed, 09 Sep 2020 09:39:57 +0000
treeherdermozilla-central@6cc2266faca2 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersjandem, geckoview-reviewers, agi
bugs1663365
milestone82.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 1663365 - Create a new js/public/String.h header seeded with the inline string functions previously found in jsfriendapi.h. (More functions ought be added/moved here, but these make a good start.) r=jandem,geckoview-reviewers,agi Differential Revision: https://phabricator.services.mozilla.com/D89330
dom/base/nsJSUtils.h
dom/bindings/BindingUtils.cpp
dom/bindings/BindingUtils.h
dom/bindings/Codegen.py
dom/bindings/DOMJSProxyHandler.h
js/public/CharacterEncoding.h
js/public/GCAPI.h
js/public/StableStringChars.h
js/public/String.h
js/public/shadow/String.h
js/rust/build.rs
js/rust/etc/wrapper.hpp
js/rust/src/conversions.rs
js/src/builtin/SelfHostingDefines.h
js/src/builtin/TestingFunctions.cpp
js/src/debugger/Object.cpp
js/src/jsapi-tests/testDeduplication.cpp
js/src/jsapi-tests/testScriptSourceCompression.cpp
js/src/jsapi.cpp
js/src/jsapi.h
js/src/jsfriendapi.cpp
js/src/jsfriendapi.h
js/src/moz.build
js/src/vm/StringType.h
js/src/wasm/WasmValidate.cpp
js/xpconnect/src/JSServices.cpp
js/xpconnect/src/XPCConvert.cpp
js/xpconnect/src/xpcpublic.h
widget/android/EventDispatcher.cpp
xpcom/ds/tools/perfecthash.py
--- a/dom/base/nsJSUtils.h
+++ b/dom/base/nsJSUtils.h
@@ -19,16 +19,17 @@
 #include "mozilla/Utf8.h"  // mozilla::Utf8Unit
 
 #include "GeckoProfiler.h"
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "js/Conversions.h"
 #include "js/SourceText.h"
 #include "js/StableStringChars.h"
+#include "js/String.h"  // JS::{,Lossy}CopyLinearStringChars, JS::CopyStringChars, JS::Get{,Linear}StringLength, JS::MaxStringLength, JS::StringHasLatin1Chars
 #include "nsString.h"
 #include "xpcpublic.h"
 
 class nsIScriptContext;
 class nsIScriptElement;
 class nsIScriptGlobalObject;
 class nsXBLPrototypeBinding;
 
@@ -240,17 +241,17 @@ inline void AssignFromStringBuffer(nsStr
                                    nsAString& dest) {
   buffer->ToString(len, dest);
 }
 
 template <typename T, typename std::enable_if_t<std::is_same<
                           typename T::char_type, char16_t>::value>* = nullptr>
 inline bool AssignJSString(JSContext* cx, T& dest, JSString* s) {
   size_t len = JS::GetStringLength(s);
-  static_assert(js::MaxStringLength < (1 << 30),
+  static_assert(JS::MaxStringLength < (1 << 30),
                 "Shouldn't overflow here or in SetCapacity");
 
   const char16_t* chars;
   if (XPCStringConvert::MaybeGetDOMStringChars(s, &chars)) {
     // The characters represent an existing string buffer that we shared with
     // JS.  We can share that buffer ourselves if the string corresponds to the
     // whole buffer; otherwise we have to copy.
     if (chars[len] == '\0') {
@@ -267,28 +268,28 @@ inline bool AssignJSString(JSContext* cx
 
   // We don't bother checking for a dynamic-atom external string, because we'd
   // just need to copy out of it anyway.
 
   if (MOZ_UNLIKELY(!dest.SetLength(len, mozilla::fallible))) {
     JS_ReportOutOfMemory(cx);
     return false;
   }
-  return js::CopyStringChars(cx, dest.BeginWriting(), s, len);
+  return JS::CopyStringChars(cx, dest.BeginWriting(), s, len);
 }
 
 // Specialization for UTF8String.
 template <typename T, typename std::enable_if_t<std::is_same<
                           typename T::char_type, char>::value>* = nullptr>
 inline bool AssignJSString(JSContext* cx, T& dest, JSString* s) {
   using namespace mozilla;
   CheckedInt<size_t> bufLen(JS::GetStringLength(s));
   // From the contract for JS_EncodeStringToUTF8BufferPartial, to guarantee that
   // the whole string is converted.
-  if (js::StringHasLatin1Chars(s)) {
+  if (JS::StringHasLatin1Chars(s)) {
     bufLen *= 2;
   } else {
     bufLen *= 3;
   }
 
   if (MOZ_UNLIKELY(!bufLen.isValid())) {
     JS_ReportOutOfMemory(cx);
     return false;
@@ -316,29 +317,29 @@ inline bool AssignJSString(JSContext* cx
   Tie(read, written) = *maybe;
 
   MOZ_ASSERT(read == JS::GetStringLength(s));
   handle.Finish(written, kAllowShrinking);
   return true;
 }
 
 inline void AssignJSLinearString(nsAString& dest, JSLinearString* s) {
-  size_t len = js::GetLinearStringLength(s);
-  static_assert(js::MaxStringLength < (1 << 30),
+  size_t len = JS::GetLinearStringLength(s);
+  static_assert(JS::MaxStringLength < (1 << 30),
                 "Shouldn't overflow here or in SetCapacity");
   dest.SetLength(len);
-  js::CopyLinearStringChars(dest.BeginWriting(), s, len);
+  JS::CopyLinearStringChars(dest.BeginWriting(), s, len);
 }
 
 inline void AssignJSLinearString(nsACString& dest, JSLinearString* s) {
-  size_t len = js::GetLinearStringLength(s);
-  static_assert(js::MaxStringLength < (1 << 30),
+  size_t len = JS::GetLinearStringLength(s);
+  static_assert(JS::MaxStringLength < (1 << 30),
                 "Shouldn't overflow here or in SetCapacity");
   dest.SetLength(len);
-  js::CopyLinearStringChars(dest.BeginWriting(), s, len);
+  JS::LossyCopyLinearStringChars(dest.BeginWriting(), s, len);
 }
 
 template <typename T>
 class nsTAutoJSLinearString : public nsTAutoString<T> {
  public:
   explicit nsTAutoJSLinearString(JSLinearString* str) {
     AssignJSLinearString(*this, str);
   }
--- a/dom/bindings/BindingUtils.cpp
+++ b/dom/bindings/BindingUtils.cpp
@@ -18,16 +18,17 @@
 #include "mozilla/Unused.h"
 #include "mozilla/UseCounter.h"
 
 #include "AccessCheck.h"
 #include "js/friend/StackLimits.h"  // js::CheckRecursionLimitConservative
 #include "js/Id.h"
 #include "js/JSON.h"
 #include "js/StableStringChars.h"
+#include "js/String.h"  // JS::GetStringLength, JS::MaxStringLength, JS::StringHasLatin1Chars
 #include "js/Symbol.h"
 #include "jsfriendapi.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsContentUtils.h"
 #include "nsGlobalWindow.h"
 #include "nsHTMLTags.h"
 #include "nsIDOMGlobalPropertyInitializer.h"
 #include "nsINode.h"
@@ -2653,17 +2654,17 @@ bool ConvertJSValueToByteString(BindingC
     if (!s) {
       return false;
     }
   }
 
   // Conversion from Javascript string to ByteString is only valid if all
   // characters < 256. This is always the case for Latin1 strings.
   size_t length;
-  if (!js::StringHasLatin1Chars(s)) {
+  if (!JS::StringHasLatin1Chars(s)) {
     // ThrowErrorMessage can GC, so we first scan the string for bad chars
     // and report the error outside the AutoCheckCannotGC scope.
     bool foundBadChar = false;
     size_t badCharIndex;
     char16_t badChar;
     {
       JS::AutoCheckCannotGC nogc;
       const char16_t* chars =
@@ -2699,17 +2700,17 @@ bool ConvertJSValueToByteString(BindingC
       cx.ThrowErrorMessage<MSG_INVALID_BYTESTRING>(sourceDescription, index,
                                                    badCharArray);
       return false;
     }
   } else {
     length = JS::GetStringLength(s);
   }
 
-  static_assert(js::MaxStringLength < UINT32_MAX,
+  static_assert(JS::MaxStringLength < UINT32_MAX,
                 "length+1 shouldn't overflow");
 
   if (!result.SetLength(length, fallible)) {
     return false;
   }
 
   if (!JS_EncodeStringToBuffer(cx, s, result.BeginWriting(), length)) {
     return false;
--- a/dom/bindings/BindingUtils.h
+++ b/dom/bindings/BindingUtils.h
@@ -9,16 +9,17 @@
 
 #include <type_traits>
 
 #include "jsfriendapi.h"
 #include "js/CharacterEncoding.h"
 #include "js/Conversions.h"
 #include "js/friend/WindowProxy.h"  // js::IsWindow, js::IsWindowProxy, js::ToWindowProxyIfWindow
 #include "js/MemoryFunctions.h"
+#include "js/String.h"  // JS::GetLatin1LinearStringChars, JS::GetTwoByteLinearStringChars, JS::GetLinearStringLength, JS::LinearStringHasLatin1Chars, JS::StringHasLatin1Chars
 #include "js/Wrapper.h"
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/Array.h"
 #include "mozilla/Assertions.h"
 #include "mozilla/DeferredFinalize.h"
 #include "mozilla/UniquePtr.h"
 #include "mozilla/dom/BindingCallContext.h"
 #include "mozilla/dom/BindingDeclarations.h"
@@ -1317,17 +1318,17 @@ inline bool FindEnumStringIndex(BindingC
   JS::RootedString str(cx, JS::ToString(cx, v));
   if (!str) {
     return false;
   }
 
   {
     size_t length;
     JS::AutoCheckCannotGC nogc;
-    if (js::StringHasLatin1Chars(str)) {
+    if (JS::StringHasLatin1Chars(str)) {
       const JS::Latin1Char* chars =
           JS_GetLatin1StringCharsAndLength(cx, nogc, str, &length);
       if (!chars) {
         return false;
       }
       *index = FindEnumStringIndexImpl(chars, length, values);
     } else {
       const char16_t* chars =
@@ -3138,24 +3139,24 @@ bool IsGetterEnabled(JSContext* aCx, JS:
                      const Prefable<const JSPropertySpec>* aAttributes);
 
 // A class that can be used to examine the chars of a linear string.
 class StringIdChars {
  public:
   // Require a non-const ref to an AutoRequireNoGC to prevent callers
   // from passing temporaries.
   StringIdChars(JS::AutoRequireNoGC& nogc, JSLinearString* str) {
-    mIsLatin1 = js::LinearStringHasLatin1Chars(str);
+    mIsLatin1 = JS::LinearStringHasLatin1Chars(str);
     if (mIsLatin1) {
-      mLatin1Chars = js::GetLatin1LinearStringChars(nogc, str);
+      mLatin1Chars = JS::GetLatin1LinearStringChars(nogc, str);
     } else {
-      mTwoByteChars = js::GetTwoByteLinearStringChars(nogc, str);
+      mTwoByteChars = JS::GetTwoByteLinearStringChars(nogc, str);
     }
 #ifdef DEBUG
-    mLength = js::GetLinearStringLength(str);
+    mLength = JS::GetLinearStringLength(str);
 #endif  // DEBUG
   }
 
   MOZ_ALWAYS_INLINE char16_t operator[](size_t index) {
     MOZ_ASSERT(index < mLength);
     if (mIsLatin1) {
       return mLatin1Chars[index];
     }
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -12354,33 +12354,33 @@ class CGCountMaybeMissingProperty(CGAbst
         instrumentedProps = self.descriptor.instrumentedProps
         if not instrumentedProps:
             return body + dedent(
                 """
                 return false;
                 """)
 
         lengths = set(len(prop) for prop in instrumentedProps)
-        switchDesc = { 'condition': 'js::GetLinearStringLength(str)',
+        switchDesc = { 'condition': 'JS::GetLinearStringLength(str)',
                        'precondition': '' }
         switchDesc['cases'] = dict()
         for length in sorted(lengths):
             switchDesc['cases'][str(length)] = self.charSwitch(
                 list(sorted(prop for prop in instrumentedProps
                             if len(prop) == length)),
                 0)
 
         return body + fill(
             """
             MOZ_ASSERT(StaticPrefs::${pref}() && JSID_IS_ATOM(id));
             Maybe<UseCounter> counter;
             {
               // Scope for our no-GC section, so we don't need to rely on SetUseCounter not GCing.
               JS::AutoCheckCannotGC nogc;
-              JSLinearString* str = js::AtomToLinearString(JSID_TO_ATOM(id));
+              JSLinearString* str = JS::AtomToLinearString(JSID_TO_ATOM(id));
               // Don't waste time fetching the chars until we've done the length switch.
               $*{switch}
             }
             if (counter) {
               SetUseCounter(proxy, *counter);
               return true;
             }
 
@@ -15497,16 +15497,20 @@ class CGBindingRoot(CGThing):
             iface = desc.interface
             return any(m.getExtendedAttribute("Deprecated") for m in iface.members + [iface])
 
         bindingHeaders["mozilla/dom/Document.h"] = any(
             descriptorDeprecated(d) for d in descriptors)
 
         bindingHeaders["mozilla/dom/DOMJSProxyHandler.h"] = any(
             d.concrete and d.proxy for d in descriptors)
+
+        bindingHeaders["js/String.h"] = any(
+            d.needsMissingPropUseCounters for d in descriptors)
+
         hasCrossOriginObjects = any(
             d.concrete and d.isMaybeCrossOriginObject() for d in descriptors)
         bindingHeaders["mozilla/dom/MaybeCrossOriginObject.h"] = hasCrossOriginObjects
         bindingHeaders["AccessCheck.h"] = hasCrossOriginObjects
         hasCEReactions = any(d.hasCEReactions() for d in descriptors)
         bindingHeaders["mozilla/dom/CustomElementRegistry.h"] = hasCEReactions
         bindingHeaders["mozilla/dom/DocGroup.h"] = hasCEReactions
 
@@ -18752,16 +18756,17 @@ class GlobalGenRoots():
         # Add the includes
         defineIncludes = [CGHeaders.getDeclarationFilename(desc.interface)
                           for desc in config.getDescriptors(hasInterfaceObject=True,
                                                             isExposedInWindow=True,
                                                             register=True)]
         defineIncludes.append('mozilla/dom/WebIDLGlobalNameHash.h')
         defineIncludes.append('mozilla/dom/PrototypeList.h')
         defineIncludes.append('mozilla/PerfectHash.h')
+        defineIncludes.append('js/String.h')
         curr = CGHeaders([], [], [], [], [], defineIncludes, 'RegisterBindings',
                          curr)
 
         # Add include guards.
         curr = CGIncludeGuard('RegisterBindings', curr)
 
         # Done.
         return curr
--- a/dom/bindings/DOMJSProxyHandler.h
+++ b/dom/bindings/DOMJSProxyHandler.h
@@ -8,16 +8,17 @@
 #define mozilla_dom_DOMJSProxyHandler_h
 
 #include "mozilla/Attributes.h"
 #include "mozilla/Likely.h"
 #include "mozilla/TextUtils.h"
 
 #include "jsapi.h"
 #include "js/Proxy.h"
+#include "js/String.h"  // JS::AtomToLinearString, JS::GetLinearString{CharAt,Length}
 #include "nsString.h"
 
 namespace mozilla {
 namespace dom {
 
 /**
  * DOM proxies store the expando object in the private slot.
  *
@@ -185,22 +186,22 @@ inline uint32_t GetArrayIndexFromId(JS::
   }
   if (MOZ_LIKELY(id.get() == s_length_id)) {
     return UINT32_MAX;
   }
   if (MOZ_UNLIKELY(!JSID_IS_ATOM(id))) {
     return UINT32_MAX;
   }
 
-  JSLinearString* str = js::AtomToLinearString(JSID_TO_ATOM(id));
-  if (MOZ_UNLIKELY(js::GetLinearStringLength(str) == 0)) {
+  JSLinearString* str = JS::AtomToLinearString(JSID_TO_ATOM(id));
+  if (MOZ_UNLIKELY(JS::GetLinearStringLength(str) == 0)) {
     return UINT32_MAX;
   }
 
-  char16_t firstChar = js::GetLinearStringCharAt(str, 0);
+  char16_t firstChar = JS::GetLinearStringCharAt(str, 0);
   if (MOZ_LIKELY(IsAsciiLowercaseAlpha(firstChar))) {
     return UINT32_MAX;
   }
 
   uint32_t i;
   return js::StringIsArrayIndex(str, &i) ? i : UINT32_MAX;
 }
 
--- a/js/public/CharacterEncoding.h
+++ b/js/public/CharacterEncoding.h
@@ -305,17 +305,17 @@ JS_PUBLIC_API size_t GetDeflatedUTF8Stri
  * exhausted or too little space is available in |dst| to fit the scalar
  * value. Lone surrogates are converted to REPLACEMENT CHARACTER. Return
  * the number of bytes of |dst| that were filled.
  *
  * Use |JS_EncodeStringToUTF8BufferPartial| if your string isn't already
  * linear.
  *
  * Given |JSString* str = JS_FORGET_STRING_LINEARNESS(src)|,
- * if |JS_StringHasLatin1Chars(str)|, then |src| is always fully converted
+ * if |JS::StringHasLatin1Chars(str)|, then |src| is always fully converted
  * if |dst.Length() >= JS_GetStringLength(str) * 2|. Otherwise |src| is
  * always fully converted if |dst.Length() >= JS_GetStringLength(str) * 3|.
  *
  * The exact space required is always |GetDeflatedUTF8StringLength(str)|.
  */
 JS_PUBLIC_API size_t DeflateStringToUTF8Buffer(JSLinearString* src,
                                                mozilla::Span<char> dst);
 
--- a/js/public/GCAPI.h
+++ b/js/public/GCAPI.h
@@ -1111,22 +1111,16 @@ extern JS_PUBLIC_API JSString* JS_NewExt
  * external string allocated by a previous call and |*allocatedExternal| is set
  * to false. If |*allocatedExternal| is false, |fin| won't be called.
  */
 extern JS_PUBLIC_API JSString* JS_NewMaybeExternalString(
     JSContext* cx, const char16_t* chars, size_t length,
     const JSExternalStringCallbacks* callbacks, bool* allocatedExternal);
 
 /**
- * Return whether 'str' was created with JS_NewExternalString or
- * JS_NewExternalStringWithClosure.
- */
-extern JS_PUBLIC_API bool JS_IsExternalString(JSString* str);
-
-/**
  * Return the 'callbacks' arg passed to JS_NewExternalString or
  * JS_NewMaybeExternalString.
  */
 extern JS_PUBLIC_API const JSExternalStringCallbacks*
 JS_GetExternalStringCallbacks(JSString* str);
 
 namespace JS {
 
--- a/js/public/StableStringChars.h
+++ b/js/public/StableStringChars.h
@@ -16,30 +16,25 @@
 #include "mozilla/Maybe.h"  // mozilla::Maybe
 #include "mozilla/Range.h"  // mozilla::Range
 
 #include <stddef.h>  // size_t
 #include <stdint.h>  // uint8_t
 
 #include "jstypes.h"  // JS_FRIEND_API
 
-#include "js/HeapAPI.h"        // JS::shadow::String
-#include "js/RootingAPI.h"     // JS::Handle, JS::Rooted
-#include "js/shadow/String.h"  // JS::shadow::String
-#include "js/TypeDecls.h"      // JSContext, JS::Latin1Char, JSString
-#include "js/Vector.h"         // js::Vector
+#include "js/RootingAPI.h"  // JS::Handle, JS::Rooted
+#include "js/String.h"      // JS::GetStringLength
+#include "js/TypeDecls.h"   // JSContext, JS::Latin1Char, JSString
+#include "js/Vector.h"      // js::Vector
 
 class JSLinearString;
 
 namespace JS {
 
-MOZ_ALWAYS_INLINE size_t GetStringLength(JSString* s) {
-  return reinterpret_cast<shadow::String*>(s)->length();
-}
-
 /**
  * This class provides safe access to a string's chars across a GC. If we ever
  * nursery allocate strings' out of line chars, this class will have to make a
  * copy, so it's best to avoid using this class unless you really need it. It's
  * usually more efficient to use the latin1Chars/twoByteChars JSString methods
  * and often the code can be rewritten so that only indexes instead of char
  * pointers are used in parts of the code that can GC.
  */
copy from js/src/jsfriendapi.h
copy to js/public/String.h
--- a/js/src/jsfriendapi.h
+++ b/js/public/String.h
@@ -1,1659 +1,233 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * 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/. */
 
-#ifndef jsfriendapi_h
-#define jsfriendapi_h
-
-#include "mozilla/MemoryReporting.h"
-#include "mozilla/PodOperations.h"
-
-#include "jspubtd.h"
+/* JavaScript string operations. */
 
-#include "js/CallArgs.h"
-#include "js/CharacterEncoding.h"
-#include "js/Class.h"
-#include "js/ErrorReport.h"
-#include "js/Exception.h"
-#include "js/friend/ErrorMessages.h"
-#include "js/HeapAPI.h"
-#include "js/shadow/Function.h"     // JS::shadow::Function
-#include "js/shadow/Object.h"       // JS::shadow::Object
-#include "js/shadow/ObjectGroup.h"  // JS::shadow::ObjectGroup
-#include "js/shadow/String.h"       // JS::shadow::String
-#include "js/TypeDecls.h"
-#include "js/Utility.h"
-
-struct JSJitInfo;
-
-namespace JS {
-template <class T>
-class Heap;
-
-class ExceptionStack;
-} /* namespace JS */
-
-namespace js {
-class JS_FRIEND_API BaseProxyHandler;
-} /* namespace js */
-
-extern JS_FRIEND_API void JS_SetGrayGCRootsTracer(JSContext* cx,
-                                                  JSTraceDataOp traceOp,
-                                                  void* data);
+#ifndef js_String_h
+#define js_String_h
 
-extern JS_FRIEND_API JSObject* JS_FindCompilationScope(JSContext* cx,
-                                                       JS::HandleObject obj);
-
-extern JS_FRIEND_API JSFunction* JS_GetObjectFunction(JSObject* obj);
-
-extern JS_FRIEND_API bool JS_SplicePrototype(JSContext* cx,
-                                             JS::HandleObject obj,
-                                             JS::HandleObject proto);
-
-extern JS_FRIEND_API JSObject* JS_NewObjectWithUniqueType(
-    JSContext* cx, const JSClass* clasp, JS::HandleObject proto);
+#include "js/shadow/String.h"  // JS::shadow::String
 
-/**
- * Allocate an object in exactly the same way as JS_NewObjectWithGivenProto, but
- * without invoking the metadata callback on it.  This allows creation of
- * internal bookkeeping objects that are guaranteed to not have metadata
- * attached to them.
- */
-extern JS_FRIEND_API JSObject* JS_NewObjectWithoutMetadata(
-    JSContext* cx, const JSClass* clasp, JS::Handle<JSObject*> proto);
-
-extern JS_FRIEND_API bool JS_NondeterministicGetWeakMapKeys(
-    JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject ret);
-
-extern JS_FRIEND_API bool JS_NondeterministicGetWeakSetKeys(
-    JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject ret);
-
-// Raw JSScript* because this needs to be callable from a signal handler.
-extern JS_FRIEND_API unsigned JS_PCToLineNumber(JSScript* script,
-                                                jsbytecode* pc,
-                                                unsigned* columnp = nullptr);
-
-/**
- * Determine whether the given object is backed by a DeadObjectProxy.
- *
- * Such objects hold no other objects (they have no outgoing reference edges)
- * and will throw if you touch them (e.g. by reading/writing a property).
- */
-extern JS_FRIEND_API bool JS_IsDeadWrapper(JSObject* obj);
+#include "mozilla/Assertions.h"  // MOZ_ASSERT
+#include "mozilla/Attributes.h"  // MOZ_ALWAYS_INLINE, MOZ_MUST_USE
+#include "mozilla/Likely.h"      // MOZ_LIKELY
 
-/**
- * Creates a new dead wrapper object in the given scope. To be used when
- * attempting to wrap objects from scopes which are already dead.
- *
- * If origObject is passed, it must be an proxy object, and will be
- * used to determine the characteristics of the new dead wrapper.
- */
-extern JS_FRIEND_API JSObject* JS_NewDeadWrapper(
-    JSContext* cx, JSObject* origObject = nullptr);
-
-namespace js {
+#include <algorithm>  // std::copy_n
+#include <stddef.h>   // size_t
+#include <stdint.h>   // uint32_t, uint64_t, INT32_MAX
 
-/**
- * Get the script private value associated with an object, if any.
- *
- * The private value is set with SetScriptPrivate() or SetModulePrivate() and is
- * internally stored on the relevant ScriptSourceObject.
- *
- * This is used by the cycle collector to trace through
- * ScriptSourceObjects. This allows private values to contain an nsISupports
- * pointer and hence support references to cycle collected C++ objects.
- */
-JS_FRIEND_API JS::Value MaybeGetScriptPrivate(JSObject* object);
-
-}  // namespace js
-
-/*
- * Used by the cycle collector to trace through a shape or object group and
- * all cycle-participating data it reaches, using bounded stack space.
- */
-extern JS_FRIEND_API void JS_TraceShapeCycleCollectorChildren(
-    JS::CallbackTracer* trc, JS::GCCellPtr shape);
-extern JS_FRIEND_API void JS_TraceObjectGroupCycleCollectorChildren(
-    JS::CallbackTracer* trc, JS::GCCellPtr group);
-
-extern JS_FRIEND_API JSPrincipals* JS_GetScriptPrincipals(JSScript* script);
-
-namespace js {
-
-// Release-assert the compartment contains exactly one realm.
-extern JS_FRIEND_API void AssertCompartmentHasSingleRealm(
-    JS::Compartment* comp);
+#include "jstypes.h"  // JS_PUBLIC_API
 
-extern JS_FRIEND_API JS::Realm* GetScriptRealm(JSScript* script);
-} /* namespace js */
-
-extern JS_FRIEND_API bool JS_ScriptHasMutedErrors(JSScript* script);
-
-extern JS_FRIEND_API JSObject* JS_CloneObject(JSContext* cx,
-                                              JS::HandleObject obj,
-                                              JS::HandleObject proto);
+#include "js/TypeDecls.h"  // JS::Latin1Char
 
-/**
- * Copy the own properties of src to dst in a fast way.  src and dst must both
- * be native and must be in the compartment of cx.  They must have the same
- * class, the same parent, and the same prototype.  Class reserved slots will
- * NOT be copied.
- *
- * dst must not have any properties on it before this function is called.
- *
- * src must have been allocated via JS_NewObjectWithoutMetadata so that we can
- * be sure it has no metadata that needs copying to dst.  This also means that
- * dst needs to have the compartment global as its parent.  This function will
- * preserve the existing metadata on dst, if any.
- */
-extern JS_FRIEND_API bool JS_InitializePropertiesFromCompatibleNativeObject(
-    JSContext* cx, JS::HandleObject dst, JS::HandleObject src);
-
-namespace js {
-
-JS_FRIEND_API bool GetBuiltinClass(JSContext* cx, JS::HandleObject obj,
-                                   ESClass* cls);
-
-JS_FRIEND_API bool IsArgumentsObject(JS::HandleObject obj);
-
-JS_FRIEND_API const char* ObjectClassName(JSContext* cx, JS::HandleObject obj);
-
-JS_FRIEND_API bool AddRawValueRoot(JSContext* cx, JS::Value* vp,
-                                   const char* name);
-
-JS_FRIEND_API void RemoveRawValueRoot(JSContext* cx, JS::Value* vp);
-
-JS_FRIEND_API JSAtom* GetPropertyNameFromPC(JSScript* script, jsbytecode* pc);
-
-}  // namespace js
+class JS_PUBLIC_API JSAtom;
+class JSLinearString;
+class JS_PUBLIC_API JSString;
 
 namespace JS {
 
-/**
- * Set all of the uninitialized lexicals on an object to undefined. Return
- * true if any lexicals were initialized and false otherwise.
- * */
-extern JS_FRIEND_API bool ForceLexicalInitialization(JSContext* cx,
-                                                     HandleObject obj);
-
-/**
- * Whether we are poisoning unused/released data for error detection. Governed
- * by the JS_GC_POISONING #ifdef as well as the $JSGC_DISABLE_POISONING
- * environment variable.
- */
-extern JS_FRIEND_API int IsGCPoisoning();
-
-extern JS_FRIEND_API JSPrincipals* GetRealmPrincipals(JS::Realm* realm);
-
-extern JS_FRIEND_API void SetRealmPrincipals(JS::Realm* realm,
-                                             JSPrincipals* principals);
-
-extern JS_FRIEND_API bool GetIsSecureContext(JS::Realm* realm);
-
-}  // namespace JS
-
-/**
- * Copies all own properties and private fields from |obj| to |target|. Both
- * |obj| and |target| must not be cross-compartment wrappers because we have to
- * enter their realms.
- *
- * This function immediately enters a realm, and does not impose any
- * restrictions on the realm of |cx|.
- */
-extern JS_FRIEND_API bool JS_CopyOwnPropertiesAndPrivateFields(
-    JSContext* cx, JS::HandleObject target, JS::HandleObject obj);
-
-/*
- * Single-property version of the above. This function asserts that an |own|
- * property of the given name exists on |obj|.
- *
- * On entry, |cx| must be same-compartment with |obj|. |target| must not be a
- * cross-compartment wrapper because we have to enter its realm.
- *
- * The copyBehavior argument controls what happens with
- * non-configurable properties.
- */
-typedef enum {
-  MakeNonConfigurableIntoConfigurable,
-  CopyNonConfigurableAsIs
-} PropertyCopyBehavior;
-
-extern JS_FRIEND_API bool JS_CopyPropertyFrom(
-    JSContext* cx, JS::HandleId id, JS::HandleObject target,
-    JS::HandleObject obj,
-    PropertyCopyBehavior copyBehavior = CopyNonConfigurableAsIs);
-
-extern JS_FRIEND_API bool JS_WrapPropertyDescriptor(
-    JSContext* cx, JS::MutableHandle<JS::PropertyDescriptor> desc);
-
-struct JSFunctionSpecWithHelp {
-  const char* name;
-  JSNative call;
-  uint16_t nargs;
-  uint16_t flags;
-  const JSJitInfo* jitInfo;
-  const char* usage;
-  const char* help;
-};
-
-#define JS_FN_HELP(name, call, nargs, flags, usage, help) \
-  { name, call, nargs, (flags) | JSPROP_ENUMERATE, nullptr, usage, help }
-#define JS_INLINABLE_FN_HELP(name, call, nargs, flags, native, usage, help)    \
-  {                                                                            \
-    name, call, nargs, (flags) | JSPROP_ENUMERATE, &js::jit::JitInfo_##native, \
-        usage, help                                                            \
-  }
-#define JS_FS_HELP_END \
-  { nullptr, nullptr, 0, 0, nullptr, nullptr }
-
-extern JS_FRIEND_API bool JS_DefineFunctionsWithHelp(
-    JSContext* cx, JS::HandleObject obj, const JSFunctionSpecWithHelp* fs);
-
-namespace js {
-
-/**
- * Use the runtime's internal handling of job queues for Promise jobs.
- *
- * Most embeddings, notably web browsers, will have their own task scheduling
- * systems and need to integrate handling of Promise jobs into that, so they
- * will want to manage job queues themselves. For basic embeddings such as the
- * JS shell that don't have an event loop of their own, it's easier to have
- * SpiderMonkey handle job queues internally.
- *
- * Note that the embedding still has to trigger processing of job queues at
- * right time(s), such as after evaluation of a script has run to completion.
- */
-extern JS_FRIEND_API bool UseInternalJobQueues(JSContext* cx);
-
-/**
- * Enqueue |job| on the internal job queue.
- *
- * This is useful in tests for creating situations where a call occurs with no
- * other JavaScript on the stack.
- */
-extern JS_FRIEND_API bool EnqueueJob(JSContext* cx, JS::HandleObject job);
-
-/**
- * Instruct the runtime to stop draining the internal job queue.
- *
- * Useful if the embedding is in the process of quitting in reaction to a
- * builtin being called, or if it wants to resume executing jobs later on.
- */
-extern JS_FRIEND_API void StopDrainingJobQueue(JSContext* cx);
-
-extern JS_FRIEND_API void RunJobs(JSContext* cx);
-
-extern JS_FRIEND_API JS::Zone* GetRealmZone(JS::Realm* realm);
-
-using PreserveWrapperCallback = bool (*)(JSContext*, JS::HandleObject);
-using HasReleasedWrapperCallback = bool (*)(JS::HandleObject);
-
-extern JS_FRIEND_API bool IsSystemRealm(JS::Realm* realm);
-
-extern JS_FRIEND_API bool IsSystemCompartment(JS::Compartment* comp);
-
-extern JS_FRIEND_API bool IsSystemZone(JS::Zone* zone);
-
-extern JS_FRIEND_API bool IsAtomsZone(JS::Zone* zone);
-
-struct WeakMapTracer {
-  JSRuntime* runtime;
-
-  explicit WeakMapTracer(JSRuntime* rt) : runtime(rt) {}
-
-  // Weak map tracer callback, called once for every binding of every
-  // weak map that was live at the time of the last garbage collection.
-  //
-  // m will be nullptr if the weak map is not contained in a JS Object.
-  //
-  // The callback should not GC (and will assert in a debug build if it does
-  // so.)
-  virtual void trace(JSObject* m, JS::GCCellPtr key, JS::GCCellPtr value) = 0;
-};
-
-extern JS_FRIEND_API void TraceWeakMaps(WeakMapTracer* trc);
-
-extern JS_FRIEND_API bool AreGCGrayBitsValid(JSRuntime* rt);
-
-extern JS_FRIEND_API bool ZoneGlobalsAreAllGray(JS::Zone* zone);
-
-extern JS_FRIEND_API bool IsCompartmentZoneSweepingOrCompacting(
-    JS::Compartment* comp);
-
-using IterateGCThingCallback = void (*)(void*, JS::GCCellPtr,
-                                        const JS::AutoRequireNoGC&);
-
-extern JS_FRIEND_API void VisitGrayWrapperTargets(
-    JS::Zone* zone, IterateGCThingCallback callback, void* closure);
+class JS_PUBLIC_API AutoRequireNoGC;
 
 /**
- * Invoke cellCallback on every gray JSObject in the given zone.
+ * Maximum length of a JS string. This is chosen so that the number of bytes
+ * allocated for a null-terminated TwoByte string still fits in int32_t.
  */
-extern JS_FRIEND_API void IterateGrayObjects(
-    JS::Zone* zone, IterateGCThingCallback cellCallback, void* data);
-
-#if defined(JS_GC_ZEAL) || defined(DEBUG)
-// Trace the heap and check there are no black to gray edges. These are
-// not allowed since the cycle collector could throw away the gray thing and
-// leave a dangling pointer.
-//
-// This doesn't trace weak maps as these are handled separately.
-extern JS_FRIEND_API bool CheckGrayMarkingState(JSRuntime* rt);
-#endif
-
-#ifdef JS_HAS_CTYPES
-extern JS_FRIEND_API size_t
-SizeOfDataIfCDataObject(mozilla::MallocSizeOf mallocSizeOf, JSObject* obj);
-#endif
-
-// Note: this returns nullptr iff |zone| is the atoms zone.
-extern JS_FRIEND_API JS::Realm* GetAnyRealmInZone(JS::Zone* zone);
-
-// Returns the first realm's global in a compartment. Note: this is not
-// guaranteed to always be the same realm because individual realms can be
-// collected by the GC.
-extern JS_FRIEND_API JSObject* GetFirstGlobalInCompartment(
-    JS::Compartment* comp);
-
-// Returns true if the compartment contains a global object and this global is
-// not being collected.
-extern JS_FRIEND_API bool CompartmentHasLiveGlobal(JS::Compartment* comp);
-
-// Returns true if this compartment can be shared across multiple Realms.  Used
-// when we're looking for an existing compartment to place a new Realm in.
-extern JS_FRIEND_API bool IsSharableCompartment(JS::Compartment* comp);
-
-// This is equal to |&JSObject::class_|.  Use it in places where you don't want
-// to #include vm/JSObject.h.
-extern JS_FRIEND_DATA const JSClass* const ObjectClassPtr;
-
-inline const JSClass* GetObjectClass(const JSObject* obj) {
-  return reinterpret_cast<const JS::shadow::Object*>(obj)->group->clasp;
-}
-
-JS_FRIEND_API const JSClass* ProtoKeyToClass(JSProtoKey key);
-
-// Returns the key for the class inherited by a given standard class (that
-// is to say, the prototype of this standard class's prototype).
-//
-// You must be sure that this corresponds to a standard class with a cached
-// JSProtoKey before calling this function. In general |key| will match the
-// cached proto key, except in cases where multiple JSProtoKeys share a
-// JSClass.
-inline JSProtoKey InheritanceProtoKeyForStandardClass(JSProtoKey key) {
-  // [Object] has nothing to inherit from.
-  if (key == JSProto_Object) {
-    return JSProto_Null;
-  }
-
-  // If we're ClassSpec defined return the proto key from that
-  if (ProtoKeyToClass(key)->specDefined()) {
-    return ProtoKeyToClass(key)->specInheritanceProtoKey();
-  }
-
-  // Otherwise, we inherit [Object].
-  return JSProto_Object;
-}
-
-JS_FRIEND_API bool ShouldIgnorePropertyDefinition(JSContext* cx, JSProtoKey key,
-                                                  jsid id);
-
-JS_FRIEND_API bool IsFunctionObject(JSObject* obj);
-
-JS_FRIEND_API bool UninlinedIsCrossCompartmentWrapper(const JSObject* obj);
-
-static MOZ_ALWAYS_INLINE JS::Compartment* GetObjectCompartment(JSObject* obj) {
-  JS::Realm* realm = reinterpret_cast<JS::shadow::Object*>(obj)->group->realm;
-  return JS::GetCompartmentForRealm(realm);
-}
-
-// CrossCompartmentWrappers are shared by all realms within the compartment, so
-// getting a wrapper's realm usually doesn't make sense.
-static MOZ_ALWAYS_INLINE JS::Realm* GetNonCCWObjectRealm(JSObject* obj) {
-  MOZ_ASSERT(!js::UninlinedIsCrossCompartmentWrapper(obj));
-  return reinterpret_cast<JS::shadow::Object*>(obj)->group->realm;
-}
-
-JS_FRIEND_API JSObject* GetPrototypeNoProxy(JSObject* obj);
-
-JS_FRIEND_API void AssertSameCompartment(JSContext* cx, JSObject* obj);
-
-JS_FRIEND_API void AssertSameCompartment(JSContext* cx, JS::HandleValue v);
-
-#ifdef JS_DEBUG
-JS_FRIEND_API void AssertSameCompartment(JSObject* objA, JSObject* objB);
-#else
-inline void AssertSameCompartment(JSObject* objA, JSObject* objB) {}
-#endif
-
-JS_FRIEND_API void NotifyAnimationActivity(JSObject* obj);
-
-JS_FRIEND_API JSFunction* DefineFunctionWithReserved(
-    JSContext* cx, JSObject* obj, const char* name, JSNative call,
-    unsigned nargs, unsigned attrs);
-
-JS_FRIEND_API JSFunction* NewFunctionWithReserved(JSContext* cx, JSNative call,
-                                                  unsigned nargs,
-                                                  unsigned flags,
-                                                  const char* name);
-
-JS_FRIEND_API JSFunction* NewFunctionByIdWithReserved(JSContext* cx,
-                                                      JSNative native,
-                                                      unsigned nargs,
-                                                      unsigned flags, jsid id);
-
-JS_FRIEND_API const JS::Value& GetFunctionNativeReserved(JSObject* fun,
-                                                         size_t which);
-
-JS_FRIEND_API void SetFunctionNativeReserved(JSObject* fun, size_t which,
-                                             const JS::Value& val);
-
-JS_FRIEND_API bool FunctionHasNativeReserved(JSObject* fun);
-
-JS_FRIEND_API bool GetObjectProto(JSContext* cx, JS::HandleObject obj,
-                                  JS::MutableHandleObject proto);
-
-extern JS_FRIEND_API JSObject* GetStaticPrototype(JSObject* obj);
-
-JS_FRIEND_API bool GetRealmOriginalEval(JSContext* cx,
-                                        JS::MutableHandleObject eval);
-
-inline void* GetObjectPrivate(JSObject* obj) {
-  MOZ_ASSERT(GetObjectClass(obj)->flags & JSCLASS_HAS_PRIVATE);
-  const auto* nobj = reinterpret_cast<const JS::shadow::Object*>(obj);
-  void** addr =
-      reinterpret_cast<void**>(&nobj->fixedSlots()[nobj->numFixedSlots()]);
-  return *addr;
-}
-
-/**
- * Get the value stored in an object's reserved slot. This can be used with
- * both native objects and proxies, but if |obj| is known to be a proxy
- * GetProxyReservedSlot is a bit more efficient.
- */
-inline const JS::Value& GetReservedSlot(JSObject* obj, size_t slot) {
-  MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj)));
-  return reinterpret_cast<const JS::shadow::Object*>(obj)->slotRef(slot);
-}
-
-JS_FRIEND_API void SetReservedSlotWithBarrier(JSObject* obj, size_t slot,
-                                              const JS::Value& value);
-
-/**
- * Store a value in an object's reserved slot. This can be used with
- * both native objects and proxies, but if |obj| is known to be a proxy
- * SetProxyReservedSlot is a bit more efficient.
- */
-inline void SetReservedSlot(JSObject* obj, size_t slot,
-                            const JS::Value& value) {
-  MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj)));
-  auto* sobj = reinterpret_cast<JS::shadow::Object*>(obj);
-  if (sobj->slotRef(slot).isGCThing() || value.isGCThing()) {
-    SetReservedSlotWithBarrier(obj, slot, value);
-  } else {
-    sobj->slotRef(slot) = value;
-  }
-}
-
-JS_FRIEND_API uint32_t GetObjectSlotSpan(JSObject* obj);
-
-inline const JS::Value& GetObjectSlot(JSObject* obj, size_t slot) {
-  MOZ_ASSERT(slot < GetObjectSlotSpan(obj));
-  return reinterpret_cast<const JS::shadow::Object*>(obj)->slotRef(slot);
-}
-
-MOZ_ALWAYS_INLINE size_t GetAtomLength(JSAtom* atom) {
-  return reinterpret_cast<JS::shadow::String*>(atom)->length();
-}
-
-// Maximum length of a JS string. This is chosen so that the number of bytes
-// allocated for a null-terminated TwoByte string still fits in int32_t.
-static const uint32_t MaxStringLength = (1 << 30) - 2;
+static constexpr uint32_t MaxStringLength = (1 << 30) - 2;
 
 static_assert((uint64_t(MaxStringLength) + 1) * sizeof(char16_t) <= INT32_MAX,
               "size of null-terminated JSString char buffer must fit in "
               "INT32_MAX");
 
-MOZ_ALWAYS_INLINE size_t GetLinearStringLength(JSLinearString* s) {
-  return reinterpret_cast<JS::shadow::String*>(s)->length();
-}
-
-MOZ_ALWAYS_INLINE bool LinearStringHasLatin1Chars(JSLinearString* s) {
-  return reinterpret_cast<JS::shadow::String*>(s)->flags() &
-         JS::shadow::String::LATIN1_CHARS_BIT;
+/** Compute the length of a string. */
+MOZ_ALWAYS_INLINE size_t GetStringLength(JSString* s) {
+  return shadow::AsShadowString(s)->length();
 }
 
-MOZ_ALWAYS_INLINE bool AtomHasLatin1Chars(JSAtom* atom) {
-  return reinterpret_cast<JS::shadow::String*>(atom)->flags() &
-         JS::shadow::String::LATIN1_CHARS_BIT;
+/** Compute the length of a linear string. */
+MOZ_ALWAYS_INLINE size_t GetLinearStringLength(JSLinearString* s) {
+  return shadow::AsShadowString(s)->length();
 }
 
+/** Return true iff the given linear string uses Latin-1 storage. */
+MOZ_ALWAYS_INLINE bool LinearStringHasLatin1Chars(JSLinearString* s) {
+  return shadow::AsShadowString(s)->hasLatin1Chars();
+}
+
+/** Return true iff the given string uses Latin-1 storage. */
 MOZ_ALWAYS_INLINE bool StringHasLatin1Chars(JSString* s) {
-  return reinterpret_cast<JS::shadow::String*>(s)->flags() &
-         JS::shadow::String::LATIN1_CHARS_BIT;
+  return shadow::AsShadowString(s)->hasLatin1Chars();
 }
 
-MOZ_ALWAYS_INLINE const JS::Latin1Char* GetLatin1LinearStringChars(
-    const JS::AutoRequireNoGC& nogc, JSLinearString* linear) {
-  MOZ_ASSERT(LinearStringHasLatin1Chars(linear));
+/**
+ * Given a linear string known to use Latin-1 storage, return a pointer to that
+ * storage.  This pointer remains valid only as long as no GC occurs.
+ */
+MOZ_ALWAYS_INLINE const Latin1Char* GetLatin1LinearStringChars(
+    const AutoRequireNoGC& nogc, JSLinearString* linear) {
+  return shadow::AsShadowString(linear)->latin1LinearChars();
+}
 
-  using JS::shadow::String;
-  String* s = reinterpret_cast<String*>(linear);
-  if (s->flags() & String::INLINE_CHARS_BIT) {
-    return s->inlineStorageLatin1;
-  }
-  return s->nonInlineCharsLatin1;
+/**
+ * Given a linear string known to use two-byte storage, return a pointer to that
+ * storage.  This pointer remains valid only as long as no GC occurs.
+ */
+MOZ_ALWAYS_INLINE const char16_t* GetTwoByteLinearStringChars(
+    const AutoRequireNoGC& nogc, JSLinearString* linear) {
+  return shadow::AsShadowString(linear)->twoByteLinearChars();
 }
 
-MOZ_ALWAYS_INLINE const char16_t* GetTwoByteLinearStringChars(
-    const JS::AutoRequireNoGC& nogc, JSLinearString* linear) {
-  MOZ_ASSERT(!LinearStringHasLatin1Chars(linear));
+/**
+ * Given an in-range index into the provided string, return the character at
+ * that index.
+ */
+MOZ_ALWAYS_INLINE char16_t GetLinearStringCharAt(JSLinearString* linear,
+                                                 size_t index) {
+  shadow::String* s = shadow::AsShadowString(linear);
+  MOZ_ASSERT(index < s->length());
 
-  using JS::shadow::String;
-  String* s = reinterpret_cast<String*>(linear);
-  if (s->flags() & String::INLINE_CHARS_BIT) {
-    return s->inlineStorageTwoByte;
-  }
-  return s->nonInlineCharsTwoByte;
+  return s->hasLatin1Chars() ? s->latin1LinearChars()[index]
+                             : s->twoByteLinearChars()[index];
 }
 
-MOZ_ALWAYS_INLINE char16_t GetLinearStringCharAt(JSLinearString* linear,
-                                                 size_t index) {
-  MOZ_ASSERT(index < GetLinearStringLength(linear));
-  JS::AutoCheckCannotGC nogc;
-  return LinearStringHasLatin1Chars(linear)
-             ? GetLatin1LinearStringChars(nogc, linear)[index]
-             : GetTwoByteLinearStringChars(nogc, linear)[index];
-}
-
+/**
+ * Convert an atom to a linear string.  All atoms are linear, so this
+ * operation is infallible.
+ */
 MOZ_ALWAYS_INLINE JSLinearString* AtomToLinearString(JSAtom* atom) {
   return reinterpret_cast<JSLinearString*>(atom);
 }
 
-MOZ_ALWAYS_INLINE const JS::Latin1Char* GetLatin1AtomChars(
-    const JS::AutoRequireNoGC& nogc, JSAtom* atom) {
-  return GetLatin1LinearStringChars(nogc, AtomToLinearString(atom));
-}
-
-MOZ_ALWAYS_INLINE const char16_t* GetTwoByteAtomChars(
-    const JS::AutoRequireNoGC& nogc, JSAtom* atom) {
-  return GetTwoByteLinearStringChars(nogc, AtomToLinearString(atom));
-}
-
+/**
+ * If the provided string uses externally-managed storage, return true and set
+ * |*callbacks| to the external-string callbacks used to create it and |*chars|
+ * to a pointer to its two-byte storage.  (These pointers remain valid as long
+ * as the provided string is kept alive.)
+ */
 MOZ_ALWAYS_INLINE bool IsExternalString(
     JSString* str, const JSExternalStringCallbacks** callbacks,
     const char16_t** chars) {
-  using JS::shadow::String;
-  String* s = reinterpret_cast<String*>(str);
+  shadow::String* s = shadow::AsShadowString(str);
 
-  if ((s->flags() & String::TYPE_FLAGS_MASK) != String::EXTERNAL_FLAGS) {
+  if (!s->isExternal()) {
     return false;
   }
 
-  MOZ_ASSERT(JS_IsExternalString(str));
   *callbacks = s->externalCallbacks;
   *chars = s->nonInlineCharsTwoByte;
   return true;
 }
 
-JS_FRIEND_API JSLinearString* StringToLinearStringSlow(JSContext* cx,
-                                                       JSString* str);
+namespace detail {
 
+extern JS_FRIEND_API JSLinearString* StringToLinearStringSlow(JSContext* cx,
+                                                              JSString* str);
+
+}  // namespace detail
+
+/** Convert a string to a linear string. */
 MOZ_ALWAYS_INLINE JSLinearString* StringToLinearString(JSContext* cx,
                                                        JSString* str) {
-  using JS::shadow::String;
-  String* s = reinterpret_cast<String*>(str);
-  if (MOZ_UNLIKELY(!(s->flags() & String::LINEAR_BIT))) {
-    return StringToLinearStringSlow(cx, str);
+  if (MOZ_LIKELY(shadow::AsShadowString(str)->isLinear())) {
+    return reinterpret_cast<JSLinearString*>(str);
   }
-  return reinterpret_cast<JSLinearString*>(str);
+
+  return detail::StringToLinearStringSlow(cx, str);
 }
 
-template <typename CharType>
-MOZ_ALWAYS_INLINE void CopyLinearStringChars(CharType* dest, JSLinearString* s,
-                                             size_t len, size_t start = 0);
-
+/** Copy characters in |s[start..start + len]| to |dest[0..len]|. */
 MOZ_ALWAYS_INLINE void CopyLinearStringChars(char16_t* dest, JSLinearString* s,
                                              size_t len, size_t start = 0) {
-  MOZ_ASSERT(start + len <= GetLinearStringLength(s));
-  JS::AutoCheckCannotGC nogc;
-  if (LinearStringHasLatin1Chars(s)) {
-    const JS::Latin1Char* src = GetLatin1LinearStringChars(nogc, s);
+#ifdef DEBUG
+  size_t stringLen = GetLinearStringLength(s);
+  MOZ_ASSERT(start <= stringLen);
+  MOZ_ASSERT(len <= stringLen - start);
+#endif
+
+  shadow::String* str = shadow::AsShadowString(s);
+
+  if (str->hasLatin1Chars()) {
+    const Latin1Char* src = str->latin1LinearChars();
     for (size_t i = 0; i < len; i++) {
       dest[i] = src[start + i];
     }
   } else {
-    const char16_t* src = GetTwoByteLinearStringChars(nogc, s);
-    mozilla::PodCopy(dest, src + start, len);
+    const char16_t* src = str->twoByteLinearChars();
+    std::copy_n(src + start, len, dest);
   }
 }
 
-MOZ_ALWAYS_INLINE void CopyLinearStringChars(char* dest, JSLinearString* s,
-                                             size_t len, size_t start = 0) {
-  MOZ_ASSERT(start + len <= GetLinearStringLength(s));
-  JS::AutoCheckCannotGC nogc;
+/**
+ * Copy characters in |s[start..start + len]| to |dest[0..len]|, lossily
+ * truncating 16-bit values to |char| if necessary.
+ */
+MOZ_ALWAYS_INLINE void LossyCopyLinearStringChars(char* dest, JSLinearString* s,
+                                                  size_t len,
+                                                  size_t start = 0) {
+#ifdef DEBUG
+  size_t stringLen = GetLinearStringLength(s);
+  MOZ_ASSERT(start <= stringLen);
+  MOZ_ASSERT(len <= stringLen - start);
+#endif
+
+  shadow::String* str = shadow::AsShadowString(s);
+
   if (LinearStringHasLatin1Chars(s)) {
-    const JS::Latin1Char* src = GetLatin1LinearStringChars(nogc, s);
+    const Latin1Char* src = str->latin1LinearChars();
     for (size_t i = 0; i < len; i++) {
       dest[i] = char(src[start + i]);
     }
   } else {
-    const char16_t* src = GetTwoByteLinearStringChars(nogc, s);
+    const char16_t* src = str->twoByteLinearChars();
     for (size_t i = 0; i < len; i++) {
       dest[i] = char(src[start + i]);
     }
   }
 }
 
-template <typename CharType>
-inline bool CopyStringChars(JSContext* cx, CharType* dest, JSString* s,
-                            size_t len, size_t start = 0) {
+/**
+ * Copy characters in |s[start..start + len]| to |dest[0..len]|.
+ *
+ * This function is fallible.  If you already have a linear string, use the
+ * infallible |JS::CopyLinearStringChars| above instead.
+ */
+inline MOZ_MUST_USE bool CopyStringChars(JSContext* cx, char16_t* dest,
+                                         JSString* s, size_t len,
+                                         size_t start = 0) {
   JSLinearString* linear = StringToLinearString(cx, s);
   if (!linear) {
     return false;
   }
 
   CopyLinearStringChars(dest, linear, len, start);
   return true;
 }
 
 /**
- * Add some or all property keys of obj to the id vector *props.
- *
- * The flags parameter controls which property keys are added. Pass a
- * combination of the following bits:
- *
- *     JSITER_OWNONLY - Don't also search the prototype chain; only consider
- *       obj's own properties.
- *
- *     JSITER_HIDDEN - Include nonenumerable properties.
- *
- *     JSITER_SYMBOLS - Include property keys that are symbols. The default
- *       behavior is to filter out symbols.
- *
- *     JSITER_SYMBOLSONLY - Exclude non-symbol property keys.
- *
- * This is the closest C++ API we have to `Reflect.ownKeys(obj)`, or
- * equivalently, the ES6 [[OwnPropertyKeys]] internal method. Pass
- * `JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS` as flags to get
- * results that match the output of Reflect.ownKeys.
- */
-JS_FRIEND_API bool GetPropertyKeys(JSContext* cx, JS::HandleObject obj,
-                                   unsigned flags,
-                                   JS::MutableHandleIdVector props);
-
-JS_FRIEND_API bool AppendUnique(JSContext* cx, JS::MutableHandleIdVector base,
-                                JS::HandleIdVector others);
-
-/**
- * Determine whether the given string is an array index in the sense of
- * <https://tc39.github.io/ecma262/#array-index>.
- *
- * If it isn't, returns false.
+ * Copy characters in |s[start..start + len]| to |dest[0..len]|, lossily
+ * truncating 16-bit values to |char| if necessary.
  *
- * If it is, returns true and outputs the index in *indexp.
- */
-JS_FRIEND_API bool StringIsArrayIndex(JSLinearString* str, uint32_t* indexp);
-
-/**
- * Overloads of StringIsArrayIndex taking (char*,length) pairs.  These
- * behave the same as the JSLinearString version.
- */
-JS_FRIEND_API bool StringIsArrayIndex(const char* str, uint32_t length,
-                                      uint32_t* indexp);
-
-JS_FRIEND_API bool StringIsArrayIndex(const char16_t* str, uint32_t length,
-                                      uint32_t* indexp);
-
-JS_FRIEND_API void SetPreserveWrapperCallbacks(
-    JSContext* cx, PreserveWrapperCallback preserveWrapper,
-    HasReleasedWrapperCallback hasReleasedWrapper);
-
-JS_FRIEND_API bool IsObjectInContextCompartment(JSObject* obj,
-                                                const JSContext* cx);
-
-/*
- * NB: keep these in sync with the copy in builtin/SelfHostingDefines.h.
- */
-/* 0x1 is no longer used */
-/* 0x2 is no longer used */
-#define JSITER_PRIVATE 0x4      /* Include private names in iteration */
-#define JSITER_OWNONLY 0x8      /* iterate over obj's own properties only */
-#define JSITER_HIDDEN 0x10      /* also enumerate non-enumerable properties */
-#define JSITER_SYMBOLS 0x20     /* also include symbol property keys */
-#define JSITER_SYMBOLSONLY 0x40 /* exclude string property keys */
-#define JSITER_FORAWAITOF 0x80  /* for-await-of */
-
-JS_FRIEND_API void StartPCCountProfiling(JSContext* cx);
-
-JS_FRIEND_API void StopPCCountProfiling(JSContext* cx);
-
-JS_FRIEND_API void PurgePCCounts(JSContext* cx);
-
-JS_FRIEND_API size_t GetPCCountScriptCount(JSContext* cx);
-
-JS_FRIEND_API JSString* GetPCCountScriptSummary(JSContext* cx, size_t script);
-
-JS_FRIEND_API JSString* GetPCCountScriptContents(JSContext* cx, size_t script);
-
-using DOMInstanceClassHasProtoAtDepth = bool (*)(const JSClass*, uint32_t,
-                                                 uint32_t);
-struct JSDOMCallbacks {
-  DOMInstanceClassHasProtoAtDepth instanceClassMatchesProto;
-};
-using DOMCallbacks = struct JSDOMCallbacks;
-
-extern JS_FRIEND_API void SetDOMCallbacks(JSContext* cx,
-                                          const DOMCallbacks* callbacks);
-
-extern JS_FRIEND_API const DOMCallbacks* GetDOMCallbacks(JSContext* cx);
-
-extern JS_FRIEND_API JSObject* GetTestingFunctions(JSContext* cx);
-
-/* Implemented in jsexn.cpp. */
-
-/**
- * Get an error type name from a JSExnType constant.
- * Returns nullptr for invalid arguments and JSEXN_INTERNALERR
- */
-extern JS_FRIEND_API JSLinearString* GetErrorTypeName(JSContext* cx,
-                                                      int16_t exnType);
-
-extern JS_FRIEND_API RegExpShared* RegExpToSharedNonInline(
-    JSContext* cx, JS::HandleObject regexp);
-
-/* Implemented in CrossCompartmentWrapper.cpp. */
-typedef enum NukeReferencesToWindow {
-  NukeWindowReferences,
-  DontNukeWindowReferences
-} NukeReferencesToWindow;
-
-typedef enum NukeReferencesFromTarget {
-  NukeAllReferences,
-  NukeIncomingReferences,
-} NukeReferencesFromTarget;
-
-/*
- * These filters are designed to be ephemeral stack classes, and thus don't
- * do any rooting or holding of their members.
- */
-struct CompartmentFilter {
-  virtual bool match(JS::Compartment* c) const = 0;
-};
-
-struct AllCompartments : public CompartmentFilter {
-  virtual bool match(JS::Compartment* c) const override { return true; }
-};
-
-struct ContentCompartmentsOnly : public CompartmentFilter {
-  virtual bool match(JS::Compartment* c) const override {
-    return !IsSystemCompartment(c);
-  }
-};
-
-struct ChromeCompartmentsOnly : public CompartmentFilter {
-  virtual bool match(JS::Compartment* c) const override {
-    return IsSystemCompartment(c);
-  }
-};
-
-struct SingleCompartment : public CompartmentFilter {
-  JS::Compartment* ours;
-  explicit SingleCompartment(JS::Compartment* c) : ours(c) {}
-  virtual bool match(JS::Compartment* c) const override { return c == ours; }
-};
-
-extern JS_FRIEND_API bool NukeCrossCompartmentWrappers(
-    JSContext* cx, const CompartmentFilter& sourceFilter, JS::Realm* target,
-    NukeReferencesToWindow nukeReferencesToWindow,
-    NukeReferencesFromTarget nukeReferencesFromTarget);
-
-extern JS_FRIEND_API bool AllowNewWrapper(JS::Compartment* target,
-                                          JSObject* obj);
-
-extern JS_FRIEND_API bool NukedObjectRealm(JSObject* obj);
-
-/* Specify information about DOMProxy proxies in the DOM, for use by ICs. */
-
-/*
- * The DOMProxyShadowsCheck function will be called to check if the property for
- * id should be gotten from the prototype, or if there is an own property that
- * shadows it.
- * * If ShadowsViaDirectExpando is returned, then the slot at
- *   listBaseExpandoSlot contains an expando object which has the property in
- *   question.
- * * If ShadowsViaIndirectExpando is returned, then the slot at
- *   listBaseExpandoSlot contains a private pointer to an ExpandoAndGeneration
- *   and the expando object in the ExpandoAndGeneration has the property in
- *   question.
- * * If DoesntShadow is returned then the slot at listBaseExpandoSlot should
- *   either be undefined or point to an expando object that would contain the
- *   own property.
- * * If DoesntShadowUnique is returned then the slot at listBaseExpandoSlot
- *   should contain a private pointer to a ExpandoAndGeneration, which contains
- *   a JS::Value that should either be undefined or point to an expando object,
- *   and a uint64 value. If that value changes then the IC for getting a
- *   property will be invalidated.
- * * If Shadows is returned, that means the property is an own property of the
- *   proxy but doesn't live on the expando object.
+ * This function is fallible.  If you already have a linear string, use the
+ * infallible |JS::LossyCopyLinearStringChars| above instead.
  */
-
-struct ExpandoAndGeneration {
-  ExpandoAndGeneration() : expando(JS::UndefinedValue()), generation(0) {}
-
-  void OwnerUnlinked() { ++generation; }
-
-  static size_t offsetOfExpando() {
-    return offsetof(ExpandoAndGeneration, expando);
-  }
-
-  static size_t offsetOfGeneration() {
-    return offsetof(ExpandoAndGeneration, generation);
-  }
-
-  JS::Heap<JS::Value> expando;
-  uint64_t generation;
-};
-
-typedef enum DOMProxyShadowsResult {
-  ShadowCheckFailed,
-  Shadows,
-  DoesntShadow,
-  DoesntShadowUnique,
-  ShadowsViaDirectExpando,
-  ShadowsViaIndirectExpando
-} DOMProxyShadowsResult;
-using DOMProxyShadowsCheck = DOMProxyShadowsResult (*)(JSContext*,
-                                                       JS::HandleObject,
-                                                       JS::HandleId);
-JS_FRIEND_API void SetDOMProxyInformation(
-    const void* domProxyHandlerFamily,
-    DOMProxyShadowsCheck domProxyShadowsCheck,
-    const void* domRemoteProxyHandlerFamily);
-
-const void* GetDOMProxyHandlerFamily();
-DOMProxyShadowsCheck GetDOMProxyShadowsCheck();
-inline bool DOMProxyIsShadowing(DOMProxyShadowsResult result) {
-  return result == Shadows || result == ShadowsViaDirectExpando ||
-         result == ShadowsViaIndirectExpando;
-}
-
-const void* GetDOMRemoteProxyHandlerFamily();
-
-extern JS_FRIEND_API bool IsDOMRemoteProxyObject(JSObject* object);
-
-// Callbacks and other information for use by the JITs when optimizing accesses
-// on xray wrappers.
-struct XrayJitInfo {
-  // Test whether a proxy handler is a cross compartment xray with no
-  // security checks.
-  bool (*isCrossCompartmentXray)(const BaseProxyHandler* handler);
-
-  // Test whether xrays in |obj|'s compartment have expandos of their own,
-  // instead of sharing them with Xrays from other compartments.
-  bool (*compartmentHasExclusiveExpandos)(JSObject* obj);
-
-  // Proxy reserved slot used by xrays in sandboxes to store their holder
-  // object.
-  size_t xrayHolderSlot;
-
-  // Reserved slot used by xray holders to store the xray's expando object.
-  size_t holderExpandoSlot;
-
-  // Reserved slot used by xray expandos to store a custom prototype.
-  size_t expandoProtoSlot;
-};
-
-JS_FRIEND_API void SetXrayJitInfo(XrayJitInfo* info);
-
-XrayJitInfo* GetXrayJitInfo();
-
-/* Implemented in jsdate.cpp. */
-
-/** Detect whether the internal date value is NaN. */
-extern JS_FRIEND_API bool DateIsValid(JSContext* cx, JS::HandleObject obj,
-                                      bool* isValid);
-
-extern JS_FRIEND_API bool DateGetMsecSinceEpoch(JSContext* cx,
-                                                JS::HandleObject obj,
-                                                double* msecSinceEpoch);
-
-} /* namespace js */
-
-namespace js {
-
-/* Implemented in vm/StructuredClone.cpp. */
-extern JS_FRIEND_API uint64_t GetSCOffset(JSStructuredCloneWriter* writer);
-
-namespace jit {
-
-enum class InlinableNative : uint16_t;
-
-}  // namespace jit
-
-}  // namespace js
-
-/**
- * A class, expected to be passed by value, which represents the CallArgs for a
- * JSJitGetterOp.
- */
-class JSJitGetterCallArgs : protected JS::MutableHandleValue {
- public:
-  explicit JSJitGetterCallArgs(const JS::CallArgs& args)
-      : JS::MutableHandleValue(args.rval()) {}
-
-  explicit JSJitGetterCallArgs(JS::RootedValue* rooted)
-      : JS::MutableHandleValue(rooted) {}
-
-  JS::MutableHandleValue rval() { return *this; }
-};
-
-/**
- * A class, expected to be passed by value, which represents the CallArgs for a
- * JSJitSetterOp.
- */
-class JSJitSetterCallArgs : protected JS::MutableHandleValue {
- public:
-  explicit JSJitSetterCallArgs(const JS::CallArgs& args)
-      : JS::MutableHandleValue(args[0]) {}
-
-  JS::MutableHandleValue operator[](unsigned i) {
-    MOZ_ASSERT(i == 0);
-    return *this;
-  }
-
-  unsigned length() const { return 1; }
-
-  // Add get() or maybe hasDefined() as needed
-};
-
-struct JSJitMethodCallArgsTraits;
-
-/**
- * A class, expected to be passed by reference, which represents the CallArgs
- * for a JSJitMethodOp.
- */
-class JSJitMethodCallArgs
-    : protected JS::detail::CallArgsBase<JS::detail::NoUsedRval> {
- private:
-  using Base = JS::detail::CallArgsBase<JS::detail::NoUsedRval>;
-  friend struct JSJitMethodCallArgsTraits;
-
- public:
-  explicit JSJitMethodCallArgs(const JS::CallArgs& args) {
-    argv_ = args.array();
-    argc_ = args.length();
-  }
-
-  JS::MutableHandleValue rval() const { return Base::rval(); }
-
-  unsigned length() const { return Base::length(); }
-
-  JS::MutableHandleValue operator[](unsigned i) const {
-    return Base::operator[](i);
-  }
-
-  bool hasDefined(unsigned i) const { return Base::hasDefined(i); }
-
-  JSObject& callee() const {
-    // We can't use Base::callee() because that will try to poke at
-    // this->usedRval_, which we don't have.
-    return argv_[-2].toObject();
-  }
-
-  JS::HandleValue get(unsigned i) const { return Base::get(i); }
-
-  bool requireAtLeast(JSContext* cx, const char* fnname,
-                      unsigned required) const {
-    // Can just forward to Base, since it only needs the length and we
-    // forward that already.
-    return Base::requireAtLeast(cx, fnname, required);
-  }
-};
-
-struct JSJitMethodCallArgsTraits {
-  static const size_t offsetOfArgv = offsetof(JSJitMethodCallArgs, argv_);
-  static const size_t offsetOfArgc = offsetof(JSJitMethodCallArgs, argc_);
-};
-
-using JSJitGetterOp = bool (*)(JSContext*, JS::HandleObject, void*,
-                               JSJitGetterCallArgs);
-using JSJitSetterOp = bool (*)(JSContext*, JS::HandleObject, void*,
-                               JSJitSetterCallArgs);
-using JSJitMethodOp = bool (*)(JSContext*, JS::HandleObject, void*,
-                               const JSJitMethodCallArgs&);
-
-/**
- * This struct contains metadata passed from the DOM to the JS Engine for JIT
- * optimizations on DOM property accessors. Eventually, this should be made
- * available to general JSAPI users, but we are not currently ready to do so.
- */
-struct JSJitInfo {
-  enum OpType {
-    Getter,
-    Setter,
-    Method,
-    StaticMethod,
-    InlinableNative,
-    IgnoresReturnValueNative,
-    // Must be last
-    OpTypeCount
-  };
-
-  enum ArgType {
-    // Basic types
-    String = (1 << 0),
-    Integer = (1 << 1),  // Only 32-bit or less
-    Double = (1 << 2),   // Maybe we want to add Float sometime too
-    Boolean = (1 << 3),
-    Object = (1 << 4),
-    Null = (1 << 5),
-
-    // And derived types
-    Numeric = Integer | Double,
-    // Should "Primitive" use the WebIDL definition, which
-    // excludes string and null, or the typical JS one that includes them?
-    Primitive = Numeric | Boolean | Null | String,
-    ObjectOrNull = Object | Null,
-    Any = ObjectOrNull | Primitive,
-
-    // Our sentinel value.
-    ArgTypeListEnd = (1 << 31)
-  };
-
-  static_assert(Any & String, "Any must include String.");
-  static_assert(Any & Integer, "Any must include Integer.");
-  static_assert(Any & Double, "Any must include Double.");
-  static_assert(Any & Boolean, "Any must include Boolean.");
-  static_assert(Any & Object, "Any must include Object.");
-  static_assert(Any & Null, "Any must include Null.");
-
-  /**
-   * An enum that describes what this getter/setter/method aliases.  This
-   * determines what things can be hoisted past this call, and if this
-   * call is movable what it can be hoisted past.
-   */
-  enum AliasSet {
-    /**
-     * Alias nothing: a constant value, getting it can't affect any other
-     * values, nothing can affect it.
-     */
-    AliasNone,
-
-    /**
-     * Alias things that can modify the DOM but nothing else.  Doing the
-     * call can't affect the behavior of any other function.
-     */
-    AliasDOMSets,
-
-    /**
-     * Alias the world.  Calling this can change arbitrary values anywhere
-     * in the system.  Most things fall in this bucket.
-     */
-    AliasEverything,
-
-    /** Must be last. */
-    AliasSetCount
-  };
-
-  bool needsOuterizedThisObject() const {
-    return type() != Getter && type() != Setter;
-  }
-
-  bool isTypedMethodJitInfo() const { return isTypedMethod; }
-
-  OpType type() const { return OpType(type_); }
-
-  AliasSet aliasSet() const { return AliasSet(aliasSet_); }
-
-  JSValueType returnType() const { return JSValueType(returnType_); }
-
-  union {
-    JSJitGetterOp getter;
-    JSJitSetterOp setter;
-    JSJitMethodOp method;
-    /** A DOM static method, used for Promise wrappers */
-    JSNative staticMethod;
-    JSNative ignoresReturnValueMethod;
-  };
-
-  static unsigned offsetOfIgnoresReturnValueNative() {
-    return offsetof(JSJitInfo, ignoresReturnValueMethod);
+inline MOZ_MUST_USE bool LossyCopyStringChars(JSContext* cx, char* dest,
+                                              JSString* s, size_t len,
+                                              size_t start = 0) {
+  JSLinearString* linear = StringToLinearString(cx, s);
+  if (!linear) {
+    return false;
   }
 
-  union {
-    uint16_t protoID;
-    js::jit::InlinableNative inlinableNative;
-  };
-
-  union {
-    uint16_t depth;
-
-    // Additional opcode for some InlinableNative functions.
-    uint16_t nativeOp;
-  };
-
-  // These fields are carefully packed to take up 4 bytes.  If you need more
-  // bits for whatever reason, please see if you can steal bits from existing
-  // fields before adding more members to this structure.
-
-#define JITINFO_OP_TYPE_BITS 4
-#define JITINFO_ALIAS_SET_BITS 4
-#define JITINFO_RETURN_TYPE_BITS 8
-#define JITINFO_SLOT_INDEX_BITS 10
-
-  /** The OpType that says what sort of function we are. */
-  uint32_t type_ : JITINFO_OP_TYPE_BITS;
-
-  /**
-   * The alias set for this op.  This is a _minimal_ alias set; in
-   * particular for a method it does not include whatever argument
-   * conversions might do.  That's covered by argTypes and runtime
-   * analysis of the actual argument types being passed in.
-   */
-  uint32_t aliasSet_ : JITINFO_ALIAS_SET_BITS;
-
-  /** The return type tag.  Might be JSVAL_TYPE_UNKNOWN. */
-  uint32_t returnType_ : JITINFO_RETURN_TYPE_BITS;
-
-  static_assert(OpTypeCount <= (1 << JITINFO_OP_TYPE_BITS),
-                "Not enough space for OpType");
-  static_assert(AliasSetCount <= (1 << JITINFO_ALIAS_SET_BITS),
-                "Not enough space for AliasSet");
-  static_assert((sizeof(JSValueType) * 8) <= JITINFO_RETURN_TYPE_BITS,
-                "Not enough space for JSValueType");
-
-#undef JITINFO_RETURN_TYPE_BITS
-#undef JITINFO_ALIAS_SET_BITS
-#undef JITINFO_OP_TYPE_BITS
-
-  /** Is op fallible? False in setters. */
-  uint32_t isInfallible : 1;
-
-  /**
-   * Is op movable?  To be movable the op must
-   * not AliasEverything, but even that might
-   * not be enough (e.g. in cases when it can
-   * throw or is explicitly not movable).
-   */
-  uint32_t isMovable : 1;
-
-  /**
-   * Can op be dead-code eliminated? Again, this
-   * depends on whether the op can throw, in
-   * addition to the alias set.
-   */
-  uint32_t isEliminatable : 1;
-
-  // XXXbz should we have a JSValueType for the type of the member?
-  /**
-   * True if this is a getter that can always
-   * get the value from a slot of the "this" object.
-   */
-  uint32_t isAlwaysInSlot : 1;
-
-  /**
-   * True if this is a getter that can sometimes (if the slot doesn't contain
-   * UndefinedValue()) get the value from a slot of the "this" object.
-   */
-  uint32_t isLazilyCachedInSlot : 1;
-
-  /** True if this is an instance of JSTypedMethodJitInfo. */
-  uint32_t isTypedMethod : 1;
-
-  /**
-   * If isAlwaysInSlot or isSometimesInSlot is true,
-   * the index of the slot to get the value from.
-   * Otherwise 0.
-   */
-  uint32_t slotIndex : JITINFO_SLOT_INDEX_BITS;
-
-  static const size_t maxSlotIndex = (1 << JITINFO_SLOT_INDEX_BITS) - 1;
-
-#undef JITINFO_SLOT_INDEX_BITS
-};
-
-static_assert(sizeof(JSJitInfo) == (sizeof(void*) + 2 * sizeof(uint32_t)),
-              "There are several thousand instances of JSJitInfo stored in "
-              "a binary. Please don't increase its space requirements without "
-              "verifying that there is no other way forward (better packing, "
-              "smaller datatypes for fields, subclassing, etc.).");
-
-struct JSTypedMethodJitInfo {
-  // We use C-style inheritance here, rather than C++ style inheritance
-  // because not all compilers support brace-initialization for non-aggregate
-  // classes. Using C++ style inheritance and constructors instead of
-  // brace-initialization would also force the creation of static
-  // constructors (on some compilers) when JSJitInfo and JSTypedMethodJitInfo
-  // structures are declared. Since there can be several thousand of these
-  // structures present and we want to have roughly equivalent performance
-  // across a range of compilers, we do things manually.
-  JSJitInfo base;
-
-  const JSJitInfo::ArgType* const argTypes; /* For a method, a list of sets of
-                                               types that the function
-                                               expects.  This can be used,
-                                               for example, to figure out
-                                               when argument coercions can
-                                               have side-effects. */
-};
-
-namespace js {
-
-static MOZ_ALWAYS_INLINE JS::shadow::Function* FunctionObjectToShadowFunction(
-    JSObject* fun) {
-  MOZ_ASSERT(GetObjectClass(fun) == FunctionClassPtr);
-  return reinterpret_cast<JS::shadow::Function*>(fun);
-}
-
-/* Statically asserted in FunctionFlags.cpp. */
-static const unsigned JS_FUNCTION_INTERPRETED_BITS = 0x0060;
-
-// Return whether the given function object is native.
-static MOZ_ALWAYS_INLINE bool FunctionObjectIsNative(JSObject* fun) {
-  return !(FunctionObjectToShadowFunction(fun)->flags &
-           JS_FUNCTION_INTERPRETED_BITS);
-}
-
-static MOZ_ALWAYS_INLINE JSNative GetFunctionObjectNative(JSObject* fun) {
-  MOZ_ASSERT(FunctionObjectIsNative(fun));
-  return FunctionObjectToShadowFunction(fun)->native;
-}
-
-}  // namespace js
-
-static MOZ_ALWAYS_INLINE const JSJitInfo* FUNCTION_VALUE_TO_JITINFO(
-    const JS::Value& v) {
-  MOZ_ASSERT(js::FunctionObjectIsNative(&v.toObject()));
-  return js::FunctionObjectToShadowFunction(&v.toObject())->jitinfo;
-}
-
-static MOZ_ALWAYS_INLINE void SET_JITINFO(JSFunction* func,
-                                          const JSJitInfo* info) {
-  auto* fun = reinterpret_cast<JS::shadow::Function*>(func);
-  MOZ_ASSERT(!(fun->flags & js::JS_FUNCTION_INTERPRETED_BITS));
-  fun->jitinfo = info;
-}
-
-// All strings stored in jsids are atomized, but are not necessarily property
-// names.
-static MOZ_ALWAYS_INLINE bool JSID_IS_ATOM(jsid id) {
-  return JSID_IS_STRING(id);
-}
-
-static MOZ_ALWAYS_INLINE bool JSID_IS_ATOM(jsid id, JSAtom* atom) {
-  return id == JS::PropertyKey::fromNonIntAtom(atom);
-}
-
-static MOZ_ALWAYS_INLINE JSAtom* JSID_TO_ATOM(jsid id) {
-  return (JSAtom*)JSID_TO_STRING(id);
-}
-
-static_assert(sizeof(jsid) == sizeof(void*));
-
-namespace js {
-
-static MOZ_ALWAYS_INLINE JS::Value IdToValue(jsid id) {
-  if (JSID_IS_STRING(id)) {
-    return JS::StringValue(JSID_TO_STRING(id));
-  }
-  if (JSID_IS_INT(id)) {
-    return JS::Int32Value(JSID_TO_INT(id));
-  }
-  if (JSID_IS_SYMBOL(id)) {
-    return JS::SymbolValue(JSID_TO_SYMBOL(id));
-  }
-  MOZ_ASSERT(JSID_IS_VOID(id));
-  return JS::UndefinedValue();
+  LossyCopyLinearStringChars(dest, linear, len, start);
+  return true;
 }
 
-/**
- * PrepareScriptEnvironmentAndInvoke asserts the embedder has registered a
- * ScriptEnvironmentPreparer and then it calls the preparer's 'invoke' method
- * with the given |closure|, with the assumption that the preparer will set up
- * any state necessary to run script in |global|, invoke |closure| with a valid
- * JSContext*, report any exceptions thrown from the closure, and return.
- *
- * PrepareScriptEnvironmentAndInvoke will report any exceptions that are thrown
- * by the closure.  Consumers who want to propagate back whether the closure
- * succeeded should do so via members of the closure itself.
- */
-
-struct ScriptEnvironmentPreparer {
-  struct Closure {
-    virtual bool operator()(JSContext* cx) = 0;
-  };
-
-  virtual void invoke(JS::HandleObject global, Closure& closure) = 0;
-};
-
-extern JS_FRIEND_API void PrepareScriptEnvironmentAndInvoke(
-    JSContext* cx, JS::HandleObject global,
-    ScriptEnvironmentPreparer::Closure& closure);
-
-JS_FRIEND_API void SetScriptEnvironmentPreparer(
-    JSContext* cx, ScriptEnvironmentPreparer* preparer);
-
-enum CTypesActivityType {
-  CTYPES_CALL_BEGIN,
-  CTYPES_CALL_END,
-  CTYPES_CALLBACK_BEGIN,
-  CTYPES_CALLBACK_END
-};
-
-using CTypesActivityCallback = void (*)(JSContext*, CTypesActivityType);
-
-/**
- * Sets a callback that is run whenever js-ctypes is about to be used when
- * calling into C.
- */
-JS_FRIEND_API void SetCTypesActivityCallback(JSContext* cx,
-                                             CTypesActivityCallback cb);
-
-class MOZ_RAII JS_FRIEND_API AutoCTypesActivityCallback {
- private:
-  JSContext* cx;
-  CTypesActivityCallback callback;
-  CTypesActivityType endType;
-
- public:
-  AutoCTypesActivityCallback(JSContext* cx, CTypesActivityType beginType,
-                             CTypesActivityType endType);
-  ~AutoCTypesActivityCallback() { DoEndCallback(); }
-  void DoEndCallback() {
-    if (callback) {
-      callback(cx, endType);
-      callback = nullptr;
-    }
-  }
-};
-
-// Abstract base class for objects that build allocation metadata for JavaScript
-// values.
-struct AllocationMetadataBuilder {
-  AllocationMetadataBuilder() = default;
-
-  // Return a metadata object for the newly constructed object |obj|, or
-  // nullptr if there's no metadata to attach.
-  //
-  // Implementations should treat all errors as fatal; there is no way to
-  // report errors from this callback. In particular, the caller provides an
-  // oomUnsafe for overriding implementations to use.
-  virtual JSObject* build(JSContext* cx, JS::HandleObject obj,
-                          AutoEnterOOMUnsafeRegion& oomUnsafe) const {
-    return nullptr;
-  }
-};
-
-/**
- * Specify a callback to invoke when creating each JS object in the current
- * compartment, which may return a metadata object to associate with the
- * object.
- */
-JS_FRIEND_API void SetAllocationMetadataBuilder(
-    JSContext* cx, const AllocationMetadataBuilder* callback);
-
-/** Get the metadata associated with an object. */
-JS_FRIEND_API JSObject* GetAllocationMetadata(JSObject* obj);
-
-JS_FRIEND_API bool GetElementsWithAdder(JSContext* cx, JS::HandleObject obj,
-                                        JS::HandleObject receiver,
-                                        uint32_t begin, uint32_t end,
-                                        js::ElementAdder* adder);
-
-JS_FRIEND_API bool ForwardToNative(JSContext* cx, JSNative native,
-                                   const JS::CallArgs& args);
-
-/**
- * Helper function for HTMLDocument and HTMLFormElement.
- *
- * These are the only two interfaces that have [OverrideBuiltins], a named
- * getter, and no named setter. They're implemented as proxies with a custom
- * getOwnPropertyDescriptor() method. Unfortunately, overriding
- * getOwnPropertyDescriptor() automatically affects the behavior of set(),
- * which normally is just common sense but is *not* desired for these two
- * interfaces.
- *
- * The fix is for these two interfaces to override set() to ignore the
- * getOwnPropertyDescriptor() override.
- *
- * SetPropertyIgnoringNamedGetter is exposed to make it easier to override
- * set() in this way.  It carries out all the steps of BaseProxyHandler::set()
- * except the initial getOwnPropertyDescriptor() call.  The caller must supply
- * that descriptor as the 'ownDesc' parameter.
- *
- * Implemented in proxy/BaseProxyHandler.cpp.
- */
-JS_FRIEND_API bool SetPropertyIgnoringNamedGetter(
-    JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v,
-    JS::HandleValue receiver, JS::Handle<JS::PropertyDescriptor> ownDesc,
-    JS::ObjectOpResult& result);
-
-// This function is for one specific use case, please don't use this for
-// anything else!
-extern JS_FRIEND_API bool ExecuteInFrameScriptEnvironment(
-    JSContext* cx, JS::HandleObject obj, JS::HandleScript script,
-    JS::MutableHandleObject scope);
-
-// These functions are provided for the JSM component loader in Gecko.
-//
-// A 'JSMEnvironment' refers to an environment chain constructed for JSM loading
-// in a shared global. Internally it is a NonSyntacticVariablesObject with a
-// corresponding extensible LexicalEnvironmentObject that is accessible by
-// JS_ExtensibleLexicalEnvironment. The |this| value of that lexical environment
-// is the NSVO itself.
-//
-// Normal global environment (ES6):     JSM "global" environment:
-//
-//                                      * - extensible lexical environment
-//                                      |   (code runs in this environment;
-//                                      |    `let/const` bindings go here)
-//                                      |
-//                                      * - JSMEnvironment (=== `this`)
-//                                      |   (`var` bindings go here)
-//                                      |
-// * - extensible lexical environment   * - extensible lexical environment
-// |   (code runs in this environment;  |   (empty)
-// |    `let/const` bindings go here)   |
-// |                                    |
-// * - actual global (=== `this`)       * - shared JSM global
-//     (var bindings go here; and           (Object, Math, etc. live here)
-//      Object, Math, etc. live here)
-
-// Allocate a new environment in current compartment that is compatible with JSM
-// shared loading.
-extern JS_FRIEND_API JSObject* NewJSMEnvironment(JSContext* cx);
-
-// Execute the given script (copied into compartment if necessary) in the given
-// JSMEnvironment. The script must have been compiled for hasNonSyntacticScope.
-// The |jsmEnv| must have been previously allocated by NewJSMEnvironment.
-//
-// NOTE: The associated extensible lexical environment is reused.
-extern JS_FRIEND_API bool ExecuteInJSMEnvironment(JSContext* cx,
-                                                  JS::HandleScript script,
-                                                  JS::HandleObject jsmEnv);
+}  // namespace JS
 
-// Additionally, target objects may be specified as required by the Gecko
-// subscript loader. These are wrapped in non-syntactic WithEnvironments and
-// temporarily placed on environment chain.
-//
-// See also: JS::CloneAndExecuteScript(...)
-extern JS_FRIEND_API bool ExecuteInJSMEnvironment(
-    JSContext* cx, JS::HandleScript script, JS::HandleObject jsmEnv,
-    JS::HandleObjectVector targetObj);
-
-// Used by native methods to determine the JSMEnvironment of caller if possible
-// by looking at stack frames. Returns nullptr if top frame isn't a scripted
-// caller in a JSM.
-//
-// NOTE: This may find NonSyntacticVariablesObject generated by other embedding
-// such as a Gecko FrameScript. Caller can check the compartment if needed.
-extern JS_FRIEND_API JSObject* GetJSMEnvironmentOfScriptedCaller(JSContext* cx);
-
-// Determine if obj is a JSMEnvironment
-//
-// NOTE: This may return true for an NonSyntacticVariablesObject generated by
-// other embedding such as a Gecko FrameScript. Caller can check compartment.
-extern JS_FRIEND_API bool IsJSMEnvironment(JSObject* obj);
-
-extern JS_FRIEND_API bool IsSavedFrame(JSObject* obj);
-
-// Matches the condition in js/src/jit/ProcessExecutableMemory.cpp
-#if defined(XP_WIN)
-// Parameters use void* types to avoid #including windows.h. The return value of
-// this function is returned from the exception handler.
-typedef long (*JitExceptionHandler)(void* exceptionRecord,  // PEXECTION_RECORD
-                                    void* context);         // PCONTEXT
-
-/**
- * Windows uses "structured exception handling" to handle faults. When a fault
- * occurs, the stack is searched for a handler (similar to C++ exception
- * handling). If the search does not find a handler, the "unhandled exception
- * filter" is called. Breakpad uses the unhandled exception filter to do crash
- * reporting. Unfortunately, on Win64, JIT code on the stack completely throws
- * off this unwinding process and prevents the unhandled exception filter from
- * being called. The reason is that Win64 requires unwind information be
- * registered for all code regions and JIT code has none. While it is possible
- * to register full unwind information for JIT code, this is a lot of work (one
- * has to be able to recover the frame pointer at any PC) so instead we register
- * a handler for all JIT code that simply calls breakpad's unhandled exception
- * filter (which will perform crash reporting and then terminate the process).
- * This would be wrong if there was an outer __try block that expected to handle
- * the fault, but this is not generally allowed.
- *
- * Gecko must call SetJitExceptionFilter before any JIT code is compiled and
- * only once per process.
- */
-extern JS_FRIEND_API void SetJitExceptionHandler(JitExceptionHandler handler);
-#endif
-
-extern JS_FRIEND_API bool ReportIsNotFunction(JSContext* cx, JS::HandleValue v);
-
-extern JS_FRIEND_API JSObject* ConvertArgsToArray(JSContext* cx,
-                                                  const JS::CallArgs& args);
-
-// Create and add the Intl.MozDateTimeFormat constructor function to the
-// provided object.
-// If JS was built without JS_HAS_INTL_API, this function will throw an
-// exception.
-//
-// This custom date/time formatter constructor gives users the ability
-// to specify a custom format pattern. This pattern is passed *directly*
-// to ICU with NO SYNTAX PARSING OR VALIDATION WHATSOEVER. ICU appears to
-// have a a modicum of testing of this, and it won't fall over completely
-// if passed bad input. But the current behavior is entirely under-specified
-// and emphatically not shippable on the web, and it *must* be fixed before
-// this functionality can be exposed in the real world. (There are also some
-// questions about whether the format exposed here is the *right* one to
-// standardize, that will also need to be resolved to ship this.)
-extern bool AddMozDateTimeFormatConstructor(JSContext* cx,
-                                            JS::Handle<JSObject*> intl);
-
-// Create and add the Intl.MozDisplayNames constructor function to the
-// provided object.
-// If JS was built without JS_HAS_INTL_API, this function will throw an
-// exception.
-extern bool AddMozDisplayNamesConstructor(JSContext* cx,
-                                          JS::Handle<JSObject*> intl);
-
-// Create and add the Intl.DisplayNames constructor function to the provided
-// object.
-// If JS was built without JS_HAS_INTL_API, this function will throw an
-// exception.
-extern bool AddDisplayNamesConstructor(JSContext* cx,
-                                       JS::Handle<JSObject*> intl);
+/** DO NOT USE, only present for Rust bindings as a temporary hack */
+[[deprecated]] extern JS_PUBLIC_API bool JS_DeprecatedStringHasLatin1Chars(
+    JSString* str);
 
-class MOZ_STACK_CLASS JS_FRIEND_API AutoAssertNoContentJS {
- public:
-  explicit AutoAssertNoContentJS(JSContext* cx);
-  ~AutoAssertNoContentJS();
-
- private:
-  JSContext* context_;
-  bool prevAllowContentJS_;
-};
-
-// Turn on assertions so that we assert that
-//     !realm->validAccessPtr || *realm->validAccessPtr
-// is true for every |realm| that we run JS code in. The realm's validAccessPtr
-// is set via SetRealmValidAccessPtr.
-extern JS_FRIEND_API void EnableAccessValidation(JSContext* cx, bool enabled);
-
-// See EnableAccessValidation above. The caller must guarantee that accessp will
-// live at least as long as |global| is alive. The JS engine reads accessp from
-// threads that are allowed to run code on |global|, so all changes to *accessp
-// should be made from whichever thread owns |global| at a given time.
-extern JS_FRIEND_API void SetRealmValidAccessPtr(JSContext* cx,
-                                                 JS::HandleObject global,
-                                                 bool* accessp);
-
-// Returns true if the system zone is available (i.e., if no cooperative
-// contexts are using it now).
-extern JS_FRIEND_API bool SystemZoneAvailable(JSContext* cx);
-
-using LogCtorDtor = void (*)(void*, const char*, uint32_t);
-
-/**
- * Set global function used to monitor a few internal classes to highlight
- * leaks, and to hint at the origin of the leaks.
- */
-extern JS_FRIEND_API void SetLogCtorDtorFunctions(LogCtorDtor ctor,
-                                                  LogCtorDtor dtor);
-
-extern JS_FRIEND_API void LogCtor(void* self, const char* type, uint32_t sz);
-
-extern JS_FRIEND_API void LogDtor(void* self, const char* type, uint32_t sz);
-
-#define JS_COUNT_CTOR(Class) LogCtor((void*)this, #Class, sizeof(Class))
-
-#define JS_COUNT_DTOR(Class) LogDtor((void*)this, #Class, sizeof(Class))
-
-/**
- * This function only reports GC heap memory,
- * and not malloc allocated memory associated with GC things.
- */
-extern JS_FRIEND_API uint64_t GetGCHeapUsageForObjectZone(JSObject* obj);
-
-/**
- * Return whether a global object's realm has had instrumentation enabled by a
- * Debugger.
- */
-extern JS_FRIEND_API bool GlobalHasInstrumentation(JSObject* global);
-
-class JS_FRIEND_API CompartmentTransplantCallback {
- public:
-  virtual JSObject* getObjectToTransplant(JS::Compartment* compartment) = 0;
-};
-
-// Gather a set of remote window proxies by calling the callback on every
-// compartment, then transform them into cross-compartment wrappers to newTarget
-// via brain transplants. If there's a proxy in newTarget's compartment, it will
-// get swapped with newTarget, and the value of newTarget will be updated. If
-// the callback returns null for a compartment, no cross-compartment wrapper
-// will be created for that compartment. Any non-null values it returns must be
-// DOM remote proxies from the compartment that was passed in.
-extern JS_FRIEND_API void RemapRemoteWindowProxies(
-    JSContext* cx, CompartmentTransplantCallback* callback,
-    JS::MutableHandleObject newTarget);
-
-namespace gc {
-
-// API to let the DOM tell us whether we're currently in pageload, so we can
-// change the GC triggers to discourage collection of the atoms zone.
-//
-// This is a temporary measure; bug 1544117 will make this unnecessary.
-
-enum class PerformanceHint { Normal, InPageLoad };
-
-extern JS_FRIEND_API void SetPerformanceHint(JSContext* cx,
-                                             PerformanceHint hint);
-
-} /* namespace gc */
-
-extern JS_FRIEND_API JS::Zone* GetObjectZoneFromAnyThread(const JSObject* obj);
-
-} /* namespace js */
-
-#endif /* jsfriendapi_h */
+#endif  // js_String_h
--- a/js/public/shadow/String.h
+++ b/js/public/shadow/String.h
@@ -6,21 +6,24 @@
 
 /* Shadow definition of |JSString| innards.  Don't use this directly! */
 
 #ifndef js_shadow_String_h
 #define js_shadow_String_h
 
 #include <stdint.h>  // uint32_t, uintptr_t
 
-#include "jstypes.h"  // js::Bit, JS_BITS_PER_WORD
+#include "jstypes.h"  // JS_PUBLIC_API, js::Bit, js::BitMask, JS_BITS_PER_WORD
 
 #include "js/TypeDecls.h"  // JS::Latin1Char
 
+class JS_PUBLIC_API JSAtom;
 struct JSExternalStringCallbacks;
+class JSLinearString;
+class JS_PUBLIC_API JSString;
 
 namespace js {
 namespace gc {
 struct Cell;
 }  // namespace gc
 }  // namespace js
 
 namespace JS {
@@ -57,15 +60,61 @@ struct String {
     return static_cast<uint32_t>(flags_ >> 32);
 #endif
   }
 
   static bool isPermanentAtom(const js::gc::Cell* cell) {
     uint32_t flags = reinterpret_cast<const String*>(cell)->flags();
     return (flags & PERMANENT_ATOM_MASK) == PERMANENT_ATOM_MASK;
   }
+
+  bool isLinear() const { return flags() & LINEAR_BIT; }
+  bool hasLatin1Chars() const { return flags() & LATIN1_CHARS_BIT; }
+
+  // For hot code, prefer other type queries.
+  bool isExternal() const {
+    return (flags() & TYPE_FLAGS_MASK) == EXTERNAL_FLAGS;
+  }
+
+  const JS::Latin1Char* latin1LinearChars() const {
+    MOZ_ASSERT(isLinear());
+    MOZ_ASSERT(hasLatin1Chars());
+    return (flags() & String::INLINE_CHARS_BIT) ? inlineStorageLatin1
+                                                : nonInlineCharsLatin1;
+  }
+
+  const char16_t* twoByteLinearChars() const {
+    MOZ_ASSERT(isLinear());
+    MOZ_ASSERT(!hasLatin1Chars());
+    return (flags() & String::INLINE_CHARS_BIT) ? inlineStorageTwoByte
+                                                : nonInlineCharsTwoByte;
+  }
 };
 
+inline const String* AsShadowString(const JSString* str) {
+  return reinterpret_cast<const String*>(str);
+}
+
+inline String* AsShadowString(JSString* str) {
+  return reinterpret_cast<String*>(str);
+}
+
+inline const String* AsShadowString(const JSLinearString* str) {
+  return reinterpret_cast<const String*>(str);
+}
+
+inline String* AsShadowString(JSLinearString* str) {
+  return reinterpret_cast<String*>(str);
+}
+
+inline const String* AsShadowString(const JSAtom* str) {
+  return reinterpret_cast<const String*>(str);
+}
+
+inline String* AsShadowString(JSAtom* str) {
+  return reinterpret_cast<String*>(str);
+}
+
 }  // namespace shadow
 
 }  // namespace JS
 
 #endif  // js_shadow_String_h
--- a/js/rust/build.rs
+++ b/js/rust/build.rs
@@ -319,16 +319,17 @@ const WHITELIST_FUNCTIONS: &'static [&'s
     "JS_ClearPendingException",
     "JS_DefineElement",
     "JS_DefineFunction",
     "JS_DefineFunctions",
     "JS_DefineProperties",
     "JS_DefineProperty",
     "JS_DefinePropertyById",
     "JS_DefineUCProperty",
+    "JS_DeprecatedStringHasLatin1Chars",
     "JS::detail::InitWithFailureDiagnostic",
     "JS_DestroyContext",
     "JS::DisableIncrementalGC",
     "js::Dump.*",
     "JS::EnterRealm",
     "JS_EnumerateStandardClasses",
     "JS_ErrorFromException",
     "JS_FireOnNewGlobalObject",
@@ -432,17 +433,16 @@ const WHITELIST_FUNCTIONS: &'static [&'s
     "JS_SetProperty",
     "JS_SetReservedSlot",
     "JS_SetWrapObjectCallbacks",
     "JS_ShutDown",
     "JS_SplicePrototype",
     "js::StopDrainingJobQueue",
     "JS_StrictPropertyStub",
     "JS_StringEqualsAscii",
-    "JS_StringHasLatin1Chars",
     "JS_WrapObject",
     "JS_WrapValue",
     "JS_WriteBytes",
     "JS_WriteStructuredClone",
     "JS_WriteUint32Pair",
     "JS::ResolvePromise",
     "JS::RejectPromise",
     "JS::SetWarningReporter",
--- a/js/rust/etc/wrapper.hpp
+++ b/js/rust/etc/wrapper.hpp
@@ -28,16 +28,17 @@ typedef uint32_t HashNumber;
 #include "js/Initialization.h"
 #include "js/MemoryMetrics.h"
 #include "js/PropertySpec.h"
 #include "js/shadow/Object.h"
 #include "js/shadow/ObjectGroup.h"
 #include "js/shadow/Realm.h"
 #include "js/shadow/Zone.h"
 #include "js/SourceText.h"
+#include "js/String.h"
 #include "js/StructuredClone.h"
 #include "js/ValueArray.h"
 #include "js/Warnings.h"
 
 // Replacements for types that are too difficult for rust-bindgen.
 
 /// <div rustbindgen replaces="JS::detail::RootedPtr" />
 template <typename T>
--- a/js/rust/src/conversions.rs
+++ b/js/rust/src/conversions.rs
@@ -556,17 +556,17 @@ impl FromJSValConvertible for f64 {
     ) -> Result<ConversionResult<f64>, ()> {
         ToNumber(cx, val).map(ConversionResult::Success)
     }
 }
 
 /// Converts a `JSString`, encoded in "Latin1" (i.e. U+0000-U+00FF encoded as 0x00-0xFF) into a
 /// `String`.
 pub unsafe fn latin1_to_string(cx: *mut JSContext, s: *mut JSString) -> String {
-    assert!(JS_StringHasLatin1Chars(s));
+    assert!(JS_DeprecatedStringHasLatin1Chars(s));
 
     let mut length = 0;
     let chars = JS_GetLatin1StringCharsAndLength(cx, ptr::null(), s, &mut length);
     assert!(!chars.is_null());
 
     let chars = slice::from_raw_parts(chars, length as usize);
     let mut s = String::with_capacity(length as usize);
     s.extend(chars.iter().map(|&c| c as char));
@@ -607,17 +607,17 @@ impl FromJSValConvertible for String {
         value: JS::HandleValue,
         _: (),
     ) -> Result<ConversionResult<String>, ()> {
         let jsstr = ToString(cx, value);
         if jsstr.is_null() {
             debug!("ToString failed");
             return Err(());
         }
-        if JS_StringHasLatin1Chars(jsstr) {
+        if JS_DeprecatedStringHasLatin1Chars(jsstr) {
             return Ok(latin1_to_string(cx, jsstr)).map(ConversionResult::Success);
         }
 
         let mut length = 0;
         let chars = JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), jsstr, &mut length);
         assert!(!chars.is_null());
         let char_vec = slice::from_raw_parts(chars, length as usize);
         Ok(String::from_utf16_lossy(char_vec)).map(ConversionResult::Success)
--- a/js/src/builtin/SelfHostingDefines.h
+++ b/js/src/builtin/SelfHostingDefines.h
@@ -18,17 +18,17 @@
 
 // Unforgeable version of Function.prototype.apply.
 #define FUN_APPLY(FUN, RECEIVER, ARGS) \
   callFunction(std_Function_apply, FUN, RECEIVER, ARGS)
 
 // NB: keep this in sync with the copy in vm/ArgumentsObject.h.
 #define MAX_ARGS_LENGTH (500 * 1000)
 
-// NB: keep this in sync with js::MaxStringLength in jsfriendapi.h.
+// NB: keep this in sync with JS::MaxStringLength in js/public/String.h.
 #define MAX_STRING_LENGTH ((1 << 30) - 2)
 
 // Spread non-empty argument list of up to 15 elements.
 #define SPREAD(v, n) SPREAD_##n(v)
 #define SPREAD_1(v) v[0]
 #define SPREAD_2(v) SPREAD_1(v), v[1]
 #define SPREAD_3(v) SPREAD_2(v), v[2]
 #define SPREAD_4(v) SPREAD_3(v), v[3]
--- a/js/src/builtin/TestingFunctions.cpp
+++ b/js/src/builtin/TestingFunctions.cpp
@@ -60,16 +60,17 @@
 #include "js/friend/DumpFunctions.h"  // js::Dump{Backtrace,Heap,Object}, JS::FormatStackDump, js::IgnoreNurseryObjects
 #include "js/friend/WindowProxy.h"    // js::ToWindowProxyIfWindow
 #include "js/HashTable.h"
 #include "js/LocaleSensitive.h"
 #include "js/PropertySpec.h"
 #include "js/RegExpFlags.h"  // JS::RegExpFlag, JS::RegExpFlags
 #include "js/SourceText.h"
 #include "js/StableStringChars.h"
+#include "js/String.h"  // JS::GetLinearStringLength, JS::StringToLinearString
 #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"
 #include "threading/CpuCount.h"
@@ -5784,21 +5785,22 @@ static bool EncodeAsUtf8InBuffer(JSConte
   args.rval().setObject(*array);
   return true;
 }
 
 JSScript* js::TestingFunctionArgumentToScript(
     JSContext* cx, HandleValue v, JSFunction** funp /* = nullptr */) {
   if (v.isString()) {
     // To convert a string to a script, compile it. Parse it as an ES6 Program.
-    RootedLinearString linearStr(cx, StringToLinearString(cx, v.toString()));
+    RootedLinearString linearStr(cx,
+                                 JS::StringToLinearString(cx, v.toString()));
     if (!linearStr) {
       return nullptr;
     }
-    size_t len = GetLinearStringLength(linearStr);
+    size_t len = JS::GetLinearStringLength(linearStr);
     AutoStableStringChars linearChars(cx);
     if (!linearChars.initTwoByte(cx, linearStr)) {
       return nullptr;
     }
     const char16_t* chars = linearChars.twoByteRange().begin().get();
 
     SourceText<char16_t> source;
     if (!source.init(cx, chars, len, SourceOwnership::Borrowed)) {
--- a/js/src/debugger/Object.cpp
+++ b/js/src/debugger/Object.cpp
@@ -31,16 +31,17 @@
 #include "gc/Tracer.h"  // for TraceManuallyBarrieredCrossCompartmentEdge
 #include "js/CompilationAndEvaluation.h"  //  for Compile
 #include "js/Conversions.h"               // for ToObject
 #include "js/friend/WindowProxy.h"  // for IsWindow, IsWindowProxy, ToWindowIfWindowProxy
 #include "js/HeapAPI.h"             // for IsInsideNursery
 #include "js/Promise.h"             // for PromiseState
 #include "js/Proxy.h"               // for PropertyDescriptor
 #include "js/StableStringChars.h"        // for AutoStableStringChars
+#include "js/String.h"                   // for JS::StringHasLatin1Chars
 #include "proxy/ScriptedProxyHandler.h"  // for ScriptedProxyHandler
 #include "vm/ArgumentsObject.h"          // for ARGS_LENGTH_MAX
 #include "vm/ArrayObject.h"              // for ArrayObject
 #include "vm/AsyncFunction.h"            // for AsyncGeneratorObject
 #include "vm/AsyncIteration.h"           // for AsyncFunctionGeneratorObject
 #include "vm/BytecodeUtil.h"             // for JSDVG_SEARCH_STACK
 #include "vm/Compartment.h"              // for Compartment
 #include "vm/EnvironmentObject.h"        // for GetDebugEnvironmentForFunction
@@ -1238,17 +1239,17 @@ bool DebuggerObject::CallData::createSou
     return false;
   }
 
   bool isScriptElement = ToBoolean(v);
 
   JS::CompileOptions compileOptions(cx);
   compileOptions.lineno = startLine;
 
-  if (!JS_StringHasLatin1Chars(url)) {
+  if (!JS::StringHasLatin1Chars(url)) {
     JS_ReportErrorASCII(cx, "URL must be a narrow string");
     return false;
   }
 
   Vector<Latin1Char> urlChars(cx);
   if (!CopyStringToVector(cx, url, urlChars)) {
     return false;
   }
--- a/js/src/jsapi-tests/testDeduplication.cpp
+++ b/js/src/jsapi-tests/testDeduplication.cpp
@@ -6,32 +6,33 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <string.h>
 
 #include "jsfriendapi.h"
 
 #include "js/RootingAPI.h"
 #include "js/StableStringChars.h"
+#include "js/String.h"  // JS::StringToLinearString
 
 #include "jsapi-tests/tests.h"
 
 #include "vm/JSContext.h"
 #include "vm/StringType.h"
 
 #include "vm/JSContext-inl.h"
 
 static bool SameChars(JSContext* cx, JSString* str1, JSString* str2,
                       size_t offset) {
   JS::AutoCheckCannotGC nogc(cx);
 
   const JS::Latin1Char* chars1 =
-      js::StringToLinearString(cx, str1)->latin1Chars(nogc);
+      JS::StringToLinearString(cx, str1)->latin1Chars(nogc);
   const JS::Latin1Char* chars2 =
-      js::StringToLinearString(cx, str2)->latin1Chars(nogc);
+      JS::StringToLinearString(cx, str2)->latin1Chars(nogc);
 
   return chars1 == chars2 + offset;
 }
 
 BEGIN_TEST(testDeduplication_ASSC) {
   // Test with a long enough string to avoid inline chars allocation.
   const char text[] =
       "Andthebeastshallcomeforthsurroundedbyaroilingcloudofvengeance."
--- a/js/src/jsapi-tests/testScriptSourceCompression.cpp
+++ b/js/src/jsapi-tests/testScriptSourceCompression.cpp
@@ -18,16 +18,17 @@
 #include "jstypes.h"  // JS_PUBLIC_API
 
 #include "js/CompilationAndEvaluation.h"  // JS::Evaluate
 #include "js/CompileOptions.h"            // JS::CompileOptions
 #include "js/Conversions.h"               // JS::ToString
 #include "js/MemoryFunctions.h"           // JS_malloc
 #include "js/RootingAPI.h"                // JS::MutableHandle, JS::Rooted
 #include "js/SourceText.h"                // JS::SourceOwnership, JS::SourceText
+#include "js/String.h"  // JS::GetLatin1LinearStringChars, JS::GetTwoByteLinearStringChars, JS::StringHasLatin1Chars
 #include "js/UniquePtr.h"                 // js::UniquePtr
 #include "js/Utility.h"                   // JS::FreePolicy
 #include "js/Value.h"  // JS::NullValue, JS::ObjectValue, JS::Value
 #include "jsapi-tests/tests.h"
 #include "vm/Compression.h"  // js::Compressor::CHUNK_SIZE
 #include "vm/JSFunction.h"   // JSFunction::getOrCreateScript
 #include "vm/JSScript.h"  // JSScript, js::ScriptSource::MinimumCompressibleLength, js::SynchronouslyCompressSource
 
@@ -180,21 +181,21 @@ static bool IsExpectedFunctionString(JS:
            std::all_of(chars + FunctionStartLength,
                        chars + len - FunctionEndLength,
                        [](auto c) { return c == FillerWhitespace; }) &&
            std::equal(chars + len - FunctionEndLength, chars + len,
                       FunctionEnd);
   };
 
   bool hasExpectedContents;
-  if (JS_StringHasLatin1Chars(str)) {
-    const JS::Latin1Char* chars = JS_GetLatin1LinearStringChars(nogc, lstr);
+  if (JS::StringHasLatin1Chars(str)) {
+    const JS::Latin1Char* chars = JS::GetLatin1LinearStringChars(nogc, lstr);
     hasExpectedContents = CheckContents(chars);
   } else {
-    const char16_t* chars = JS_GetTwoByteLinearStringChars(nogc, lstr);
+    const char16_t* chars = JS::GetTwoByteLinearStringChars(nogc, lstr);
     hasExpectedContents = CheckContents(chars);
   }
 
   return hasExpectedContents;
 }
 
 BEGIN_TEST(testScriptSourceCompression_inOneChunk) {
   CHECK(run<char16_t>());
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -61,16 +61,17 @@
 #include "js/JSON.h"
 #include "js/LocaleSensitive.h"
 #include "js/MemoryFunctions.h"
 #include "js/PropertySpec.h"
 #include "js/Proxy.h"
 #include "js/SliceBudget.h"
 #include "js/SourceText.h"
 #include "js/StableStringChars.h"
+#include "js/String.h"  // JS::MaxStringLength
 #include "js/StructuredClone.h"
 #include "js/Symbol.h"
 #include "js/Utility.h"
 #include "js/WasmModule.h"
 #include "js/Wrapper.h"
 #include "util/CompleteFile.h"
 #include "util/StringBuffer.h"
 #include "util/Text.h"
@@ -1501,20 +1502,16 @@ JS_PUBLIC_API JSString* JS_NewMaybeExter
     JSContext* cx, const char16_t* chars, size_t length,
     const JSExternalStringCallbacks* callbacks, bool* allocatedExternal) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   return NewMaybeExternalString(cx, chars, length, callbacks,
                                 allocatedExternal);
 }
 
-extern JS_PUBLIC_API bool JS_IsExternalString(JSString* str) {
-  return str->isExternal();
-}
-
 extern JS_PUBLIC_API const JSExternalStringCallbacks*
 JS_GetExternalStringCallbacks(JSString* str) {
   return str->asExternal().callbacks();
 }
 
 static void SetNativeStackLimit(JSContext* cx, JS::StackKind kind,
                                 size_t stackSize) {
 #if JS_STACK_GROWTH_DIRECTION > 0
@@ -4254,17 +4251,17 @@ JS_PUBLIC_API JSString* JS_AtomizeAndPin
                                                  const char16_t* s) {
   return JS_AtomizeAndPinUCStringN(cx, s, js_strlen(s));
 }
 
 JS_PUBLIC_API size_t JS_GetStringLength(JSString* str) { return str->length(); }
 
 JS_PUBLIC_API bool JS_StringIsLinear(JSString* str) { return str->isLinear(); }
 
-JS_PUBLIC_API bool JS_StringHasLatin1Chars(JSString* str) {
+JS_PUBLIC_API bool JS_DeprecatedStringHasLatin1Chars(JSString* str) {
   return str->hasLatin1Chars();
 }
 
 JS_PUBLIC_API const JS::Latin1Char* JS_GetLatin1StringCharsAndLength(
     JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
     size_t* plength) {
   MOZ_ASSERT(plength);
   AssertHeapIsIdle();
@@ -4307,21 +4304,16 @@ JS_PUBLIC_API bool JS_GetStringCharAt(JS
   if (!linear) {
     return false;
   }
 
   *res = linear->latin1OrTwoByteChar(index);
   return true;
 }
 
-JS_PUBLIC_API char16_t JS_GetLinearStringCharAt(JSLinearString* str,
-                                                size_t index) {
-  return str->latin1OrTwoByteChar(index);
-}
-
 JS_PUBLIC_API bool JS_CopyStringChars(JSContext* cx,
                                       mozilla::Range<char16_t> dest,
                                       JSString* str) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   cx->check(str);
 
   JSLinearString* linear = str->ensureLinear(cx);
@@ -4341,17 +4333,17 @@ extern JS_PUBLIC_API JS::UniqueTwoByteCh
 
   JSLinearString* linear = str->ensureLinear(cx);
   if (!linear) {
     return nullptr;
   }
 
   size_t len = linear->length();
 
-  static_assert(js::MaxStringLength < UINT32_MAX,
+  static_assert(JS::MaxStringLength < UINT32_MAX,
                 "len + 1 must not overflow on 32-bit platforms");
 
   UniqueTwoByteChars chars(cx->pod_malloc<char16_t>(len + 1));
   if (!chars) {
     return nullptr;
   }
 
   CopyChars(chars.get(), *linear);
@@ -4363,26 +4355,16 @@ extern JS_PUBLIC_API JS::UniqueTwoByteCh
 extern JS_PUBLIC_API JSLinearString* JS_EnsureLinearString(JSContext* cx,
                                                            JSString* str) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   cx->check(str);
   return str->ensureLinear(cx);
 }
 
-extern JS_PUBLIC_API const Latin1Char* JS_GetLatin1LinearStringChars(
-    const JS::AutoRequireNoGC& nogc, JSLinearString* str) {
-  return str->latin1Chars(nogc);
-}
-
-extern JS_PUBLIC_API const char16_t* JS_GetTwoByteLinearStringChars(
-    const JS::AutoRequireNoGC& nogc, JSLinearString* str) {
-  return str->twoByteChars(nogc);
-}
-
 JS_PUBLIC_API bool JS_CompareStrings(JSContext* cx, JSString* str1,
                                      JSString* str2, int32_t* result) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
 
   return CompareStrings(cx, str1, str2, result);
 }
 
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -2126,50 +2126,44 @@ extern JS_PUBLIC_API size_t JS_PutEscape
  *   JSLinearString* lstr = JS_EnsureLinearString(cx, str);
  *   if (!lstr) {
  *     return false;
  *   }
  *   MOZ_ASSERT(lstr == JS_ASSERT_STRING_IS_LINEAR(str));
  *
  *   // In an infallible context, for the same 'str'.
  *   AutoCheckCannotGC nogc;
- *   const char16_t* chars = JS_GetTwoByteLinearStringChars(nogc, lstr)
+ *   const char16_t* chars = JS::GetTwoByteLinearStringChars(nogc, lstr)
  *   MOZ_ASSERT(chars);
  *
  * Note: JS strings (including linear strings and atoms) are not
  * null-terminated!
  *
  * Additionally, string characters are stored as either Latin1Char (8-bit)
- * or char16_t (16-bit). Clients can use JS_StringHasLatin1Chars and can then
+ * or char16_t (16-bit). Clients can use JS::StringHasLatin1Chars and can then
  * call either the Latin1* or TwoByte* functions. Some functions like
  * JS_CopyStringChars and JS_GetStringCharAt accept both Latin1 and TwoByte
  * strings.
  */
 
 extern JS_PUBLIC_API size_t JS_GetStringLength(JSString* str);
 
 extern JS_PUBLIC_API bool JS_StringIsLinear(JSString* str);
 
-/** Returns true iff the string's characters are stored as Latin1. */
-extern JS_PUBLIC_API bool JS_StringHasLatin1Chars(JSString* str);
-
 extern JS_PUBLIC_API const JS::Latin1Char* JS_GetLatin1StringCharsAndLength(
     JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
     size_t* length);
 
 extern JS_PUBLIC_API const char16_t* JS_GetTwoByteStringCharsAndLength(
     JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
     size_t* length);
 
 extern JS_PUBLIC_API bool JS_GetStringCharAt(JSContext* cx, JSString* str,
                                              size_t index, char16_t* res);
 
-extern JS_PUBLIC_API char16_t JS_GetLinearStringCharAt(JSLinearString* str,
-                                                       size_t index);
-
 extern JS_PUBLIC_API const char16_t* JS_GetTwoByteExternalStringChars(
     JSString* str);
 
 extern JS_PUBLIC_API bool JS_CopyStringChars(JSContext* cx,
                                              mozilla::Range<char16_t> dest,
                                              JSString* str);
 
 /**
@@ -2178,22 +2172,16 @@ extern JS_PUBLIC_API bool JS_CopyStringC
  * Returns nullptr on OOM.
  */
 extern JS_PUBLIC_API JS::UniqueTwoByteChars JS_CopyStringCharsZ(JSContext* cx,
                                                                 JSString* str);
 
 extern JS_PUBLIC_API JSLinearString* JS_EnsureLinearString(JSContext* cx,
                                                            JSString* str);
 
-extern JS_PUBLIC_API const JS::Latin1Char* JS_GetLatin1LinearStringChars(
-    const JS::AutoRequireNoGC& nogc, JSLinearString* str);
-
-extern JS_PUBLIC_API const char16_t* JS_GetTwoByteLinearStringChars(
-    const JS::AutoRequireNoGC& nogc, JSLinearString* str);
-
 static MOZ_ALWAYS_INLINE JSLinearString* JSID_TO_LINEAR_STRING(jsid id) {
   MOZ_ASSERT(JSID_IS_STRING(id));
   return reinterpret_cast<JSLinearString*>(JSID_TO_STRING(id));
 }
 
 static MOZ_ALWAYS_INLINE JSLinearString* JS_ASSERT_STRING_IS_LINEAR(
     JSString* str) {
   MOZ_ASSERT(JS_StringIsLinear(str));
@@ -2280,17 +2268,17 @@ MOZ_MUST_USE JS_PUBLIC_API bool JS_Encod
                                                         char* buffer,
                                                         size_t length);
 
 /**
  * Encode as many scalar values of the string as UTF-8 as can fit
  * into the caller-provided buffer replacing unpaired surrogates
  * with the REPLACEMENT CHARACTER.
  *
- * If JS_StringHasLatin1Chars(str) returns true, the function
+ * If JS::StringHasLatin1Chars(str) returns true, the function
  * is guaranteed to convert the entire string if
  * buffer.Length() >= 2 * JS_GetStringLength(str). Otherwise,
  * the function is guaranteed to convert the entire string if
  * buffer.Length() >= 3 * JS_GetStringLength(str).
  *
  * This function does not alter the representation of |str| or
  * any |JSString*| substring that is a constituent part of it.
  * Returns mozilla::Nothing() on OOM, without reporting an error;
--- a/js/src/jsfriendapi.cpp
+++ b/js/src/jsfriendapi.cpp
@@ -21,16 +21,17 @@
 #include "gc/WeakMap.h"
 #include "js/CharacterEncoding.h"
 #include "js/experimental/CodeCoverage.h"
 #include "js/friend/StackLimits.h"  // JS_STACK_GROWTH_DIRECTION
 #include "js/friend/WindowProxy.h"  // js::ToWindowIfWindowProxy
 #include "js/Printf.h"
 #include "js/Proxy.h"
 #include "js/shadow/Object.h"  // JS::shadow::Object
+#include "js/String.h"         // JS::detail::StringToLinearStringSlow
 #include "js/Wrapper.h"
 #include "proxy/DeadObjectProxy.h"
 #include "util/Poison.h"
 #include "vm/ArgumentsObject.h"
 #include "vm/DateObject.h"
 #include "vm/ErrorObject.h"
 #include "vm/FrameIter.h"  // js::FrameIter
 #include "vm/JSContext.h"
@@ -562,18 +563,18 @@ JS_FRIEND_API void js::VisitGrayWrapperT
       JSObject* target = e.front().key();
       if (target->isMarkedGray()) {
         callback(closure, JS::GCCellPtr(target), nogc);
       }
     }
   }
 }
 
-JS_FRIEND_API JSLinearString* js::StringToLinearStringSlow(JSContext* cx,
-                                                           JSString* str) {
+JSLinearString* JS::detail::StringToLinearStringSlow(JSContext* cx,
+                                                     JSString* str) {
   return str->ensureLinear(cx);
 }
 
 static bool CopyProxyObject(JSContext* cx, Handle<ProxyObject*> from,
                             Handle<ProxyObject*> to) {
   MOZ_ASSERT(from->getClass() == to->getClass());
 
   if (from->is<WrapperObject>() &&
--- a/js/src/jsfriendapi.h
+++ b/js/src/jsfriendapi.h
@@ -17,17 +17,16 @@
 #include "js/Class.h"
 #include "js/ErrorReport.h"
 #include "js/Exception.h"
 #include "js/friend/ErrorMessages.h"
 #include "js/HeapAPI.h"
 #include "js/shadow/Function.h"     // JS::shadow::Function
 #include "js/shadow/Object.h"       // JS::shadow::Object
 #include "js/shadow/ObjectGroup.h"  // JS::shadow::ObjectGroup
-#include "js/shadow/String.h"       // JS::shadow::String
 #include "js/TypeDecls.h"
 #include "js/Utility.h"
 
 struct JSJitInfo;
 
 namespace JS {
 template <class T>
 class Heap;
@@ -499,171 +498,16 @@ inline void SetReservedSlot(JSObject* ob
 
 JS_FRIEND_API uint32_t GetObjectSlotSpan(JSObject* obj);
 
 inline const JS::Value& GetObjectSlot(JSObject* obj, size_t slot) {
   MOZ_ASSERT(slot < GetObjectSlotSpan(obj));
   return reinterpret_cast<const JS::shadow::Object*>(obj)->slotRef(slot);
 }
 
-MOZ_ALWAYS_INLINE size_t GetAtomLength(JSAtom* atom) {
-  return reinterpret_cast<JS::shadow::String*>(atom)->length();
-}
-
-// Maximum length of a JS string. This is chosen so that the number of bytes
-// allocated for a null-terminated TwoByte string still fits in int32_t.
-static const uint32_t MaxStringLength = (1 << 30) - 2;
-
-static_assert((uint64_t(MaxStringLength) + 1) * sizeof(char16_t) <= INT32_MAX,
-              "size of null-terminated JSString char buffer must fit in "
-              "INT32_MAX");
-
-MOZ_ALWAYS_INLINE size_t GetLinearStringLength(JSLinearString* s) {
-  return reinterpret_cast<JS::shadow::String*>(s)->length();
-}
-
-MOZ_ALWAYS_INLINE bool LinearStringHasLatin1Chars(JSLinearString* s) {
-  return reinterpret_cast<JS::shadow::String*>(s)->flags() &
-         JS::shadow::String::LATIN1_CHARS_BIT;
-}
-
-MOZ_ALWAYS_INLINE bool AtomHasLatin1Chars(JSAtom* atom) {
-  return reinterpret_cast<JS::shadow::String*>(atom)->flags() &
-         JS::shadow::String::LATIN1_CHARS_BIT;
-}
-
-MOZ_ALWAYS_INLINE bool StringHasLatin1Chars(JSString* s) {
-  return reinterpret_cast<JS::shadow::String*>(s)->flags() &
-         JS::shadow::String::LATIN1_CHARS_BIT;
-}
-
-MOZ_ALWAYS_INLINE const JS::Latin1Char* GetLatin1LinearStringChars(
-    const JS::AutoRequireNoGC& nogc, JSLinearString* linear) {
-  MOZ_ASSERT(LinearStringHasLatin1Chars(linear));
-
-  using JS::shadow::String;
-  String* s = reinterpret_cast<String*>(linear);
-  if (s->flags() & String::INLINE_CHARS_BIT) {
-    return s->inlineStorageLatin1;
-  }
-  return s->nonInlineCharsLatin1;
-}
-
-MOZ_ALWAYS_INLINE const char16_t* GetTwoByteLinearStringChars(
-    const JS::AutoRequireNoGC& nogc, JSLinearString* linear) {
-  MOZ_ASSERT(!LinearStringHasLatin1Chars(linear));
-
-  using JS::shadow::String;
-  String* s = reinterpret_cast<String*>(linear);
-  if (s->flags() & String::INLINE_CHARS_BIT) {
-    return s->inlineStorageTwoByte;
-  }
-  return s->nonInlineCharsTwoByte;
-}
-
-MOZ_ALWAYS_INLINE char16_t GetLinearStringCharAt(JSLinearString* linear,
-                                                 size_t index) {
-  MOZ_ASSERT(index < GetLinearStringLength(linear));
-  JS::AutoCheckCannotGC nogc;
-  return LinearStringHasLatin1Chars(linear)
-             ? GetLatin1LinearStringChars(nogc, linear)[index]
-             : GetTwoByteLinearStringChars(nogc, linear)[index];
-}
-
-MOZ_ALWAYS_INLINE JSLinearString* AtomToLinearString(JSAtom* atom) {
-  return reinterpret_cast<JSLinearString*>(atom);
-}
-
-MOZ_ALWAYS_INLINE const JS::Latin1Char* GetLatin1AtomChars(
-    const JS::AutoRequireNoGC& nogc, JSAtom* atom) {
-  return GetLatin1LinearStringChars(nogc, AtomToLinearString(atom));
-}
-
-MOZ_ALWAYS_INLINE const char16_t* GetTwoByteAtomChars(
-    const JS::AutoRequireNoGC& nogc, JSAtom* atom) {
-  return GetTwoByteLinearStringChars(nogc, AtomToLinearString(atom));
-}
-
-MOZ_ALWAYS_INLINE bool IsExternalString(
-    JSString* str, const JSExternalStringCallbacks** callbacks,
-    const char16_t** chars) {
-  using JS::shadow::String;
-  String* s = reinterpret_cast<String*>(str);
-
-  if ((s->flags() & String::TYPE_FLAGS_MASK) != String::EXTERNAL_FLAGS) {
-    return false;
-  }
-
-  MOZ_ASSERT(JS_IsExternalString(str));
-  *callbacks = s->externalCallbacks;
-  *chars = s->nonInlineCharsTwoByte;
-  return true;
-}
-
-JS_FRIEND_API JSLinearString* StringToLinearStringSlow(JSContext* cx,
-                                                       JSString* str);
-
-MOZ_ALWAYS_INLINE JSLinearString* StringToLinearString(JSContext* cx,
-                                                       JSString* str) {
-  using JS::shadow::String;
-  String* s = reinterpret_cast<String*>(str);
-  if (MOZ_UNLIKELY(!(s->flags() & String::LINEAR_BIT))) {
-    return StringToLinearStringSlow(cx, str);
-  }
-  return reinterpret_cast<JSLinearString*>(str);
-}
-
-template <typename CharType>
-MOZ_ALWAYS_INLINE void CopyLinearStringChars(CharType* dest, JSLinearString* s,
-                                             size_t len, size_t start = 0);
-
-MOZ_ALWAYS_INLINE void CopyLinearStringChars(char16_t* dest, JSLinearString* s,
-                                             size_t len, size_t start = 0) {
-  MOZ_ASSERT(start + len <= GetLinearStringLength(s));
-  JS::AutoCheckCannotGC nogc;
-  if (LinearStringHasLatin1Chars(s)) {
-    const JS::Latin1Char* src = GetLatin1LinearStringChars(nogc, s);
-    for (size_t i = 0; i < len; i++) {
-      dest[i] = src[start + i];
-    }
-  } else {
-    const char16_t* src = GetTwoByteLinearStringChars(nogc, s);
-    mozilla::PodCopy(dest, src + start, len);
-  }
-}
-
-MOZ_ALWAYS_INLINE void CopyLinearStringChars(char* dest, JSLinearString* s,
-                                             size_t len, size_t start = 0) {
-  MOZ_ASSERT(start + len <= GetLinearStringLength(s));
-  JS::AutoCheckCannotGC nogc;
-  if (LinearStringHasLatin1Chars(s)) {
-    const JS::Latin1Char* src = GetLatin1LinearStringChars(nogc, s);
-    for (size_t i = 0; i < len; i++) {
-      dest[i] = char(src[start + i]);
-    }
-  } else {
-    const char16_t* src = GetTwoByteLinearStringChars(nogc, s);
-    for (size_t i = 0; i < len; i++) {
-      dest[i] = char(src[start + i]);
-    }
-  }
-}
-
-template <typename CharType>
-inline bool CopyStringChars(JSContext* cx, CharType* dest, JSString* s,
-                            size_t len, size_t start = 0) {
-  JSLinearString* linear = StringToLinearString(cx, s);
-  if (!linear) {
-    return false;
-  }
-
-  CopyLinearStringChars(dest, linear, len, start);
-  return true;
-}
-
 /**
  * Add some or all property keys of obj to the id vector *props.
  *
  * The flags parameter controls which property keys are added. Pass a
  * combination of the following bits:
  *
  *     JSITER_OWNONLY - Don't also search the prototype chain; only consider
  *       obj's own properties.
--- a/js/src/moz.build
+++ b/js/src/moz.build
@@ -179,16 +179,17 @@ EXPORTS.js += [
     '../public/RootingAPI.h',
     '../public/SavedFrameAPI.h',
     '../public/ScalarType.h',
     '../public/SharedArrayBuffer.h',
     '../public/SliceBudget.h',
     '../public/SourceText.h',
     '../public/StableStringChars.h',
     '../public/Stream.h',
+    '../public/String.h',
     '../public/StructuredClone.h',
     '../public/SweepingAPI.h',
     '../public/Symbol.h',
     '../public/TraceKind.h',
     '../public/TraceLoggerAPI.h',
     '../public/TracingAPI.h',
     '../public/Transcoding.h',
     '../public/TypeDecls.h',
--- a/js/src/vm/StringType.h
+++ b/js/src/vm/StringType.h
@@ -10,28 +10,28 @@
 #include "mozilla/Maybe.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/Range.h"
 #include "mozilla/TextUtils.h"
 
 #include <type_traits>  // std::is_same
 
 #include "jsapi.h"
-#include "jsfriendapi.h"
 
 #include "gc/Allocator.h"
 #include "gc/Barrier.h"
 #include "gc/Cell.h"
 #include "gc/MaybeRooted.h"
 #include "gc/Nursery.h"
 #include "gc/RelocationOverlay.h"
 #include "gc/Rooting.h"
 #include "js/CharacterEncoding.h"
 #include "js/RootingAPI.h"
 #include "js/shadow/String.h"  // JS::shadow::String
+#include "js/String.h"         // JS::MaxStringLength
 #include "js/UniquePtr.h"
 #include "util/Text.h"
 #include "vm/Printer.h"
 
 class JSDependentString;
 class JSExtensibleString;
 class JSExternalString;
 class JSInlineString;
@@ -307,17 +307,17 @@ class JSString : public js::gc::CellWith
   // NON_DEDUP_BIT is used in string deduplication during tenuring.
   static const uint32_t NON_DEDUP_BIT = js::Bit(11);
 
   // If IN_STRING_TO_ATOM_CACHE is set, this string had an entry in the
   // StringToAtomCache at some point. Note that GC can purge the cache without
   // clearing this bit.
   static const uint32_t IN_STRING_TO_ATOM_CACHE = js::Bit(12);
 
-  static const uint32_t MAX_LENGTH = js::MaxStringLength;
+  static const uint32_t MAX_LENGTH = JS::MaxStringLength;
 
   static const JS::Latin1Char MAX_LATIN1_CHAR = 0xff;
 
   /*
    * Helper function to validate that a string of a given length is
    * representable by a JSString. An allocation overflow is reported if false
    * is returned.
    */
--- a/js/src/wasm/WasmValidate.cpp
+++ b/js/src/wasm/WasmValidate.cpp
@@ -20,16 +20,17 @@
 
 #include "mozilla/CheckedInt.h"
 #include "mozilla/Unused.h"
 #include "mozilla/Utf8.h"
 
 #include "builtin/TypedObject.h"
 #include "jit/JitOptions.h"
 #include "js/Printf.h"
+#include "js/String.h"  // JS::MaxStringLength
 #include "vm/JSContext.h"
 #include "vm/Realm.h"
 #include "wasm/WasmOpIter.h"
 
 using namespace js;
 using namespace js::jit;
 using namespace js::wasm;
 
@@ -3109,17 +3110,18 @@ static bool DecodeFunctionNameSubsection
     }
 
     // Names must refer to real functions and be given in ascending order.
     if (funcIndex >= env->numFuncs() || funcIndex < funcNames.length()) {
       return d.fail("invalid function index");
     }
 
     Name funcName;
-    if (!d.readVarU32(&funcName.length) || funcName.length > MaxStringLength) {
+    if (!d.readVarU32(&funcName.length) ||
+        funcName.length > JS::MaxStringLength) {
       return d.fail("unable to read function name length");
     }
 
     if (!funcName.length) {
       continue;
     }
 
     if (!funcNames.resize(funcIndex + 1)) {
--- a/js/xpconnect/src/JSServices.cpp
+++ b/js/xpconnect/src/JSServices.cpp
@@ -2,16 +2,17 @@
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* 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 "xpcprivate.h"
 #include "StaticComponents.h"
 #include "mozilla/ErrorResult.h"
+#include "js/String.h"  // JS::LinearStringHasLatin1Chars
 #include "nsJSUtils.h"
 
 using namespace mozilla;
 using namespace JS;
 
 namespace xpc {
 
 static bool Services_NewEnumerate(JSContext* cx, HandleObject obj,
@@ -63,17 +64,17 @@ static bool Services_NewEnumerate(JSCont
   }
 
   return true;
 }
 
 static JSLinearString* GetNameIfLatin1(jsid id) {
   if (JSID_IS_STRING(id)) {
     JSLinearString* name = JSID_TO_LINEAR_STRING(id);
-    if (js::LinearStringHasLatin1Chars(name)) {
+    if (JS::LinearStringHasLatin1Chars(name)) {
       return name;
     }
   }
   return nullptr;
 }
 
 static JSObject* GetService(JSContext* cx, const xpcom::JSServiceEntry& service,
                             ErrorResult& aRv) {
--- a/js/xpconnect/src/XPCConvert.cpp
+++ b/js/xpconnect/src/XPCConvert.cpp
@@ -22,16 +22,17 @@
 #include "nsWrapperCacheInlines.h"
 
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "js/Array.h"  // JS::GetArrayLength, JS::IsArrayObject, JS::NewArrayObject
 #include "js/CharacterEncoding.h"
 #include "js/experimental/TypedData.h"  // JS_GetArrayBufferViewType, JS_GetArrayBufferViewData, JS_GetTypedArrayLength, JS_IsTypedArrayObject
 #include "js/MemoryFunctions.h"
+#include "js/String.h"  // JS::StringHasLatin1Chars
 
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/dom/DOMException.h"
 #include "mozilla/dom/PrimitiveConversions.h"
 #include "mozilla/dom/Promise.h"
 
 using namespace xpc;
 using namespace mozilla;
@@ -562,17 +563,17 @@ bool XPCConvert::JSData2Native(JSContext
       }
 
       JSString* str = ToString(cx, s);
       if (!str) {
         return false;
       }
 
 #ifdef DEBUG
-      if (JS_StringHasLatin1Chars(str)) {
+      if (JS::StringHasLatin1Chars(str)) {
         size_t len;
         AutoCheckCannotGC nogc;
         const Latin1Char* chars =
             JS_GetLatin1StringCharsAndLength(cx, nogc, str, &len);
         if (chars) {
           CheckCharsInCharRange(chars, len);
         }
       } else {
--- a/js/xpconnect/src/xpcpublic.h
+++ b/js/xpconnect/src/xpcpublic.h
@@ -7,16 +7,17 @@
 #ifndef xpcpublic_h
 #define xpcpublic_h
 
 #include "jsapi.h"
 #include "js/BuildId.h"  // JS::BuildIdCharVector
 #include "js/HeapAPI.h"
 #include "js/GCAPI.h"
 #include "js/Proxy.h"
+#include "js/String.h"  // JS::IsExternalString
 #include "js/Wrapper.h"
 
 #include "nsAtom.h"
 #include "nsISupports.h"
 #include "nsIURI.h"
 #include "nsIPrincipal.h"
 #include "nsIGlobalObject.h"
 #include "nsWrapperCache.h"
@@ -263,17 +264,17 @@ class XPCStringConvert {
     rval.setString(str);
     return true;
   }
 
   static MOZ_ALWAYS_INLINE bool MaybeGetExternalStringChars(
       JSString* str, const JSExternalStringCallbacks* desiredCallbacks,
       const char16_t** chars) {
     const JSExternalStringCallbacks* callbacks;
-    return js::IsExternalString(str, &callbacks, chars) &&
+    return JS::IsExternalString(str, &callbacks, chars) &&
            callbacks == desiredCallbacks;
   }
 
   // Returns non-null chars if the given string is a literal external string.
   static MOZ_ALWAYS_INLINE bool MaybeGetLiteralStringChars(
       JSString* str, const char16_t** chars) {
     return MaybeGetExternalStringChars(str, &sLiteralExternalString, chars);
   }
--- a/widget/android/EventDispatcher.cpp
+++ b/widget/android/EventDispatcher.cpp
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "EventDispatcher.h"
 
 #include "JavaBuiltins.h"
 #include "nsAppShell.h"
 #include "nsJSUtils.h"
 #include "js/Array.h"  // JS::GetArrayLength, JS::IsArrayObject, JS::NewArrayObject
+#include "js/String.h"    // JS::StringHasLatin1Chars
 #include "js/Warnings.h"  // JS::WarnUTF8
 #include "xpcpublic.h"
 
 #include "mozilla/ScopeExit.h"
 #include "mozilla/dom/ScriptSettings.h"
 #include "mozilla/java/EventCallbackWrappers.h"
 
 // Disable the C++ 2a warning. See bug #1509926
@@ -41,17 +42,17 @@ nsresult BoxString(JSContext* aCx, JS::H
     aOut = nullptr;
     return NS_OK;
   }
 
   MOZ_ASSERT(aData.isString());
 
   JS::RootedString str(aCx, aData.toString());
 
-  if (JS_StringHasLatin1Chars(str)) {
+  if (JS::StringHasLatin1Chars(str)) {
     nsAutoJSString autoStr;
     NS_ENSURE_TRUE(CheckJS(aCx, autoStr.init(aCx, str)), NS_ERROR_FAILURE);
 
     // StringParam can automatically convert a nsString to jstring.
     aOut = jni::StringParam(autoStr, aOut.Env());
     return NS_OK;
   }
 
--- a/xpcom/ds/tools/perfecthash.py
+++ b/xpcom/ds/tools/perfecthash.py
@@ -308,28 +308,28 @@ class CGHelper(object):
             return_type = 'const %s&' % self.entry_type
 
         return textwrap.dedent("""
             %(return_type)s
             %(name)s(JSLinearString* aKey)
             {
               %(basis_table)s
 
-              size_t length = js::GetLinearStringLength(aKey);
+              size_t length = JS::GetLinearStringLength(aKey);
 
               JS::AutoCheckCannotGC nogc;
-              if (js::LinearStringHasLatin1Chars(aKey)) {
+              if (JS::LinearStringHasLatin1Chars(aKey)) {
                 auto& entry = mozilla::perfecthash::Lookup(
-                  js::GetLatin1LinearStringChars(nogc, aKey),
+                  JS::GetLatin1LinearStringChars(nogc, aKey),
                   length, BASES, %(entries_name)s);
 
                 %(return_entry)s
               } else {
                 auto& entry = mozilla::perfecthash::Lookup(
-                  js::GetTwoByteLinearStringChars(nogc, aKey),
+                  JS::GetTwoByteLinearStringChars(nogc, aKey),
                   length, BASES, %(entries_name)s);
 
                 %(return_entry)s
               }
             }
             """) % {
                 'name': name,
                 'basis_table': self._indent(self.basis_table()),