Bug 1485066 - Part 1: Remove JSAutoByteString. r=Waldo

This commit is contained in:
André Bargull 2018-09-05 02:25:42 -07:00
Родитель da0b67cc1f
Коммит 775b7277cc
66 изменённых файлов: 711 добавлений и 769 удалений

Просмотреть файл

@ -6,7 +6,7 @@
#include "ChromeUtils.h" #include "ChromeUtils.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/SavedFrameAPI.h" #include "js/SavedFrameAPI.h"
#include "jsfriendapi.h" #include "jsfriendapi.h"
#include "WrapperFactory.h" #include "WrapperFactory.h"
@ -467,11 +467,11 @@ namespace module_getter {
JS::Rooted<JSString*> moduleURI( JS::Rooted<JSString*> moduleURI(
aCx, js::GetFunctionNativeReserved(callee, SLOT_URI).toString()); aCx, js::GetFunctionNativeReserved(callee, SLOT_URI).toString());
JSAutoByteString bytes; JS::UniqueChars bytes = JS_EncodeStringToUTF8(aCx, moduleURI);
if (!bytes.encodeUtf8(aCx, moduleURI)) { if (!bytes) {
return false; return false;
} }
nsDependentCString uri(bytes.ptr()); nsDependentCString uri(bytes.get());
RefPtr<mozJSComponentLoader> moduleloader = mozJSComponentLoader::Get(); RefPtr<mozJSComponentLoader> moduleloader = mozJSComponentLoader::Get();
MOZ_ASSERT(moduleloader); MOZ_ASSERT(moduleloader);

Просмотреть файл

@ -19,7 +19,6 @@
#include "GeckoProfiler.h" #include "GeckoProfiler.h"
#include "jsapi.h" #include "jsapi.h"
#include "jsfriendapi.h" #include "jsfriendapi.h"
#include "js/AutoByteString.h"
#include "js/Conversions.h" #include "js/Conversions.h"
#include "js/StableStringChars.h" #include "js/StableStringChars.h"
#include "nsString.h" #include "nsString.h"

Просмотреть файл

@ -8,7 +8,7 @@
#define mozilla_dom_BindingUtils_h__ #define mozilla_dom_BindingUtils_h__
#include "jsfriendapi.h" #include "jsfriendapi.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/Wrapper.h" #include "js/Wrapper.h"
#include "js/Conversions.h" #include "js/Conversions.h"
#include "mozilla/ArrayUtils.h" #include "mozilla/ArrayUtils.h"
@ -1313,12 +1313,12 @@ inline bool
EnumValueNotFound<true>(JSContext* cx, JS::HandleString str, const char* type, EnumValueNotFound<true>(JSContext* cx, JS::HandleString str, const char* type,
const char* sourceDescription) const char* sourceDescription)
{ {
JSAutoByteString deflated; JS::UniqueChars deflated = JS_EncodeStringToUTF8(cx, str);
if (!deflated.encodeUtf8(cx, str)) { if (!deflated) {
return false; return false;
} }
return ThrowErrorMessage(cx, MSG_INVALID_ENUM_VALUE, sourceDescription, return ThrowErrorMessage(cx, MSG_INVALID_ENUM_VALUE, sourceDescription,
deflated.ptr(), type); deflated.get(), type);
} }
template<typename CharT> template<typename CharT>

Просмотреть файл

@ -6,6 +6,7 @@
#include "mozilla/dom/CallbackInterface.h" #include "mozilla/dom/CallbackInterface.h"
#include "jsapi.h" #include "jsapi.h"
#include "js/CharacterEncoding.h"
#include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/BindingUtils.h"
#include "nsPrintfCString.h" #include "nsPrintfCString.h"
@ -21,10 +22,9 @@ CallbackInterface::GetCallableProperty(JSContext* cx, JS::Handle<jsid> aPropId,
} }
if (!aCallable.isObject() || if (!aCallable.isObject() ||
!JS::IsCallable(&aCallable.toObject())) { !JS::IsCallable(&aCallable.toObject())) {
char* propName = JS::UniqueChars propName =
JS_EncodeString(cx, JS_FORGET_STRING_FLATNESS(JSID_TO_FLAT_STRING(aPropId))); JS_EncodeString(cx, JS_FORGET_STRING_FLATNESS(JSID_TO_FLAT_STRING(aPropId)));
nsPrintfCString description("Property '%s'", propName); nsPrintfCString description("Property '%s'", propName.get());
JS_free(cx, propName);
ThrowErrorMessage(cx, MSG_NOT_CALLABLE, description.get()); ThrowErrorMessage(cx, MSG_NOT_CALLABLE, description.get());
return false; return false;
} }

Просмотреть файл

@ -16,7 +16,7 @@
#include "base/basictypes.h" #include "base/basictypes.h"
#include "jsapi.h" #include "jsapi.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h" #include "js/CompilationAndEvaluation.h"
#include "js/SourceBufferHolder.h" #include "js/SourceBufferHolder.h"
@ -83,10 +83,10 @@ Print(JSContext *cx, unsigned argc, JS::Value *vp)
JSString *str = JS::ToString(cx, args[i]); JSString *str = JS::ToString(cx, args[i]);
if (!str) if (!str)
return false; return false;
JSAutoByteString bytes(cx, str); JS::UniqueChars bytes = JS_EncodeString(cx, str);
if (!bytes) if (!bytes)
return false; return false;
fprintf(stdout, "%s%s", i ? " " : "", bytes.ptr()); fprintf(stdout, "%s%s", i ? " " : "", bytes.get());
fflush(stdout); fflush(stdout);
} }
fputc('\n', stdout); fputc('\n', stdout);
@ -119,11 +119,11 @@ Dump(JSContext *cx, unsigned argc, JS::Value *vp)
JSString *str = JS::ToString(cx, args[0]); JSString *str = JS::ToString(cx, args[0]);
if (!str) if (!str)
return false; return false;
JSAutoByteString bytes(cx, str); JS::UniqueChars bytes = JS_EncodeString(cx, str);
if (!bytes) if (!bytes)
return false; return false;
fputs(bytes.ptr(), stdout); fputs(bytes.get(), stdout);
fflush(stdout); fflush(stdout);
return true; return true;
} }
@ -147,20 +147,20 @@ Load(JSContext *cx,
JS::Rooted<JSString*> str(cx, JS::ToString(cx, args[i])); JS::Rooted<JSString*> str(cx, JS::ToString(cx, args[i]));
if (!str) if (!str)
return false; return false;
JSAutoByteString filename(cx, str); JS::UniqueChars filename = JS_EncodeString(cx, str);
if (!filename) if (!filename)
return false; return false;
FILE *file = fopen(filename.ptr(), "r"); FILE *file = fopen(filename.get(), "r");
if (!file) { if (!file) {
filename.clear(); filename = JS_EncodeStringToUTF8(cx, str);
if (!filename.encodeUtf8(cx, str)) if (!filename)
return false; return false;
JS_ReportErrorUTF8(cx, "cannot open file '%s' for reading", filename.ptr()); JS_ReportErrorUTF8(cx, "cannot open file '%s' for reading", filename.get());
return false; return false;
} }
JS::CompileOptions options(cx); JS::CompileOptions options(cx);
options.setUTF8(true) options.setUTF8(true)
.setFileAndLine(filename.ptr(), 1); .setFileAndLine(filename.get(), 1);
JS::Rooted<JSScript*> script(cx); JS::Rooted<JSScript*> script(cx);
bool ok = JS::Compile(cx, options, file, &script); bool ok = JS::Compile(cx, options, file, &script);
fclose(file); fclose(file);
@ -346,13 +346,13 @@ XPCShellEnvironment::ProcessFile(JSContext *cx,
/* Suppress warnings from JS::ToString(). */ /* Suppress warnings from JS::ToString(). */
older = JS::SetWarningReporter(cx, nullptr); older = JS::SetWarningReporter(cx, nullptr);
str = JS::ToString(cx, result); str = JS::ToString(cx, result);
JSAutoByteString bytes; JS::UniqueChars bytes;
if (str) if (str)
bytes.encodeLatin1(cx, str); bytes = JS_EncodeString(cx, str);
JS::SetWarningReporter(cx, older); JS::SetWarningReporter(cx, older);
if (!!bytes) if (!!bytes)
fprintf(stdout, "%s\n", bytes.ptr()); fprintf(stdout, "%s\n", bytes.get());
else else
ok = false; ok = false;
} }

Просмотреть файл

@ -1,140 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* DEPRECATED functions and classes for heap-allocating copies of a JSString's
* data.
*/
#ifndef js_AutoByteString_h
#define js_AutoByteString_h
#include "mozilla/Assertions.h" // MOZ_ASSERT
#include "mozilla/Attributes.h" // MOZ_RAII, MOZ_GUARD*
#include <string.h> // strlen
#include "jstypes.h" // JS_PUBLIC_API
#include "js/MemoryFunctions.h" // JS_free
#include "js/RootingAPI.h" // JS::Handle
#include "js/TypeDecls.h" // JSContext, JSString
#include "js/Utility.h" // js_free, JS::UniqueChars
/**
* DEPRECATED
*
* Allocate memory sufficient to contain the characters of |str| truncated to
* Latin-1 and a trailing null terminator, fill the memory with the characters
* interpreted in that manner plus the null terminator, and return a pointer to
* the memory. The memory must be freed using JS_free to avoid leaking.
*
* This function *loses information* when it copies the characters of |str| if
* |str| contains code units greater than 0xFF. Additionally, users that
* depend on null-termination will misinterpret the copied characters if |str|
* contains any nulls. Avoid using this function if possible, because it will
* eventually be removed.
*/
extern JS_PUBLIC_API(char*)
JS_EncodeString(JSContext* cx, JSString* str);
/**
* DEPRECATED
*
* Same behavior as JS_EncodeString(), but encode into a UTF-8 string.
*
* This function *loses information* when it copies the characters of |str| if
* |str| contains invalid UTF-16: U+FFFD REPLACEMENT CHARACTER will be copied
* instead.
*
* The returned string is also subject to misinterpretation if |str| contains
* any nulls (which are faithfully transcribed into the returned string, but
* which will implicitly truncate the string if it's passed to functions that
* expect null-terminated strings).
*
* Avoid using this function if possible, because we'll remove it once we can
* devise a better API for the task.
*/
extern JS_PUBLIC_API(char*)
JS_EncodeStringToUTF8(JSContext* cx, JS::Handle<JSString*> str);
/**
* DEPRECATED
*
* A lightweight RAII helper class around the various JS_Encode* functions
* above, subject to the same pitfalls noted above. Avoid using this class if
* possible, because as with the functions above, it too needs to be replaced
* with a better, safer API.
*/
class MOZ_RAII JSAutoByteString final
{
private:
char* mBytes;
MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
private:
JSAutoByteString(const JSAutoByteString& another) = delete;
void operator=(const JSAutoByteString& another) = delete;
public:
JSAutoByteString(JSContext* cx, JSString* str
MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
: mBytes(JS_EncodeString(cx, str))
{
MOZ_ASSERT(cx);
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
}
explicit JSAutoByteString(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM)
: mBytes(nullptr)
{
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
}
~JSAutoByteString() {
JS_free(nullptr, mBytes);
}
/* Take ownership of the given byte array. */
void initBytes(JS::UniqueChars&& bytes) {
MOZ_ASSERT(!mBytes);
mBytes = bytes.release();
}
char* encodeLatin1(JSContext* cx, JSString* str) {
MOZ_ASSERT(!mBytes);
MOZ_ASSERT(cx);
mBytes = JS_EncodeString(cx, str);
return mBytes;
}
char* encodeUtf8(JSContext* cx, JS::Handle<JSString*> str) {
MOZ_ASSERT(!mBytes);
MOZ_ASSERT(cx);
mBytes = JS_EncodeStringToUTF8(cx, str);
return mBytes;
}
void clear() {
js_free(mBytes);
mBytes = nullptr;
}
char* ptr() const {
return mBytes;
}
bool operator!() const {
return !mBytes;
}
size_t length() const {
if (!mBytes)
return 0;
return strlen(mBytes);
}
};
#endif /* js_AutoByteString_h */

Просмотреть файл

@ -331,4 +331,41 @@ StringIsASCII(const char* s);
inline void JS_free(JS::Latin1CharsZ& ptr) { js_free((void*)ptr.get()); } inline void JS_free(JS::Latin1CharsZ& ptr) { js_free((void*)ptr.get()); }
inline void JS_free(JS::UTF8CharsZ& ptr) { js_free((void*)ptr.get()); } inline void JS_free(JS::UTF8CharsZ& ptr) { js_free((void*)ptr.get()); }
/**
* DEPRECATED
*
* Allocate memory sufficient to contain the characters of |str| truncated to
* Latin-1 and a trailing null terminator, fill the memory with the characters
* interpreted in that manner plus the null terminator, and return a pointer to
* the memory.
*
* This function *loses information* when it copies the characters of |str| if
* |str| contains code units greater than 0xFF. Additionally, users that
* depend on null-termination will misinterpret the copied characters if |str|
* contains any nulls. Avoid using this function if possible, because it will
* eventually be removed.
*/
extern JS_PUBLIC_API(JS::UniqueChars)
JS_EncodeString(JSContext* cx, JSString* str);
/**
* DEPRECATED
*
* Same behavior as JS_EncodeString(), but encode into a UTF-8 string.
*
* This function *loses information* when it copies the characters of |str| if
* |str| contains invalid UTF-16: U+FFFD REPLACEMENT CHARACTER will be copied
* instead.
*
* The returned string is also subject to misinterpretation if |str| contains
* any nulls (which are faithfully transcribed into the returned string, but
* which will implicitly truncate the string if it's passed to functions that
* expect null-terminated strings).
*
* Avoid using this function if possible, because we'll remove it once we can
* devise a better API for the task.
*/
extern JS_PUBLIC_API(JS::UniqueChars)
JS_EncodeStringToUTF8(JSContext* cx, JS::Handle<JSString*> str);
#endif /* js_CharacterEncoding_h */ #endif /* js_CharacterEncoding_h */

Просмотреть файл

@ -319,7 +319,6 @@ const WHITELIST_FUNCTIONS: &'static [&'static str] = &[
"JS_DestroyContext", "JS_DestroyContext",
"JS::DisableIncrementalGC", "JS::DisableIncrementalGC",
"js::Dump.*", "js::Dump.*",
"JS_EncodeStringToUTF8",
"JS::EnterRealm", "JS::EnterRealm",
"JS_EnumerateStandardClasses", "JS_EnumerateStandardClasses",
"JS_ErrorFromException", "JS_ErrorFromException",

Просмотреть файл

@ -340,6 +340,10 @@ extern "C" {
dest: *mut JSStructuredCloneData) dest: *mut JSStructuredCloneData)
-> bool; -> bool;
pub fn JSEncodeStringToUTF8(cx: *mut JSContext,
string: JS::HandleString)
-> *mut ::libc::c_char;
pub fn IsDebugBuild() -> bool; pub fn IsDebugBuild() -> bool;
} }

Просмотреть файл

@ -15,6 +15,7 @@
#include "jsapi.h" #include "jsapi.h"
#include "jsfriendapi.h" #include "jsfriendapi.h"
#include "js/Proxy.h" #include "js/Proxy.h"
#include "js/CharacterEncoding.h"
#include "js/Class.h" #include "js/Class.h"
#include "js/MemoryMetrics.h" #include "js/MemoryMetrics.h"
#include "js/Principals.h" #include "js/Principals.h"
@ -920,4 +921,10 @@ WriteBytesToJSStructuredCloneData(const uint8_t* src, size_t len, JSStructuredCl
return dest->AppendBytes(reinterpret_cast<const char*>(src), len); return dest->AppendBytes(reinterpret_cast<const char*>(src), len);
} }
char*
JSEncodeStringToUTF8(JSContext* cx, JS::HandleString string)
{
return JS_EncodeStringToUTF8(cx, string).release();
}
} // extern "C" } // extern "C"

Просмотреть файл

@ -7,11 +7,11 @@ extern crate js;
extern crate libc; extern crate libc;
use js::ar::AutoRealm; use js::ar::AutoRealm;
use js::glue::JSEncodeStringToUTF8;
use js::jsapi::root::JS::CallArgs; use js::jsapi::root::JS::CallArgs;
use js::jsapi::root::JS::RealmOptions; use js::jsapi::root::JS::RealmOptions;
use js::jsapi::root::JSContext; use js::jsapi::root::JSContext;
use js::jsapi::root::JS_DefineFunction; use js::jsapi::root::JS_DefineFunction;
use js::jsapi::root::JS_EncodeStringToUTF8;
use js::jsapi::root::JS_NewGlobalObject; use js::jsapi::root::JS_NewGlobalObject;
use js::jsapi::root::JS_ReportErrorASCII; use js::jsapi::root::JS_ReportErrorASCII;
use js::jsapi::root::JS::OnNewGlobalHookOption; use js::jsapi::root::JS::OnNewGlobalHookOption;
@ -55,7 +55,7 @@ unsafe extern "C" fn puts(context: *mut JSContext, argc: u32, vp: *mut Value) ->
let arg = args.get(0); let arg = args.get(0);
let js = js::rust::ToString(context, arg); let js = js::rust::ToString(context, arg);
rooted!(in(context) let message_root = js); rooted!(in(context) let message_root = js);
let message = JS_EncodeStringToUTF8(context, message_root.handle()); let message = JSEncodeStringToUTF8(context, message_root.handle());
let message = CStr::from_ptr(message); let message = CStr::from_ptr(message);
println!("{}", str::from_utf8(message.to_bytes()).unwrap()); println!("{}", str::from_utf8(message.to_bytes()).unwrap());

Просмотреть файл

@ -28,6 +28,7 @@
# define getpid _getpid # define getpid _getpid
#endif #endif
#include "js/CharacterEncoding.h"
#include "js/Utility.h" #include "js/Utility.h"
#include "util/Text.h" #include "util/Text.h"
#include "vm/Probes.h" #include "vm/Probes.h"
@ -203,7 +204,7 @@ RequiredStringArg(JSContext* cx, const CallArgs& args, size_t argi, const char*
return nullptr; return nullptr;
} }
return UniqueChars(JS_EncodeString(cx, args[argi].toString())); return JS_EncodeString(cx, args[argi].toString());
} }
static bool static bool

Просмотреть файл

@ -3394,7 +3394,7 @@ reflect_parse(JSContext* cx, uint32_t argc, Value* vp)
if (!str) if (!str)
return false; return false;
filename.reset(JS_EncodeString(cx, str)); filename = JS_EncodeString(cx, str);
if (!filename) if (!filename)
return false; return false;
} }

Просмотреть файл

@ -41,7 +41,7 @@
#include "jit/BaselineJIT.h" #include "jit/BaselineJIT.h"
#include "jit/InlinableNatives.h" #include "jit/InlinableNatives.h"
#include "jit/JitRealm.h" #include "jit/JitRealm.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h" #include "js/CompilationAndEvaluation.h"
#include "js/CompileOptions.h" #include "js/CompileOptions.h"
#include "js/Debug.h" #include "js/Debug.h"
@ -1414,13 +1414,13 @@ CallFunctionWithAsyncStack(JSContext* cx, unsigned argc, Value* vp)
RootedObject function(cx, &args[0].toObject()); RootedObject function(cx, &args[0].toObject());
RootedObject stack(cx, &args[1].toObject()); RootedObject stack(cx, &args[1].toObject());
RootedString asyncCause(cx, args[2].toString()); RootedString asyncCause(cx, args[2].toString());
JSAutoByteString utf8Cause; UniqueChars utf8Cause = JS_EncodeStringToUTF8(cx, asyncCause);
if (!utf8Cause.encodeUtf8(cx, asyncCause)) { if (!utf8Cause) {
MOZ_ASSERT(cx->isExceptionPending()); MOZ_ASSERT(cx->isExceptionPending());
return false; return false;
} }
JS::AutoSetAsyncStackForNewCalls sas(cx, stack, utf8Cause.ptr(), JS::AutoSetAsyncStackForNewCalls sas(cx, stack, utf8Cause.get(),
JS::AutoSetAsyncStackForNewCalls::AsyncCallKind::EXPLICIT); JS::AutoSetAsyncStackForNewCalls::AsyncCallKind::EXPLICIT);
return Call(cx, UndefinedHandleValue, function, return Call(cx, UndefinedHandleValue, function,
JS::HandleValueArray::empty(), args.rval()); JS::HandleValueArray::empty(), args.rval());
@ -2194,16 +2194,16 @@ DumpHeap(JSContext* cx, unsigned argc, Value* vp)
if (v.isString()) { if (v.isString()) {
if (!fuzzingSafe) { if (!fuzzingSafe) {
RootedString str(cx, v.toString()); RootedString str(cx, v.toString());
JSAutoByteString fileNameBytes; UniqueChars fileNameBytes = JS_EncodeString(cx, str);
if (!fileNameBytes.encodeLatin1(cx, str)) if (!fileNameBytes)
return false; return false;
const char* fileName = fileNameBytes.ptr(); const char* fileName = fileNameBytes.get();
dumpFile = fopen(fileName, "w"); dumpFile = fopen(fileName, "w");
if (!dumpFile) { if (!dumpFile) {
fileNameBytes.clear(); fileNameBytes = JS_EncodeStringToUTF8(cx, str);
if (!fileNameBytes.encodeUtf8(cx, str)) if (!fileNameBytes)
return false; return false;
JS_ReportErrorUTF8(cx, "can't open %s", fileNameBytes.ptr()); JS_ReportErrorUTF8(cx, "can't open %s", fileNameBytes.get());
return false; return false;
} }
} }
@ -2746,23 +2746,25 @@ class CloneBufferObject : public NativeObject {
setCloneBuffer_impl(JSContext* cx, const CallArgs& args) { setCloneBuffer_impl(JSContext* cx, const CallArgs& args) {
Rooted<CloneBufferObject*> obj(cx, &args.thisv().toObject().as<CloneBufferObject>()); Rooted<CloneBufferObject*> obj(cx, &args.thisv().toObject().as<CloneBufferObject>());
uint8_t* data = nullptr; const char* data = nullptr;
UniquePtr<uint8_t[], JS::FreePolicy> dataOwner; UniqueChars dataOwner;
uint32_t nbytes; uint32_t nbytes;
if (args.get(0).isObject() && args[0].toObject().is<ArrayBufferObject>()) { if (args.get(0).isObject() && args[0].toObject().is<ArrayBufferObject>()) {
ArrayBufferObject* buffer = &args[0].toObject().as<ArrayBufferObject>(); ArrayBufferObject* buffer = &args[0].toObject().as<ArrayBufferObject>();
bool isSharedMemory; bool isSharedMemory;
js::GetArrayBufferLengthAndData(buffer, &nbytes, &isSharedMemory, &data); uint8_t* dataBytes = nullptr;
js::GetArrayBufferLengthAndData(buffer, &nbytes, &isSharedMemory, &dataBytes);
MOZ_ASSERT(!isSharedMemory); MOZ_ASSERT(!isSharedMemory);
data = reinterpret_cast<char*>(dataBytes);
} else { } else {
JSString* str = JS::ToString(cx, args.get(0)); JSString* str = JS::ToString(cx, args.get(0));
if (!str) if (!str)
return false; return false;
data = reinterpret_cast<uint8_t*>(JS_EncodeString(cx, str)); dataOwner = JS_EncodeString(cx, str);
if (!data) if (!dataOwner)
return false; return false;
dataOwner.reset(data); data = dataOwner.get();
nbytes = JS_GetStringLength(str); nbytes = JS_GetStringLength(str);
} }
@ -2777,7 +2779,7 @@ class CloneBufferObject : public NativeObject {
return false; return false;
} }
MOZ_ALWAYS_TRUE(buf->AppendBytes((const char*)data, nbytes)); MOZ_ALWAYS_TRUE(buf->AppendBytes(data, nbytes));
obj->discard(); obj->discard();
obj->setData(buf.release(), true); obj->setData(buf.release(), true);
@ -2914,17 +2916,17 @@ ParseCloneScope(JSContext* cx, HandleString str)
{ {
mozilla::Maybe<JS::StructuredCloneScope> scope; mozilla::Maybe<JS::StructuredCloneScope> scope;
JSAutoByteString scopeStr(cx, str); UniqueChars scopeStr = JS_EncodeString(cx, str);
if (!scopeStr) if (!scopeStr)
return scope; return scope;
if (strcmp(scopeStr.ptr(), "SameProcessSameThread") == 0) if (strcmp(scopeStr.get(), "SameProcessSameThread") == 0)
scope.emplace(JS::StructuredCloneScope::SameProcessSameThread); scope.emplace(JS::StructuredCloneScope::SameProcessSameThread);
else if (strcmp(scopeStr.ptr(), "SameProcessDifferentThread") == 0) else if (strcmp(scopeStr.get(), "SameProcessDifferentThread") == 0)
scope.emplace(JS::StructuredCloneScope::SameProcessDifferentThread); scope.emplace(JS::StructuredCloneScope::SameProcessDifferentThread);
else if (strcmp(scopeStr.ptr(), "DifferentProcess") == 0) else if (strcmp(scopeStr.get(), "DifferentProcess") == 0)
scope.emplace(JS::StructuredCloneScope::DifferentProcess); scope.emplace(JS::StructuredCloneScope::DifferentProcess);
else if (strcmp(scopeStr.ptr(), "DifferentProcessForIndexedDB") == 0) else if (strcmp(scopeStr.get(), "DifferentProcessForIndexedDB") == 0)
scope.emplace(JS::StructuredCloneScope::DifferentProcessForIndexedDB); scope.emplace(JS::StructuredCloneScope::DifferentProcessForIndexedDB);
return scope; return scope;
@ -2951,13 +2953,13 @@ Serialize(JSContext* cx, unsigned argc, Value* vp)
JSString* str = JS::ToString(cx, v); JSString* str = JS::ToString(cx, v);
if (!str) if (!str)
return false; return false;
JSAutoByteString poli(cx, str); UniqueChars poli = JS_EncodeString(cx, str);
if (!poli) if (!poli)
return false; return false;
if (strcmp(poli.ptr(), "allow") == 0) { if (strcmp(poli.get(), "allow") == 0) {
// default // default
} else if (strcmp(poli.ptr(), "deny") == 0) { } else if (strcmp(poli.get(), "deny") == 0) {
policy.denySharedArrayBuffer(); policy.denySharedArrayBuffer();
} else { } else {
JS_ReportErrorASCII(cx, "Invalid policy value for 'SharedArrayBuffer'"); JS_ReportErrorASCII(cx, "Invalid policy value for 'SharedArrayBuffer'");
@ -4121,12 +4123,12 @@ SetGCCallback(JSContext* cx, unsigned argc, Value* vp)
JSString* str = JS::ToString(cx, v); JSString* str = JS::ToString(cx, v);
if (!str) if (!str)
return false; return false;
JSAutoByteString action(cx, str); UniqueChars action = JS_EncodeString(cx, str);
if (!action) if (!action)
return false; return false;
int32_t phases = 0; int32_t phases = 0;
if ((strcmp(action.ptr(), "minorGC") == 0) || (strcmp(action.ptr(), "majorGC") == 0)) { if ((strcmp(action.get(), "minorGC") == 0) || (strcmp(action.get(), "majorGC") == 0)) {
if (!JS_GetProperty(cx, opts, "phases", &v)) if (!JS_GetProperty(cx, opts, "phases", &v))
return false; return false;
if (v.isUndefined()) { if (v.isUndefined()) {
@ -4135,15 +4137,15 @@ SetGCCallback(JSContext* cx, unsigned argc, Value* vp)
JSString* str = JS::ToString(cx, v); JSString* str = JS::ToString(cx, v);
if (!str) if (!str)
return false; return false;
JSAutoByteString phasesStr(cx, str); UniqueChars phasesStr = JS_EncodeString(cx, str);
if (!phasesStr) if (!phasesStr)
return false; return false;
if (strcmp(phasesStr.ptr(), "begin") == 0) if (strcmp(phasesStr.get(), "begin") == 0)
phases = (1 << JSGC_BEGIN); phases = (1 << JSGC_BEGIN);
else if (strcmp(phasesStr.ptr(), "end") == 0) else if (strcmp(phasesStr.get(), "end") == 0)
phases = (1 << JSGC_END); phases = (1 << JSGC_END);
else if (strcmp(phasesStr.ptr(), "both") == 0) else if (strcmp(phasesStr.get(), "both") == 0)
phases = (1 << JSGC_BEGIN) | (1 << JSGC_END); phases = (1 << JSGC_BEGIN) | (1 << JSGC_END);
else { else {
JS_ReportErrorASCII(cx, "Invalid callback phase"); JS_ReportErrorASCII(cx, "Invalid callback phase");
@ -4164,7 +4166,7 @@ SetGCCallback(JSContext* cx, unsigned argc, Value* vp)
gcCallback::prevMinorGC = nullptr; gcCallback::prevMinorGC = nullptr;
} }
if (strcmp(action.ptr(), "minorGC") == 0) { if (strcmp(action.get(), "minorGC") == 0) {
auto info = js_new<gcCallback::MinorGC>(); auto info = js_new<gcCallback::MinorGC>();
if (!info) { if (!info) {
ReportOutOfMemory(cx); ReportOutOfMemory(cx);
@ -4174,7 +4176,7 @@ SetGCCallback(JSContext* cx, unsigned argc, Value* vp)
info->phases = phases; info->phases = phases;
info->active = true; info->active = true;
JS_SetGCCallback(cx, gcCallback::minorGC, info); JS_SetGCCallback(cx, gcCallback::minorGC, info);
} else if (strcmp(action.ptr(), "majorGC") == 0) { } else if (strcmp(action.get(), "majorGC") == 0) {
if (!JS_GetProperty(cx, opts, "depth", &v)) if (!JS_GetProperty(cx, opts, "depth", &v))
return false; return false;
int32_t depth = 1; int32_t depth = 1;
@ -4734,11 +4736,11 @@ SetTimeZone(JSContext* cx, unsigned argc, Value* vp)
}; };
if (args[0].isString() && !args[0].toString()->empty()) { if (args[0].isString() && !args[0].toString()->empty()) {
JSAutoByteString timeZone; UniqueChars timeZone = JS_EncodeString(cx, args[0].toString());
if (!timeZone.encodeLatin1(cx, args[0].toString())) if (!timeZone)
return false; return false;
if (!setTimeZone(timeZone.ptr())) { if (!setTimeZone(timeZone.get())) {
JS_ReportErrorASCII(cx, "Failed to set 'TZ' environment variable"); JS_ReportErrorASCII(cx, "Failed to set 'TZ' environment variable");
return false; return false;
} }
@ -4824,11 +4826,11 @@ SetDefaultLocale(JSContext* cx, unsigned argc, Value* vp)
return false; return false;
} }
JSAutoByteString locale; UniqueChars locale = JS_EncodeString(cx, str);
if (!locale.encodeLatin1(cx, str)) if (!locale)
return false; return false;
if (!JS_SetDefaultLocale(cx->runtime(), locale.ptr())) { if (!JS_SetDefaultLocale(cx->runtime(), locale.get())) {
ReportOutOfMemory(cx); ReportOutOfMemory(cx);
return false; return false;
} }

Просмотреть файл

@ -12,6 +12,7 @@
#include "jsutil.h" #include "jsutil.h"
#include "gc/Marking.h" #include "gc/Marking.h"
#include "js/CharacterEncoding.h"
#include "js/Vector.h" #include "js/Vector.h"
#include "util/StringBuffer.h" #include "util/StringBuffer.h"
#include "vm/GlobalObject.h" #include "vm/GlobalObject.h"
@ -1598,7 +1599,7 @@ ReportTypedObjTypeError(JSContext* cx,
{ {
// Serialize type string of obj // Serialize type string of obj
RootedAtom typeReprAtom(cx, &obj->typeDescr().stringRepr()); RootedAtom typeReprAtom(cx, &obj->typeDescr().stringRepr());
UniqueChars typeReprStr(JS_EncodeStringToUTF8(cx, typeReprAtom)); UniqueChars typeReprStr = JS_EncodeStringToUTF8(cx, typeReprAtom);
if (!typeReprStr) if (!typeReprStr)
return false; return false;
@ -1705,7 +1706,7 @@ ReportPropertyError(JSContext* cx,
if (!str) if (!str)
return false; return false;
UniqueChars propName(JS_EncodeStringToUTF8(cx, str)); UniqueChars propName = JS_EncodeStringToUTF8(cx, str);
if (!propName) if (!propName)
return false; return false;

Просмотреть файл

@ -17,7 +17,7 @@
#include "builtin/intl/ScopedICUObject.h" #include "builtin/intl/ScopedICUObject.h"
#include "builtin/intl/SharedIntlData.h" #include "builtin/intl/SharedIntlData.h"
#include "gc/FreeOp.h" #include "gc/FreeOp.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/StableStringChars.h" #include "js/StableStringChars.h"
#include "js/TypeDecls.h" #include "js/TypeDecls.h"
#include "vm/GlobalObject.h" #include "vm/GlobalObject.h"
@ -200,11 +200,11 @@ js::intl_availableCollations(JSContext* cx, unsigned argc, Value* vp)
MOZ_ASSERT(args.length() == 1); MOZ_ASSERT(args.length() == 1);
MOZ_ASSERT(args[0].isString()); MOZ_ASSERT(args[0].isString());
JSAutoByteString locale(cx, args[0].toString()); UniqueChars locale = JS_EncodeString(cx, args[0].toString());
if (!locale) if (!locale)
return false; return false;
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UEnumeration* values = ucol_getKeywordValuesForLocale("co", locale.ptr(), false, &status); UEnumeration* values = ucol_getKeywordValuesForLocale("co", locale.get(), false, &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
ReportInternalError(cx); ReportInternalError(cx);
return false; return false;
@ -277,7 +277,7 @@ NewUCollator(JSContext* cx, Handle<CollatorObject*> collator)
if (!GetProperty(cx, internals, internals, cx->names().locale, &value)) if (!GetProperty(cx, internals, internals, cx->names().locale, &value))
return nullptr; return nullptr;
JSAutoByteString locale(cx, value.toString()); UniqueChars locale = JS_EncodeString(cx, value.toString());
if (!locale) if (!locale)
return nullptr; return nullptr;
@ -300,7 +300,7 @@ NewUCollator(JSContext* cx, Handle<CollatorObject*> collator)
if (StringEqualsAscii(usage, "search")) { if (StringEqualsAscii(usage, "search")) {
// ICU expects search as a Unicode locale extension on locale. // ICU expects search as a Unicode locale extension on locale.
// Unicode locale extensions must occur before private use extensions. // Unicode locale extensions must occur before private use extensions.
const char* oldLocale = locale.ptr(); const char* oldLocale = locale.get();
const char* p; const char* p;
size_t index; size_t index;
size_t localeLen = strlen(oldLocale); size_t localeLen = strlen(oldLocale);
@ -323,8 +323,7 @@ NewUCollator(JSContext* cx, Handle<CollatorObject*> collator)
memcpy(newLocale, oldLocale, index); memcpy(newLocale, oldLocale, index);
memcpy(newLocale + index, insert, insertLen); memcpy(newLocale + index, insert, insertLen);
memcpy(newLocale + index + insertLen, oldLocale + index, localeLen - index + 1); // '\0' memcpy(newLocale + index + insertLen, oldLocale + index, localeLen - index + 1); // '\0'
locale.clear(); locale = JS::UniqueChars(newLocale);
locale.initBytes(JS::UniqueChars(newLocale));
} else { } else {
MOZ_ASSERT(StringEqualsAscii(usage, "sort")); MOZ_ASSERT(StringEqualsAscii(usage, "sort"));
} }
@ -386,7 +385,7 @@ NewUCollator(JSContext* cx, Handle<CollatorObject*> collator)
} }
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UCollator* coll = ucol_open(IcuLocale(locale.ptr()), &status); UCollator* coll = ucol_open(IcuLocale(locale.get()), &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
ReportInternalError(cx); ReportInternalError(cx);
return nullptr; return nullptr;

Просмотреть файл

@ -19,7 +19,7 @@
#include "builtin/intl/SharedIntlData.h" #include "builtin/intl/SharedIntlData.h"
#include "builtin/intl/TimeZoneDataGenerated.h" #include "builtin/intl/TimeZoneDataGenerated.h"
#include "gc/FreeOp.h" #include "gc/FreeOp.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/StableStringChars.h" #include "js/StableStringChars.h"
#include "vm/DateTime.h" #include "vm/DateTime.h"
#include "vm/GlobalObject.h" #include "vm/GlobalObject.h"
@ -236,10 +236,10 @@ js::intl_DateTimeFormat_availableLocales(JSContext* cx, unsigned argc, Value* vp
} }
static bool static bool
DefaultCalendar(JSContext* cx, const JSAutoByteString& locale, MutableHandleValue rval) DefaultCalendar(JSContext* cx, const UniqueChars& locale, MutableHandleValue rval)
{ {
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UCalendar* cal = ucal_open(nullptr, 0, locale.ptr(), UCAL_DEFAULT, &status); UCalendar* cal = ucal_open(nullptr, 0, locale.get(), UCAL_DEFAULT, &status);
// This correctly handles nullptr |cal| when opening failed. // This correctly handles nullptr |cal| when opening failed.
ScopedICUObject<UCalendar, ucal_close> closeCalendar(cal); ScopedICUObject<UCalendar, ucal_close> closeCalendar(cal);
@ -283,7 +283,7 @@ js::intl_availableCalendars(JSContext* cx, unsigned argc, Value* vp)
MOZ_ASSERT(args.length() == 1); MOZ_ASSERT(args.length() == 1);
MOZ_ASSERT(args[0].isString()); MOZ_ASSERT(args[0].isString());
JSAutoByteString locale(cx, args[0].toString()); UniqueChars locale = JS_EncodeString(cx, args[0].toString());
if (!locale) if (!locale)
return false; return false;
@ -302,7 +302,7 @@ js::intl_availableCalendars(JSContext* cx, unsigned argc, Value* vp)
// Now get the calendars that "would make a difference", i.e., not the default. // Now get the calendars that "would make a difference", i.e., not the default.
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UEnumeration* values = ucal_getKeywordValuesForLocale("ca", locale.ptr(), false, &status); UEnumeration* values = ucal_getKeywordValuesForLocale("ca", locale.get(), false, &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
intl::ReportInternalError(cx); intl::ReportInternalError(cx);
return false; return false;
@ -360,7 +360,7 @@ js::intl_defaultCalendar(JSContext* cx, unsigned argc, Value* vp)
MOZ_ASSERT(args.length() == 1); MOZ_ASSERT(args.length() == 1);
MOZ_ASSERT(args[0].isString()); MOZ_ASSERT(args[0].isString());
JSAutoByteString locale(cx, args[0].toString()); UniqueChars locale = JS_EncodeString(cx, args[0].toString());
if (!locale) if (!locale)
return false; return false;
@ -527,7 +527,7 @@ js::intl_patternForSkeleton(JSContext* cx, unsigned argc, Value* vp)
MOZ_ASSERT(args[0].isString()); MOZ_ASSERT(args[0].isString());
MOZ_ASSERT(args[1].isString()); MOZ_ASSERT(args[1].isString());
JSAutoByteString locale(cx, args[0].toString()); UniqueChars locale = JS_EncodeString(cx, args[0].toString());
if (!locale) if (!locale)
return false; return false;
@ -538,7 +538,7 @@ js::intl_patternForSkeleton(JSContext* cx, unsigned argc, Value* vp)
mozilla::Range<const char16_t> skelChars = skeleton.twoByteRange(); mozilla::Range<const char16_t> skelChars = skeleton.twoByteRange();
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UDateTimePatternGenerator* gen = udatpg_open(IcuLocale(locale.ptr()), &status); UDateTimePatternGenerator* gen = udatpg_open(IcuLocale(locale.get()), &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
intl::ReportInternalError(cx); intl::ReportInternalError(cx);
return false; return false;
@ -564,7 +564,7 @@ js::intl_patternForStyle(JSContext* cx, unsigned argc, Value* vp)
MOZ_ASSERT(args.length() == 4); MOZ_ASSERT(args.length() == 4);
MOZ_ASSERT(args[0].isString()); MOZ_ASSERT(args[0].isString());
JSAutoByteString locale(cx, args[0].toString()); UniqueChars locale = JS_EncodeString(cx, args[0].toString());
if (!locale) if (!locale)
return false; return false;
@ -612,7 +612,7 @@ js::intl_patternForStyle(JSContext* cx, unsigned argc, Value* vp)
mozilla::Range<const char16_t> timeZoneChars = timeZone.twoByteRange(); mozilla::Range<const char16_t> timeZoneChars = timeZone.twoByteRange();
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UDateFormat* df = udat_open(timeStyle, dateStyle, IcuLocale(locale.ptr()), UDateFormat* df = udat_open(timeStyle, dateStyle, IcuLocale(locale.get()),
timeZoneChars.begin().get(), timeZoneChars.length(), timeZoneChars.begin().get(), timeZoneChars.length(),
nullptr, -1, &status); nullptr, -1, &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
@ -645,7 +645,7 @@ NewUDateFormat(JSContext* cx, Handle<DateTimeFormatObject*> dateTimeFormat)
if (!GetProperty(cx, internals, internals, cx->names().locale, &value)) if (!GetProperty(cx, internals, internals, cx->names().locale, &value))
return nullptr; return nullptr;
JSAutoByteString locale(cx, value.toString()); UniqueChars locale = JS_EncodeString(cx, value.toString());
if (!locale) if (!locale)
return nullptr; return nullptr;
@ -673,7 +673,7 @@ NewUDateFormat(JSContext* cx, Handle<DateTimeFormatObject*> dateTimeFormat)
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UDateFormat* df = UDateFormat* df =
udat_open(UDAT_PATTERN, UDAT_PATTERN, IcuLocale(locale.ptr()), udat_open(UDAT_PATTERN, UDAT_PATTERN, IcuLocale(locale.get()),
timeZoneChars.begin().get(), timeZoneChars.length(), timeZoneChars.begin().get(), timeZoneChars.length(),
patternChars.begin().get(), patternChars.length(), &status); patternChars.begin().get(), patternChars.length(), &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {

Просмотреть файл

@ -21,7 +21,7 @@
#include "builtin/intl/NumberFormat.h" #include "builtin/intl/NumberFormat.h"
#include "builtin/intl/PluralRules.h" #include "builtin/intl/PluralRules.h"
#include "builtin/intl/ScopedICUObject.h" #include "builtin/intl/ScopedICUObject.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/Class.h" #include "js/Class.h"
#include "js/StableStringChars.h" #include "js/StableStringChars.h"
#include "vm/GlobalObject.h" #include "vm/GlobalObject.h"
@ -50,14 +50,14 @@ js::intl_GetCalendarInfo(JSContext* cx, unsigned argc, Value* vp)
CallArgs args = CallArgsFromVp(argc, vp); CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 1); MOZ_ASSERT(args.length() == 1);
JSAutoByteString locale(cx, args[0].toString()); UniqueChars locale = JS_EncodeString(cx, args[0].toString());
if (!locale) if (!locale)
return false; return false;
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
const UChar* uTimeZone = nullptr; const UChar* uTimeZone = nullptr;
int32_t uTimeZoneLength = 0; int32_t uTimeZoneLength = 0;
UCalendar* cal = ucal_open(uTimeZone, uTimeZoneLength, locale.ptr(), UCAL_DEFAULT, &status); UCalendar* cal = ucal_open(uTimeZone, uTimeZoneLength, locale.get(), UCAL_DEFAULT, &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
intl::ReportInternalError(cx); intl::ReportInternalError(cx);
return false; return false;
@ -371,8 +371,8 @@ js::intl_ComputeDisplayNames(JSContext* cx, unsigned argc, Value* vp)
// 1. Assert: locale is a string. // 1. Assert: locale is a string.
RootedString str(cx, args[0].toString()); RootedString str(cx, args[0].toString());
JSAutoByteString locale; UniqueChars locale = JS_EncodeStringToUTF8(cx, str);
if (!locale.encodeUtf8(cx, str)) if (!locale)
return false; return false;
// 2. Assert: style is a string. // 2. Assert: style is a string.
@ -405,7 +405,7 @@ js::intl_ComputeDisplayNames(JSContext* cx, unsigned argc, Value* vp)
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UDateFormat* fmt = UDateFormat* fmt =
udat_open(UDAT_DEFAULT, UDAT_DEFAULT, IcuLocale(locale.ptr()), udat_open(UDAT_DEFAULT, UDAT_DEFAULT, IcuLocale(locale.get()),
nullptr, 0, nullptr, 0, &status); nullptr, 0, nullptr, 0, &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
intl::ReportInternalError(cx); intl::ReportInternalError(cx);
@ -415,7 +415,7 @@ js::intl_ComputeDisplayNames(JSContext* cx, unsigned argc, Value* vp)
// UDateTimePatternGenerator will be needed for translations of date and // UDateTimePatternGenerator will be needed for translations of date and
// time fields like "month", "week", "day" etc. // time fields like "month", "week", "day" etc.
UDateTimePatternGenerator* dtpg = udatpg_open(IcuLocale(locale.ptr()), &status); UDateTimePatternGenerator* dtpg = udatpg_open(IcuLocale(locale.get()), &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
intl::ReportInternalError(cx); intl::ReportInternalError(cx);
return false; return false;
@ -461,7 +461,7 @@ js::intl_GetLocaleInfo(JSContext* cx, unsigned argc, Value* vp)
CallArgs args = CallArgsFromVp(argc, vp); CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 1); MOZ_ASSERT(args.length() == 1);
JSAutoByteString locale(cx, args[0].toString()); UniqueChars locale = JS_EncodeString(cx, args[0].toString());
if (!locale) if (!locale)
return false; return false;
@ -472,7 +472,7 @@ js::intl_GetLocaleInfo(JSContext* cx, unsigned argc, Value* vp)
if (!DefineDataProperty(cx, info, cx->names().locale, args[0])) if (!DefineDataProperty(cx, info, cx->names().locale, args[0]))
return false; return false;
bool rtl = uloc_isRightToLeft(IcuLocale(locale.ptr())); bool rtl = uloc_isRightToLeft(IcuLocale(locale.get()));
RootedValue dir(cx, StringValue(rtl ? cx->names().rtl : cx->names().ltr)); RootedValue dir(cx, StringValue(rtl ? cx->names().rtl : cx->names().ltr));

Просмотреть файл

@ -20,6 +20,7 @@
#include "builtin/intl/ScopedICUObject.h" #include "builtin/intl/ScopedICUObject.h"
#include "ds/Sort.h" #include "ds/Sort.h"
#include "gc/FreeOp.h" #include "gc/FreeOp.h"
#include "js/CharacterEncoding.h"
#include "js/RootingAPI.h" #include "js/RootingAPI.h"
#include "js/StableStringChars.h" #include "js/StableStringChars.h"
#include "js/TypeDecls.h" #include "js/TypeDecls.h"
@ -213,12 +214,12 @@ js::intl_numberingSystem(JSContext* cx, unsigned argc, Value* vp)
MOZ_ASSERT(args.length() == 1); MOZ_ASSERT(args.length() == 1);
MOZ_ASSERT(args[0].isString()); MOZ_ASSERT(args[0].isString());
JSAutoByteString locale(cx, args[0].toString()); UniqueChars locale = JS_EncodeString(cx, args[0].toString());
if (!locale) if (!locale)
return false; return false;
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UNumberingSystem* numbers = unumsys_open(IcuLocale(locale.ptr()), &status); UNumberingSystem* numbers = unumsys_open(IcuLocale(locale.get()), &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
intl::ReportInternalError(cx); intl::ReportInternalError(cx);
return false; return false;
@ -255,7 +256,7 @@ NewUNumberFormat(JSContext* cx, Handle<NumberFormatObject*> numberFormat)
if (!GetProperty(cx, internals, internals, cx->names().locale, &value)) if (!GetProperty(cx, internals, internals, cx->names().locale, &value))
return nullptr; return nullptr;
JSAutoByteString locale(cx, value.toString()); UniqueChars locale = JS_EncodeString(cx, value.toString());
if (!locale) if (!locale)
return nullptr; return nullptr;
@ -347,7 +348,7 @@ NewUNumberFormat(JSContext* cx, Handle<NumberFormatObject*> numberFormat)
uUseGrouping = value.toBoolean(); uUseGrouping = value.toBoolean();
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UNumberFormat* nf = unum_open(uStyle, nullptr, 0, IcuLocale(locale.ptr()), nullptr, &status); UNumberFormat* nf = unum_open(uStyle, nullptr, 0, IcuLocale(locale.get()), nullptr, &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
intl::ReportInternalError(cx); intl::ReportInternalError(cx);
return nullptr; return nullptr;

Просмотреть файл

@ -15,7 +15,7 @@
#include "builtin/intl/ICUStubs.h" #include "builtin/intl/ICUStubs.h"
#include "builtin/intl/ScopedICUObject.h" #include "builtin/intl/ScopedICUObject.h"
#include "gc/FreeOp.h" #include "gc/FreeOp.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "vm/GlobalObject.h" #include "vm/GlobalObject.h"
#include "vm/JSContext.h" #include "vm/JSContext.h"
#include "vm/StringType.h" #include "vm/StringType.h"
@ -196,7 +196,7 @@ NewUNumberFormatForPluralRules(JSContext* cx, Handle<PluralRulesObject*> pluralR
if (!GetProperty(cx, internals, internals, cx->names().locale, &value)) if (!GetProperty(cx, internals, internals, cx->names().locale, &value))
return nullptr; return nullptr;
JSAutoByteString locale(cx, value.toString()); UniqueChars locale = JS_EncodeString(cx, value.toString());
if (!locale) if (!locale)
return nullptr; return nullptr;
@ -234,7 +234,7 @@ NewUNumberFormatForPluralRules(JSContext* cx, Handle<PluralRulesObject*> pluralR
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UNumberFormat* nf = UNumberFormat* nf =
unum_open(UNUM_DECIMAL, nullptr, 0, IcuLocale(locale.ptr()), nullptr, &status); unum_open(UNUM_DECIMAL, nullptr, 0, IcuLocale(locale.get()), nullptr, &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
intl::ReportInternalError(cx); intl::ReportInternalError(cx);
return nullptr; return nullptr;
@ -269,7 +269,7 @@ NewUPluralRules(JSContext* cx, Handle<PluralRulesObject*> pluralRules)
if (!GetProperty(cx, internals, internals, cx->names().locale, &value)) if (!GetProperty(cx, internals, internals, cx->names().locale, &value))
return nullptr; return nullptr;
JSAutoByteString locale(cx, value.toString()); UniqueChars locale = JS_EncodeString(cx, value.toString());
if (!locale) if (!locale)
return nullptr; return nullptr;
@ -291,7 +291,7 @@ NewUPluralRules(JSContext* cx, Handle<PluralRulesObject*> pluralRules)
} }
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
UPluralRules* pr = uplrules_openForType(IcuLocale(locale.ptr()), category, &status); UPluralRules* pr = uplrules_openForType(IcuLocale(locale.get()), category, &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
intl::ReportInternalError(cx); intl::ReportInternalError(cx);
return nullptr; return nullptr;

Просмотреть файл

@ -15,7 +15,7 @@
#include "builtin/intl/ICUStubs.h" #include "builtin/intl/ICUStubs.h"
#include "builtin/intl/ScopedICUObject.h" #include "builtin/intl/ScopedICUObject.h"
#include "gc/FreeOp.h" #include "gc/FreeOp.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "vm/GlobalObject.h" #include "vm/GlobalObject.h"
#include "vm/JSContext.h" #include "vm/JSContext.h"
@ -224,7 +224,7 @@ NewURelativeDateTimeFormatter(JSContext* cx, Handle<RelativeTimeFormatObject*> r
if (!GetProperty(cx, internals, internals, cx->names().locale, &value)) if (!GetProperty(cx, internals, internals, cx->names().locale, &value))
return nullptr; return nullptr;
JSAutoByteString locale(cx, value.toString()); UniqueChars locale = JS_EncodeString(cx, value.toString());
if (!locale) if (!locale)
return nullptr; return nullptr;
@ -249,7 +249,7 @@ NewURelativeDateTimeFormatter(JSContext* cx, Handle<RelativeTimeFormatObject*> r
UErrorCode status = U_ZERO_ERROR; UErrorCode status = U_ZERO_ERROR;
URelativeDateTimeFormatter* rtf = URelativeDateTimeFormatter* rtf =
ureldatefmt_open(IcuLocale(locale.ptr()), nullptr, relDateTimeStyle, ureldatefmt_open(IcuLocale(locale.get()), nullptr, relDateTimeStyle,
UDISPCTX_CAPITALIZATION_FOR_STANDALONE, &status); UDISPCTX_CAPITALIZATION_FOR_STANDALONE, &status);
if (U_FAILURE(status)) { if (U_FAILURE(status)) {
intl::ReportInternalError(cx); intl::ReportInternalError(cx);

Просмотреть файл

@ -39,9 +39,10 @@
#include "gc/FreeOp.h" #include "gc/FreeOp.h"
#include "gc/Policy.h" #include "gc/Policy.h"
#include "jit/AtomicOperations.h" #include "jit/AtomicOperations.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/StableStringChars.h" #include "js/StableStringChars.h"
#include "js/UniquePtr.h" #include "js/UniquePtr.h"
#include "js/Utility.h"
#include "js/Vector.h" #include "js/Vector.h"
#include "util/Windows.h" #include "util/Windows.h"
#include "vm/JSContext.h" #include "vm/JSContext.h"
@ -982,20 +983,22 @@ GetErrorMessage(void* userRef, const unsigned errorNumber)
} }
static const char* static const char*
EncodeLatin1(JSContext* cx, AutoString& str, JSAutoByteString& bytes) EncodeLatin1(JSContext* cx, AutoString& str, JS::UniqueChars& bytes)
{ {
return bytes.encodeLatin1(cx, NewUCString(cx, str.finish())); bytes = JS_EncodeString(cx, NewUCString(cx, str.finish()));
return bytes.get();
} }
static const char* static const char*
CTypesToSourceForError(JSContext* cx, HandleValue val, JSAutoByteString& bytes) CTypesToSourceForError(JSContext* cx, HandleValue val, JS::UniqueChars& bytes)
{ {
if (val.isObject()) { if (val.isObject()) {
RootedObject obj(cx, &val.toObject()); RootedObject obj(cx, &val.toObject());
if (CType::IsCType(obj) || CData::IsCDataMaybeUnwrap(&obj)) { if (CType::IsCType(obj) || CData::IsCDataMaybeUnwrap(&obj)) {
RootedValue v(cx, ObjectValue(*obj)); RootedValue v(cx, ObjectValue(*obj));
RootedString str(cx, JS_ValueToSource(cx, v)); RootedString str(cx, JS_ValueToSource(cx, v));
return bytes.encodeLatin1(cx, str); bytes = JS_EncodeString(cx, str);
return bytes.get();
} }
} }
return ValueToSourceForError(cx, val, bytes); return ValueToSourceForError(cx, val, bytes);
@ -1179,7 +1182,7 @@ ConvError(JSContext* cx, const char* expectedStr, HandleValue actual,
HandleObject funObj = nullptr, unsigned argIndex = 0, HandleObject funObj = nullptr, unsigned argIndex = 0,
HandleObject arrObj = nullptr, unsigned arrIndex = 0) HandleObject arrObj = nullptr, unsigned arrIndex = 0)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes); const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1195,7 +1198,7 @@ ConvError(JSContext* cx, const char* expectedStr, HandleValue actual,
SprintfLiteral(indexStr, "%u", arrIndex); SprintfLiteral(indexStr, "%u", arrIndex);
AutoString arrSource; AutoString arrSource;
JSAutoByteString arrBytes; JS::UniqueChars arrBytes;
BuildTypeSource(cx, arrObj, true, arrSource); BuildTypeSource(cx, arrObj, true, arrSource);
if (!arrSource) if (!arrSource)
return false; return false;
@ -1211,13 +1214,13 @@ ConvError(JSContext* cx, const char* expectedStr, HandleValue actual,
case TYPE_struct: { case TYPE_struct: {
JSFlatString* name = GetFieldName(arrObj, arrIndex); JSFlatString* name = GetFieldName(arrObj, arrIndex);
MOZ_ASSERT(name); MOZ_ASSERT(name);
JSAutoByteString nameBytes; JS::UniqueChars nameBytes = JS_EncodeString(cx, name);
const char* nameStr = nameBytes.encodeLatin1(cx, name); const char* nameStr = nameBytes.get();
if (!nameStr) if (!nameStr)
return false; return false;
AutoString structSource; AutoString structSource;
JSAutoByteString structBytes; JS::UniqueChars structBytes;
BuildTypeSource(cx, arrObj, true, structSource); BuildTypeSource(cx, arrObj, true, structSource);
if (!structSource) if (!structSource)
return false; return false;
@ -1225,7 +1228,7 @@ ConvError(JSContext* cx, const char* expectedStr, HandleValue actual,
if (!structStr) if (!structStr)
return false; return false;
JSAutoByteString posBytes; JS::UniqueChars posBytes;
const char* posStr; const char* posStr;
if (funObj) { if (funObj) {
AutoString posSource; AutoString posSource;
@ -1258,7 +1261,7 @@ ConvError(JSContext* cx, const char* expectedStr, HandleValue actual,
SprintfLiteral(indexStr, "%u", argIndex + 1); SprintfLiteral(indexStr, "%u", argIndex + 1);
AutoString funSource; AutoString funSource;
JSAutoByteString funBytes; JS::UniqueChars funBytes;
BuildFunctionTypeSource(cx, funObj, funSource); BuildFunctionTypeSource(cx, funObj, funSource);
if (!funSource) if (!funSource)
return false; return false;
@ -1275,7 +1278,7 @@ ConvError(JSContext* cx, const char* expectedStr, HandleValue actual,
MOZ_ASSERT(funObj); MOZ_ASSERT(funObj);
AutoString funSource; AutoString funSource;
JSAutoByteString funBytes; JS::UniqueChars funBytes;
BuildFunctionTypeSource(cx, funObj, funSource); BuildFunctionTypeSource(cx, funObj, funSource);
if (!funSource) if (!funSource)
return false; return false;
@ -1291,7 +1294,7 @@ ConvError(JSContext* cx, const char* expectedStr, HandleValue actual,
MOZ_ASSERT(funObj); MOZ_ASSERT(funObj);
AutoString funSource; AutoString funSource;
JSAutoByteString funBytes; JS::UniqueChars funBytes;
BuildFunctionTypeSource(cx, funObj, funSource); BuildFunctionTypeSource(cx, funObj, funSource);
if (!funSource) if (!funSource)
return false; return false;
@ -1324,7 +1327,7 @@ ConvError(JSContext* cx, HandleObject expectedType, HandleValue actual,
MOZ_ASSERT(CType::IsCType(expectedType)); MOZ_ASSERT(CType::IsCType(expectedType));
AutoString expectedSource; AutoString expectedSource;
JSAutoByteString expectedBytes; JS::UniqueChars expectedBytes;
BuildTypeSource(cx, expectedType, true, expectedSource); BuildTypeSource(cx, expectedType, true, expectedSource);
if (!expectedSource) if (!expectedSource)
return false; return false;
@ -1340,7 +1343,7 @@ static bool
ArgumentConvError(JSContext* cx, HandleValue actual, const char* funStr, ArgumentConvError(JSContext* cx, HandleValue actual, const char* funStr,
unsigned argIndex) unsigned argIndex)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes); const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1369,7 +1372,7 @@ ArrayLengthMismatch(JSContext* cx, unsigned expectedLength, HandleObject arrObj,
{ {
MOZ_ASSERT(arrObj && CType::IsCType(arrObj)); MOZ_ASSERT(arrObj && CType::IsCType(arrObj));
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes); const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1380,7 +1383,7 @@ ArrayLengthMismatch(JSContext* cx, unsigned expectedLength, HandleObject arrObj,
SprintfLiteral(actualLengthStr, "%u", actualLength); SprintfLiteral(actualLengthStr, "%u", actualLength);
AutoString arrSource; AutoString arrSource;
JSAutoByteString arrBytes; JS::UniqueChars arrBytes;
BuildTypeSource(cx, arrObj, true, arrSource); BuildTypeSource(cx, arrObj, true, arrSource);
if (!arrSource) if (!arrSource)
return false; return false;
@ -1401,7 +1404,7 @@ ArrayLengthOverflow(JSContext* cx, unsigned expectedLength, HandleObject arrObj,
{ {
MOZ_ASSERT(arrObj && CType::IsCType(arrObj)); MOZ_ASSERT(arrObj && CType::IsCType(arrObj));
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes); const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1412,7 +1415,7 @@ ArrayLengthOverflow(JSContext* cx, unsigned expectedLength, HandleObject arrObj,
SprintfLiteral(actualLengthStr, "%u", actualLength); SprintfLiteral(actualLengthStr, "%u", actualLength);
AutoString arrSource; AutoString arrSource;
JSAutoByteString arrBytes; JS::UniqueChars arrBytes;
BuildTypeSource(cx, arrObj, true, arrSource); BuildTypeSource(cx, arrObj, true, arrSource);
if (!arrSource) if (!arrSource)
return false; return false;
@ -1454,8 +1457,8 @@ CannotConstructError(JSContext* cx, const char* type)
static bool static bool
DuplicateFieldError(JSContext* cx, Handle<JSFlatString*> name) DuplicateFieldError(JSContext* cx, Handle<JSFlatString*> name)
{ {
JSAutoByteString nameBytes; JS::UniqueChars nameBytes = JS_EncodeString(cx, name);
const char* nameStr = nameBytes.encodeLatin1(cx, name); const char* nameStr = nameBytes.get();
if (!nameStr) if (!nameStr)
return false; return false;
@ -1476,7 +1479,7 @@ static bool
EmptyFinalizerError(JSContext* cx, ConversionType convType, EmptyFinalizerError(JSContext* cx, ConversionType convType,
HandleObject funObj = nullptr, unsigned argIndex = 0) HandleObject funObj = nullptr, unsigned argIndex = 0)
{ {
JSAutoByteString posBytes; JS::UniqueChars posBytes;
const char* posStr; const char* posStr;
if (funObj) { if (funObj) {
AutoString posSource; AutoString posSource;
@ -1504,13 +1507,13 @@ FieldCountMismatch(JSContext* cx,
{ {
MOZ_ASSERT(structObj && CType::IsCType(structObj)); MOZ_ASSERT(structObj && CType::IsCType(structObj));
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes); const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr) if (!valStr)
return false; return false;
AutoString structSource; AutoString structSource;
JSAutoByteString structBytes; JS::UniqueChars structBytes;
BuildTypeSource(cx, structObj, true, structSource); BuildTypeSource(cx, structObj, true, structSource);
if (!structSource) if (!structSource)
return false; return false;
@ -1523,7 +1526,7 @@ FieldCountMismatch(JSContext* cx,
char actualCountStr[16]; char actualCountStr[16];
SprintfLiteral(actualCountStr, "%u", actualCount); SprintfLiteral(actualCountStr, "%u", actualCount);
JSAutoByteString posBytes; JS::UniqueChars posBytes;
const char* posStr; const char* posStr;
if (funObj) { if (funObj) {
AutoString posSource; AutoString posSource;
@ -1547,7 +1550,7 @@ FieldCountMismatch(JSContext* cx,
static bool static bool
FieldDescriptorCountError(JSContext* cx, HandleValue typeVal, size_t length) FieldDescriptorCountError(JSContext* cx, HandleValue typeVal, size_t length)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, typeVal, valBytes); const char* valStr = CTypesToSourceForError(cx, typeVal, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1563,7 +1566,7 @@ FieldDescriptorCountError(JSContext* cx, HandleValue typeVal, size_t length)
static bool static bool
FieldDescriptorNameError(JSContext* cx, HandleId id) FieldDescriptorNameError(JSContext* cx, HandleId id)
{ {
JSAutoByteString idBytes; JS::UniqueChars idBytes;
RootedValue idVal(cx, IdToValue(id)); RootedValue idVal(cx, IdToValue(id));
const char* propStr = CTypesToSourceForError(cx, idVal, idBytes); const char* propStr = CTypesToSourceForError(cx, idVal, idBytes);
if (!propStr) if (!propStr)
@ -1578,14 +1581,14 @@ static bool
FieldDescriptorSizeError(JSContext* cx, HandleObject typeObj, HandleId id) FieldDescriptorSizeError(JSContext* cx, HandleObject typeObj, HandleId id)
{ {
RootedValue typeVal(cx, ObjectValue(*typeObj)); RootedValue typeVal(cx, ObjectValue(*typeObj));
JSAutoByteString typeBytes; JS::UniqueChars typeBytes;
const char* typeStr = CTypesToSourceForError(cx, typeVal, typeBytes); const char* typeStr = CTypesToSourceForError(cx, typeVal, typeBytes);
if (!typeStr) if (!typeStr)
return false; return false;
RootedString idStr(cx, IdToString(cx, id)); RootedString idStr(cx, IdToString(cx, id));
JSAutoByteString idBytes; JS::UniqueChars idBytes = JS_EncodeString(cx, idStr);
const char* propStr = idBytes.encodeLatin1(cx, idStr); const char* propStr = idBytes.get();
if (!propStr) if (!propStr)
return false; return false;
@ -1597,7 +1600,7 @@ FieldDescriptorSizeError(JSContext* cx, HandleObject typeObj, HandleId id)
static bool static bool
FieldDescriptorNameTypeError(JSContext* cx, HandleValue typeVal) FieldDescriptorNameTypeError(JSContext* cx, HandleValue typeVal)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, typeVal, valBytes); const char* valStr = CTypesToSourceForError(cx, typeVal, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1610,14 +1613,14 @@ FieldDescriptorNameTypeError(JSContext* cx, HandleValue typeVal)
static bool static bool
FieldDescriptorTypeError(JSContext* cx, HandleValue poroVal, HandleId id) FieldDescriptorTypeError(JSContext* cx, HandleValue poroVal, HandleId id)
{ {
JSAutoByteString typeBytes; JS::UniqueChars typeBytes;
const char* typeStr = CTypesToSourceForError(cx, poroVal, typeBytes); const char* typeStr = CTypesToSourceForError(cx, poroVal, typeBytes);
if (!typeStr) if (!typeStr)
return false; return false;
RootedString idStr(cx, IdToString(cx, id)); RootedString idStr(cx, IdToString(cx, id));
JSAutoByteString idBytes; JS::UniqueChars idBytes = JS_EncodeString(cx, idStr);
const char* propStr = idBytes.encodeLatin1(cx, idStr); const char* propStr = idBytes.get();
if (!propStr) if (!propStr)
return false; return false;
@ -1629,15 +1632,15 @@ FieldDescriptorTypeError(JSContext* cx, HandleValue poroVal, HandleId id)
static bool static bool
FieldMissingError(JSContext* cx, JSObject* typeObj, JSFlatString* name_) FieldMissingError(JSContext* cx, JSObject* typeObj, JSFlatString* name_)
{ {
JSAutoByteString typeBytes; JS::UniqueChars typeBytes;
RootedString name(cx, name_); RootedString name(cx, name_);
RootedValue typeVal(cx, ObjectValue(*typeObj)); RootedValue typeVal(cx, ObjectValue(*typeObj));
const char* typeStr = CTypesToSourceForError(cx, typeVal, typeBytes); const char* typeStr = CTypesToSourceForError(cx, typeVal, typeBytes);
if (!typeStr) if (!typeStr)
return false; return false;
JSAutoByteString nameBytes; JS::UniqueChars nameBytes = JS_EncodeString(cx, name);
const char* nameStr = nameBytes.encodeLatin1(cx, name); const char* nameStr = nameBytes.get();
if (!nameStr) if (!nameStr)
return false; return false;
@ -1651,13 +1654,13 @@ FinalizerSizeError(JSContext* cx, HandleObject funObj, HandleValue actual)
{ {
MOZ_ASSERT(CType::IsCType(funObj)); MOZ_ASSERT(CType::IsCType(funObj));
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes); const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr) if (!valStr)
return false; return false;
AutoString funSource; AutoString funSource;
JSAutoByteString funBytes; JS::UniqueChars funBytes;
BuildFunctionTypeSource(cx, funObj, funSource); BuildFunctionTypeSource(cx, funObj, funSource);
if (!funSource) if (!funSource)
return false; return false;
@ -1677,7 +1680,7 @@ FunctionArgumentLengthMismatch(JSContext* cx,
bool isVariadic) bool isVariadic)
{ {
AutoString funSource; AutoString funSource;
JSAutoByteString funBytes; JS::UniqueChars funBytes;
Value slot = JS_GetReservedSlot(funObj, SLOT_REFERENT); Value slot = JS_GetReservedSlot(funObj, SLOT_REFERENT);
if (!slot.isUndefined() && Library::IsLibrary(&slot.toObject())) { if (!slot.isUndefined() && Library::IsLibrary(&slot.toObject())) {
BuildFunctionTypeSource(cx, funObj, funSource); BuildFunctionTypeSource(cx, funObj, funSource);
@ -1708,7 +1711,7 @@ static bool
FunctionArgumentTypeError(JSContext* cx, FunctionArgumentTypeError(JSContext* cx,
uint32_t index, HandleValue typeVal, const char* reason) uint32_t index, HandleValue typeVal, const char* reason)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, typeVal, valBytes); const char* valStr = CTypesToSourceForError(cx, typeVal, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1725,7 +1728,7 @@ FunctionArgumentTypeError(JSContext* cx,
static bool static bool
FunctionReturnTypeError(JSContext* cx, HandleValue type, const char* reason) FunctionReturnTypeError(JSContext* cx, HandleValue type, const char* reason)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, type, valBytes); const char* valStr = CTypesToSourceForError(cx, type, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1738,7 +1741,7 @@ FunctionReturnTypeError(JSContext* cx, HandleValue type, const char* reason)
static bool static bool
IncompatibleCallee(JSContext* cx, const char* funName, HandleObject actualObj) IncompatibleCallee(JSContext* cx, const char* funName, HandleObject actualObj)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
RootedValue val(cx, ObjectValue(*actualObj)); RootedValue val(cx, ObjectValue(*actualObj));
const char* valStr = CTypesToSourceForError(cx, val, valBytes); const char* valStr = CTypesToSourceForError(cx, val, valBytes);
if (!valStr) if (!valStr)
@ -1762,7 +1765,7 @@ IncompatibleThisProto(JSContext* cx, const char* funName,
static bool static bool
IncompatibleThisProto(JSContext* cx, const char* funName, HandleValue actualVal) IncompatibleThisProto(JSContext* cx, const char* funName, HandleValue actualVal)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actualVal, valBytes); const char* valStr = CTypesToSourceForError(cx, actualVal, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1786,7 +1789,7 @@ static bool
IncompatibleThisType(JSContext* cx, const char* funName, const char* actualType, IncompatibleThisType(JSContext* cx, const char* funName, const char* actualType,
HandleValue actualVal) HandleValue actualVal)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actualVal, valBytes); const char* valStr = CTypesToSourceForError(cx, actualVal, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1800,7 +1803,7 @@ IncompatibleThisType(JSContext* cx, const char* funName, const char* actualType,
static bool static bool
InvalidIndexError(JSContext* cx, HandleValue val) InvalidIndexError(JSContext* cx, HandleValue val)
{ {
JSAutoByteString idBytes; JS::UniqueChars idBytes;
const char* indexStr = CTypesToSourceForError(cx, val, idBytes); const char* indexStr = CTypesToSourceForError(cx, val, idBytes);
if (!indexStr) if (!indexStr)
return false; return false;
@ -1837,7 +1840,7 @@ NonPrimitiveError(JSContext* cx, HandleObject typeObj)
MOZ_ASSERT(CType::IsCType(typeObj)); MOZ_ASSERT(CType::IsCType(typeObj));
AutoString typeSource; AutoString typeSource;
JSAutoByteString typeBytes; JS::UniqueChars typeBytes;
BuildTypeSource(cx, typeObj, true, typeSource); BuildTypeSource(cx, typeObj, true, typeSource);
if (!typeSource) if (!typeSource)
return false; return false;
@ -1853,7 +1856,7 @@ NonPrimitiveError(JSContext* cx, HandleObject typeObj)
static bool static bool
NonStringBaseError(JSContext* cx, HandleValue thisVal) NonStringBaseError(JSContext* cx, HandleValue thisVal)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, thisVal, valBytes); const char* valStr = CTypesToSourceForError(cx, thisVal, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1866,7 +1869,7 @@ NonStringBaseError(JSContext* cx, HandleValue thisVal)
static bool static bool
NullPointerError(JSContext* cx, const char* action, HandleObject obj) NullPointerError(JSContext* cx, const char* action, HandleObject obj)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
RootedValue val(cx, ObjectValue(*obj)); RootedValue val(cx, ObjectValue(*obj));
const char* valStr = CTypesToSourceForError(cx, val, valBytes); const char* valStr = CTypesToSourceForError(cx, val, valBytes);
if (!valStr) if (!valStr)
@ -1882,18 +1885,18 @@ PropNameNonStringError(JSContext* cx, HandleId id, HandleValue actual,
ConversionType convType, ConversionType convType,
HandleObject funObj = nullptr, unsigned argIndex = 0) HandleObject funObj = nullptr, unsigned argIndex = 0)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes); const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr) if (!valStr)
return false; return false;
JSAutoByteString idBytes; JS::UniqueChars idBytes;
RootedValue idVal(cx, IdToValue(id)); RootedValue idVal(cx, IdToValue(id));
const char* propStr = CTypesToSourceForError(cx, idVal, idBytes); const char* propStr = CTypesToSourceForError(cx, idVal, idBytes);
if (!propStr) if (!propStr)
return false; return false;
JSAutoByteString posBytes; JS::UniqueChars posBytes;
const char* posStr; const char* posStr;
if (funObj) { if (funObj) {
AutoString posSource; AutoString posSource;
@ -1923,7 +1926,7 @@ SizeOverflow(JSContext* cx, const char* name, const char* limit)
static bool static bool
TypeError(JSContext* cx, const char* expected, HandleValue actual) TypeError(JSContext* cx, const char* expected, HandleValue actual)
{ {
JSAutoByteString bytes; JS::UniqueChars bytes;
const char* src = CTypesToSourceForError(cx, actual, bytes); const char* src = CTypesToSourceForError(cx, actual, bytes);
if (!src) if (!src)
return false; return false;
@ -1936,7 +1939,7 @@ TypeError(JSContext* cx, const char* expected, HandleValue actual)
static bool static bool
TypeOverflow(JSContext* cx, const char* expected, HandleValue actual) TypeOverflow(JSContext* cx, const char* expected, HandleValue actual)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes); const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr) if (!valStr)
return false; return false;
@ -1950,7 +1953,7 @@ static bool
UndefinedSizeCastError(JSContext* cx, HandleObject targetTypeObj) UndefinedSizeCastError(JSContext* cx, HandleObject targetTypeObj)
{ {
AutoString targetTypeSource; AutoString targetTypeSource;
JSAutoByteString targetTypeBytes; JS::UniqueChars targetTypeBytes;
BuildTypeSource(cx, targetTypeObj, true, targetTypeSource); BuildTypeSource(cx, targetTypeObj, true, targetTypeSource);
if (!targetTypeSource) if (!targetTypeSource)
return false; return false;
@ -1969,7 +1972,7 @@ SizeMismatchCastError(JSContext* cx,
size_t sourceSize, size_t targetSize) size_t sourceSize, size_t targetSize)
{ {
AutoString sourceTypeSource; AutoString sourceTypeSource;
JSAutoByteString sourceTypeBytes; JS::UniqueChars sourceTypeBytes;
BuildTypeSource(cx, sourceTypeObj, true, sourceTypeSource); BuildTypeSource(cx, sourceTypeObj, true, sourceTypeSource);
if (!sourceTypeSource) if (!sourceTypeSource)
return false; return false;
@ -1978,7 +1981,7 @@ SizeMismatchCastError(JSContext* cx,
return false; return false;
AutoString targetTypeSource; AutoString targetTypeSource;
JSAutoByteString targetTypeBytes; JS::UniqueChars targetTypeBytes;
BuildTypeSource(cx, targetTypeObj, true, targetTypeSource); BuildTypeSource(cx, targetTypeObj, true, targetTypeSource);
if (!targetTypeSource) if (!targetTypeSource)
return false; return false;
@ -2001,7 +2004,7 @@ SizeMismatchCastError(JSContext* cx,
static bool static bool
UndefinedSizePointerError(JSContext* cx, const char* action, HandleObject obj) UndefinedSizePointerError(JSContext* cx, const char* action, HandleObject obj)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
RootedValue val(cx, ObjectValue(*obj)); RootedValue val(cx, ObjectValue(*obj));
const char* valStr = CTypesToSourceForError(cx, val, valBytes); const char* valStr = CTypesToSourceForError(cx, val, valBytes);
if (!valStr) if (!valStr)
@ -2015,7 +2018,7 @@ UndefinedSizePointerError(JSContext* cx, const char* action, HandleObject obj)
static bool static bool
VariadicArgumentTypeError(JSContext* cx, uint32_t index, HandleValue actual) VariadicArgumentTypeError(JSContext* cx, uint32_t index, HandleValue actual)
{ {
JSAutoByteString valBytes; JS::UniqueChars valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes); const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr) if (!valStr)
return false; return false;

Просмотреть файл

@ -10,7 +10,7 @@
#include "prlink.h" #include "prlink.h"
#include "ctypes/CTypes.h" #include "ctypes/CTypes.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/StableStringChars.h" #include "js/StableStringChars.h"
using JS::AutoStableStringChars; using JS::AutoStableStringChars;
@ -169,13 +169,13 @@ Library::Create(JSContext* cx, HandleValue path, const JSCTypesCallbacks* callba
#undef MAX_ERROR_LEN #undef MAX_ERROR_LEN
if (JS::StringIsASCII(error)) { if (JS::StringIsASCII(error)) {
JSAutoByteString pathCharsUTF8; JS::UniqueChars pathCharsUTF8 = JS_EncodeStringToUTF8(cx, pathStr);
if (pathCharsUTF8.encodeUtf8(cx, pathStr)) if (pathCharsUTF8)
JS_ReportErrorUTF8(cx, "couldn't open library %s: %s", pathCharsUTF8.ptr(), error); JS_ReportErrorUTF8(cx, "couldn't open library %s: %s", pathCharsUTF8.get(), error);
} else { } else {
JSAutoByteString pathCharsLatin1; JS::UniqueChars pathCharsLatin1 = JS_EncodeString(cx, pathStr);
if (pathCharsLatin1.encodeLatin1(cx, pathStr)) if (pathCharsLatin1)
JS_ReportErrorLatin1(cx, "couldn't open library %s: %s", pathCharsLatin1.ptr(), error); JS_ReportErrorLatin1(cx, "couldn't open library %s: %s", pathCharsLatin1.get(), error);
} }
return nullptr; return nullptr;
} }

Просмотреть файл

@ -8,7 +8,6 @@
#include "frontend/BytecodeEmitter.h" #include "frontend/BytecodeEmitter.h"
#include "frontend/TDZCheckCache.h" #include "frontend/TDZCheckCache.h"
#include "js/AutoByteString.h"
#include "vm/GlobalObject.h" #include "vm/GlobalObject.h"
@ -400,13 +399,13 @@ EmitterScope::dump(BytecodeEmitter* bce)
for (NameLocationMap::Range r = nameCache_->all(); !r.empty(); r.popFront()) { for (NameLocationMap::Range r = nameCache_->all(); !r.empty(); r.popFront()) {
const NameLocation& l = r.front().value(); const NameLocation& l = r.front().value();
JSAutoByteString bytes; UniqueChars bytes;
if (!AtomToPrintableString(bce->cx, r.front().key(), &bytes)) if (!AtomToPrintableString(bce->cx, r.front().key(), &bytes))
return; return;
if (l.kind() != NameLocation::Kind::Dynamic) if (l.kind() != NameLocation::Kind::Dynamic)
fprintf(stdout, " %s %s ", BindingKindString(l.bindingKind()), bytes.ptr()); fprintf(stdout, " %s %s ", BindingKindString(l.bindingKind()), bytes.get());
else else
fprintf(stdout, " %s ", bytes.ptr()); fprintf(stdout, " %s ", bytes.get());
switch (l.kind()) { switch (l.kind()) {
case NameLocation::Kind::Dynamic: case NameLocation::Kind::Dynamic:

Просмотреть файл

@ -37,7 +37,6 @@
#include "frontend/FoldConstants.h" #include "frontend/FoldConstants.h"
#include "frontend/TokenStream.h" #include "frontend/TokenStream.h"
#include "irregexp/RegExpParser.h" #include "irregexp/RegExpParser.h"
#include "js/AutoByteString.h"
#include "vm/BytecodeUtil.h" #include "vm/BytecodeUtil.h"
#include "vm/JSAtom.h" #include "vm/JSAtom.h"
#include "vm/JSContext.h" #include "vm/JSContext.h"
@ -171,13 +170,13 @@ ParseContext::Scope::dump(ParseContext* pc)
fprintf(stdout, "\n decls:\n"); fprintf(stdout, "\n decls:\n");
for (DeclaredNameMap::Range r = declared_->all(); !r.empty(); r.popFront()) { for (DeclaredNameMap::Range r = declared_->all(); !r.empty(); r.popFront()) {
JSAutoByteString bytes; UniqueChars bytes;
if (!AtomToPrintableString(cx, r.front().key(), &bytes)) if (!AtomToPrintableString(cx, r.front().key(), &bytes))
return; return;
DeclaredNameInfo& info = r.front().value().wrapped; DeclaredNameInfo& info = r.front().value().wrapped;
fprintf(stdout, " %s %s%s\n", fprintf(stdout, " %s %s%s\n",
DeclarationKindString(info.kind()), DeclarationKindString(info.kind()),
bytes.ptr(), bytes.get(),
info.closedOver() ? " (closed over)" : ""); info.closedOver() ? " (closed over)" : "");
} }
@ -1227,12 +1226,12 @@ GeneralParser<ParseHandler, CharT>::reportRedeclaration(HandlePropertyName name,
DeclarationKind prevKind, DeclarationKind prevKind,
TokenPos pos, uint32_t prevPos) TokenPos pos, uint32_t prevPos)
{ {
JSAutoByteString bytes; UniqueChars bytes;
if (!AtomToPrintableString(context, name, &bytes)) if (!AtomToPrintableString(context, name, &bytes))
return; return;
if (prevPos == DeclaredNameInfo::npos) { if (prevPos == DeclaredNameInfo::npos) {
errorAt(pos.begin, JSMSG_REDECLARED_VAR, DeclarationKindString(prevKind), bytes.ptr()); errorAt(pos.begin, JSMSG_REDECLARED_VAR, DeclarationKindString(prevKind), bytes.get());
return; return;
} }
@ -1261,7 +1260,7 @@ GeneralParser<ParseHandler, CharT>::reportRedeclaration(HandlePropertyName name,
} }
errorWithNotesAt(std::move(notes), pos.begin, JSMSG_REDECLARED_VAR, errorWithNotesAt(std::move(notes), pos.begin, JSMSG_REDECLARED_VAR,
DeclarationKindString(prevKind), bytes.ptr()); DeclarationKindString(prevKind), bytes.get());
} }
// notePositionalFormalParameter is called for both the arguments of a regular // notePositionalFormalParameter is called for both the arguments of a regular
@ -1291,10 +1290,10 @@ GeneralParser<ParseHandler, CharT>::notePositionalFormalParameter(Node fn, Handl
// In such cases, report will queue up the potential error and return // In such cases, report will queue up the potential error and return
// 'true'. // 'true'.
if (pc->sc()->needStrictChecks()) { if (pc->sc()->needStrictChecks()) {
JSAutoByteString bytes; UniqueChars bytes;
if (!AtomToPrintableString(context, name, &bytes)) if (!AtomToPrintableString(context, name, &bytes))
return false; return false;
if (!strictModeError(JSMSG_DUPLICATE_FORMAL, bytes.ptr())) if (!strictModeError(JSMSG_DUPLICATE_FORMAL, bytes.get()))
return false; return false;
} }
@ -2426,11 +2425,11 @@ Parser<FullParseHandler, CharT>::moduleBody(ModuleSharedContext* modulesc)
DeclaredNamePtr p = modulepc.varScope().lookupDeclaredName(name); DeclaredNamePtr p = modulepc.varScope().lookupDeclaredName(name);
if (!p) { if (!p) {
JSAutoByteString str; UniqueChars str;
if (!AtomToPrintableString(context, name, &str)) if (!AtomToPrintableString(context, name, &str))
return null(); return null();
errorAt(TokenStream::NoOffset, JSMSG_MISSING_EXPORT, str.ptr()); errorAt(TokenStream::NoOffset, JSMSG_MISSING_EXPORT, str.get());
return null(); return null();
} }
@ -5464,11 +5463,11 @@ Parser<FullParseHandler, CharT>::checkExportedName(JSAtom* exportName)
if (!pc->sc()->asModuleContext()->builder.hasExportedName(exportName)) if (!pc->sc()->asModuleContext()->builder.hasExportedName(exportName))
return true; return true;
JSAutoByteString str; UniqueChars str;
if (!AtomToPrintableString(context, exportName, &str)) if (!AtomToPrintableString(context, exportName, &str))
return false; return false;
error(JSMSG_DUPLICATE_EXPORT_NAME, str.ptr()); error(JSMSG_DUPLICATE_EXPORT_NAME, str.get());
return false; return false;
} }

Просмотреть файл

@ -17,7 +17,7 @@
#include "gc/GC.h" #include "gc/GC.h"
#include "js/AllocPolicy.h" #include "js/AllocPolicy.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/Vector.h" #include "js/Vector.h"
#include "vm/JSContext.h" #include "vm/JSContext.h"
@ -105,9 +105,8 @@ class JSAPITest
JSAPITestString jsvalToSource(JS::HandleValue v) { JSAPITestString jsvalToSource(JS::HandleValue v) {
JSString* str = JS_ValueToSource(cx, v); JSString* str = JS_ValueToSource(cx, v);
if (str) { if (str) {
JSAutoByteString bytes(cx, str); if (JS::UniqueChars bytes = JS_EncodeString(cx, str))
if (!!bytes) return JSAPITestString(bytes.get());
return JSAPITestString(bytes.ptr());
} }
JS_ClearPendingException(cx); JS_ClearPendingException(cx);
return JSAPITestString("<<error converting value to string>>"); return JSAPITestString("<<error converting value to string>>");
@ -233,9 +232,8 @@ class JSAPITest
JS_ClearPendingException(cx); JS_ClearPendingException(cx);
JSString* s = JS::ToString(cx, v); JSString* s = JS::ToString(cx, v);
if (s) { if (s) {
JSAutoByteString bytes(cx, s); if (JS::UniqueChars bytes = JS_EncodeString(cx, s))
if (!!bytes) message += bytes.get();
message += bytes.ptr();
} }
} }
@ -273,11 +271,10 @@ class JSAPITest
JSString* str = JS::ToString(cx, args[i]); JSString* str = JS::ToString(cx, args[i]);
if (!str) if (!str)
return false; return false;
char* bytes = JS_EncodeString(cx, str); JS::UniqueChars bytes = JS_EncodeString(cx, str);
if (!bytes) if (!bytes)
return false; return false;
printf("%s%s", i ? " " : "", bytes); printf("%s%s", i ? " " : "", bytes.get());
JS_free(cx, bytes);
} }
putchar('\n'); putchar('\n');

Просмотреть файл

@ -55,7 +55,6 @@
#include "gc/WeakMap.h" #include "gc/WeakMap.h"
#include "jit/JitCommon.h" #include "jit/JitCommon.h"
#include "jit/JitSpewer.h" #include "jit/JitSpewer.h"
#include "js/AutoByteString.h"
#include "js/CharacterEncoding.h" #include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h" #include "js/CompilationAndEvaluation.h"
#include "js/CompileOptions.h" #include "js/CompileOptions.h"
@ -181,8 +180,8 @@ JS::ObjectOpResult::reportStrictErrorOrWarning(JSContext* cx, HandleObject obj,
if (!str) if (!str)
return false; return false;
JSAutoByteString propName; UniqueChars propName = JS_EncodeStringToUTF8(cx, str);
if (!propName.encodeUtf8(cx, str)) if (!propName)
return false; return false;
if (code_ == JSMSG_SET_NON_OBJECT_RECEIVER) { if (code_ == JSMSG_SET_NON_OBJECT_RECEIVER) {
@ -193,16 +192,16 @@ JS::ObjectOpResult::reportStrictErrorOrWarning(JSContext* cx, HandleObject obj,
return false; return false;
} }
return ReportValueErrorFlags(cx, flags, code_, JSDVG_IGNORE_STACK, val, return ReportValueErrorFlags(cx, flags, code_, JSDVG_IGNORE_STACK, val,
nullptr, propName.ptr(), nullptr); nullptr, propName.get(), nullptr);
} }
if (ErrorTakesObjectArgument(code_)) { if (ErrorTakesObjectArgument(code_)) {
return JS_ReportErrorFlagsAndNumberUTF8(cx, flags, GetErrorMessage, nullptr, code_, return JS_ReportErrorFlagsAndNumberUTF8(cx, flags, GetErrorMessage, nullptr, code_,
obj->getClass()->name, propName.ptr()); obj->getClass()->name, propName.get());
} }
return JS_ReportErrorFlagsAndNumberUTF8(cx, flags, GetErrorMessage, nullptr, code_, return JS_ReportErrorFlagsAndNumberUTF8(cx, flags, GetErrorMessage, nullptr, code_,
propName.ptr()); propName.get());
} }
return JS_ReportErrorFlagsAndNumberASCII(cx, flags, GetErrorMessage, nullptr, code_); return JS_ReportErrorFlagsAndNumberASCII(cx, flags, GetErrorMessage, nullptr, code_);
} }
@ -1649,7 +1648,7 @@ JS::GetFirstArgumentAsTypeHint(JSContext* cx, CallArgs args, JSType *result)
return true; return true;
} }
JSAutoByteString bytes; UniqueChars bytes;
const char* source = ValueToSourceForError(cx, args.get(0), bytes); const char* source = ValueToSourceForError(cx, args.get(0), bytes);
if (!source) { if (!source) {
ReportOutOfMemory(cx); ReportOutOfMemory(cx);
@ -5066,9 +5065,8 @@ JS::DumpPromiseAllocationSite(JSContext* cx, JS::HandleObject promise)
{ {
RootedObject stack(cx, promise->as<PromiseObject>().allocationSite()); RootedObject stack(cx, promise->as<PromiseObject>().allocationSite());
JSPrincipals* principals = cx->realm()->principals(); JSPrincipals* principals = cx->realm()->principals();
UniqueChars stackStr( UniqueChars stackStr = BuildUTF8StackString(cx, principals, stack);
reinterpret_cast<char*>(BuildUTF8StackString(cx, principals, stack).get())); if (stackStr)
if (stackStr.get())
fputs(stackStr.get(), stderr); fputs(stackStr.get(), stderr);
} }
@ -5077,9 +5075,8 @@ JS::DumpPromiseResolutionSite(JSContext* cx, JS::HandleObject promise)
{ {
RootedObject stack(cx, promise->as<PromiseObject>().resolutionSite()); RootedObject stack(cx, promise->as<PromiseObject>().resolutionSite());
JSPrincipals* principals = cx->realm()->principals(); JSPrincipals* principals = cx->realm()->principals();
UniqueChars stackStr( UniqueChars stackStr = BuildUTF8StackString(cx, principals, stack);
reinterpret_cast<char*>(BuildUTF8StackString(cx, principals, stack).get())); if (stackStr)
if (stackStr.get())
fputs(stackStr.get(), stderr); fputs(stackStr.get(), stderr);
} }
#endif #endif
@ -6055,22 +6052,22 @@ JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen, char16_t* dst, siz
return true; return true;
} }
JS_PUBLIC_API(char*) JS_PUBLIC_API(JS::UniqueChars)
JS_EncodeString(JSContext* cx, JSString* str) JS_EncodeString(JSContext* cx, JSString* str)
{ {
AssertHeapIsIdle(); AssertHeapIsIdle();
CHECK_THREAD(cx); CHECK_THREAD(cx);
return js::EncodeLatin1(cx, str).release(); return js::EncodeLatin1(cx, str);
} }
JS_PUBLIC_API(char*) JS_PUBLIC_API(JS::UniqueChars)
JS_EncodeStringToUTF8(JSContext* cx, HandleString str) JS_EncodeStringToUTF8(JSContext* cx, HandleString str)
{ {
AssertHeapIsIdle(); AssertHeapIsIdle();
CHECK_THREAD(cx); CHECK_THREAD(cx);
return StringToNewUTF8CharsZ(cx, *str).release(); return StringToNewUTF8CharsZ(cx, *str);
} }
JS_PUBLIC_API(size_t) JS_PUBLIC_API(size_t)

Просмотреть файл

@ -23,7 +23,6 @@
#include "gc/FreeOp.h" #include "gc/FreeOp.h"
#include "gc/Marking.h" #include "gc/Marking.h"
#include "js/AutoByteString.h"
#include "js/CharacterEncoding.h" #include "js/CharacterEncoding.h"
#include "js/UniquePtr.h" #include "js/UniquePtr.h"
#include "js/Wrapper.h" #include "js/Wrapper.h"
@ -884,7 +883,7 @@ ErrorReport::init(JSContext* cx, HandleValue exn,
if (JS_GetProperty(cx, exnObject, filename_str, &val)) { if (JS_GetProperty(cx, exnObject, filename_str, &val)) {
RootedString tmp(cx, ToString<CanGC>(cx, val)); RootedString tmp(cx, ToString<CanGC>(cx, val));
if (tmp) if (tmp)
filename.encodeUtf8(cx, tmp); filename = JS_EncodeStringToUTF8(cx, tmp);
else else
cx->clearPendingException(); cx->clearPendingException();
} else { } else {
@ -909,7 +908,7 @@ ErrorReport::init(JSContext* cx, HandleValue exn,
reportp = &ownedReport; reportp = &ownedReport;
new (reportp) JSErrorReport(); new (reportp) JSErrorReport();
ownedReport.filename = filename.ptr(); ownedReport.filename = filename.get();
ownedReport.lineno = lineno; ownedReport.lineno = lineno;
ownedReport.exnType = JSEXN_INTERNALERR; ownedReport.exnType = JSEXN_INTERNALERR;
ownedReport.column = column; ownedReport.column = column;
@ -935,8 +934,10 @@ ErrorReport::init(JSContext* cx, HandleValue exn,
} }
const char* utf8Message = nullptr; const char* utf8Message = nullptr;
if (str) if (str) {
utf8Message = toStringResultBytesStorage.encodeUtf8(cx, str); toStringResultBytesStorage = JS_EncodeStringToUTF8(cx, str);
utf8Message = toStringResultBytesStorage.get();
}
if (!utf8Message) if (!utf8Message)
utf8Message = "unknown (can't convert to string)"; utf8Message = "unknown (can't convert to string)";
@ -1054,7 +1055,7 @@ JS::CreateError(JSContext* cx, JSExnType type, HandleObject stack, HandleString
} }
const char* const char*
js::ValueToSourceForError(JSContext* cx, HandleValue val, JSAutoByteString& bytes) js::ValueToSourceForError(JSContext* cx, HandleValue val, UniqueChars& bytes)
{ {
if (val.isUndefined()) if (val.isUndefined())
return "undefined"; return "undefined";
@ -1093,14 +1094,16 @@ js::ValueToSourceForError(JSContext* cx, HandleValue val, JSAutoByteString& byte
return "<<error converting value to string>>"; return "<<error converting value to string>>";
} else { } else {
MOZ_ASSERT(val.isBoolean() || val.isSymbol()); MOZ_ASSERT(val.isBoolean() || val.isSymbol());
return bytes.encodeLatin1(cx, str); bytes = JS_EncodeString(cx, str);
return bytes.get();
} }
if (!sb.append(str)) if (!sb.append(str))
return "<<error converting value to string>>"; return "<<error converting value to string>>";
str = sb.finishString(); str = sb.finishString();
if (!str) if (!str)
return "<<error converting value to string>>"; return "<<error converting value to string>>";
return bytes.encodeLatin1(cx, str); bytes = JS_EncodeString(cx, str);
return bytes.get();
} }
bool bool

Просмотреть файл

@ -17,8 +17,6 @@
#include "js/UniquePtr.h" #include "js/UniquePtr.h"
#include "vm/JSContext.h" #include "vm/JSContext.h"
class JSAutoByteString;
namespace js { namespace js {
class ErrorObject; class ErrorObject;
@ -134,7 +132,7 @@ class AutoAssertNoPendingException
}; };
extern const char* extern const char*
ValueToSourceForError(JSContext* cx, HandleValue val, JSAutoByteString& bytes); ValueToSourceForError(JSContext* cx, HandleValue val, JS::UniqueChars& bytes);
bool bool
GetInternalError(JSContext* cx, unsigned errorNumber, MutableHandleValue error); GetInternalError(JSContext* cx, unsigned errorNumber, MutableHandleValue error);

Просмотреть файл

@ -20,7 +20,7 @@
#include "gc/GCInternals.h" #include "gc/GCInternals.h"
#include "gc/PublicIterators.h" #include "gc/PublicIterators.h"
#include "gc/WeakMap.h" #include "gc/WeakMap.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/Printf.h" #include "js/Printf.h"
#include "js/Proxy.h" #include "js/Proxy.h"
#include "js/Wrapper.h" #include "js/Wrapper.h"
@ -808,7 +808,7 @@ js::DumpScript(JSContext* cx, JSScript* scriptArg)
#endif #endif
static const char* static const char*
FormatValue(JSContext* cx, const Value& vArg, JSAutoByteString& bytes) FormatValue(JSContext* cx, const Value& vArg, UniqueChars& bytes)
{ {
RootedValue v(cx, vArg); RootedValue v(cx, vArg);
@ -832,7 +832,8 @@ FormatValue(JSContext* cx, const Value& vArg, JSAutoByteString& bytes)
if (!str) if (!str)
return nullptr; return nullptr;
const char* buf = bytes.encodeLatin1(cx, str); bytes = JS_EncodeString(cx, str);
const char* buf = bytes.get();
if (!buf) if (!buf)
return nullptr; return nullptr;
const char* found = strstr(buf, "function "); const char* found = strstr(buf, "function ");
@ -892,8 +893,8 @@ FormatFrame(JSContext* cx, const FrameIter& iter, JS::UniqueChars&& inBuf, int n
// print the frame number and function name // print the frame number and function name
JS::UniqueChars buf(std::move(inBuf)); JS::UniqueChars buf(std::move(inBuf));
if (funname) { if (funname) {
JSAutoByteString funbytes; UniqueChars funbytes = JS_EncodeString(cx, funname);
char* str = funbytes.encodeLatin1(cx, funname); char* str = funbytes.get();
if (!str) if (!str)
return nullptr; return nullptr;
buf = sprintf_append(cx, std::move(buf), "%d %s(", num, str); buf = sprintf_append(cx, std::move(buf), "%d %s(", num, str);
@ -925,7 +926,7 @@ FormatFrame(JSContext* cx, const FrameIter& iter, JS::UniqueChars&& inBuf, int n
arg = MagicValue(JS_OPTIMIZED_OUT); arg = MagicValue(JS_OPTIMIZED_OUT);
} }
JSAutoByteString valueBytes; UniqueChars valueBytes;
const char* value = FormatValue(cx, arg, valueBytes); const char* value = FormatValue(cx, arg, valueBytes);
if (!value) { if (!value) {
if (cx->isThrowingOutOfMemory()) if (cx->isThrowingOutOfMemory())
@ -933,13 +934,14 @@ FormatFrame(JSContext* cx, const FrameIter& iter, JS::UniqueChars&& inBuf, int n
cx->clearPendingException(); cx->clearPendingException();
} }
JSAutoByteString nameBytes; UniqueChars nameBytes;
const char* name = nullptr; const char* name = nullptr;
if (i < iter.numFormalArgs()) { if (i < iter.numFormalArgs()) {
MOZ_ASSERT(fi.argumentSlot() == i); MOZ_ASSERT(fi.argumentSlot() == i);
if (!fi.isDestructured()) { if (!fi.isDestructured()) {
name = nameBytes.encodeLatin1(cx, fi.name()); nameBytes = JS_EncodeString(cx, fi.name());
name = nameBytes.get();
if (!name) if (!name)
return nullptr; return nullptr;
} else { } else {
@ -985,7 +987,7 @@ FormatFrame(JSContext* cx, const FrameIter& iter, JS::UniqueChars&& inBuf, int n
// print the value of 'this' // print the value of 'this'
if (showLocals) { if (showLocals) {
if (!thisVal.isUndefined()) { if (!thisVal.isUndefined()) {
JSAutoByteString thisValBytes; UniqueChars thisValBytes;
RootedString thisValStr(cx, ToString<CanGC>(cx, thisVal)); RootedString thisValStr(cx, ToString<CanGC>(cx, thisVal));
if (!thisValStr) { if (!thisValStr) {
if (cx->isThrowingOutOfMemory()) if (cx->isThrowingOutOfMemory())
@ -993,7 +995,8 @@ FormatFrame(JSContext* cx, const FrameIter& iter, JS::UniqueChars&& inBuf, int n
cx->clearPendingException(); cx->clearPendingException();
} }
if (thisValStr) { if (thisValStr) {
const char* str = thisValBytes.encodeLatin1(cx, thisValStr); thisValBytes = JS_EncodeString(cx, thisValStr);
const char* str = thisValBytes.get();
if (!str) if (!str)
return nullptr; return nullptr;
buf = sprintf_append(cx, std::move(buf), " this = %s\n", str); buf = sprintf_append(cx, std::move(buf), " this = %s\n", str);
@ -1032,7 +1035,7 @@ FormatFrame(JSContext* cx, const FrameIter& iter, JS::UniqueChars&& inBuf, int n
continue; continue;
} }
JSAutoByteString nameBytes; UniqueChars nameBytes;
const char* name = FormatValue(cx, key, nameBytes); const char* name = FormatValue(cx, key, nameBytes);
if (!name) { if (!name) {
if (cx->isThrowingOutOfMemory()) if (cx->isThrowingOutOfMemory())
@ -1040,7 +1043,7 @@ FormatFrame(JSContext* cx, const FrameIter& iter, JS::UniqueChars&& inBuf, int n
cx->clearPendingException(); cx->clearPendingException();
} }
JSAutoByteString valueBytes; UniqueChars valueBytes;
const char* value = FormatValue(cx, v, valueBytes); const char* value = FormatValue(cx, v, valueBytes);
if (!value) { if (!value) {
if (cx->isThrowingOutOfMemory()) if (cx->isThrowingOutOfMemory())

Просмотреть файл

@ -15,7 +15,6 @@
#include "jspubtd.h" #include "jspubtd.h"
#include "js/AutoByteString.h"
#include "js/CallArgs.h" #include "js/CallArgs.h"
#include "js/CallNonGenericMethod.h" #include "js/CallNonGenericMethod.h"
#include "js/CharacterEncoding.h" #include "js/CharacterEncoding.h"
@ -1464,13 +1463,13 @@ struct MOZ_STACK_CLASS JS_FRIEND_API(ErrorReport)
JS::RootedObject exnObject; JS::RootedObject exnObject;
// And for our filename. // And for our filename.
JSAutoByteString filename; JS::UniqueChars filename;
// We may have a result of error.toString(). // We may have a result of error.toString().
// FIXME: We should not call error.toString(), since it could have side // FIXME: We should not call error.toString(), since it could have side
// effect (see bug 633623). // effect (see bug 633623).
JS::ConstUTF8CharsZ toStringResult_; JS::ConstUTF8CharsZ toStringResult_;
JSAutoByteString toStringResultBytesStorage; JS::UniqueChars toStringResultBytesStorage;
}; };
/* Implemented in vm/StructuredClone.cpp. */ /* Implemented in vm/StructuredClone.cpp. */

Просмотреть файл

@ -27,6 +27,7 @@
#include "builtin/String.h" #include "builtin/String.h"
#include "double-conversion/double-conversion.h" #include "double-conversion/double-conversion.h"
#include "js/CharacterEncoding.h"
#include "js/Conversions.h" #include "js/Conversions.h"
#if !EXPOSE_INTL_API #if !EXPOSE_INTL_API
#include "js/LocaleSensitive.h" #include "js/LocaleSensitive.h"
@ -796,10 +797,10 @@ num_toLocaleString_impl(JSContext* cx, const CallArgs& args)
* Create the string, move back to bytes to make string twiddling * Create the string, move back to bytes to make string twiddling
* a bit easier and so we can insert platform charset seperators. * a bit easier and so we can insert platform charset seperators.
*/ */
JSAutoByteString numBytes(cx, str); UniqueChars numBytes = JS_EncodeString(cx, str);
if (!numBytes) if (!numBytes)
return false; return false;
const char* num = numBytes.ptr(); const char* num = numBytes.get();
if (!num) if (!num)
return false; return false;

Просмотреть файл

@ -124,7 +124,6 @@ EXPORTS += [
EXPORTS.js += [ EXPORTS.js += [
'../public/AllocPolicy.h', '../public/AllocPolicy.h',
'../public/AutoByteString.h',
'../public/CallArgs.h', '../public/CallArgs.h',
'../public/CallNonGenericMethod.h', '../public/CallNonGenericMethod.h',
'../public/CharacterEncoding.h', '../public/CharacterEncoding.h',

Просмотреть файл

@ -8,7 +8,7 @@
#include "jsapi.h" #include "jsapi.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "vm/Interpreter.h" // For InstanceOfOperator #include "vm/Interpreter.h" // For InstanceOfOperator
#include "vm/JSObject-inl.h" #include "vm/JSObject-inl.h"
@ -179,11 +179,11 @@ GetProxyTrap(JSContext* cx, HandleObject handler, HandlePropertyName name, Mutab
// Step 4. // Step 4.
if (!IsCallable(func)) { if (!IsCallable(func)) {
JSAutoByteString bytes(cx, name); UniqueChars bytes = JS_EncodeString(cx, name);
if (!bytes) if (!bytes)
return false; return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_BAD_TRAP, bytes.ptr()); JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_BAD_TRAP, bytes.get());
return false; return false;
} }

Просмотреть файл

@ -25,7 +25,7 @@
#include "builtin/String.h" #include "builtin/String.h"
#include "gc/FreeOp.h" #include "gc/FreeOp.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/Conversions.h" #include "js/Conversions.h"
#include "js/Wrapper.h" #include "js/Wrapper.h"
#include "shell/jsshell.h" #include "shell/jsshell.h"
@ -58,9 +58,9 @@ const char PathSeparator = '/';
#endif #endif
static bool static bool
IsAbsolutePath(const JSAutoByteString& filename) IsAbsolutePath(const UniqueChars& filename)
{ {
const char* pathname = filename.ptr(); const char* pathname = filename.get();
if (pathname[0] == PathSeparator) if (pathname[0] == PathSeparator)
return true; return true;
@ -106,7 +106,7 @@ ResolvePath(JSContext* cx, HandleString filenameStr, PathResolutionMode resolveM
#endif #endif
} }
JSAutoByteString filename(cx, filenameStr); UniqueChars filename = JS_EncodeString(cx, filenameStr);
if (!filename) if (!filename)
return nullptr; return nullptr;
@ -148,7 +148,7 @@ ResolvePath(JSContext* cx, HandleString filenameStr, PathResolutionMode resolveM
size_t len = strlen(buffer); size_t len = strlen(buffer);
buffer[len] = '/'; buffer[len] = '/';
strncpy(buffer + len + 1, filename.ptr(), sizeof(buffer) - (len+1)); strncpy(buffer + len + 1, filename.get(), sizeof(buffer) - (len+1));
if (buffer[PATH_MAX] != '\0') if (buffer[PATH_MAX] != '\0')
return nullptr; return nullptr;
@ -158,34 +158,34 @@ ResolvePath(JSContext* cx, HandleString filenameStr, PathResolutionMode resolveM
JSObject* JSObject*
FileAsTypedArray(JSContext* cx, JS::HandleString pathnameStr) FileAsTypedArray(JSContext* cx, JS::HandleString pathnameStr)
{ {
JSAutoByteString pathname(cx, pathnameStr); UniqueChars pathname = JS_EncodeString(cx, pathnameStr);
if (!pathname) if (!pathname)
return nullptr; return nullptr;
FILE* file = fopen(pathname.ptr(), "rb"); FILE* file = fopen(pathname.get(), "rb");
if (!file) { if (!file) {
/* /*
* Use Latin1 variant here because the encoding of the return value of * Use Latin1 variant here because the encoding of the return value of
* strerror function can be non-UTF-8. * strerror function can be non-UTF-8.
*/ */
JS_ReportErrorLatin1(cx, "can't open %s: %s", pathname.ptr(), strerror(errno)); JS_ReportErrorLatin1(cx, "can't open %s: %s", pathname.get(), strerror(errno));
return nullptr; return nullptr;
} }
AutoCloseFile autoClose(file); AutoCloseFile autoClose(file);
RootedObject obj(cx); RootedObject obj(cx);
if (fseek(file, 0, SEEK_END) != 0) { if (fseek(file, 0, SEEK_END) != 0) {
pathname.clear(); pathname = JS_EncodeStringToUTF8(cx, pathnameStr);
if (!pathname.encodeUtf8(cx, pathnameStr)) if (!pathname)
return nullptr; return nullptr;
JS_ReportErrorUTF8(cx, "can't seek end of %s", pathname.ptr()); JS_ReportErrorUTF8(cx, "can't seek end of %s", pathname.get());
} else { } else {
size_t len = ftell(file); size_t len = ftell(file);
if (fseek(file, 0, SEEK_SET) != 0) { if (fseek(file, 0, SEEK_SET) != 0) {
pathname.clear(); pathname = JS_EncodeStringToUTF8(cx, pathnameStr);
if (!pathname.encodeUtf8(cx, pathnameStr)) if (!pathname)
return nullptr; return nullptr;
JS_ReportErrorUTF8(cx, "can't seek start of %s", pathname.ptr()); JS_ReportErrorUTF8(cx, "can't seek start of %s", pathname.get());
} else { } else {
obj = JS_NewUint8Array(cx, len); obj = JS_NewUint8Array(cx, len);
if (!obj) if (!obj)
@ -201,10 +201,10 @@ FileAsTypedArray(JSContext* cx, JS::HandleString pathnameStr)
// temporary buffer, read into that, and use a // temporary buffer, read into that, and use a
// race-safe primitive to copy memory into the // race-safe primitive to copy memory into the
// buffer.) // buffer.)
pathname.clear(); pathname = JS_EncodeStringToUTF8(cx, pathnameStr);
if (!pathname.encodeUtf8(cx, pathnameStr)) if (!pathname)
return nullptr; return nullptr;
JS_ReportErrorUTF8(cx, "can't read %s: shared memory buffer", pathname.ptr()); JS_ReportErrorUTF8(cx, "can't read %s: shared memory buffer", pathname.get());
return nullptr; return nullptr;
} }
char* buf = static_cast<char*>(ta.viewDataUnshared()); char* buf = static_cast<char*>(ta.viewDataUnshared());
@ -215,12 +215,12 @@ FileAsTypedArray(JSContext* cx, JS::HandleString pathnameStr)
* Use Latin1 variant here because the encoding of the return * Use Latin1 variant here because the encoding of the return
* value of strerror function can be non-UTF-8. * value of strerror function can be non-UTF-8.
*/ */
JS_ReportErrorLatin1(cx, "can't read %s: %s", pathname.ptr(), strerror(errno)); JS_ReportErrorLatin1(cx, "can't read %s: %s", pathname.get(), strerror(errno));
} else { } else {
pathname.clear(); pathname = JS_EncodeStringToUTF8(cx, pathnameStr);
if (!pathname.encodeUtf8(cx, pathnameStr)) if (!pathname)
return nullptr; return nullptr;
JS_ReportErrorUTF8(cx, "can't read %s: short read", pathname.ptr()); JS_ReportErrorUTF8(cx, "can't read %s: short read", pathname.get());
} }
obj = nullptr; obj = nullptr;
} }
@ -319,17 +319,17 @@ osfile_writeTypedArrayToFile(JSContext* cx, unsigned argc, Value* vp)
if (!str) if (!str)
return false; return false;
JSAutoByteString filename(cx, str); UniqueChars filename = JS_EncodeString(cx, str);
if (!filename) if (!filename)
return false; return false;
FILE* file = fopen(filename.ptr(), "wb"); FILE* file = fopen(filename.get(), "wb");
if (!file) { if (!file) {
/* /*
* Use Latin1 variant here because the encoding of the return value of * Use Latin1 variant here because the encoding of the return value of
* strerror function can be non-UTF-8. * strerror function can be non-UTF-8.
*/ */
JS_ReportErrorLatin1(cx, "can't open %s: %s", filename.ptr(), strerror(errno)); JS_ReportErrorLatin1(cx, "can't open %s: %s", filename.get(), strerror(errno));
return false; return false;
} }
AutoCloseFile autoClose(file); AutoCloseFile autoClose(file);
@ -340,20 +340,20 @@ osfile_writeTypedArrayToFile(JSContext* cx, unsigned argc, Value* vp)
// Must opt in to use shared memory. For now, don't. // Must opt in to use shared memory. For now, don't.
// //
// See further comments in FileAsTypedArray, above. // See further comments in FileAsTypedArray, above.
filename.clear(); filename = JS_EncodeStringToUTF8(cx, str);
if (!filename.encodeUtf8(cx, str)) if (!filename)
return false; return false;
JS_ReportErrorUTF8(cx, "can't write %s: shared memory buffer", filename.ptr()); JS_ReportErrorUTF8(cx, "can't write %s: shared memory buffer", filename.get());
return false; return false;
} }
void* buf = obj->viewDataUnshared(); void* buf = obj->viewDataUnshared();
if (fwrite(buf, obj->bytesPerElement(), obj->length(), file) != obj->length() || if (fwrite(buf, obj->bytesPerElement(), obj->length(), file) != obj->length() ||
!autoClose.release()) !autoClose.release())
{ {
filename.clear(); filename = JS_EncodeStringToUTF8(cx, str);
if (!filename.encodeUtf8(cx, str)) if (!filename)
return false; return false;
JS_ReportErrorUTF8(cx, "can't write %s", filename.ptr()); JS_ReportErrorUTF8(cx, "can't write %s", filename.get());
return false; return false;
} }
@ -472,16 +472,16 @@ redirect(JSContext* cx, HandleString relFilename, RCFile** globalFile)
RootedString filename(cx, ResolvePath(cx, relFilename, RootRelative)); RootedString filename(cx, ResolvePath(cx, relFilename, RootRelative));
if (!filename) if (!filename)
return nullptr; return nullptr;
JSAutoByteString filenameABS(cx, filename); UniqueChars filenameABS = JS_EncodeString(cx, filename);
if (!filenameABS) if (!filenameABS)
return nullptr; return nullptr;
RCFile* file = RCFile::create(cx, filenameABS.ptr(), "wb"); RCFile* file = RCFile::create(cx, filenameABS.get(), "wb");
if (!file) { if (!file) {
/* /*
* Use Latin1 variant here because the encoding of the return value of * Use Latin1 variant here because the encoding of the return value of
* strerror function can be non-UTF-8. * strerror function can be non-UTF-8.
*/ */
JS_ReportErrorLatin1(cx, "cannot redirect to %s: %s", filenameABS.ptr(), strerror(errno)); JS_ReportErrorLatin1(cx, "cannot redirect to %s: %s", filenameABS.get(), strerror(errno));
return nullptr; return nullptr;
} }
@ -636,7 +636,7 @@ ospath_isAbsolute(JSContext* cx, unsigned argc, Value* vp)
return false; return false;
} }
JSAutoByteString path(cx, args[0].toString()); UniqueChars path = JS_EncodeString(cx, args[0].toString());
if (!path) if (!path)
return false; return false;
@ -665,7 +665,7 @@ ospath_join(JSContext* cx, unsigned argc, Value* vp)
return false; return false;
} }
JSAutoByteString path(cx, args[i].toString()); UniqueChars path = JS_EncodeString(cx, args[i].toString());
if (!path) if (!path)
return false; return false;
@ -711,11 +711,11 @@ os_getenv(JSContext* cx, unsigned argc, Value* vp)
RootedString key(cx, ToString(cx, args[0])); RootedString key(cx, ToString(cx, args[0]));
if (!key) if (!key)
return false; return false;
JSAutoByteString keyBytes; UniqueChars keyBytes = JS_EncodeStringToUTF8(cx, key);
if (!keyBytes.encodeUtf8(cx, key)) if (!keyBytes)
return false; return false;
if (const char* valueBytes = getenv(keyBytes.ptr())) { if (const char* valueBytes = getenv(keyBytes.get())) {
RootedString value(cx, JS_NewStringCopyZ(cx, valueBytes)); RootedString value(cx, JS_NewStringCopyZ(cx, valueBytes));
if (!value) if (!value)
return false; return false;
@ -795,11 +795,11 @@ os_system(JSContext* cx, unsigned argc, Value* vp)
if (!str) if (!str)
return false; return false;
JSAutoByteString command(cx, str); UniqueChars command = JS_EncodeString(cx, str);
if (!command) if (!command)
return false; return false;
int result = system(command.ptr()); int result = system(command.get());
if (result == -1) { if (result == -1) {
ReportSysError(cx, "system call failed"); ReportSysError(cx, "system call failed");
return false; return false;
@ -824,7 +824,7 @@ os_spawn(JSContext* cx, unsigned argc, Value* vp)
if (!str) if (!str)
return false; return false;
JSAutoByteString command(cx, str); UniqueChars command = JS_EncodeString(cx, str);
if (!command) if (!command)
return false; return false;
@ -842,7 +842,7 @@ os_spawn(JSContext* cx, unsigned argc, Value* vp)
// We are in the child // We are in the child
const char* cmd[] = {"sh", "-c", nullptr, nullptr}; const char* cmd[] = {"sh", "-c", nullptr, nullptr};
cmd[2] = command.ptr(); cmd[2] = command.get();
execvp("sh", (char * const*)cmd); execvp("sh", (char * const*)cmd);
exit(1); exit(1);

Просмотреть файл

@ -77,7 +77,7 @@
#include "jit/JitcodeMap.h" #include "jit/JitcodeMap.h"
#include "jit/JitRealm.h" #include "jit/JitRealm.h"
#include "jit/shared/CodeGenerator-shared.h" #include "jit/shared/CodeGenerator-shared.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h" #include "js/CompilationAndEvaluation.h"
#include "js/CompileOptions.h" #include "js/CompileOptions.h"
#include "js/Debug.h" #include "js/Debug.h"
@ -1053,7 +1053,6 @@ BoundToAsyncStack(JSContext* cx, unsigned argc, Value* vp)
RootedObject options(cx, &GetFunctionNativeReserved(&args.callee(), 1).toObject()); RootedObject options(cx, &GetFunctionNativeReserved(&args.callee(), 1).toObject());
RootedSavedFrame stack(cx, nullptr); RootedSavedFrame stack(cx, nullptr);
JSAutoByteString cause;
bool isExplicit; bool isExplicit;
RootedValue v(cx); RootedValue v(cx);
@ -1069,7 +1068,13 @@ BoundToAsyncStack(JSContext* cx, unsigned argc, Value* vp)
if (!JS_GetProperty(cx, options, "cause", &v)) if (!JS_GetProperty(cx, options, "cause", &v))
return false; return false;
RootedString causeString(cx, ToString(cx, v)); RootedString causeString(cx, ToString(cx, v));
if (!causeString || !cause.encodeUtf8(cx, causeString)) { if (!causeString) {
MOZ_ASSERT(cx->isExceptionPending());
return false;
}
UniqueChars cause = JS_EncodeStringToUTF8(cx, causeString);
if (!cause) {
MOZ_ASSERT(cx->isExceptionPending()); MOZ_ASSERT(cx->isExceptionPending());
return false; return false;
} }
@ -1082,7 +1087,7 @@ BoundToAsyncStack(JSContext* cx, unsigned argc, Value* vp)
? JS::AutoSetAsyncStackForNewCalls::AsyncCallKind::EXPLICIT ? JS::AutoSetAsyncStackForNewCalls::AsyncCallKind::EXPLICIT
: JS::AutoSetAsyncStackForNewCalls::AsyncCallKind::IMPLICIT); : JS::AutoSetAsyncStackForNewCalls::AsyncCallKind::IMPLICIT);
JS::AutoSetAsyncStackForNewCalls asasfnckthxbye(cx, stack, cause.ptr(), kind); JS::AutoSetAsyncStackForNewCalls asasfnckthxbye(cx, stack, cause.get(), kind);
return Call(cx, UndefinedHandleValue, function, return Call(cx, UndefinedHandleValue, function,
JS::HandleValueArray::empty(), args.rval()); JS::HandleValueArray::empty(), args.rval());
} }
@ -1176,11 +1181,10 @@ EvalAndPrint(JSContext* cx, const char* bytes, size_t length,
if (!str) if (!str)
return false; return false;
char* utf8chars = JS_EncodeStringToUTF8(cx, str); UniqueChars utf8chars = JS_EncodeStringToUTF8(cx, str);
if (!utf8chars) if (!utf8chars)
return false; return false;
fprintf(gOutFile->fp, "%s\n", utf8chars); fprintf(gOutFile->fp, "%s\n", utf8chars.get());
JS_free(cx, utf8chars);
} }
return true; return true;
} }
@ -1360,7 +1364,7 @@ CreateMappedArrayBuffer(JSContext* cx, unsigned argc, Value* vp)
JSString* filenameStr = ResolvePath(cx, rawFilenameStr, ScriptRelative); JSString* filenameStr = ResolvePath(cx, rawFilenameStr, ScriptRelative);
if (!filenameStr) if (!filenameStr)
return false; return false;
JSAutoByteString filename(cx, filenameStr); UniqueChars filename = JS_EncodeString(cx, filenameStr);
if (!filename) if (!filename)
return false; return false;
@ -1382,9 +1386,9 @@ CreateMappedArrayBuffer(JSContext* cx, unsigned argc, Value* vp)
} }
} }
FILE* file = fopen(filename.ptr(), "rb"); FILE* file = fopen(filename.get(), "rb");
if (!file) { if (!file) {
ReportCantOpenErrorUnknownEncoding(cx, filename.ptr()); ReportCantOpenErrorUnknownEncoding(cx, filename.get());
return false; return false;
} }
AutoCloseFile autoClose(file); AutoCloseFile autoClose(file);
@ -1470,13 +1474,13 @@ Options(JSContext* cx, unsigned argc, Value* vp)
return false; return false;
args[i].setString(str); args[i].setString(str);
JSAutoByteString opt; UniqueChars opt = JS_EncodeStringToUTF8(cx, str);
if (!opt.encodeUtf8(cx, str)) if (!opt)
return false; return false;
if (strcmp(opt.ptr(), "strict") == 0) { if (strcmp(opt.get(), "strict") == 0) {
JS::ContextOptionsRef(cx).toggleExtraWarnings(); JS::ContextOptionsRef(cx).toggleExtraWarnings();
} else if (strcmp(opt.ptr(), "werror") == 0) { } else if (strcmp(opt.get(), "werror") == 0) {
// Disallow toggling werror when there are off-thread jobs, to avoid // Disallow toggling werror when there are off-thread jobs, to avoid
// confusing CompileError::throwError. // confusing CompileError::throwError.
ShellContext* sc = GetShellContext(cx); ShellContext* sc = GetShellContext(cx);
@ -1485,16 +1489,16 @@ Options(JSContext* cx, unsigned argc, Value* vp)
return false; return false;
} }
JS::ContextOptionsRef(cx).toggleWerror(); JS::ContextOptionsRef(cx).toggleWerror();
} else if (strcmp(opt.ptr(), "throw_on_asmjs_validation_failure") == 0) { } else if (strcmp(opt.get(), "throw_on_asmjs_validation_failure") == 0) {
JS::ContextOptionsRef(cx).toggleThrowOnAsmJSValidationFailure(); JS::ContextOptionsRef(cx).toggleThrowOnAsmJSValidationFailure();
} else if (strcmp(opt.ptr(), "strict_mode") == 0) { } else if (strcmp(opt.get(), "strict_mode") == 0) {
JS::ContextOptionsRef(cx).toggleStrictMode(); JS::ContextOptionsRef(cx).toggleStrictMode();
} else { } else {
JS_ReportErrorUTF8(cx, JS_ReportErrorUTF8(cx,
"unknown option name '%s'." "unknown option name '%s'."
" The valid names are strict," " The valid names are strict,"
" werror, and strict_mode.", " werror, and strict_mode.",
opt.ptr()); opt.get());
return false; return false;
} }
} }
@ -1547,7 +1551,7 @@ LoadScript(JSContext* cx, unsigned argc, Value* vp, bool scriptRelative)
JS_ReportErrorASCII(cx, "unable to resolve path"); JS_ReportErrorASCII(cx, "unable to resolve path");
return false; return false;
} }
JSAutoByteString filename(cx, str); UniqueChars filename = JS_EncodeString(cx, str);
if (!filename) if (!filename)
return false; return false;
errno = 0; errno = 0;
@ -1558,8 +1562,8 @@ LoadScript(JSContext* cx, unsigned argc, Value* vp, bool scriptRelative)
.setNoScriptRval(true); .setNoScriptRval(true);
RootedScript script(cx); RootedScript script(cx);
RootedValue unused(cx); RootedValue unused(cx);
if ((compileOnly && !Compile(cx, opts, filename.ptr(), &script)) || if ((compileOnly && !Compile(cx, opts, filename.get(), &script)) ||
!Evaluate(cx, opts, filename.ptr(), &unused)) !Evaluate(cx, opts, filename.get(), &unused))
{ {
return false; return false;
} }
@ -1586,7 +1590,7 @@ LoadScriptRelativeToScript(JSContext* cx, unsigned argc, Value* vp)
// bytes. // bytes.
static bool static bool
ParseCompileOptions(JSContext* cx, CompileOptions& options, HandleObject opts, ParseCompileOptions(JSContext* cx, CompileOptions& options, HandleObject opts,
JSAutoByteString& fileNameBytes) UniqueChars& fileNameBytes)
{ {
RootedValue v(cx); RootedValue v(cx);
RootedString s(cx); RootedString s(cx);
@ -1609,7 +1613,8 @@ ParseCompileOptions(JSContext* cx, CompileOptions& options, HandleObject opts,
s = ToString(cx, v); s = ToString(cx, v);
if (!s) if (!s)
return false; return false;
char* fileName = fileNameBytes.encodeLatin1(cx, s); fileNameBytes = JS_EncodeString(cx, s);
char* fileName = fileNameBytes.get();
if (!fileName) if (!fileName)
return false; return false;
options.setFile(fileName); options.setFile(fileName);
@ -1818,7 +1823,7 @@ Evaluate(JSContext* cx, unsigned argc, Value* vp)
} }
CompileOptions options(cx); CompileOptions options(cx);
JSAutoByteString fileNameBytes; UniqueChars fileNameBytes;
RootedString displayURL(cx); RootedString displayURL(cx);
RootedString sourceMapURL(cx); RootedString sourceMapURL(cx);
RootedObject global(cx, nullptr); RootedObject global(cx, nullptr);
@ -2092,34 +2097,34 @@ Evaluate(JSContext* cx, unsigned argc, Value* vp)
JSString* JSString*
js::shell::FileAsString(JSContext* cx, JS::HandleString pathnameStr) js::shell::FileAsString(JSContext* cx, JS::HandleString pathnameStr)
{ {
JSAutoByteString pathname(cx, pathnameStr); UniqueChars pathname = JS_EncodeString(cx, pathnameStr);
if (!pathname) if (!pathname)
return nullptr; return nullptr;
FILE* file; FILE* file;
file = fopen(pathname.ptr(), "rb"); file = fopen(pathname.get(), "rb");
if (!file) { if (!file) {
ReportCantOpenErrorUnknownEncoding(cx, pathname.ptr()); ReportCantOpenErrorUnknownEncoding(cx, pathname.get());
return nullptr; return nullptr;
} }
AutoCloseFile autoClose(file); AutoCloseFile autoClose(file);
if (fseek(file, 0, SEEK_END) != 0) { if (fseek(file, 0, SEEK_END) != 0) {
pathname.clear(); pathname = JS_EncodeStringToUTF8(cx, pathnameStr);
if (!pathname.encodeUtf8(cx, pathnameStr)) if (!pathname)
return nullptr; return nullptr;
JS_ReportErrorUTF8(cx, "can't seek end of %s", pathname.ptr()); JS_ReportErrorUTF8(cx, "can't seek end of %s", pathname.get());
return nullptr; return nullptr;
} }
size_t len = ftell(file); size_t len = ftell(file);
if (fseek(file, 0, SEEK_SET) != 0) { if (fseek(file, 0, SEEK_SET) != 0) {
pathname.clear(); pathname = JS_EncodeStringToUTF8(cx, pathnameStr);
if (!pathname.encodeUtf8(cx, pathnameStr)) if (!pathname)
return nullptr; return nullptr;
JS_ReportErrorUTF8(cx, "can't seek start of %s", pathname.ptr()); JS_ReportErrorUTF8(cx, "can't seek start of %s", pathname.get());
return nullptr; return nullptr;
} }
@ -2130,12 +2135,12 @@ js::shell::FileAsString(JSContext* cx, JS::HandleString pathnameStr)
size_t cc = fread(buf.get(), 1, len, file); size_t cc = fread(buf.get(), 1, len, file);
if (cc != len) { if (cc != len) {
if (ptrdiff_t(cc) < 0) { if (ptrdiff_t(cc) < 0) {
ReportCantOpenErrorUnknownEncoding(cx, pathname.ptr()); ReportCantOpenErrorUnknownEncoding(cx, pathname.get());
} else { } else {
pathname.clear(); pathname = JS_EncodeStringToUTF8(cx, pathnameStr);
if (!pathname.encodeUtf8(cx, pathnameStr)) if (!pathname)
return nullptr; return nullptr;
JS_ReportErrorUTF8(cx, "can't read %s: short read", pathname.ptr()); JS_ReportErrorUTF8(cx, "can't read %s: short read", pathname.get());
} }
return nullptr; return nullptr;
} }
@ -2144,10 +2149,10 @@ js::shell::FileAsString(JSContext* cx, JS::HandleString pathnameStr)
JS::LossyUTF8CharsToNewTwoByteCharsZ(cx, JS::UTF8Chars(buf.get(), len), &len).get() JS::LossyUTF8CharsToNewTwoByteCharsZ(cx, JS::UTF8Chars(buf.get(), len), &len).get()
); );
if (!ucbuf) { if (!ucbuf) {
pathname.clear(); pathname = JS_EncodeStringToUTF8(cx, pathnameStr);
if (!pathname.encodeUtf8(cx, pathnameStr)) if (!pathname)
return nullptr; return nullptr;
JS_ReportErrorUTF8(cx, "Invalid UTF-8 in file '%s'", pathname.ptr()); JS_ReportErrorUTF8(cx, "Invalid UTF-8 in file '%s'", pathname.get());
return nullptr; return nullptr;
} }
@ -2188,13 +2193,13 @@ Run(JSContext* cx, unsigned argc, Value* vp)
int64_t startClock = PRMJ_Now(); int64_t startClock = PRMJ_Now();
{ {
/* FIXME: This should use UTF-8 (bug 987069). */ /* FIXME: This should use UTF-8 (bug 987069). */
JSAutoByteString filename(cx, str); UniqueChars filename = JS_EncodeString(cx, str);
if (!filename) if (!filename)
return false; return false;
JS::CompileOptions options(cx); JS::CompileOptions options(cx);
options.setIntroductionType("js shell run") options.setIntroductionType("js shell run")
.setFileAndLine(filename.ptr(), 1) .setFileAndLine(filename.get(), 1)
.setIsRunOnce(true) .setIsRunOnce(true)
.setNoScriptRval(true); .setNoScriptRval(true);
if (!JS_CompileUCScript(cx, srcBuf, options, &script)) if (!JS_CompileUCScript(cx, srcBuf, options, &script))
@ -2340,7 +2345,7 @@ ReadLineBuf(JSContext* cx, unsigned argc, Value* vp)
RootedString str(cx, JS::ToString(cx, args[0])); RootedString str(cx, JS::ToString(cx, args[0]));
if (!str) if (!str)
return false; return false;
sc->readLineBuf = UniqueChars(JS_EncodeStringToUTF8(cx, str)); sc->readLineBuf = JS_EncodeStringToUTF8(cx, str);
if (!sc->readLineBuf) if (!sc->readLineBuf)
return false; return false;
@ -2366,11 +2371,10 @@ PutStr(JSContext* cx, unsigned argc, Value* vp)
RootedString str(cx, JS::ToString(cx, args[0])); RootedString str(cx, JS::ToString(cx, args[0]));
if (!str) if (!str)
return false; return false;
char* bytes = JS_EncodeStringToUTF8(cx, str); UniqueChars bytes = JS_EncodeStringToUTF8(cx, str);
if (!bytes) if (!bytes)
return false; return false;
fputs(bytes, gOutFile->fp); fputs(bytes.get(), gOutFile->fp);
JS_free(cx, bytes);
fflush(gOutFile->fp); fflush(gOutFile->fp);
} }
@ -2399,11 +2403,10 @@ PrintInternal(JSContext* cx, const CallArgs& args, RCFile* file)
RootedString str(cx, JS::ToString(cx, args[i])); RootedString str(cx, JS::ToString(cx, args[i]));
if (!str) if (!str)
return false; return false;
char* bytes = JS_EncodeStringToUTF8(cx, str); UniqueChars bytes = JS_EncodeStringToUTF8(cx, str);
if (!bytes) if (!bytes)
return false; return false;
fprintf(file->fp, "%s%s", i ? " " : "", bytes); fprintf(file->fp, "%s%s", i ? " " : "", bytes.get());
JS_free(cx, bytes);
} }
fputc('\n', file->fp); fputc('\n', file->fp);
@ -2507,13 +2510,14 @@ StopTimingMutator(JSContext* cx, unsigned argc, Value* vp)
} }
static const char* static const char*
ToSource(JSContext* cx, MutableHandleValue vp, JSAutoByteString* bytes) ToSource(JSContext* cx, MutableHandleValue vp, UniqueChars* bytes)
{ {
JSString* str = JS_ValueToSource(cx, vp); JSString* str = JS_ValueToSource(cx, vp);
if (str) { if (str) {
vp.setString(str); vp.setString(str);
if (bytes->encodeLatin1(cx, str)) *bytes = JS_EncodeString(cx, str);
return bytes->ptr(); if (*bytes)
return bytes->get();
} }
JS_ClearPendingException(cx); JS_ClearPendingException(cx);
return "<<error converting value to string>>"; return "<<error converting value to string>>";
@ -2538,19 +2542,19 @@ AssertEq(JSContext* cx, unsigned argc, Value* vp)
if (!JS_SameValue(cx, args[0], args[1], &same)) if (!JS_SameValue(cx, args[0], args[1], &same))
return false; return false;
if (!same) { if (!same) {
JSAutoByteString bytes0, bytes1; UniqueChars bytes0, bytes1;
const char* actual = ToSource(cx, args[0], &bytes0); const char* actual = ToSource(cx, args[0], &bytes0);
const char* expected = ToSource(cx, args[1], &bytes1); const char* expected = ToSource(cx, args[1], &bytes1);
if (args.length() == 2) { if (args.length() == 2) {
JS_ReportErrorNumberLatin1(cx, my_GetErrorMessage, nullptr, JSSMSG_ASSERT_EQ_FAILED, JS_ReportErrorNumberLatin1(cx, my_GetErrorMessage, nullptr, JSSMSG_ASSERT_EQ_FAILED,
actual, expected); actual, expected);
} else { } else {
JSAutoByteString bytes2(cx, args[2].toString()); UniqueChars bytes2 = JS_EncodeString(cx, args[2].toString());
if (!bytes2) if (!bytes2)
return false; return false;
JS_ReportErrorNumberLatin1(cx, my_GetErrorMessage, nullptr, JS_ReportErrorNumberLatin1(cx, my_GetErrorMessage, nullptr,
JSSMSG_ASSERT_EQ_FAILED_MSG, JSSMSG_ASSERT_EQ_FAILED_MSG,
actual, expected, bytes2.ptr()); actual, expected, bytes2.get());
} }
return false; return false;
} }
@ -3148,7 +3152,7 @@ DisassFile(JSContext* cx, unsigned argc, Value* vp)
JSString* str = JS::ToString(cx, HandleValue::fromMarkedLocation(&p.argv[0])); JSString* str = JS::ToString(cx, HandleValue::fromMarkedLocation(&p.argv[0]));
if (!str) if (!str)
return false; return false;
JSAutoByteString filename(cx, str); UniqueChars filename = JS_EncodeString(cx, str);
if (!filename) if (!filename)
return false; return false;
RootedScript script(cx); RootedScript script(cx);
@ -3157,11 +3161,11 @@ DisassFile(JSContext* cx, unsigned argc, Value* vp)
CompileOptions options(cx); CompileOptions options(cx);
options.setIntroductionType("js shell disFile") options.setIntroductionType("js shell disFile")
.setUTF8(true) .setUTF8(true)
.setFileAndLine(filename.ptr(), 1) .setFileAndLine(filename.get(), 1)
.setIsRunOnce(true) .setIsRunOnce(true)
.setNoScriptRval(true); .setNoScriptRval(true);
if (!JS::Compile(cx, options, filename.ptr(), &script)) if (!JS::Compile(cx, options, filename.get(), &script))
return false; return false;
} }
@ -3368,7 +3372,7 @@ Crash(JSContext* cx, unsigned argc, Value* vp)
RootedString message(cx, JS::ToString(cx, args[0])); RootedString message(cx, JS::ToString(cx, args[0]));
if (!message) if (!message)
return false; return false;
char* utf8chars = JS_EncodeStringToUTF8(cx, message); UniqueChars utf8chars = JS_EncodeStringToUTF8(cx, message);
if (!utf8chars) if (!utf8chars)
return false; return false;
if (args.get(1).isObject()) { if (args.get(1).isObject()) {
@ -3380,9 +3384,9 @@ Crash(JSContext* cx, unsigned argc, Value* vp)
js::NoteIntentionalCrash(); js::NoteIntentionalCrash();
} }
#ifndef DEBUG #ifndef DEBUG
MOZ_ReportCrash(utf8chars, __FILE__, __LINE__); MOZ_ReportCrash(utf8chars.get(), __FILE__, __LINE__);
#endif #endif
MOZ_CRASH_UNSAFE_OOL(utf8chars); MOZ_CRASH_UNSAFE_OOL(utf8chars.get());
} }
static bool static bool
@ -4373,7 +4377,7 @@ ParseModule(JSContext* cx, unsigned argc, Value* vp)
} }
RootedString str(cx, args[1].toString()); RootedString str(cx, args[1].toString());
filename.reset(JS_EncodeString(cx, str)); filename = JS_EncodeString(cx, str);
if (!filename) if (!filename)
return false; return false;
@ -4756,7 +4760,7 @@ BinParse(JSContext* cx, unsigned argc, Value* vp)
} else if (StringEqualsAscii(linearFormat, "simple")) { } else if (StringEqualsAscii(linearFormat, "simple")) {
useMultipart = false; useMultipart = false;
} else { } else {
JSAutoByteString printable; UniqueChars printable;
JS_ReportErrorUTF8(cx, JS_ReportErrorUTF8(cx,
"Unknown value for option `format`, expected 'multipart' or " "Unknown value for option `format`, expected 'multipart' or "
"'simple', got %s", "'simple', got %s",
@ -4983,7 +4987,7 @@ OffThreadCompileScript(JSContext* cx, unsigned argc, Value* vp)
return false; return false;
} }
JSAutoByteString fileNameBytes; UniqueChars fileNameBytes;
CompileOptions options(cx); CompileOptions options(cx);
options.setIntroductionType("js shell offThreadCompileScript") options.setIntroductionType("js shell offThreadCompileScript")
.setFileAndLine("<string>", 1); .setFileAndLine("<string>", 1);
@ -5088,7 +5092,7 @@ OffThreadCompileModule(JSContext* cx, unsigned argc, Value* vp)
return false; return false;
} }
JSAutoByteString fileNameBytes; UniqueChars fileNameBytes;
CompileOptions options(cx); CompileOptions options(cx);
options.setIntroductionType("js shell offThreadCompileModule") options.setIntroductionType("js shell offThreadCompileModule")
.setFileAndLine("<string>", 1); .setFileAndLine("<string>", 1);
@ -5192,7 +5196,7 @@ OffThreadDecodeScript(JSContext* cx, unsigned argc, Value* vp)
} }
RootedObject cacheEntry(cx, &args[0].toObject()); RootedObject cacheEntry(cx, &args[0].toObject());
JSAutoByteString fileNameBytes; UniqueChars fileNameBytes;
CompileOptions options(cx); CompileOptions options(cx);
options.setIntroductionType("js shell offThreadDecodeScript") options.setIntroductionType("js shell offThreadDecodeScript")
.setFileAndLine("<string>", 1); .setFileAndLine("<string>", 1);
@ -5421,7 +5425,7 @@ NestedShell(JSContext* cx, unsigned argc, Value* vp)
if (!str) if (!str)
return false; return false;
UniqueChars arg(JS_EncodeString(cx, str)); UniqueChars arg = JS_EncodeString(cx, str);
if (!arg || !argv.append(std::move(arg))) if (!arg || !argv.append(std::move(arg)))
return false; return false;
@ -6961,7 +6965,7 @@ class ShellAutoEntryMonitor : JS::dbg::AutoEntryMonitor {
RootedString displayId(cx, JS_GetFunctionDisplayId(function)); RootedString displayId(cx, JS_GetFunctionDisplayId(function));
if (displayId) { if (displayId) {
UniqueChars displayIdStr(JS_EncodeStringToUTF8(cx, displayId)); UniqueChars displayIdStr = JS_EncodeStringToUTF8(cx, displayId);
if (!displayIdStr) { if (!displayIdStr) {
// We report OOM in buildResult. // We report OOM in buildResult.
cx->recoverFromOutOfMemory(); cx->recoverFromOutOfMemory();
@ -7159,11 +7163,11 @@ SetARMHwCapFlags(JSContext* cx, unsigned argc, Value* vp)
return false; return false;
#if defined(JS_CODEGEN_ARM) #if defined(JS_CODEGEN_ARM)
JSAutoByteString flagsList(cx, flagsListString); UniqueChars flagsList = JS_EncodeString(cx, flagsListString);
if (!flagsList) if (!flagsList)
return false; return false;
jit::ParseARMHwCapFlags(flagsList.ptr()); jit::ParseARMHwCapFlags(flagsList.get());
#endif #endif
args.rval().setUndefined(); args.rval().setUndefined();
@ -8197,7 +8201,7 @@ PrintStackTrace(JSContext* cx, HandleValue exn)
if (!BuildStackString(cx, principals, stackObj, &stackStr, 2)) if (!BuildStackString(cx, principals, stackObj, &stackStr, 2))
return false; return false;
UniqueChars stack(JS_EncodeStringToUTF8(cx, stackStr)); UniqueChars stack = JS_EncodeStringToUTF8(cx, stackStr);
if (!stack) if (!stack)
return false; return false;
@ -9056,7 +9060,7 @@ ProcessArgs(JSContext* cx, OptionParser* op)
if (!absolutePath) if (!absolutePath)
return false; return false;
sc->moduleLoadPath = UniqueChars(JS_EncodeString(cx, absolutePath)); sc->moduleLoadPath = JS_EncodeString(cx, absolutePath);
} else { } else {
sc->moduleLoadPath = js::shell::GetCWD(); sc->moduleLoadPath = js::shell::GetCWD();
} }

Просмотреть файл

@ -32,7 +32,6 @@
#include "frontend/SourceNotes.h" #include "frontend/SourceNotes.h"
#include "gc/FreeOp.h" #include "gc/FreeOp.h"
#include "gc/GCInternals.h" #include "gc/GCInternals.h"
#include "js/AutoByteString.h"
#include "js/CharacterEncoding.h" #include "js/CharacterEncoding.h"
#include "js/Printf.h" #include "js/Printf.h"
#include "util/StringBuffer.h" #include "util/StringBuffer.h"
@ -1132,7 +1131,7 @@ js::DumpScript(JSContext* cx, JSScript* scriptArg, FILE* fp)
} }
static bool static bool
ToDisassemblySource(JSContext* cx, HandleValue v, JSAutoByteString* bytes) ToDisassemblySource(JSContext* cx, HandleValue v, UniqueChars* bytes)
{ {
if (v.isString()) { if (v.isString()) {
Sprinter sprinter(cx); Sprinter sprinter(cx);
@ -1146,7 +1145,7 @@ ToDisassemblySource(JSContext* cx, HandleValue v, JSAutoByteString* bytes)
ReportOutOfMemory(cx); ReportOutOfMemory(cx);
return false; return false;
} }
bytes->initBytes(std::move(copy)); *bytes = std::move(copy);
return true; return true;
} }
@ -1156,7 +1155,7 @@ ToDisassemblySource(JSContext* cx, HandleValue v, JSAutoByteString* bytes)
ReportOutOfMemory(cx); ReportOutOfMemory(cx);
return false; return false;
} }
bytes->initBytes(std::move(source)); *bytes = std::move(source);
return true; return true;
} }
@ -1168,14 +1167,16 @@ ToDisassemblySource(JSContext* cx, HandleValue v, JSAutoByteString* bytes)
JSString* str = JS_DecompileFunction(cx, fun); JSString* str = JS_DecompileFunction(cx, fun);
if (!str) if (!str)
return false; return false;
return bytes->encodeLatin1(cx, str); *bytes = JS_EncodeString(cx, str);
return !!*bytes;
} }
if (obj.is<RegExpObject>()) { if (obj.is<RegExpObject>()) {
JSString* source = obj.as<RegExpObject>().toString(cx); JSString* source = obj.as<RegExpObject>().toString(cx);
if (!source) if (!source)
return false; return false;
return bytes->encodeLatin1(cx, source); *bytes = JS_EncodeString(cx, source);
return !!*bytes;
} }
} }
@ -1183,7 +1184,7 @@ ToDisassemblySource(JSContext* cx, HandleValue v, JSAutoByteString* bytes)
} }
static bool static bool
ToDisassemblySource(JSContext* cx, HandleScope scope, JSAutoByteString* bytes) ToDisassemblySource(JSContext* cx, HandleScope scope, UniqueChars* bytes)
{ {
UniqueChars source = JS_smprintf("%s {", ScopeKindString(scope->kind())); UniqueChars source = JS_smprintf("%s {", ScopeKindString(scope->kind()));
if (!source) { if (!source) {
@ -1192,11 +1193,11 @@ ToDisassemblySource(JSContext* cx, HandleScope scope, JSAutoByteString* bytes)
} }
for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) { for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) {
JSAutoByteString nameBytes; UniqueChars nameBytes;
if (!AtomToPrintableString(cx, bi.name(), &nameBytes)) if (!AtomToPrintableString(cx, bi.name(), &nameBytes))
return false; return false;
source = JS_sprintf_append(std::move(source), "%s: ", nameBytes.ptr()); source = JS_sprintf_append(std::move(source), "%s: ", nameBytes.get());
if (!source) { if (!source) {
ReportOutOfMemory(cx); ReportOutOfMemory(cx);
return false; return false;
@ -1249,7 +1250,7 @@ ToDisassemblySource(JSContext* cx, HandleScope scope, JSAutoByteString* bytes)
return false; return false;
} }
bytes->initBytes(std::move(source)); *bytes = std::move(source);
return true; return true;
} }
@ -1421,10 +1422,10 @@ Disassemble1(JSContext* cx, HandleScript script, jsbytecode* pc,
case JOF_SCOPE: { case JOF_SCOPE: {
RootedScope scope(cx, script->getScope(GET_UINT32_INDEX(pc))); RootedScope scope(cx, script->getScope(GET_UINT32_INDEX(pc)));
JSAutoByteString bytes; UniqueChars bytes;
if (!ToDisassemblySource(cx, scope, &bytes)) if (!ToDisassemblySource(cx, scope, &bytes))
return 0; return 0;
if (!sp->jsprintf(" %s", bytes.ptr())) if (!sp->jsprintf(" %s", bytes.get()))
return 0; return 0;
break; break;
} }
@ -1432,31 +1433,31 @@ Disassemble1(JSContext* cx, HandleScript script, jsbytecode* pc,
case JOF_ENVCOORD: { case JOF_ENVCOORD: {
RootedValue v(cx, RootedValue v(cx,
StringValue(EnvironmentCoordinateName(cx->caches().envCoordinateNameCache, script, pc))); StringValue(EnvironmentCoordinateName(cx->caches().envCoordinateNameCache, script, pc)));
JSAutoByteString bytes; UniqueChars bytes;
if (!ToDisassemblySource(cx, v, &bytes)) if (!ToDisassemblySource(cx, v, &bytes))
return 0; return 0;
EnvironmentCoordinate ec(pc); EnvironmentCoordinate ec(pc);
if (!sp->jsprintf(" %s (hops = %u, slot = %u)", bytes.ptr(), ec.hops(), ec.slot())) if (!sp->jsprintf(" %s (hops = %u, slot = %u)", bytes.get(), ec.hops(), ec.slot()))
return 0; return 0;
break; break;
} }
case JOF_ATOM: { case JOF_ATOM: {
RootedValue v(cx, StringValue(script->getAtom(GET_UINT32_INDEX(pc)))); RootedValue v(cx, StringValue(script->getAtom(GET_UINT32_INDEX(pc))));
JSAutoByteString bytes; UniqueChars bytes;
if (!ToDisassemblySource(cx, v, &bytes)) if (!ToDisassemblySource(cx, v, &bytes))
return 0; return 0;
if (!sp->jsprintf(" %s", bytes.ptr())) if (!sp->jsprintf(" %s", bytes.get()))
return 0; return 0;
break; break;
} }
case JOF_DOUBLE: { case JOF_DOUBLE: {
RootedValue v(cx, script->getConst(GET_UINT32_INDEX(pc))); RootedValue v(cx, script->getConst(GET_UINT32_INDEX(pc)));
JSAutoByteString bytes; UniqueChars bytes;
if (!ToDisassemblySource(cx, v, &bytes)) if (!ToDisassemblySource(cx, v, &bytes))
return 0; return 0;
if (!sp->jsprintf(" %s", bytes.ptr())) if (!sp->jsprintf(" %s", bytes.get()))
return 0; return 0;
break; break;
} }
@ -1471,11 +1472,11 @@ Disassemble1(JSContext* cx, HandleScript script, jsbytecode* pc,
JSObject* obj = script->getObject(GET_UINT32_INDEX(pc)); JSObject* obj = script->getObject(GET_UINT32_INDEX(pc));
{ {
JSAutoByteString bytes; UniqueChars bytes;
RootedValue v(cx, ObjectValue(*obj)); RootedValue v(cx, ObjectValue(*obj));
if (!ToDisassemblySource(cx, v, &bytes)) if (!ToDisassemblySource(cx, v, &bytes))
return 0; return 0;
if (!sp->jsprintf(" %s", bytes.ptr())) if (!sp->jsprintf(" %s", bytes.get()))
return 0; return 0;
} }
break; break;
@ -1483,11 +1484,11 @@ Disassemble1(JSContext* cx, HandleScript script, jsbytecode* pc,
case JOF_REGEXP: { case JOF_REGEXP: {
js::RegExpObject* obj = script->getRegExp(pc); js::RegExpObject* obj = script->getRegExp(pc);
JSAutoByteString bytes; UniqueChars bytes;
RootedValue v(cx, ObjectValue(*obj)); RootedValue v(cx, ObjectValue(*obj));
if (!ToDisassemblySource(cx, v, &bytes)) if (!ToDisassemblySource(cx, v, &bytes))
return 0; return 0;
if (!sp->jsprintf(" %s", bytes.ptr())) if (!sp->jsprintf(" %s", bytes.get()))
return 0; return 0;
break; break;
} }
@ -2317,7 +2318,7 @@ js::DecompileValueGenerator(JSContext* cx, int spindex, HandleValue v,
return nullptr; return nullptr;
} }
return UniqueChars(JS_EncodeString(cx, fallback)); return JS_EncodeString(cx, fallback);
} }
static bool static bool
@ -2407,7 +2408,7 @@ js::DecompileArgument(JSContext* cx, int formalIndex, HandleValue v)
if (!fallback) if (!fallback)
return nullptr; return nullptr;
return UniqueChars(JS_EncodeString(cx, fallback)); return JS_EncodeString(cx, fallback);
} }
extern bool extern bool

Просмотреть файл

@ -25,7 +25,7 @@
#include "gc/PublicIterators.h" #include "gc/PublicIterators.h"
#include "jit/BaselineDebugModeOSR.h" #include "jit/BaselineDebugModeOSR.h"
#include "jit/BaselineJIT.h" #include "jit/BaselineJIT.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/Date.h" #include "js/Date.h"
#include "js/SourceBufferHolder.h" #include "js/SourceBufferHolder.h"
#include "js/StableStringChars.h" #include "js/StableStringChars.h"
@ -486,10 +486,10 @@ ParseEvalOptions(JSContext* cx, HandleValue value, EvalOptions& options)
RootedString url_str(cx, ToString<CanGC>(cx, v)); RootedString url_str(cx, ToString<CanGC>(cx, v));
if (!url_str) if (!url_str)
return false; return false;
JSAutoByteString url_bytes(cx, url_str); UniqueChars url_bytes = JS_EncodeString(cx, url_str);
if (!url_bytes) if (!url_bytes)
return false; return false;
if (!options.setFilename(cx, url_bytes.ptr())) if (!options.setFilename(cx, url_bytes.get()))
return false; return false;
} }
@ -4481,7 +4481,7 @@ class MOZ_STACK_CLASS Debugger::ScriptQuery
RootedValue url; RootedValue url;
/* url as a C string. */ /* url as a C string. */
JSAutoByteString urlCString; UniqueChars urlCString;
/* If this is a string, matching scripts' sources have displayURLs equal to /* If this is a string, matching scripts' sources have displayURLs equal to
* it. */ * it. */
@ -4567,7 +4567,8 @@ class MOZ_STACK_CLASS Debugger::ScriptQuery
// Compute urlCString and displayURLChars, if a url or displayURL was // Compute urlCString and displayURLChars, if a url or displayURL was
// given respectively. // given respectively.
if (url.isString()) { if (url.isString()) {
if (!urlCString.encodeLatin1(cx, url.toString())) urlCString = JS_EncodeString(cx, url.toString());
if (!urlCString)
return false; return false;
} }
@ -4608,14 +4609,14 @@ class MOZ_STACK_CLASS Debugger::ScriptQuery
template <typename T> template <typename T>
MOZ_MUST_USE bool commonFilter(T script, const JS::AutoRequireNoGC& nogc) { MOZ_MUST_USE bool commonFilter(T script, const JS::AutoRequireNoGC& nogc) {
if (urlCString.ptr()) { if (urlCString) {
bool gotFilename = false; bool gotFilename = false;
if (script->filename() && strcmp(script->filename(), urlCString.ptr()) == 0) if (script->filename() && strcmp(script->filename(), urlCString.get()) == 0)
gotFilename = true; gotFilename = true;
bool gotSourceURL = false; bool gotSourceURL = false;
if (!gotFilename && script->scriptSource()->introducerFilename() && if (!gotFilename && script->scriptSource()->introducerFilename() &&
strcmp(script->scriptSource()->introducerFilename(), urlCString.ptr()) == 0) strcmp(script->scriptSource()->introducerFilename(), urlCString.get()) == 0)
{ {
gotSourceURL = true; gotSourceURL = true;
} }
@ -4920,7 +4921,7 @@ class MOZ_STACK_CLASS Debugger::ObjectQuery
if (!className.isUndefined()) { if (!className.isUndefined()) {
const char* objClassName = obj->getClass()->name; const char* objClassName = obj->getClass()->name;
if (strcmp(objClassName, classNameCString.ptr()) != 0) if (strcmp(objClassName, classNameCString.get()) != 0)
return true; return true;
} }
@ -4941,7 +4942,7 @@ class MOZ_STACK_CLASS Debugger::ObjectQuery
RootedValue className; RootedValue className;
/* The className member, as a C string. */ /* The className member, as a C string. */
JSAutoByteString classNameCString; UniqueChars classNameCString;
/* /*
* Given that either omittedQuery or parseQuery has been called, prepare the * Given that either omittedQuery or parseQuery has been called, prepare the
@ -4949,7 +4950,8 @@ class MOZ_STACK_CLASS Debugger::ObjectQuery
*/ */
bool prepareQuery() { bool prepareQuery() {
if (className.isString()) { if (className.isString()) {
if (!classNameCString.encodeLatin1(cx, className.toString())) classNameCString = JS_EncodeString(cx, className.toString());
if (!classNameCString)
return false; return false;
} }

Просмотреть файл

@ -8,7 +8,6 @@
#include "builtin/ModuleObject.h" #include "builtin/ModuleObject.h"
#include "gc/Policy.h" #include "gc/Policy.h"
#include "js/AutoByteString.h"
#include "vm/ArgumentsObject.h" #include "vm/ArgumentsObject.h"
#include "vm/AsyncFunction.h" #include "vm/AsyncFunction.h"
#include "vm/GlobalObject.h" #include "vm/GlobalObject.h"
@ -1415,10 +1414,10 @@ namespace {
static void static void
ReportOptimizedOut(JSContext* cx, HandleId id) ReportOptimizedOut(JSContext* cx, HandleId id)
{ {
JSAutoByteString printable; UniqueChars printable;
if (ValueToPrintableLatin1(cx, IdToValue(id), &printable)) { if (ValueToPrintableLatin1(cx, IdToValue(id), &printable)) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_DEBUG_OPTIMIZED_OUT, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_DEBUG_OPTIMIZED_OUT,
printable.ptr()); printable.get());
} }
} }
@ -3359,11 +3358,11 @@ js::CheckVarNameConflict(JSContext* cx, Handle<LexicalEnvironmentObject*> lexica
static void static void
ReportCannotDeclareGlobalBinding(JSContext* cx, HandlePropertyName name, const char* reason) ReportCannotDeclareGlobalBinding(JSContext* cx, HandlePropertyName name, const char* reason)
{ {
JSAutoByteString printable; UniqueChars printable;
if (AtomToPrintableString(cx, name, &printable)) { if (AtomToPrintableString(cx, name, &printable)) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
JSMSG_CANT_DECLARE_GLOBAL_BINDING, JSMSG_CANT_DECLARE_GLOBAL_BINDING,
printable.ptr(), reason); printable.get(), reason);
} }
} }

Просмотреть файл

@ -13,7 +13,6 @@
#include "jsexn.h" #include "jsexn.h"
#include "js/AutoByteString.h"
#include "js/CallArgs.h" #include "js/CallArgs.h"
#include "js/CharacterEncoding.h" #include "js/CharacterEncoding.h"
#include "vm/GlobalObject.h" #include "vm/GlobalObject.h"
@ -146,10 +145,10 @@ js::ErrorObject::getOrCreateErrorReport(JSContext* cx)
report.exnType = type_; report.exnType = type_;
// Filename. // Filename.
JSAutoByteString filenameStr; UniqueChars filenameStr = JS_EncodeString(cx, fileName(cx));
if (!filenameStr.encodeLatin1(cx, fileName(cx))) if (!filenameStr)
return nullptr; return nullptr;
report.filename = filenameStr.ptr(); report.filename = filenameStr.get();
// Coordinates. // Coordinates.
report.lineno = lineNumber(); report.lineno = lineNumber();

Просмотреть файл

@ -31,7 +31,7 @@
#include "jit/Ion.h" #include "jit/Ion.h"
#include "jit/IonAnalysis.h" #include "jit/IonAnalysis.h"
#include "jit/Jit.h" #include "jit/Jit.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "util/StringBuffer.h" #include "util/StringBuffer.h"
#include "vm/AsyncFunction.h" #include "vm/AsyncFunction.h"
#include "vm/AsyncIteration.h" #include "vm/AsyncIteration.h"
@ -1861,7 +1861,7 @@ js::ReportInNotObjectError(JSContext* cx, HandleValue lref, int lindex,
if (!str) if (!str)
return nullptr; return nullptr;
} }
return UniqueChars(JS_EncodeString(cx, str)); return JS_EncodeString(cx, str);
}; };
if (lref.isString() && rref.isString()) { if (lref.isString() && rref.isString()) {
@ -5339,9 +5339,9 @@ js::ReportRuntimeLexicalError(JSContext* cx, unsigned errorNumber, HandleId id)
{ {
MOZ_ASSERT(errorNumber == JSMSG_UNINITIALIZED_LEXICAL || MOZ_ASSERT(errorNumber == JSMSG_UNINITIALIZED_LEXICAL ||
errorNumber == JSMSG_BAD_CONST_ASSIGN); errorNumber == JSMSG_BAD_CONST_ASSIGN);
JSAutoByteString printable; UniqueChars printable;
if (ValueToPrintableLatin1(cx, IdToValue(id), &printable)) if (ValueToPrintableLatin1(cx, IdToValue(id), &printable))
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, errorNumber, printable.ptr()); JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, errorNumber, printable.get());
} }
void void
@ -5382,10 +5382,10 @@ js::ReportRuntimeLexicalError(JSContext* cx, unsigned errorNumber,
void void
js::ReportRuntimeRedeclaration(JSContext* cx, HandlePropertyName name, const char* redeclKind) js::ReportRuntimeRedeclaration(JSContext* cx, HandlePropertyName name, const char* redeclKind)
{ {
JSAutoByteString printable; UniqueChars printable;
if (AtomToPrintableString(cx, name, &printable)) { if (AtomToPrintableString(cx, name, &printable)) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_REDECLARED_VAR, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_REDECLARED_VAR,
redeclKind, printable.ptr()); redeclKind, printable.get());
} }
} }
@ -5461,11 +5461,11 @@ js::ThrowUninitializedThis(JSContext* cx, AbstractFramePtr frame)
if (fun->isDerivedClassConstructor()) { if (fun->isDerivedClassConstructor()) {
const char* name = "anonymous"; const char* name = "anonymous";
JSAutoByteString str; UniqueChars str;
if (fun->explicitName()) { if (fun->explicitName()) {
if (!AtomToPrintableString(cx, fun->explicitName(), &str)) if (!AtomToPrintableString(cx, fun->explicitName(), &str))
return false; return false;
name = str.ptr(); name = str.get();
} }
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_UNINITIALIZED_THIS, name); JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_UNINITIALIZED_THIS, name);

Просмотреть файл

@ -21,7 +21,7 @@
#include "builtin/String.h" #include "builtin/String.h"
#include "gc/Marking.h" #include "gc/Marking.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "util/Text.h" #include "util/Text.h"
#include "vm/JSContext.h" #include "vm/JSContext.h"
#include "vm/SymbolType.h" #include "vm/SymbolType.h"
@ -117,13 +117,13 @@ js::AtomStateEntry::asPtr(JSContext* cx) const
} }
const char* const char*
js::AtomToPrintableString(JSContext* cx, JSAtom* atom, JSAutoByteString* bytes) js::AtomToPrintableString(JSContext* cx, JSAtom* atom, UniqueChars* bytes)
{ {
JSString* str = QuoteString(cx, atom, 0); JSString* str = QuoteString(cx, atom, 0);
if (!str) if (!str)
return nullptr; return nullptr;
bytes->initBytes(EncodeLatin1(cx, str)); *bytes = EncodeLatin1(cx, str);
return bytes->ptr(); return bytes->get();
} }
#define DEFINE_PROTO_STRING(name,init,clasp) const char js_##name##_str[] = #name; #define DEFINE_PROTO_STRING(name,init,clasp) const char js_##name##_str[] = #name;

Просмотреть файл

@ -11,10 +11,9 @@
#include "gc/Rooting.h" #include "gc/Rooting.h"
#include "js/TypeDecls.h" #include "js/TypeDecls.h"
#include "js/Utility.h"
#include "vm/CommonPropertyNames.h" #include "vm/CommonPropertyNames.h"
class JSAutoByteString;
namespace js { namespace js {
/* /*
@ -22,7 +21,7 @@ namespace js {
* The lifetime of the result matches the lifetime of bytes. * The lifetime of the result matches the lifetime of bytes.
*/ */
extern const char* extern const char*
AtomToPrintableString(JSContext* cx, JSAtom* atom, JSAutoByteString* bytes); AtomToPrintableString(JSContext* cx, JSAtom* atom, UniqueChars* bytes);
class PropertyName; class PropertyName;

Просмотреть файл

@ -37,7 +37,6 @@
#include "gc/Marking.h" #include "gc/Marking.h"
#include "jit/Ion.h" #include "jit/Ion.h"
#include "jit/PcScriptCache.h" #include "jit/PcScriptCache.h"
#include "js/AutoByteString.h"
#include "js/CharacterEncoding.h" #include "js/CharacterEncoding.h"
#include "js/Printf.h" #include "js/Printf.h"
#ifdef JS_SIMULATOR_ARM64 #ifdef JS_SIMULATOR_ARM64
@ -442,10 +441,10 @@ js::ReportUsageErrorASCII(JSContext* cx, HandleObject callee, const char* msg)
JS_ReportErrorASCII(cx, "%s", msg); JS_ReportErrorASCII(cx, "%s", msg);
} else { } else {
RootedString usageStr(cx, usage.toString()); RootedString usageStr(cx, usage.toString());
JSAutoByteString str; UniqueChars str = JS_EncodeStringToUTF8(cx, usageStr);
if (!str.encodeUtf8(cx, usageStr)) if (!str)
return; return;
JS_ReportErrorUTF8(cx, "%s. Usage: %s", msg, str.ptr()); JS_ReportErrorUTF8(cx, "%s. Usage: %s", msg, str.get());
} }
} }
@ -893,10 +892,10 @@ js::ReportErrorNumberUCArray(JSContext* cx, unsigned flags, JSErrorCallback call
void void
js::ReportIsNotDefined(JSContext* cx, HandleId id) js::ReportIsNotDefined(JSContext* cx, HandleId id)
{ {
JSAutoByteString printable; UniqueChars printable;
if (!ValueToPrintableUTF8(cx, IdToValue(id), &printable)) if (!ValueToPrintableUTF8(cx, IdToValue(id), &printable))
return; return;
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_NOT_DEFINED, printable.ptr()); JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_NOT_DEFINED, printable.get());
} }
void void
@ -934,15 +933,15 @@ js::ReportIsNullOrUndefinedForPropertyAccess(JSContext* cx, HandleValue v, bool
} }
} }
char* static UniqueChars
EncodeIdAsLatin1(JSContext* cx, HandleId id, JSAutoByteString& bytes) EncodeIdAsLatin1(JSContext* cx, HandleId id)
{ {
RootedValue idVal(cx, IdToValue(id)); RootedValue idVal(cx, IdToValue(id));
RootedString idStr(cx, ValueToSource(cx, idVal)); JSString* idStr = ValueToSource(cx, idVal);
if (!idStr) if (!idStr)
return nullptr; return nullptr;
return bytes.encodeLatin1(cx, idStr); return EncodeLatin1(cx, idStr);
} }
void void
@ -951,13 +950,13 @@ js::ReportIsNullOrUndefinedForPropertyAccess(JSContext* cx, HandleValue v, Handl
{ {
MOZ_ASSERT(v.isNullOrUndefined()); MOZ_ASSERT(v.isNullOrUndefined());
JSAutoByteString keyBytes; UniqueChars keyBytes = EncodeIdAsLatin1(cx, key);
if (!EncodeIdAsLatin1(cx, key, keyBytes)) if (!keyBytes)
return; return;
if (!reportScanStack) { if (!reportScanStack) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_PROPERTY_FAIL, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_PROPERTY_FAIL,
keyBytes.ptr(), keyBytes.get(),
v.isUndefined() ? js_undefined_str : js_null_str); v.isUndefined() ? js_undefined_str : js_null_str);
return; return;
} }
@ -968,14 +967,14 @@ js::ReportIsNullOrUndefinedForPropertyAccess(JSContext* cx, HandleValue v, Handl
if (strcmp(bytes.get(), js_undefined_str) == 0 || strcmp(bytes.get(), js_null_str) == 0) { if (strcmp(bytes.get(), js_undefined_str) == 0 || strcmp(bytes.get(), js_null_str) == 0) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_PROPERTY_FAIL, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_PROPERTY_FAIL,
keyBytes.ptr(), bytes.get()); keyBytes.get(), bytes.get());
} else if (v.isUndefined()) { } else if (v.isUndefined()) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_PROPERTY_FAIL_EXPR, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_PROPERTY_FAIL_EXPR,
bytes.get(), js_undefined_str, keyBytes.ptr()); bytes.get(), js_undefined_str, keyBytes.get());
} else { } else {
MOZ_ASSERT(v.isNull()); MOZ_ASSERT(v.isNull());
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_PROPERTY_FAIL_EXPR, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_PROPERTY_FAIL_EXPR,
bytes.get(), js_null_str, keyBytes.ptr()); bytes.get(), js_null_str, keyBytes.get());
} }
} }

Просмотреть файл

@ -11,19 +11,20 @@
#include "gc/Allocator.h" #include "gc/Allocator.h"
#include "gc/GCTrace.h" #include "gc/GCTrace.h"
#include "js/CharacterEncoding.h"
#include "vm/EnvironmentObject.h" #include "vm/EnvironmentObject.h"
#include "vm/JSObject-inl.h" #include "vm/JSObject-inl.h"
class JSAutoByteString;
namespace js { namespace js {
inline const char* inline const char*
GetFunctionNameBytes(JSContext* cx, JSFunction* fun, JSAutoByteString* bytes) GetFunctionNameBytes(JSContext* cx, JSFunction* fun, UniqueChars* bytes)
{ {
if (JSAtom* name = fun->explicitName()) if (JSAtom* name = fun->explicitName()) {
return bytes->encodeLatin1(cx, name); *bytes = JS_EncodeString(cx, name);
return bytes->get();
}
return js_anonymous_str; return js_anonymous_str;
} }

Просмотреть файл

@ -31,7 +31,6 @@
#include "gc/Policy.h" #include "gc/Policy.h"
#include "jit/InlinableNatives.h" #include "jit/InlinableNatives.h"
#include "jit/Ion.h" #include "jit/Ion.h"
#include "js/AutoByteString.h"
#include "js/CallNonGenericMethod.h" #include "js/CallNonGenericMethod.h"
#include "js/CompileOptions.h" #include "js/CompileOptions.h"
#include "js/Proxy.h" #include "js/Proxy.h"
@ -2499,7 +2498,7 @@ js::ReportIncompatibleMethod(JSContext* cx, const CallArgs& args, const Class* c
#endif #endif
if (JSFunction* fun = ReportIfNotFunction(cx, args.calleev())) { if (JSFunction* fun = ReportIfNotFunction(cx, args.calleev())) {
JSAutoByteString funNameBytes; UniqueChars funNameBytes;
if (const char* funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) { if (const char* funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO,
clasp->name, funName, InformalValueTypeName(thisv)); clasp->name, funName, InformalValueTypeName(thisv));
@ -2511,7 +2510,7 @@ void
js::ReportIncompatible(JSContext* cx, const CallArgs& args) js::ReportIncompatible(JSContext* cx, const CallArgs& args)
{ {
if (JSFunction* fun = ReportIfNotFunction(cx, args.calleev())) { if (JSFunction* fun = ReportIfNotFunction(cx, args.calleev())) {
JSAutoByteString funNameBytes; UniqueChars funNameBytes;
if (const char* funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) { if (const char* funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_METHOD, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_METHOD,
funName, "method", InformalValueTypeName(args.thisv())); funName, "method", InformalValueTypeName(args.thisv()));

Просмотреть файл

@ -35,7 +35,7 @@
#include "frontend/BytecodeCompiler.h" #include "frontend/BytecodeCompiler.h"
#include "gc/Policy.h" #include "gc/Policy.h"
#include "jit/BaselineJIT.h" #include "jit/BaselineJIT.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/MemoryMetrics.h" #include "js/MemoryMetrics.h"
#include "js/Proxy.h" #include "js/Proxy.h"
#include "js/UbiNode.h" #include "js/UbiNode.h"
@ -95,7 +95,7 @@ js::ReportNotObjectArg(JSContext* cx, const char* nth, const char* fun, HandleVa
{ {
MOZ_ASSERT(!v.isObject()); MOZ_ASSERT(!v.isObject());
JSAutoByteString bytes; UniqueChars bytes;
if (const char* chars = ValueToSourceForError(cx, v, bytes)) { if (const char* chars = ValueToSourceForError(cx, v, bytes)) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT_ARG, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT_ARG,
nth, fun, chars); nth, fun, chars);
@ -107,7 +107,7 @@ js::ReportNotObjectWithName(JSContext* cx, const char* name, HandleValue v)
{ {
MOZ_ASSERT(!v.isObject()); MOZ_ASSERT(!v.isObject());
JSAutoByteString bytes; UniqueChars bytes;
if (const char* chars = ValueToSourceForError(cx, v, bytes)) { if (const char* chars = ValueToSourceForError(cx, v, bytes)) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT_NAME, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT_NAME,
name, chars); name, chars);
@ -261,15 +261,15 @@ js::Throw(JSContext* cx, jsid id, unsigned errorNumber, const char* details)
JSString* idstr = ValueToSource(cx, idVal); JSString* idstr = ValueToSource(cx, idVal);
if (!idstr) if (!idstr)
return false; return false;
JSAutoByteString bytes(cx, idstr); UniqueChars bytes = JS_EncodeString(cx, idstr);
if (!bytes) if (!bytes)
return false; return false;
if (details) { if (details) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, errorNumber, bytes.ptr(), JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, errorNumber, bytes.get(),
details); details);
} else { } else {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, errorNumber, bytes.ptr()); JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, errorNumber, bytes.get());
} }
return false; return false;

Просмотреть файл

@ -12,7 +12,7 @@
#include "mozilla/DebugOnly.h" #include "mozilla/DebugOnly.h"
#include "gc/Marking.h" #include "gc/Marking.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/Value.h" #include "js/Value.h"
#include "vm/Debugger.h" #include "vm/Debugger.h"
#include "vm/TypedArrayObject.h" #include "vm/TypedArrayObject.h"
@ -2475,11 +2475,11 @@ MaybeReportUndeclaredVarAssignment(JSContext* cx, HandleString propname)
return true; return true;
} }
JSAutoByteString bytes; UniqueChars bytes = JS_EncodeStringToUTF8(cx, propname);
if (!bytes.encodeUtf8(cx, propname)) if (!bytes)
return false; return false;
return JS_ReportErrorFlagsAndNumberUTF8(cx, flags, GetErrorMessage, nullptr, return JS_ReportErrorFlagsAndNumberUTF8(cx, flags, GetErrorMessage, nullptr,
JSMSG_UNDECLARED_VAR, bytes.ptr()); JSMSG_UNDECLARED_VAR, bytes.get());
} }
/* /*

Просмотреть файл

@ -6,7 +6,7 @@
#include "vm/Probes-inl.h" #include "vm/Probes-inl.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "vm/JSContext.h" #include "vm/JSContext.h"
#ifdef INCLUDE_MOZILLA_DTRACE #ifdef INCLUDE_MOZILLA_DTRACE
@ -34,13 +34,14 @@ ScriptFilename(const JSScript* script)
} }
static const char* static const char*
FunctionName(JSContext* cx, JSFunction* fun, JSAutoByteString* bytes) FunctionName(JSContext* cx, JSFunction* fun, UniqueChars* bytes)
{ {
if (!fun) if (!fun)
return probes::nullName; return probes::nullName;
if (!fun->displayAtom()) if (!fun->displayAtom())
return probes::anonymousName; return probes::anonymousName;
return bytes->encodeLatin1(cx, fun->displayAtom()) ? bytes->ptr() : probes::nullName; *bytes = JS_EncodeString(cx, fun->displayAtom());
return *bytes ? bytes->get() : probes::nullName;
} }
/* /*
@ -53,7 +54,7 @@ FunctionName(JSContext* cx, JSFunction* fun, JSAutoByteString* bytes)
void void
probes::DTraceEnterJSFun(JSContext* cx, JSFunction* fun, JSScript* script) probes::DTraceEnterJSFun(JSContext* cx, JSFunction* fun, JSScript* script)
{ {
JSAutoByteString funNameBytes; UniqueChars funNameBytes;
JAVASCRIPT_FUNCTION_ENTRY(ScriptFilename(script), probes::nullName, JAVASCRIPT_FUNCTION_ENTRY(ScriptFilename(script), probes::nullName,
FunctionName(cx, fun, &funNameBytes)); FunctionName(cx, fun, &funNameBytes));
} }
@ -61,7 +62,7 @@ probes::DTraceEnterJSFun(JSContext* cx, JSFunction* fun, JSScript* script)
void void
probes::DTraceExitJSFun(JSContext* cx, JSFunction* fun, JSScript* script) probes::DTraceExitJSFun(JSContext* cx, JSFunction* fun, JSScript* script)
{ {
JSAutoByteString funNameBytes; UniqueChars funNameBytes;
JAVASCRIPT_FUNCTION_RETURN(ScriptFilename(script), probes::nullName, JAVASCRIPT_FUNCTION_RETURN(ScriptFilename(script), probes::nullName,
FunctionName(cx, fun, &funNameBytes)); FunctionName(cx, fun, &funNameBytes));
} }

Просмотреть файл

@ -1820,15 +1820,14 @@ const SavedStacks::MetadataBuilder SavedStacks::metadataBuilder;
/* static */ ReconstructedSavedFramePrincipals ReconstructedSavedFramePrincipals::IsSystem; /* static */ ReconstructedSavedFramePrincipals ReconstructedSavedFramePrincipals::IsSystem;
/* static */ ReconstructedSavedFramePrincipals ReconstructedSavedFramePrincipals::IsNotSystem; /* static */ ReconstructedSavedFramePrincipals ReconstructedSavedFramePrincipals::IsNotSystem;
UTF8CharsZ UniqueChars
BuildUTF8StackString(JSContext* cx, JSPrincipals* principals, HandleObject stack) BuildUTF8StackString(JSContext* cx, JSPrincipals* principals, HandleObject stack)
{ {
RootedString stackStr(cx); RootedString stackStr(cx);
if (!JS::BuildStackString(cx, principals, stack, &stackStr)) if (!JS::BuildStackString(cx, principals, stack, &stackStr))
return UTF8CharsZ(); return nullptr;
char* chars = JS_EncodeStringToUTF8(cx, stackStr); return JS_EncodeStringToUTF8(cx, stackStr);
return UTF8CharsZ(chars, strlen(chars));
} }
uint32_t uint32_t

Просмотреть файл

@ -320,7 +320,7 @@ struct MutableWrappedPtrOperations<SavedStacks::LocationValue, Wrapper>
} }
}; };
UTF8CharsZ JS::UniqueChars
BuildUTF8StackString(JSContext* cx, JSPrincipals* principals, HandleObject stack); BuildUTF8StackString(JSContext* cx, JSPrincipals* principals, HandleObject stack);
uint32_t uint32_t

Просмотреть файл

@ -14,7 +14,6 @@
#include "builtin/ModuleObject.h" #include "builtin/ModuleObject.h"
#include "gc/Allocator.h" #include "gc/Allocator.h"
#include "gc/FreeOp.h" #include "gc/FreeOp.h"
#include "js/AutoByteString.h"
#include "util/StringBuffer.h" #include "util/StringBuffer.h"
#include "vm/EnvironmentObject.h" #include "vm/EnvironmentObject.h"
#include "vm/JSScript.h" #include "vm/JSScript.h"
@ -1520,10 +1519,10 @@ js::DumpBindings(JSContext* cx, Scope* scopeArg)
{ {
RootedScope scope(cx, scopeArg); RootedScope scope(cx, scopeArg);
for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) { for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) {
JSAutoByteString bytes; UniqueChars bytes;
if (!AtomToPrintableString(cx, bi.name(), &bytes)) if (!AtomToPrintableString(cx, bi.name(), &bytes))
return; return;
fprintf(stderr, "%s %s ", BindingKindString(bi.kind()), bytes.ptr()); fprintf(stderr, "%s %s ", BindingKindString(bi.kind()), bytes.get());
switch (bi.location().kind()) { switch (bi.location().kind()) {
case BindingLocation::Kind::Global: case BindingLocation::Kind::Global:
if (bi.isTopLevelFunction()) if (bi.isTopLevelFunction())

Просмотреть файл

@ -38,7 +38,6 @@
#include "gc/Policy.h" #include "gc/Policy.h"
#include "jit/AtomicOperations.h" #include "jit/AtomicOperations.h"
#include "jit/InlinableNatives.h" #include "jit/InlinableNatives.h"
#include "js/AutoByteString.h"
#include "js/CharacterEncoding.h" #include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h" #include "js/CompilationAndEvaluation.h"
#include "js/Date.h" #include "js/Date.h"
@ -293,28 +292,28 @@ ThrowErrorWithType(JSContext* cx, JSExnType type, const CallArgs& args)
MOZ_ASSERT(efs->exnType == type, "error-throwing intrinsic and error number are inconsistent"); MOZ_ASSERT(efs->exnType == type, "error-throwing intrinsic and error number are inconsistent");
#endif #endif
JSAutoByteString errorArgs[3]; UniqueChars errorArgs[3];
for (unsigned i = 1; i < 4 && i < args.length(); i++) { for (unsigned i = 1; i < 4 && i < args.length(); i++) {
RootedValue val(cx, args[i]); RootedValue val(cx, args[i]);
if (val.isInt32()) { if (val.isInt32()) {
JSString* str = ToString<CanGC>(cx, val); JSString* str = ToString<CanGC>(cx, val);
if (!str) if (!str)
return; return;
errorArgs[i - 1].encodeLatin1(cx, str); errorArgs[i - 1] = JS_EncodeString(cx, str);
} else if (val.isString()) { } else if (val.isString()) {
errorArgs[i - 1].encodeLatin1(cx, val.toString()); errorArgs[i - 1] = JS_EncodeString(cx, val.toString());
} else { } else {
UniqueChars bytes = DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, val, nullptr); UniqueChars bytes = DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, val, nullptr);
if (!bytes) if (!bytes)
return; return;
errorArgs[i - 1].initBytes(std::move(bytes)); errorArgs[i - 1] = std::move(bytes);
} }
if (!errorArgs[i - 1]) if (!errorArgs[i - 1])
return; return;
} }
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, errorNumber, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, errorNumber,
errorArgs[0].ptr(), errorArgs[1].ptr(), errorArgs[2].ptr()); errorArgs[0].get(), errorArgs[1].get(), errorArgs[2].get());
} }
static bool static bool
@ -1869,7 +1868,7 @@ js::ReportIncompatibleSelfHostedMethod(JSContext* cx, const CallArgs& args)
while (!iter.done()) { while (!iter.done()) {
MOZ_ASSERT(iter.callee(cx)->isSelfHostedOrIntrinsic() && MOZ_ASSERT(iter.callee(cx)->isSelfHostedOrIntrinsic() &&
!iter.callee(cx)->isBoundFunction()); !iter.callee(cx)->isBoundFunction());
JSAutoByteString funNameBytes; UniqueChars funNameBytes;
const char* funName = GetFunctionNameBytes(cx, iter.callee(cx), &funNameBytes); const char* funName = GetFunctionNameBytes(cx, iter.callee(cx), &funNameBytes);
if (!funName) if (!funName)
return false; return false;

Просмотреть файл

@ -20,7 +20,7 @@
#include "gc/GCInternals.h" #include "gc/GCInternals.h"
#include "gc/Marking.h" #include "gc/Marking.h"
#include "gc/Nursery.h" #include "gc/Nursery.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/StableStringChars.h" #include "js/StableStringChars.h"
#include "js/UbiNode.h" #include "js/UbiNode.h"
#include "util/StringBuffer.h" #include "util/StringBuffer.h"
@ -2063,7 +2063,7 @@ js::EncodeLatin1(JSContext* cx, JSString* str)
} }
const char* const char*
js::ValueToPrintableLatin1(JSContext* cx, const Value& vArg, JSAutoByteString* bytes, js::ValueToPrintableLatin1(JSContext* cx, const Value& vArg, UniqueChars* bytes,
bool asSource) bool asSource)
{ {
RootedValue v(cx, vArg); RootedValue v(cx, vArg);
@ -2077,11 +2077,12 @@ js::ValueToPrintableLatin1(JSContext* cx, const Value& vArg, JSAutoByteString* b
str = QuoteString(cx, str, 0); str = QuoteString(cx, str, 0);
if (!str) if (!str)
return nullptr; return nullptr;
return bytes->encodeLatin1(cx, str); *bytes = JS_EncodeString(cx, str);
return bytes->get();
} }
const char* const char*
js::ValueToPrintableUTF8(JSContext* cx, const Value& vArg, JSAutoByteString* bytes, bool asSource) js::ValueToPrintableUTF8(JSContext* cx, const Value& vArg, UniqueChars* bytes, bool asSource)
{ {
RootedValue v(cx, vArg); RootedValue v(cx, vArg);
JSString* str; JSString* str;
@ -2091,7 +2092,8 @@ js::ValueToPrintableUTF8(JSContext* cx, const Value& vArg, JSAutoByteString* byt
str = ToString<CanGC>(cx, v); str = ToString<CanGC>(cx, v);
if (!str) if (!str)
return nullptr; return nullptr;
return bytes->encodeUtf8(cx, RootedString(cx, str)); *bytes = JS_EncodeStringToUTF8(cx, RootedString(cx, str));
return bytes->get();
} }
template <AllowGC allowGC> template <AllowGC allowGC>

Просмотреть файл

@ -26,7 +26,6 @@
#include "util/Text.h" #include "util/Text.h"
#include "vm/Printer.h" #include "vm/Printer.h"
class JSAutoByteString;
class JSDependentString; class JSDependentString;
class JSExtensibleString; class JSExtensibleString;
class JSExternalString; class JSExternalString;
@ -1687,14 +1686,14 @@ EncodeLatin1(JSContext* cx, JSString* str);
* string. * string.
*/ */
extern const char* extern const char*
ValueToPrintableLatin1(JSContext* cx, const Value&, JSAutoByteString* bytes, ValueToPrintableLatin1(JSContext* cx, const Value&, UniqueChars* bytes,
bool asSource = false); bool asSource = false);
/* /*
* Convert a value to a printable C string encoded in UTF-8. * Convert a value to a printable C string encoded in UTF-8.
*/ */
extern const char* extern const char*
ValueToPrintableUTF8(JSContext* cx, const Value&, JSAutoByteString* bytes, bool asSource = false); ValueToPrintableUTF8(JSContext* cx, const Value&, UniqueChars* bytes, bool asSource = false);
/* /*
* Convert a non-string value to a string, returning null after reporting an * Convert a non-string value to a string, returning null after reporting an

Просмотреть файл

@ -6,7 +6,7 @@
#include "js/UbiNodeCensus.h" #include "js/UbiNodeCensus.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/StableStringChars.h" #include "js/StableStringChars.h"
#include "util/Text.h" #include "util/Text.h"
#include "vm/JSContext.h" #include "vm/JSContext.h"
@ -1265,12 +1265,12 @@ ParseBreakdown(JSContext* cx, HandleValue breakdownValue)
if (!bySource) if (!bySource)
return nullptr; return nullptr;
JSAutoByteString byBytes(cx, bySource); UniqueChars byBytes = JS_EncodeString(cx, bySource);
if (!byBytes) if (!byBytes)
return nullptr; return nullptr;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_DEBUG_CENSUS_BREAKDOWN, JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_DEBUG_CENSUS_BREAKDOWN,
byBytes.ptr()); byBytes.get());
return nullptr; return nullptr;
} }

Просмотреть файл

@ -32,7 +32,6 @@
#include "builtin/String.h" #include "builtin/String.h"
#include "frontend/Parser.h" #include "frontend/Parser.h"
#include "gc/Policy.h" #include "gc/Policy.h"
#include "js/AutoByteString.h"
#include "js/MemoryMetrics.h" #include "js/MemoryMetrics.h"
#include "js/Printf.h" #include "js/Printf.h"
#include "js/SourceBufferHolder.h" #include "js/SourceBufferHolder.h"
@ -2015,9 +2014,9 @@ class MOZ_STACK_CLASS JS_HAZ_ROOTED ModuleValidator
bool failNameOffset(uint32_t offset, const char* fmt, PropertyName* name) { bool failNameOffset(uint32_t offset, const char* fmt, PropertyName* name) {
// This function is invoked without the caller properly rooting its locals. // This function is invoked without the caller properly rooting its locals.
gc::AutoSuppressGC suppress(cx_); gc::AutoSuppressGC suppress(cx_);
JSAutoByteString bytes; UniqueChars bytes;
if (AtomToPrintableString(cx_, name, &bytes)) if (AtomToPrintableString(cx_, name, &bytes))
failfOffset(offset, fmt, bytes.ptr()); failfOffset(offset, fmt, bytes.get());
return false; return false;
} }

Просмотреть файл

@ -17,7 +17,7 @@
#endif #endif
#include "jsapi.h" #include "jsapi.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h" #include "js/CompilationAndEvaluation.h"
#include "js/Printf.h" #include "js/Printf.h"
#include "nsCOMPtr.h" #include "nsCOMPtr.h"
@ -106,12 +106,12 @@ Dump(JSContext* cx, unsigned argc, Value* vp)
if (!str) if (!str)
return false; return false;
JSAutoByteString utf8str; JS::UniqueChars utf8str = JS_EncodeStringToUTF8(cx, str);
if (!utf8str.encodeUtf8(cx, str)) if (!utf8str)
return false; return false;
#ifdef ANDROID #ifdef ANDROID
__android_log_print(ANDROID_LOG_INFO, "Gecko", "%s", utf8str.ptr()); __android_log_print(ANDROID_LOG_INFO, "Gecko", "%s", utf8str.get());
#endif #endif
#ifdef XP_WIN #ifdef XP_WIN
if (IsDebuggerPresent()) { if (IsDebuggerPresent()) {
@ -121,7 +121,7 @@ Dump(JSContext* cx, unsigned argc, Value* vp)
OutputDebugStringW(wstr.get()); OutputDebugStringW(wstr.get());
} }
#endif #endif
fputs(utf8str.ptr(), stdout); fputs(utf8str.get(), stdout);
fflush(stdout); fflush(stdout);
return true; return true;
} }
@ -1241,12 +1241,12 @@ mozJSComponentLoader::ExtractExports(JSContext* aCx, ComponentLoaderInfo& aInfo,
symbolHolder = ResolveModuleObjectPropertyById(cx, aMod->obj, symbolId); symbolHolder = ResolveModuleObjectPropertyById(cx, aMod->obj, symbolId);
if (!symbolHolder || if (!symbolHolder ||
!JS_GetPropertyById(cx, symbolHolder, symbolId, &value)) { !JS_GetPropertyById(cx, symbolHolder, symbolId, &value)) {
JSAutoByteString bytes;
RootedString symbolStr(cx, JSID_TO_STRING(symbolId)); RootedString symbolStr(cx, JSID_TO_STRING(symbolId));
if (!bytes.encodeUtf8(cx, symbolStr)) JS::UniqueChars bytes = JS_EncodeStringToUTF8(cx, symbolStr);
if (!bytes)
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;
return ReportOnCallerUTF8(cxhelper, ERROR_GETTING_SYMBOL, return ReportOnCallerUTF8(cxhelper, ERROR_GETTING_SYMBOL,
aInfo, bytes.ptr()); aInfo, bytes.get());
} }
if (value.isUndefined()) { if (value.isUndefined()) {
@ -1254,20 +1254,20 @@ mozJSComponentLoader::ExtractExports(JSContext* aCx, ComponentLoaderInfo& aInfo,
} }
if (!JS_SetPropertyById(cx, aExports, symbolId, value)) { if (!JS_SetPropertyById(cx, aExports, symbolId, value)) {
JSAutoByteString bytes;
RootedString symbolStr(cx, JSID_TO_STRING(symbolId)); RootedString symbolStr(cx, JSID_TO_STRING(symbolId));
if (!bytes.encodeUtf8(cx, symbolStr)) JS::UniqueChars bytes = JS_EncodeStringToUTF8(cx, symbolStr);
if (!bytes)
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;
return ReportOnCallerUTF8(cxhelper, ERROR_GETTING_SYMBOL, return ReportOnCallerUTF8(cxhelper, ERROR_GETTING_SYMBOL,
aInfo, bytes.ptr()); aInfo, bytes.get());
} }
#ifdef DEBUG #ifdef DEBUG
if (i == 0) { if (i == 0) {
logBuffer.AssignLiteral("Installing symbols [ "); logBuffer.AssignLiteral("Installing symbols [ ");
} }
JSAutoByteString bytes(cx, JSID_TO_STRING(symbolId)); JS::UniqueChars bytes = JS_EncodeString(cx, JSID_TO_STRING(symbolId));
if (!!bytes) if (!!bytes)
logBuffer.Append(bytes.ptr()); logBuffer.Append(bytes.get());
logBuffer.Append(' '); logBuffer.Append(' ');
if (i == symbolCount - 1) { if (i == symbolCount - 1) {
nsCString location; nsCString location;

Просмотреть файл

@ -10,7 +10,7 @@
#include "AccessCheck.h" #include "AccessCheck.h"
#include "jsfriendapi.h" #include "jsfriendapi.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h" #include "js/CompilationAndEvaluation.h"
#include "js/Proxy.h" #include "js/Proxy.h"
#include "js/SourceBufferHolder.h" #include "js/SourceBufferHolder.h"
@ -140,8 +140,8 @@ SandboxDump(JSContext* cx, unsigned argc, Value* vp)
if (!str) if (!str)
return false; return false;
JSAutoByteString utf8str; JS::UniqueChars utf8str = JS_EncodeStringToUTF8(cx, str);
char* cstr = utf8str.encodeUtf8(cx, str); char* cstr = utf8str.get();
if (!cstr) if (!cstr)
return false; return false;
@ -855,69 +855,69 @@ xpc::GlobalProperties::Parse(JSContext* cx, JS::HandleObject obj)
return false; return false;
} }
RootedString nameStr(cx, nameValue.toString()); RootedString nameStr(cx, nameValue.toString());
JSAutoByteString name; JS::UniqueChars name = JS_EncodeStringToUTF8(cx, nameStr);
if (!name.encodeUtf8(cx, nameStr)) if (!name)
return false; return false;
if (!strcmp(name.ptr(), "Blob")) { if (!strcmp(name.get(), "Blob")) {
Blob = true; Blob = true;
} else if (!strcmp(name.ptr(), "ChromeUtils")) { } else if (!strcmp(name.get(), "ChromeUtils")) {
ChromeUtils = true; ChromeUtils = true;
} else if (!strcmp(name.ptr(), "CSS")) { } else if (!strcmp(name.get(), "CSS")) {
CSS = true; CSS = true;
} else if (!strcmp(name.ptr(), "CSSRule")) { } else if (!strcmp(name.get(), "CSSRule")) {
CSSRule = true; CSSRule = true;
} else if (!strcmp(name.ptr(), "Directory")) { } else if (!strcmp(name.get(), "Directory")) {
Directory = true; Directory = true;
} else if (!strcmp(name.ptr(), "DOMParser")) { } else if (!strcmp(name.get(), "DOMParser")) {
DOMParser = true; DOMParser = true;
} else if (!strcmp(name.ptr(), "Element")) { } else if (!strcmp(name.get(), "Element")) {
Element = true; Element = true;
} else if (!strcmp(name.ptr(), "Event")) { } else if (!strcmp(name.get(), "Event")) {
Event = true; Event = true;
} else if (!strcmp(name.ptr(), "File")) { } else if (!strcmp(name.get(), "File")) {
File = true; File = true;
} else if (!strcmp(name.ptr(), "FileReader")) { } else if (!strcmp(name.get(), "FileReader")) {
FileReader = true; FileReader = true;
} else if (!strcmp(name.ptr(), "FormData")) { } else if (!strcmp(name.get(), "FormData")) {
FormData = true; FormData = true;
} else if (!strcmp(name.ptr(), "InspectorUtils")) { } else if (!strcmp(name.get(), "InspectorUtils")) {
InspectorUtils = true; InspectorUtils = true;
} else if (!strcmp(name.ptr(), "MessageChannel")) { } else if (!strcmp(name.get(), "MessageChannel")) {
MessageChannel = true; MessageChannel = true;
} else if (!strcmp(name.ptr(), "Node")) { } else if (!strcmp(name.get(), "Node")) {
Node = true; Node = true;
} else if (!strcmp(name.ptr(), "NodeFilter")) { } else if (!strcmp(name.get(), "NodeFilter")) {
NodeFilter = true; NodeFilter = true;
} else if (!strcmp(name.ptr(), "TextDecoder")) { } else if (!strcmp(name.get(), "TextDecoder")) {
TextDecoder = true; TextDecoder = true;
} else if (!strcmp(name.ptr(), "TextEncoder")) { } else if (!strcmp(name.get(), "TextEncoder")) {
TextEncoder = true; TextEncoder = true;
} else if (!strcmp(name.ptr(), "URL")) { } else if (!strcmp(name.get(), "URL")) {
URL = true; URL = true;
} else if (!strcmp(name.ptr(), "URLSearchParams")) { } else if (!strcmp(name.get(), "URLSearchParams")) {
URLSearchParams = true; URLSearchParams = true;
} else if (!strcmp(name.ptr(), "XMLHttpRequest")) { } else if (!strcmp(name.get(), "XMLHttpRequest")) {
XMLHttpRequest = true; XMLHttpRequest = true;
} else if (!strcmp(name.ptr(), "XMLSerializer")) { } else if (!strcmp(name.get(), "XMLSerializer")) {
XMLSerializer = true; XMLSerializer = true;
} else if (!strcmp(name.ptr(), "atob")) { } else if (!strcmp(name.get(), "atob")) {
atob = true; atob = true;
} else if (!strcmp(name.ptr(), "btoa")) { } else if (!strcmp(name.get(), "btoa")) {
btoa = true; btoa = true;
} else if (!strcmp(name.ptr(), "caches")) { } else if (!strcmp(name.get(), "caches")) {
caches = true; caches = true;
} else if (!strcmp(name.ptr(), "crypto")) { } else if (!strcmp(name.get(), "crypto")) {
crypto = true; crypto = true;
} else if (!strcmp(name.ptr(), "fetch")) { } else if (!strcmp(name.get(), "fetch")) {
fetch = true; fetch = true;
} else if (!strcmp(name.ptr(), "indexedDB")) { } else if (!strcmp(name.get(), "indexedDB")) {
indexedDB = true; indexedDB = true;
#ifdef MOZ_WEBRTC #ifdef MOZ_WEBRTC
} else if (!strcmp(name.ptr(), "rtcIdentityProvider")) { } else if (!strcmp(name.get(), "rtcIdentityProvider")) {
rtcIdentityProvider = true; rtcIdentityProvider = true;
#endif #endif
} else { } else {
JS_ReportErrorUTF8(cx, "Unknown property name: %s", name.ptr()); JS_ReportErrorUTF8(cx, "Unknown property name: %s", name.get());
return false; return false;
} }
} }
@ -1540,10 +1540,9 @@ OptionsBase::ParseString(const char* name, nsCString& prop)
return false; return false;
} }
char* tmp = JS_EncodeString(mCx, value.toString()); JS::UniqueChars tmp = JS_EncodeString(mCx, value.toString());
NS_ENSURE_TRUE(tmp, false); NS_ENSURE_TRUE(tmp, false);
prop.Assign(tmp, strlen(tmp)); prop.Assign(tmp.get(), strlen(tmp.get()));
js_free(tmp);
return true; return true;
} }

Просмотреть файл

@ -15,7 +15,7 @@
#include "nsContentUtils.h" #include "nsContentUtils.h"
#include "nsCycleCollector.h" #include "nsCycleCollector.h"
#include "jsfriendapi.h" #include "jsfriendapi.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/SavedFrameAPI.h" #include "js/SavedFrameAPI.h"
#include "js/StructuredClone.h" #include "js/StructuredClone.h"
#include "mozilla/Attributes.h" #include "mozilla/Attributes.h"
@ -246,12 +246,12 @@ nsXPCComponents_Interfaces::Resolve(nsIXPConnectWrappedNative* wrapper,
if (!JSID_IS_STRING(id)) if (!JSID_IS_STRING(id))
return NS_OK; return NS_OK;
JSAutoByteString name;
RootedString str(cx, JSID_TO_STRING(id)); RootedString str(cx, JSID_TO_STRING(id));
JS::UniqueChars name = JS_EncodeString(cx, str);
// we only allow interfaces by name here // we only allow interfaces by name here
if (name.encodeLatin1(cx, str) && name.ptr()[0] != '{') { if (name && name[0] != '{') {
const nsXPTInterfaceInfo* info = nsXPTInterfaceInfo::ByName(name.ptr()); const nsXPTInterfaceInfo* info = nsXPTInterfaceInfo::ByName(name.get());
if (!info) if (!info)
return NS_OK; return NS_OK;
@ -431,10 +431,10 @@ nsXPCComponents_InterfacesByID::Resolve(nsIXPConnectWrappedNative* wrapper,
if (38 != JS_GetStringLength(str)) if (38 != JS_GetStringLength(str))
return NS_OK; return NS_OK;
JSAutoByteString utf8str; JS::UniqueChars utf8str = JS_EncodeStringToUTF8(cx, str);
if (utf8str.encodeUtf8(cx, str)) { if (utf8str) {
nsID iid; nsID iid;
if (!iid.Parse(utf8str.ptr())) if (!iid.Parse(utf8str.get()))
return NS_OK; return NS_OK;
const nsXPTInterfaceInfo* info = nsXPTInterfaceInfo::ByIID(iid); const nsXPTInterfaceInfo* info = nsXPTInterfaceInfo::ByIID(iid);
@ -623,11 +623,13 @@ nsXPCComponents_Classes::Resolve(nsIXPConnectWrappedNative* wrapper,
RootedId id(cx, idArg); RootedId id(cx, idArg);
RootedObject obj(cx, objArg); RootedObject obj(cx, objArg);
JSAutoByteString name; if (!JSID_IS_STRING(id))
if (JSID_IS_STRING(id) && return NS_OK;
name.encodeLatin1(cx, JSID_TO_STRING(id)) &&
name.ptr()[0] != '{') { // we only allow contractids here JS::UniqueChars name = JS_EncodeString(cx, JSID_TO_STRING(id));
nsCOMPtr<nsIJSCID> nsid = nsJSCID::NewID(name.ptr()); if (name &&
name[0] != '{') { // we only allow contractids here
nsCOMPtr<nsIJSCID> nsid = nsJSCID::NewID(name.get());
if (nsid) { if (nsid) {
nsXPConnect* xpc = nsXPConnect::XPConnect(); nsXPConnect* xpc = nsXPConnect::XPConnect();
RootedObject idobj(cx); RootedObject idobj(cx);
@ -832,12 +834,12 @@ nsXPCComponents_ClassesByID::Resolve(nsIXPConnectWrappedNative* wrapper,
if (!JSID_IS_STRING(id)) if (!JSID_IS_STRING(id))
return NS_OK; return NS_OK;
JSAutoByteString name;
RootedString str(cx, JSID_TO_STRING(id)); RootedString str(cx, JSID_TO_STRING(id));
if (name.encodeLatin1(cx, str) && name.ptr()[0] == '{' && JS::UniqueChars name = JS_EncodeString(cx, str);
IsRegisteredCLSID(name.ptr())) // we only allow canonical CLSIDs here if (name && name[0] == '{' &&
IsRegisteredCLSID(name.get())) // we only allow canonical CLSIDs here
{ {
nsCOMPtr<nsIJSCID> nsid = nsJSCID::NewID(name.ptr()); nsCOMPtr<nsIJSCID> nsid = nsJSCID::NewID(name.get());
if (nsid) { if (nsid) {
nsXPConnect* xpc = nsXPConnect::XPConnect(); nsXPConnect* xpc = nsXPConnect::XPConnect();
RootedObject idobj(cx); RootedObject idobj(cx);
@ -998,14 +1000,16 @@ nsXPCComponents_Results::Resolve(nsIXPConnectWrappedNative* wrapper,
{ {
RootedObject obj(cx, objArg); RootedObject obj(cx, objArg);
RootedId id(cx, idArg); RootedId id(cx, idArg);
JSAutoByteString name; if (!JSID_IS_STRING(id))
return NS_OK;
if (JSID_IS_STRING(id) && name.encodeLatin1(cx, JSID_TO_STRING(id))) { JS::UniqueChars name = JS_EncodeString(cx, JSID_TO_STRING(id));
if (name) {
const char* rv_name; const char* rv_name;
const void* iter = nullptr; const void* iter = nullptr;
nsresult rv; nsresult rv;
while (nsXPCException::IterateNSResults(&rv, &rv_name, nullptr, &iter)) { while (nsXPCException::IterateNSResults(&rv, &rv_name, nullptr, &iter)) {
if (!strcmp(name.ptr(), rv_name)) { if (!strcmp(name.get(), rv_name)) {
*resolvedp = true; *resolvedp = true;
if (!JS_DefinePropertyById(cx, obj, id, (uint32_t)rv, if (!JS_DefinePropertyById(cx, obj, id, (uint32_t)rv,
JSPROP_ENUMERATE | JSPROP_ENUMERATE |
@ -1161,15 +1165,17 @@ nsXPCComponents_ID::CallOrConstruct(nsIXPConnectWrappedNative* wrapper,
// convert the first argument into a string and see if it looks like an id // convert the first argument into a string and see if it looks like an id
JSString* jsstr; JSString* jsstr = ToString(cx, args[0]);
JSAutoByteString bytes; if (!jsstr)
nsID id; return ThrowAndFail(NS_ERROR_XPC_BAD_ID_STRING, cx, _retval);
if (!(jsstr = ToString(cx, args[0])) || JS::UniqueChars bytes = JS_EncodeString(cx, jsstr);
!bytes.encodeLatin1(cx, jsstr) || if (!bytes)
!id.Parse(bytes.ptr())) { return ThrowAndFail(NS_ERROR_XPC_BAD_ID_STRING, cx, _retval);
nsID id;
if (!id.Parse(bytes.get()))
return ThrowAndFail(NS_ERROR_XPC_BAD_ID_STRING, cx, _retval); return ThrowAndFail(NS_ERROR_XPC_BAD_ID_STRING, cx, _retval);
}
// make the new object and return it. // make the new object and return it.
@ -1382,7 +1388,8 @@ struct MOZ_STACK_CLASS ExceptionArgParser
JSString* str = ToString(cx, v); JSString* str = ToString(cx, v);
if (!str) if (!str)
return false; return false;
eMsg = messageBytes.encodeLatin1(cx, str); messageBytes = JS_EncodeString(cx, str);
eMsg = messageBytes.get();
return !!eMsg; return !!eMsg;
} }
@ -1453,7 +1460,7 @@ struct MOZ_STACK_CLASS ExceptionArgParser
*/ */
// If there's a non-default exception string, hold onto the allocated bytes. // If there's a non-default exception string, hold onto the allocated bytes.
JSAutoByteString messageBytes; JS::UniqueChars messageBytes;
// Various bits and pieces that are helpful to have around. // Various bits and pieces that are helpful to have around.
JSContext* cx; JSContext* cx;
@ -1871,12 +1878,17 @@ nsXPCComponents_Constructor::CallOrConstruct(nsIXPConnectWrappedNative* wrapper,
nsCOMPtr<nsIJSCID> cClassID; nsCOMPtr<nsIJSCID> cClassID;
nsCOMPtr<nsIJSIID> cInterfaceID; nsCOMPtr<nsIJSIID> cInterfaceID;
const char* cInitializer = nullptr; const char* cInitializer = nullptr;
JSAutoByteString cInitializerBytes; JS::UniqueChars cInitializerBytes;
if (args.length() >= 3) { if (args.length() >= 3) {
// args[2] is an initializer function or property name // args[2] is an initializer function or property name
RootedString str(cx, ToString(cx, args[2])); RootedString str(cx, ToString(cx, args[2]));
if (!str || !(cInitializer = cInitializerBytes.encodeLatin1(cx, str))) if (!str)
return ThrowAndFail(NS_ERROR_XPC_BAD_CONVERT_JS, cx, _retval);
cInitializerBytes = JS_EncodeString(cx, str);
cInitializer = cInitializerBytes.get();
if (!cInitializer)
return ThrowAndFail(NS_ERROR_XPC_BAD_CONVERT_JS, cx, _retval); return ThrowAndFail(NS_ERROR_XPC_BAD_CONVERT_JS, cx, _retval);
} }

Просмотреть файл

@ -21,7 +21,6 @@
#include "jsapi.h" #include "jsapi.h"
#include "jsfriendapi.h" #include "jsfriendapi.h"
#include "js/AutoByteString.h"
#include "js/CharacterEncoding.h" #include "js/CharacterEncoding.h"
#include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/BindingUtils.h"
@ -1333,11 +1332,11 @@ XPCConvert::JSValToXPCException(MutableHandleValue s,
// extract the report and build an xpcexception from that // extract the report and build an xpcexception from that
const JSErrorReport* report; const JSErrorReport* report;
if (nullptr != (report = JS_ErrorFromException(cx, obj))) { if (nullptr != (report = JS_ErrorFromException(cx, obj))) {
JSAutoByteString toStringResult; JS::UniqueChars toStringResult;
RootedString str(cx, ToString(cx, s)); RootedString str(cx, ToString(cx, s));
if (str) if (str)
toStringResult.encodeUtf8(cx, str); toStringResult = JS_EncodeStringToUTF8(cx, str);
return JSErrorToXPCException(toStringResult.ptr(), ifaceName, return JSErrorToXPCException(toStringResult.get(), ifaceName,
methodName, report, exceptn); methodName, report, exceptn);
} }
@ -1352,12 +1351,12 @@ XPCConvert::JSValToXPCException(MutableHandleValue s,
if (!str) if (!str)
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;
JSAutoByteString strBytes(cx, str); JS::UniqueChars strBytes = JS_EncodeString(cx, str);
if (!strBytes) if (!strBytes)
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;
return ConstructException(NS_ERROR_XPC_JS_THREW_JS_OBJECT, return ConstructException(NS_ERROR_XPC_JS_THREW_JS_OBJECT,
strBytes.ptr(), ifaceName, methodName, strBytes.get(), ifaceName, methodName,
nullptr, exceptn, cx, s.address()); nullptr, exceptn, cx, s.address());
} }
} }
@ -1420,10 +1419,10 @@ XPCConvert::JSValToXPCException(MutableHandleValue s,
JSString* str = ToString(cx, s); JSString* str = ToString(cx, s);
if (str) { if (str) {
JSAutoByteString strBytes(cx, str); JS::UniqueChars strBytes = JS_EncodeString(cx, str);
if (!!strBytes) { if (!!strBytes) {
return ConstructException(NS_ERROR_XPC_JS_THREW_STRING, return ConstructException(NS_ERROR_XPC_JS_THREW_STRING,
strBytes.ptr(), ifaceName, methodName, strBytes.get(), ifaceName, methodName,
nullptr, exceptn, cx, s.address()); nullptr, exceptn, cx, s.address());
} }
} }

Просмотреть файл

@ -7,7 +7,7 @@
#include "nsXULAppAPI.h" #include "nsXULAppAPI.h"
#include "jsapi.h" #include "jsapi.h"
#include "jsfriendapi.h" #include "jsfriendapi.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h" #include "js/CompilationAndEvaluation.h"
#include "js/Printf.h" #include "js/Printf.h"
#include "mozilla/ChaosMode.h" #include "mozilla/ChaosMode.h"
@ -250,8 +250,8 @@ ReadLine(JSContext* cx, unsigned argc, Value* vp)
} }
/* Get a line from the infile */ /* Get a line from the infile */
JSAutoByteString strBytes(cx, str); JS::UniqueChars strBytes = JS_EncodeString(cx, str);
if (!strBytes || !GetLine(cx, buf, gInFile, strBytes.ptr())) if (!strBytes || !GetLine(cx, buf, gInFile, strBytes.get()))
return false; return false;
/* Strip newline character added by GetLine() */ /* Strip newline character added by GetLine() */
@ -288,13 +288,13 @@ Print(JSContext* cx, unsigned argc, Value* vp)
if (!str) if (!str)
return false; return false;
JSAutoByteString utf8str; JS::UniqueChars utf8str = JS_EncodeStringToUTF8(cx, str);
if (!utf8str.encodeUtf8(cx, str)) if (!utf8str)
return false; return false;
if (i) if (i)
utf8output.Append(' '); utf8output.Append(' ');
utf8output.Append(utf8str.ptr(), utf8str.length()); utf8output.Append(utf8str.get(), strlen(utf8str.get()));
} }
utf8output.Append('\n'); utf8output.Append('\n');
fputs(utf8output.get(), gOutFile); fputs(utf8output.get(), gOutFile);
@ -315,12 +315,12 @@ Dump(JSContext* cx, unsigned argc, Value* vp)
if (!str) if (!str)
return false; return false;
JSAutoByteString utf8str; JS::UniqueChars utf8str = JS_EncodeStringToUTF8(cx, str);
if (!utf8str.encodeUtf8(cx, str)) if (!utf8str)
return false; return false;
#ifdef ANDROID #ifdef ANDROID
__android_log_print(ANDROID_LOG_INFO, "Gecko", "%s", utf8str.ptr()); __android_log_print(ANDROID_LOG_INFO, "Gecko", "%s", utf8str.get());
#endif #endif
#ifdef XP_WIN #ifdef XP_WIN
if (IsDebuggerPresent()) { if (IsDebuggerPresent()) {
@ -330,7 +330,7 @@ Dump(JSContext* cx, unsigned argc, Value* vp)
OutputDebugStringW(wstr.get()); OutputDebugStringW(wstr.get());
} }
#endif #endif
fputs(utf8str.ptr(), gOutFile); fputs(utf8str.get(), gOutFile);
fflush(gOutFile); fflush(gOutFile);
return true; return true;
} }
@ -353,21 +353,21 @@ Load(JSContext* cx, unsigned argc, Value* vp)
str = ToString(cx, args[i]); str = ToString(cx, args[i]);
if (!str) if (!str)
return false; return false;
JSAutoByteString filename(cx, str); JS::UniqueChars filename = JS_EncodeString(cx, str);
if (!filename) if (!filename)
return false; return false;
FILE* file = fopen(filename.ptr(), "r"); FILE* file = fopen(filename.get(), "r");
if (!file) { if (!file) {
filename.clear(); filename = JS_EncodeStringToUTF8(cx, str);
if (!filename.encodeUtf8(cx, str)) if (!filename)
return false; return false;
JS_ReportErrorUTF8(cx, "cannot open file '%s' for reading", JS_ReportErrorUTF8(cx, "cannot open file '%s' for reading",
filename.ptr()); filename.get());
return false; return false;
} }
JS::CompileOptions options(cx); JS::CompileOptions options(cx);
options.setUTF8(true) options.setUTF8(true)
.setFileAndLine(filename.ptr(), 1) .setFileAndLine(filename.get(), 1)
.setIsRunOnce(true); .setIsRunOnce(true);
JS::Rooted<JSScript*> script(cx); JS::Rooted<JSScript*> script(cx);
JS::Rooted<JSObject*> global(cx, JS::CurrentGlobalOrNull(cx)); JS::Rooted<JSObject*> global(cx, JS::CurrentGlobalOrNull(cx));
@ -479,25 +479,25 @@ Options(JSContext* cx, unsigned argc, Value* vp)
ContextOptions oldContextOptions = ContextOptionsRef(cx); ContextOptions oldContextOptions = ContextOptionsRef(cx);
RootedString str(cx); RootedString str(cx);
JSAutoByteString opt; JS::UniqueChars opt;
for (unsigned i = 0; i < args.length(); ++i) { for (unsigned i = 0; i < args.length(); ++i) {
str = ToString(cx, args[i]); str = ToString(cx, args[i]);
if (!str) if (!str)
return false; return false;
opt.clear(); opt = JS_EncodeStringToUTF8(cx, str);
if (!opt.encodeUtf8(cx, str)) if (!opt)
return false; return false;
if (strcmp(opt.ptr(), "strict") == 0) if (strcmp(opt.get(), "strict") == 0)
ContextOptionsRef(cx).toggleExtraWarnings(); ContextOptionsRef(cx).toggleExtraWarnings();
else if (strcmp(opt.ptr(), "werror") == 0) else if (strcmp(opt.get(), "werror") == 0)
ContextOptionsRef(cx).toggleWerror(); ContextOptionsRef(cx).toggleWerror();
else if (strcmp(opt.ptr(), "strict_mode") == 0) else if (strcmp(opt.get(), "strict_mode") == 0)
ContextOptionsRef(cx).toggleStrictMode(); ContextOptionsRef(cx).toggleStrictMode();
else { else {
JS_ReportErrorUTF8(cx, "unknown option name '%s'. The valid names are " JS_ReportErrorUTF8(cx, "unknown option name '%s'. The valid names are "
"strict, werror, and strict_mode.", opt.ptr()); "strict, werror, and strict_mode.", opt.get());
return false; return false;
} }
} }
@ -726,11 +726,11 @@ ProcessLine(AutoJSAPI& jsapi, const char* buffer, int startline)
RootedString str(cx); RootedString str(cx);
if (!(str = ToString(cx, result))) if (!(str = ToString(cx, result)))
return false; return false;
JSAutoByteString bytes; JS::UniqueChars bytes = JS_EncodeString(cx, str);
if (!bytes.encodeLatin1(cx, str)) if (!bytes)
return false; return false;
fprintf(gOutFile, "%s\n", bytes.ptr()); fprintf(gOutFile, "%s\n", bytes.get());
return true; return true;
} }

Просмотреть файл

@ -8,7 +8,7 @@
#include "xpcprivate.h" #include "xpcprivate.h"
#include "XPCWrapper.h" #include "XPCWrapper.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/Printf.h" #include "js/Printf.h"
#include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMException.h" #include "mozilla/dom/DOMException.h"
@ -164,10 +164,13 @@ XPCThrower::Verbosify(XPCCallContext& ccx,
if (ccx.HasInterfaceAndMember()) { if (ccx.HasInterfaceAndMember()) {
XPCNativeInterface* iface = ccx.GetInterface(); XPCNativeInterface* iface = ccx.GetInterface();
jsid id = ccx.GetMember()->GetName(); jsid id = ccx.GetMember()->GetName();
JSAutoByteString bytes; const char* name;
const char* name = JSID_IS_VOID(id) ? "Unknown" : bytes.encodeLatin1(ccx, JSID_TO_STRING(id)); JS::UniqueChars bytes;
if (!name) { if (!JSID_IS_VOID(id)) {
name = ""; bytes = JS_EncodeString(ccx, JSID_TO_STRING(id));
name = bytes ? bytes.get() : "";
} else {
name = "Unknown";
} }
sz = JS_smprintf("%s [%s.%s]", *psz, iface->GetNameString(), name).release(); sz = JS_smprintf("%s [%s.%s]", *psz, iface->GetNameString(), name).release();
} }

Просмотреть файл

@ -10,7 +10,7 @@
#include "xpc_make_class.h" #include "xpc_make_class.h"
#include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/BindingUtils.h"
#include "mozilla/Preferences.h" #include "mozilla/Preferences.h"
#include "js/AutoByteString.h" #include "js/CharacterEncoding.h"
#include "js/Class.h" #include "js/Class.h"
#include "js/Printf.h" #include "js/Printf.h"
@ -289,20 +289,37 @@ DefinePropertyIfFound(XPCCallContext& ccx,
// interface and add a tearoff as necessary. // interface and add a tearoff as necessary.
if (wrapperToReflectInterfaceNames) { if (wrapperToReflectInterfaceNames) {
JSAutoByteString name; JS::UniqueChars name;
RefPtr<XPCNativeInterface> iface2; RefPtr<XPCNativeInterface> iface2;
XPCWrappedNativeTearOff* to; XPCWrappedNativeTearOff* to;
RootedObject jso(ccx); RootedObject jso(ccx);
nsresult rv = NS_OK; nsresult rv = NS_OK;
if (JSID_IS_STRING(id) && bool defineProperty = false;
name.encodeLatin1(ccx, JSID_TO_STRING(id)) && do {
(iface2 = XPCNativeInterface::GetNewOrUsed(name.ptr())) && if (!JSID_IS_STRING(id))
nullptr != (to = wrapperToReflectInterfaceNames-> break;
FindTearOff(iface2, true, &rv)) &&
nullptr != (jso = to->GetJSObject()))
{ name = JS_EncodeString(ccx, JSID_TO_STRING(id));
if (!name)
break;
iface2 = XPCNativeInterface::GetNewOrUsed(name.get());
if (!iface2)
break;
to = wrapperToReflectInterfaceNames->FindTearOff(iface2, true, &rv);
if (!to)
break;
jso = to->GetJSObject();
if (!jso)
break;
defineProperty = true;
} while (false);
if (defineProperty) {
AutoResolveName arn(ccx, id); AutoResolveName arn(ccx, id);
if (resolved) if (resolved)
*resolved = true; *resolved = true;

Просмотреть файл

@ -6,6 +6,7 @@
#include "JSControl.h" #include "JSControl.h"
#include "js/CharacterEncoding.h"
#include "js/Conversions.h" #include "js/Conversions.h"
#include "js/JSON.h" #include "js/JSON.h"
#include "ChildInternal.h" #include "ChildInternal.h"
@ -802,12 +803,11 @@ RecordReplay_Dump(JSContext* aCx, unsigned aArgc, Value* aVp)
if (!str) { if (!str) {
return false; return false;
} }
char* cstr = JS_EncodeString(aCx, str); JS::UniqueChars cstr = JS_EncodeString(aCx, str);
if (!cstr) { if (!cstr) {
return false; return false;
} }
Print("%s", cstr); Print("%s", cstr.get());
JS_free(aCx, cstr);
} }
args.rval().setUndefined(); args.rval().setUndefined();

Просмотреть файл

@ -9,6 +9,7 @@
#include "FuzzingTraits.h" #include "FuzzingTraits.h"
#include "jsapi.h" #include "jsapi.h"
#include "jsfriendapi.h" #include "jsfriendapi.h"
#include "js/CharacterEncoding.h"
#include "prenv.h" #include "prenv.h"
#include "MessageManagerFuzzer.h" #include "MessageManagerFuzzer.h"
#include "mozilla/ErrorResult.h" #include "mozilla/ErrorResult.h"
@ -195,9 +196,10 @@ MessageManagerFuzzer::MutateValue(JSContext* aCx,
} }
JSString* str = JS_NewStringCopyZ(aCx, x.get()); JSString* str = JS_NewStringCopyZ(aCx, x.get());
aOutMutationValue.set(JS::StringValue(str)); aOutMutationValue.set(JS::StringValue(str));
JS::UniqueChars valueChars = JS_EncodeString(aCx, aValue.toString());
MSGMGR_FUZZER_LOG("%*s! Mutated value of type |string|: '%s' to '%s'", MSGMGR_FUZZER_LOG("%*s! Mutated value of type |string|: '%s' to '%s'",
aRecursionCounter * 4, "", aRecursionCounter * 4, "",
JS_EncodeString(aCx, aValue.toString()), x.get()); valueChars.get(), x.get());
return true; return true;
} }
@ -258,9 +260,10 @@ MessageManagerFuzzer::Mutate(JSContext* aCx,
/* Mutated and successfully written to StructuredCloneData object. */ /* Mutated and successfully written to StructuredCloneData object. */
if (isMutated) { if (isMutated) {
JS::RootedString str(aCx, JS_ValueToSource(aCx, scdMutationContent)); JS::RootedString str(aCx, JS_ValueToSource(aCx, scdMutationContent));
JS::UniqueChars strChars = JS_EncodeStringToUTF8(aCx, str);
MSGMGR_FUZZER_LOG("Mutated '%s' Message: %s", MSGMGR_FUZZER_LOG("Mutated '%s' Message: %s",
NS_ConvertUTF16toUTF8(aMessageName).get(), NS_ConvertUTF16toUTF8(aMessageName).get(),
JS_EncodeStringToUTF8(aCx, str)); strChars.get());
} }
return true; return true;