ChromeWorkerScope.cpp (1886B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #include "ChromeWorkerScope.h" 8 9 #include "js/MemoryFunctions.h" 10 #include "js/PropertyAndElement.h" // JS_GetProperty 11 #include "js/experimental/CTypes.h" // JS::InitCTypesClass, JS::CTypesCallbacks, JS::SetCTypesCallbacks 12 #include "jsapi.h" 13 #include "nsNativeCharsetUtils.h" 14 #include "nsString.h" 15 16 namespace mozilla::dom { 17 18 namespace { 19 20 #ifdef BUILD_CTYPES 21 22 char* UnicodeToNative(JSContext* aCx, const char16_t* aSource, 23 size_t aSourceLen) { 24 nsDependentSubstring unicode(aSource, aSourceLen); 25 26 nsAutoCString native; 27 if (NS_FAILED(NS_CopyUnicodeToNative(unicode, native))) { 28 JS_ReportErrorASCII(aCx, "Could not convert string to native charset!"); 29 return nullptr; 30 } 31 32 char* result = static_cast<char*>(JS_malloc(aCx, native.Length() + 1)); 33 if (!result) { 34 return nullptr; 35 } 36 37 memcpy(result, native.get(), native.Length()); 38 result[native.Length()] = 0; 39 return result; 40 } 41 42 #endif // BUILD_CTYPES 43 44 } // namespace 45 46 bool DefineChromeWorkerFunctions(JSContext* aCx, 47 JS::Handle<JSObject*> aGlobal) { 48 // Currently ctypes is the only special property given to ChromeWorkers. 49 #ifdef BUILD_CTYPES 50 { 51 JS::Rooted<JS::Value> ctypes(aCx); 52 if (!JS::InitCTypesClass(aCx, aGlobal) || 53 !JS_GetProperty(aCx, aGlobal, "ctypes", &ctypes)) { 54 return false; 55 } 56 57 static const JS::CTypesCallbacks callbacks = {UnicodeToNative}; 58 59 JS::SetCTypesCallbacks(ctypes.toObjectOrNull(), &callbacks); 60 } 61 #endif // BUILD_CTYPES 62 63 return true; 64 } 65 66 } // namespace mozilla::dom