zotero/app/mac/mozilla-153.patch

465 lines
16 KiB
Diff

diff --git a/browser/app/nsBrowserApp.cpp b/browser/app/nsBrowserApp.cpp
--- a/browser/app/nsBrowserApp.cpp
+++ b/browser/app/nsBrowserApp.cpp
@@ -193,19 +193,31 @@ static bool HasFlag(int argc, char* argv[], const char* s) {
}
return false;
}
#endif
constinit Bootstrap::UniquePtr gBootstrap;
static int do_main(int argc, char* argv[], char* envp[]) {
+ // Allow profile downgrade for Zotero
+ setenv("MOZ_ALLOW_DOWNGRADE", "1", 1);
+ // Don't create dedicated profile (default-esr)
+ setenv("MOZ_LEGACY_PROFILES", "1", 1);
+
// Allow firefox.exe to launch XULRunner apps via -app <application.ini>
// Note that -app must be the *first* argument.
- const char* appDataFile = getenv("XUL_APP_FILE");
+ UniqueFreePtr<char> iniPath = BinaryPath::GetApplicationIni();
+ if (!iniPath) {
+ Output("Couldn't find application.ini.\n");
+ return 255;
+ }
+ char *appDataFile = iniPath.get();
+
+
if ((!appDataFile || !*appDataFile) && (argc > 1 && IsFlag(argv[1], "app"))) {
if (argc == 2) {
Output("Incorrect number of arguments passed to -app");
return 255;
}
appDataFile = argv[2];
char appEnv[MAXPATHLEN];
diff --git a/xpcom/build/BinaryPath.h b/xpcom/build/BinaryPath.h
--- a/xpcom/build/BinaryPath.h
+++ b/xpcom/build/BinaryPath.h
@@ -126,16 +126,56 @@ class BinaryPath {
} else {
rv = NS_ERROR_FAILURE;
}
CFRelease(executableURL);
return rv;
}
+ static nsresult GetApplicationIni(char aResult[MAXPATHLEN])
+ {
+ // Works even if we're not bundled.
+ CFBundleRef appBundle = CFBundleGetMainBundle();
+ if (!appBundle) {
+ return NS_ERROR_FAILURE;
+ }
+
+ CFURLRef iniURL = CFBundleCopyResourceURL(appBundle, CFSTR("application.ini"),
+ NULL, CFSTR("app"));
+ if (!iniURL) {
+ return NS_ERROR_FAILURE;
+ }
+
+ nsresult rv;
+ if (CFURLGetFileSystemRepresentation(iniURL, false, (UInt8*)aResult,
+ MAXPATHLEN)) {
+ // Sanitize path in case the app was launched from Terminal via
+ // './firefox' for example.
+ size_t readPos = 0;
+ size_t writePos = 0;
+ while (aResult[readPos] != '\0') {
+ if (aResult[readPos] == '.' && aResult[readPos + 1] == '/') {
+ readPos += 2;
+ } else {
+ aResult[writePos] = aResult[readPos];
+ readPos++;
+ writePos++;
+ }
+ }
+ aResult[writePos] = '\0';
+ rv = NS_OK;
+ } else {
+ rv = NS_ERROR_FAILURE;
+ }
+
+ CFRelease(iniURL);
+ return rv;
+ }
+
#elif defined(ANDROID)
static nsresult Get(char aResult[MAXPATHLEN]) {
// On Android, we use the MOZ_ANDROID_LIBDIR variable that is set by the
// Java bootstrap code.
const char* libDir = getenv("MOZ_ANDROID_LIBDIR");
if (!libDir) {
return NS_ERROR_FAILURE;
}
@@ -281,16 +321,29 @@ class BinaryPath {
if (NS_FAILED(Get(path))) {
return nullptr;
}
UniqueFreePtr<char> result;
result.reset(strdup(path));
return result;
}
+#if defined(XP_MACOSX)
+ static UniqueFreePtr<char> GetApplicationIni()
+ {
+ char path[MAXPATHLEN];
+ if (NS_FAILED(GetApplicationIni(path))) {
+ return nullptr;
+ }
+ UniqueFreePtr<char> result;
+ result.reset(strdup(path));
+ return result;
+ }
+#endif
+
#ifdef MOZILLA_INTERNAL_API
static nsresult GetFile(nsIFile** aResult) {
nsCOMPtr<nsIFile> lf;
# ifdef XP_WIN
wchar_t exePath[MAXPATHLEN];
nsresult rv = GetW(exePath);
# else
char exePath[MAXPATHLEN];
diff --git a/mozglue/build/AudioQueueSanitizer.cpp b/mozglue/build/AudioQueueSanitizer.cpp
new file mode 100644
index 000000000000..9efa3255c472
--- /dev/null
+++ b/mozglue/build/AudioQueueSanitizer.cpp
@@ -0,0 +1,91 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// Work around a use-after-free in the macOS 27 system speech synthesizer.
+//
+// When an utterance finishes, the AudioQueue player in the private
+// TextToSpeech framework (used by both NSSpeechSynthesizer and
+// AVSpeechSynthesizer) enqueues a short de-click ramp that starts from a
+// sample read out of a buffer it has already freed. With the system
+// allocator, which zeroes freed memory, that sample is 0 and the ramp is
+// silent. mozjemalloc poisons freed memory with 0xE5 instead, which reads
+// as -1.36e23 in float32, so every utterance ends with a ~10 ms full-scale
+// burst.
+//
+// We can't fix the framework, so we interpose AudioQueueEnqueueBuffer and
+// zero any float samples that are non-finite or far outside the nominal
+// [-1, 1] range before they reach CoreAudio. Real audio never gets close
+// to kMaxSampleMagnitude, so this only ever affects garbage.
+//
+// dyld only honors __interpose tuples in images loaded at launch, which is
+// why this needs to be in mozglue rather than in XUL (loaded with dlopen)
+// alongside OSXSpeechSynthesizerService.
+
+#include <AudioToolbox/AudioToolbox.h>
+#include <math.h>
+
+namespace {
+
+constexpr float kMaxSampleMagnitude = 16.0f;
+
+void SanitizeBuffer(AudioQueueRef aQueue, AudioQueueBufferRef aBuffer) {
+ AudioStreamBasicDescription format;
+ UInt32 size = sizeof(format);
+ if (AudioQueueGetProperty(aQueue, kAudioQueueProperty_StreamDescription,
+ &format, &size) != noErr) {
+ return;
+ }
+ if (format.mFormatID != kAudioFormatLinearPCM ||
+ !(format.mFormatFlags & kAudioFormatFlagIsFloat) ||
+ format.mBitsPerChannel != 32) {
+ return;
+ }
+
+ float* samples = static_cast<float*>(aBuffer->mAudioData);
+ UInt32 count = aBuffer->mAudioDataByteSize / sizeof(float);
+ for (UInt32 i = 0; i < count; i++) {
+ // Written so that NaN also fails the comparison.
+ if (!(fabsf(samples[i]) <= kMaxSampleMagnitude)) {
+ samples[i] = 0.0f;
+ }
+ }
+}
+
+OSStatus SanitizingEnqueueBuffer(
+ AudioQueueRef aQueue, AudioQueueBufferRef aBuffer, UInt32 aNumPackets,
+ const AudioStreamPacketDescription* aPacketDescs) {
+ SanitizeBuffer(aQueue, aBuffer);
+ return AudioQueueEnqueueBuffer(aQueue, aBuffer, aNumPackets, aPacketDescs);
+}
+
+OSStatus SanitizingEnqueueBufferWithParameters(
+ AudioQueueRef aQueue, AudioQueueBufferRef aBuffer, UInt32 aNumPackets,
+ const AudioStreamPacketDescription* aPacketDescs, UInt32 aTrimFrames,
+ UInt32 aTrimFramesAtEnd, UInt32 aNumParamValues,
+ const AudioQueueParameterEvent* aParamValues,
+ const AudioTimeStamp* aStartTime, AudioTimeStamp* aActualStartTime) {
+ SanitizeBuffer(aQueue, aBuffer);
+ return AudioQueueEnqueueBufferWithParameters(
+ aQueue, aBuffer, aNumPackets, aPacketDescs, aTrimFrames,
+ aTrimFramesAtEnd, aNumParamValues, aParamValues, aStartTime,
+ aActualStartTime);
+}
+
+struct Interpose {
+ const void* mReplacement;
+ const void* mReplacee;
+};
+
+__attribute__((used, section("__DATA,__interpose"))) const Interpose
+ kInterposes[] = {
+ {reinterpret_cast<const void*>(&SanitizingEnqueueBuffer),
+ reinterpret_cast<const void*>(&AudioQueueEnqueueBuffer)},
+ {reinterpret_cast<const void*>(&SanitizingEnqueueBufferWithParameters),
+ reinterpret_cast<const void*>(
+ &AudioQueueEnqueueBufferWithParameters)},
+};
+
+} // namespace
diff --git a/mozglue/build/SpeechSynthesizerFlusher.cpp b/mozglue/build/SpeechSynthesizerFlusher.cpp
new file mode 100644
index 000000000000..d911e0d4b03b
--- /dev/null
+++ b/mozglue/build/SpeechSynthesizerFlusher.cpp
@@ -0,0 +1,215 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// Work around a leak in the macOS 27 system speech synthesizer.
+//
+// When an utterance is stopped mid-sentence, the synthesis job in the speech
+// extension process (MauiAUSP) stays blocked waiting to hand off audio that
+// will never be played. If the NSSpeechSynthesizer is then released, job
+// stays blocked forever and pins its voice model (~150-250 MB for premium
+// voices). OSXSpeechSynthesizerService creates and releases a synthesizer
+// for every utterance, so every speechSynthesis.cancel() call leaks.
+//
+// Starting another utterance on the same synthesizer and letting it finish
+// unblocks the job. So we swizzle NSSpeechSynthesizer to remember when it was
+// stopped, and when the delegate of a stopped synthesizer is cleared, we
+// keep it alive and have it speak a short silence, then release it once that
+// has finished.
+//
+// mozglue doesn't link against AppKit, so we use the Objective-C runtime
+// directly and install the swizzles once AppKit has been loaded.
+
+#include <dlfcn.h>
+#include <mach-o/dyld.h>
+#include <objc/message.h>
+#include <objc/runtime.h>
+#include <atomic>
+
+namespace {
+
+std::atomic<bool> sInstalled{false};
+
+// Associated object keys marking a synthesizer that was stopped and one
+// that we're keeping alive while it speaks the silence
+char sStoppedKey;
+char sFlushingKey;
+
+Class sSynthClass;
+// Delegate that releases a synthesizer once it has finished the silence
+id sFlushDelegate;
+
+IMP sOrigStopSpeaking;
+IMP sOrigStopSpeakingAtBoundary;
+IMP sOrigSetDelegate;
+
+void SetFlag(id aSelf, const void* aKey, bool aValue) {
+ // Any non-nil value works, and the class object never needs retaining
+ objc_setAssociatedObject(aSelf, aKey, aValue ? (id)sSynthClass : nil,
+ OBJC_ASSOCIATION_ASSIGN);
+}
+
+bool GetFlag(id aSelf, const void* aKey) {
+ return objc_getAssociatedObject(aSelf, aKey);
+}
+
+void MarkStopped(id aSelf) { SetFlag(aSelf, &sStoppedKey, true); }
+
+void OrigSetDelegate(id aSelf, id aDelegate) {
+ reinterpret_cast<void (*)(id, SEL, id)>(sOrigSetDelegate)(
+ aSelf, sel_registerName("setDelegate:"), aDelegate);
+}
+
+void FinishFlush(id aSelf) {
+ SetFlag(aSelf, &sFlushingKey, false);
+ OrigSetDelegate(aSelf, nil);
+ reinterpret_cast<void (*)(id, SEL)>(objc_msgSend)(aSelf,
+ sel_registerName("release"));
+}
+
+// -[FlushDelegate speechSynthesizer:didFinishSpeaking:]
+void FlushDidFinishSpeaking(id aSelf, SEL aCmd, id aSynth, BOOL aFinished) {
+ if (GetFlag(aSynth, &sFlushingKey)) {
+ FinishFlush(aSynth);
+ }
+}
+
+bool EnsureFlushDelegate() {
+ if (sFlushDelegate) {
+ return true;
+ }
+ const char* name = "MozSpeechSynthesizerFlushDelegate";
+ Class cls = objc_lookUpClass(name);
+ if (!cls) {
+ cls = objc_allocateClassPair(objc_lookUpClass("NSObject"), name, 0);
+ if (!cls) {
+ return false;
+ }
+ class_addMethod(cls, sel_registerName("speechSynthesizer:didFinishSpeaking:"),
+ reinterpret_cast<IMP>(FlushDidFinishSpeaking), "v@:@c");
+ objc_registerClassPair(cls);
+ }
+ // Kept for the life of the process
+ sFlushDelegate = reinterpret_cast<id (*)(Class, SEL)>(objc_msgSend)(
+ cls, sel_registerName("new"));
+ return sFlushDelegate;
+}
+
+void Flush(id aSelf) {
+ if (!EnsureFlushDelegate()) {
+ return;
+ }
+
+ // Keep the synthesizer alive until the silence has finished
+ reinterpret_cast<id (*)(id, SEL)>(objc_msgSend)(aSelf,
+ sel_registerName("retain"));
+ SetFlag(aSelf, &sFlushingKey, true);
+ OrigSetDelegate(aSelf, sFlushDelegate);
+
+ // [self setObject:@0.0f forProperty:NSSpeechVolumeProperty error:nil]
+ auto* volumeProperty =
+ static_cast<id*>(dlsym(RTLD_DEFAULT, "NSSpeechVolumeProperty"));
+ if (volumeProperty) {
+ id volume = reinterpret_cast<id (*)(Class, SEL, float)>(objc_msgSend)(
+ objc_lookUpClass("NSNumber"), sel_registerName("numberWithFloat:"),
+ 0.0f);
+ reinterpret_cast<BOOL (*)(id, SEL, id, id, id*)>(objc_msgSend)(
+ aSelf, sel_registerName("setObject:forProperty:error:"), volume,
+ *volumeProperty, nullptr);
+ }
+
+ // [self startSpeakingString:@"[[slnc 1]]"]
+ id silence = reinterpret_cast<id (*)(id, SEL, const char*)>(objc_msgSend)(
+ reinterpret_cast<id (*)(Class, SEL)>(objc_msgSend)(
+ objc_lookUpClass("NSString"), sel_registerName("alloc")),
+ sel_registerName("initWithUTF8String:"), "[[slnc 1]]");
+ BOOL started = reinterpret_cast<BOOL (*)(id, SEL, id)>(objc_msgSend)(
+ aSelf, sel_registerName("startSpeakingString:"), silence);
+ reinterpret_cast<void (*)(id, SEL)>(objc_msgSend)(silence,
+ sel_registerName("release"));
+ if (!started) {
+ FinishFlush(aSelf);
+ }
+}
+
+void StopSpeaking(id aSelf, SEL aCmd) {
+ reinterpret_cast<void (*)(id, SEL)>(sOrigStopSpeaking)(aSelf, aCmd);
+ MarkStopped(aSelf);
+}
+
+void StopSpeakingAtBoundary(id aSelf, SEL aCmd, long aBoundary) {
+ reinterpret_cast<void (*)(id, SEL, long)>(sOrigStopSpeakingAtBoundary)(
+ aSelf, aCmd, aBoundary);
+ MarkStopped(aSelf);
+}
+
+void SetDelegate(id aSelf, SEL aCmd, id aDelegate) {
+ if (GetFlag(aSelf, &sFlushingKey)) {
+ // The owner clearing the delegate again (e.g., right before releasing the
+ // synthesizer) mustn't cut the flush short
+ if (!aDelegate) {
+ return;
+ }
+ // Someone is using the synthesizer again, which unblocks the job too
+ FinishFlush(aSelf);
+ }
+
+ OrigSetDelegate(aSelf, aDelegate);
+ if (aDelegate || !GetFlag(aSelf, &sStoppedKey)) {
+ return;
+ }
+ SetFlag(aSelf, &sStoppedKey, false);
+
+ // Don't interrupt an utterance started after the stop. That would have
+ // unblocked the job anyway.
+ if (reinterpret_cast<BOOL (*)(id, SEL)>(objc_msgSend)(
+ aSelf, sel_registerName("isSpeaking"))) {
+ return;
+ }
+ Flush(aSelf);
+}
+
+IMP Swizzle(Class aClass, const char* aSelector, IMP aReplacement) {
+ Method method = class_getInstanceMethod(aClass, sel_registerName(aSelector));
+ return method ? method_setImplementation(method, aReplacement) : nullptr;
+}
+
+void MaybeInstall(const struct mach_header*, intptr_t) {
+ if (sInstalled) {
+ return;
+ }
+ // This runs while dyld is loading images, before their initializers have
+ // run, so only touch the runtime's metadata here -- no messages.
+ Class synthClass = objc_lookUpClass("NSSpeechSynthesizer");
+ if (!synthClass ||
+ !class_getInstanceMethod(synthClass, sel_registerName("stopSpeaking")) ||
+ !class_getInstanceMethod(synthClass,
+ sel_registerName("stopSpeakingAtBoundary:")) ||
+ !class_getInstanceMethod(synthClass, sel_registerName("setDelegate:"))) {
+ return;
+ }
+ if (sInstalled.exchange(true)) {
+ return;
+ }
+
+ sSynthClass = synthClass;
+ sOrigStopSpeaking =
+ Swizzle(synthClass, "stopSpeaking", reinterpret_cast<IMP>(StopSpeaking));
+ sOrigStopSpeakingAtBoundary =
+ Swizzle(synthClass, "stopSpeakingAtBoundary:",
+ reinterpret_cast<IMP>(StopSpeakingAtBoundary));
+ sOrigSetDelegate =
+ Swizzle(synthClass, "setDelegate:", reinterpret_cast<IMP>(SetDelegate));
+}
+
+__attribute__((constructor)) void Init() {
+ // Only the speech synthesizer in macOS 27 leaks
+ if (__builtin_available(macOS 27, *)) {
+ // Called for every image already loaded and every image loaded later
+ _dyld_register_func_for_add_image(MaybeInstall);
+ }
+}
+
+} // namespace
diff --git a/mozglue/build/moz.build b/mozglue/build/moz.build
index f8f01e999e54..06695499daa4 100644
--- a/mozglue/build/moz.build
+++ b/mozglue/build/moz.build
@@ -41,6 +41,16 @@ if CONFIG["OS_TARGET"] == "WINNT":
"winmm.dll",
]
+if CONFIG["OS_TARGET"] == "Darwin" and FORCE_SHARED_LIB:
+ SOURCES += [
+ "AudioQueueSanitizer.cpp",
+ "SpeechSynthesizerFlusher.cpp",
+ ]
+ OS_LIBS += [
+ "-framework AudioToolbox",
+ "-lobjc",
+ ]
+
if CONFIG["MOZ_WIDGET_TOOLKIT"]:
if CONFIG["MOZ_MEMORY"] and FORCE_SHARED_LIB:
pass