Undefined behavior in PLDHashTable::operator=()
The move-assignment operator of a hash table class destroys the destination object and then reads and writes its non-static members, which is undefined behaviour under C++11. The code is reached in practice, for example while Firefox rebuilds approximate frame visibility on a real page, so it may explain some related crashes.
Originally disclosed on Mozilla
- Fixed in 7 days
- Paid in 18 days
- Disclosed after 7 days
PLDHashTable::operator=() (xpcom/ds/PLDHashTable.cpp) invokes undefined behavior by destroying |this|, then using the destructed object's nonstatic member variables. This directly violates C++11 s.3.8, which says:
The lifetime of an object of type T ends when: — if T is a class type with a non-trivial destructor (12.4), the destructor call starts...
[A]fter the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object will be or was located may be used but only in limited ways. For an object under construction or destruction, see 12.7. Otherwise, such a pointer refers to allocated storage (3.7.4.2), and using the pointer as if the pointer were of type void*, is well-defined. Such a pointer may be dereferenced but the resulting lvalue may only be used in limited ways, as described below.
**** The program has undefined behavior if:... — the pointer is used to access a non-static data member or call a non-static member function of the object.... ****
(emphasis added).
The bug is on lines 235, 236, 239, et seq., and on every other non-static member variable reference thereafter made to the destination object (and also the delete call that ultimately destroys it):
220: PLDHashTable& 221: PLDHashTable::operator=(PLDHashTable&& aOther) 222: { 223: if (this == &aOther) { 224: return *this; 225: } 226: 227: // Destruct |this|. 228: this->~PLDHashTable(); 229: 230: // |mOps| and |mEntrySize| are const so we can't assign them. Instead, we 231: // require that they are equal. The justification for this is that they're 232: // conceptually part of the type -- indeed, if PLDHashTable was a templated 233: // type like nsTHashtable, they would be part of the type -- so it only 234: // makes sense to assign in cases where they match. 235: MOZ_RELEASE_ASSERT(mOps == aOther.mOps); 236: MOZ_RELEASE_ASSERT(mEntrySize == aOther.mEntrySize); 237: 238: // Move non-const pieces over. 239: mHashShift = Move(aOther.mHashShift); 240: mEntryCount = Move(aOther.mEntryCount); 241: mRemovedCount = Move(aOther.mRemovedCount); 242: mEntryStore.Set(aOther.mEntryStore.Get(), &mGeneration); 243: #ifdef DEBUG 244: mChecker = Move(aOther.mChecker); 245: #endif 246: 247: // Clear up |aOther| so its destruction will be a no-op. 248: { 249: #ifdef DEBUG 250: AutoDestructorOp op(mChecker); 251: #endif 252: aOther.mEntryStore.Set(nullptr, &aOther.mGeneration); 253: } 254: 255: return *this; 256: }
This code is actually used (with a nonidentical source object), though DXR says that it isn't [1]. I found one usage by attaching a debugger to FF and loading https://www.washingtonpost.com , with the stack:
xul.dll!PLDHashTable::operator=(PLDHashTable && aOther) Line 228 C++ xul.dll!PLDHashTable::PLDHashTable(PLDHashTable && aOther) Line 301 C++ xul.dll!mozilla::Swap<PLDHashTable>(PLDHashTable & aX, PLDHashTable & aY) Line 232 C++ xul.dll!nsTHashtabledetail::VoidPtrHashKey::SwapElements(nsTHashtabledetail::VoidPtrHashKey & aOther) Line 331 C++ xul.dll!nsTHashtable<nsPtrHashKey<nsIFrame> >::SwapElements(nsTHashtable<nsPtrHashKey<nsIFrame> > & aOther) Line 623 C++ xul.dll!mozilla::PresShell::RebuildApproximateFrameVisibility(nsRect * aRect, bool aRemoveOnly) Line 6069 C++ xul.dll!mozilla::PresShell::DoUpdateApproximateFrameVisibility(bool aRemoveOnly) Line 6112 C++ xul.dll!mozilla::PresShell::UpdateApproximateFrameVisibility() Line 6090 C++ xul.dll!mozilla::detail::RunnableMethodArguments<>::applyImpl<mozilla::PresShell,void (__cdecl mozilla::PresShell::)(void) __ptr64>(mozilla::PresShell * o, void(mozilla::PresShell::)() m, mozilla::Tuple<> & args, mozilla::IndexSequence<> __formal) Line 1143 C++ xul.dll!mozilla::detail::RunnableMethodArguments<>::apply<mozilla::PresShell,void (__cdecl mozilla::PresShell::)(void) __ptr64>(mozilla::PresShell * o, void(mozilla::PresShell::)() m) Line 1150 C++ xul.dll!mozilla::detail::RunnableMethodImpl<mozilla::PresShell * __ptr64,void (__cdecl mozilla::PresShell::*)(void) __ptr64,1,0>::Run() Line 1195 C++ xul.dll!mozilla::SchedulerGroup::Runnable::Run() Line 396 C++ xul.dll!nsThread::ProcessNextEvent(bool aMayWait, bool * aResult) Line 1038 C++ xul.dll!NS_ProcessNextEvent(nsIThread * aThread, bool aMayWait) Line 513 C++ xul.dll!mozilla::ipc::MessagePump::Run(base::MessagePump::Delegate * aDelegate) Line 97 C++ xul.dll!mozilla::ipc::MessagePumpForChildProcess::Run(base::MessagePump::Delegate * aDelegate) Line 302 C++ xul.dll!MessageLoop::RunInternal() Line 327 C++ xul.dll!MessageLoop::RunHandler() Line 320 C++ xul.dll!MessageLoop::Run() Line 300 C++ xul.dll!nsBaseAppShell::Run() Line 161 C++ xul.dll!nsAppShell::Run() Line 230 C++ xul.dll!XRE_RunAppShell() Line 877 C++ xul.dll!mozilla::ipc::MessagePumpForChildProcess::Run(base::MessagePump::Delegate * aDelegate) Line 269 C++ xul.dll!MessageLoop::RunInternal() Line 327 C++ xul.dll!MessageLoop::RunHandler() Line 320 C++ xul.dll!MessageLoop::Run() Line 300 C++ xul.dll!XRE_InitChildProcess(int aArgc, char * * aArgv, const XREChildData * aChildData) Line 707 C++ xul.dll!mozilla::BootstrapImpl::XRE_InitChildProcess(int argc, char * * argv, const XREChildData * aChildData) Line 70 C++ firefox.exe!content_process_main(mozilla::Bootstrap * bootstrap, int argc, char * * argv) Line 63 C++ firefox.exe!NS_internal_main(int argc, char * * argv, char * * envp) Line 280 C++ firefox.exe!wmain(int argc, wchar_t * * argv) Line 111 C++ [External Code]
Maybe this bug is behind some of the numerous PLDHashTable-related crashes that have been reported? https://bugzilla.mozilla.org/buglist.cgi?quicksearch=PLDHashTable .
[1] DXR indicates that operator=(&&) is called only by the PLDHashTable's move contructor, which DXR then says is used only by xpcom/tests/gtest/TestPLDHash.cpp . Alas, DXR sometimes misses uses.
Context
This report is about a C++ correctness bug in Mozilla's XPCOM layer, specifically in PLDHashTable, the hash table implementation in xpcom/ds/PLDHashTable.cpp. PLDHashTable is a low-level container used throughout Gecko, and it supports move assignment through PLDHashTable::operator=(PLDHashTable&& aOther). The report is not about a remotely reachable memory-safety exploit in the usual web sense; it is about code that invokes undefined behaviour under the C++11 standard, with the potential to cause crashes.
The weakness class recorded for the report is undefined behaviour, and the affected asset is Core: XPCOM. The report was disclosed on 13 April 2018.
Setup
The researcher worked against a Firefox build on Windows, judging by the debugger stack, which shows xul.dll and firefox.exe frames. The tool used was a debugger attached to Firefox. The test case was simply loading a public website:
https://www.washingtonpost.com
No accounts, special configuration or crafted input are described. The precondition for the bug to matter is that the move assignment operator is actually reached at runtime with a source object that is not the destination, which the researcher set out to confirm because static analysis suggested otherwise.
Finding it
The report explains that PLDHashTable::operator=() destroys this and then keeps using the destroyed object's non-static member variables. The relevant code, as quoted in the report, is:
220: PLDHashTable&
221: PLDHashTable::operator=(PLDHashTable&& aOther)
222: {
223: if (this == &aOther) {
224: return *this;
225: }
226:
227: // Destruct |this|.
228: this->~PLDHashTable();
229:
230: // |mOps| and |mEntrySize| are const so we can't assign them. Instead, we
231: // require that they are equal. The justification for this is that they're
232: // conceptually part of the type -- indeed, if PLDHashTable was a templated
233: // type like nsTHashtable, they *would* be part of the type -- so it only
234: // makes sense to assign in cases where they match.
235: MOZ_RELEASE_ASSERT(mOps == aOther.mOps);
236: MOZ_RELEASE_ASSERT(mEntrySize == aOther.mEntrySize);
237:
238: // Move non-const pieces over.
239: mHashShift = Move(aOther.mHashShift);
240: mEntryCount = Move(aOther.mEntryCount);
241: mRemovedCount = Move(aOther.mRemovedCount);
242: mEntryStore.Set(aOther.mEntryStore.Get(), &mGeneration);
243: #ifdef DEBUG
244: mChecker = Move(aOther.mChecker);
245: #endif
246:
247: // Clear up |aOther| so its destruction will be a no-op.
248: {
249: #ifdef DEBUG
250: AutoDestructorOp op(mChecker);
251: #endif
252: aOther.mEntryStore.Set(nullptr, &aOther.mGeneration);
253: }
254:
255: return *this;
256: }
The problem is on lines 235, 236 and 239 onwards, and on every later reference to a non-static member variable of the destination object, including the delete call that ultimately destroys it. The report cites C++11 section 3.8, which states that the lifetime of an object of a class type with a non-trivial destructor ends when the destructor call starts. After that point, a pointer to the storage may be used only in limited ways, and the program has undefined behaviour if the pointer is used to access a non-static data member or to call a non-static member function of the object. The report reproduces the standard text and emphasises that clause.
The researcher also checked whether the operator is reachable. DXR, Mozilla's source cross-reference tool, indicated that operator=(&&) is called only by the PLDHashTable move constructor, which DXR in turn said is used only by xpcom/tests/gtest/TestPLDHash.cpp. The researcher notes that DXR sometimes misses uses, and found a real usage at runtime.
Exploitation
Step 1: attach a debugger and load a page
The researcher attached a debugger to Firefox and loaded the Washington Post site. The move assignment operator was hit. The stack captured was:
> xul.dll!PLDHashTable::operator=(PLDHashTable && aOther) Line 228 C++
xul.dll!PLDHashTable::PLDHashTable(PLDHashTable && aOther) Line 301 C++
xul.dll!mozilla::Swap<PLDHashTable>(PLDHashTable & aX, PLDHashTable & aY) Line 232 C++
xul.dll!nsTHashtable<detail::VoidPtrHashKey>::SwapElements(nsTHashtable<detail::VoidPtrHashKey> & aOther) Line 331 C++
xul.dll!nsTHashtable<nsPtrHashKey<nsIFrame> >::SwapElements(nsTHashtable<nsPtrHashKey<nsIFrame> > & aOther) Line 623 C++
xul.dll!mozilla::PresShell::RebuildApproximateFrameVisibility(nsRect * aRect, bool aRemoveOnly) Line 6069 C++
xul.dll!mozilla::PresShell::DoUpdateApproximateFrameVisibility(bool aRemoveOnly) Line 6112 C++
xul.dll!mozilla::PresShell::UpdateApproximateFrameVisibility() Line 6090 C++
xul.dll!mozilla::detail::RunnableMethodArguments<>::applyImpl<mozilla::PresShell,void (__cdecl mozilla::PresShell::*)(void) __ptr64>(mozilla::PresShell * o, void(mozilla::PresShell::*)() m, mozilla::Tuple<> & args, mozilla::IndexSequence<> __formal) Line 1143 C++
xul.dll!mozilla::detail::RunnableMethodArguments<>::apply<mozilla::PresShell,void (__cdecl mozilla::PresShell::*)(void) __ptr64>(mozilla::PresShell * o, void(mozilla::PresShell::*)() m) Line 1150 C++
xul.dll!mozilla::detail::RunnableMethodImpl<mozilla::PresShell * __ptr64,void (__cdecl mozilla::PresShell::*)(void) __ptr64,1,0>::Run() Line 1195 C++
xul.dll!mozilla::SchedulerGroup::Runnable::Run() Line 396 C++
xul.dll!nsThread::ProcessNextEvent(bool aMayWait, bool * aResult) Line 1038 C++
xul.dll!NS_ProcessNextEvent(nsIThread * aThread, bool aMayWait) Line 513 C++
xul.dll!mozilla::ipc::MessagePump::Run(base::MessagePump::Delegate * aDelegate) Line 97 C++
xul.dll!mozilla::ipc::MessagePumpForChildProcess::Run(base::MessagePump::Delegate * aDelegate) Line 302 C++
xul.dll!MessageLoop::RunInternal() Line 327 C++
xul.dll!MessageLoop::RunHandler() Line 320 C++
xul.dll!MessageLoop::Run() Line 300 C++
xul.dll!nsBaseAppShell::Run() Line 161 C++
xul.dll!nsAppShell::Run() Line 230 C++
xul.dll!XRE_RunAppShell() Line 877 C++
xul.dll!mozilla::ipc::MessagePumpForChildProcess::Run(base::MessagePump::Delegate * aDelegate) Line 269 C++
xul.dll!MessageLoop::RunInternal() Line 327 C++
xul.dll!MessageLoop::RunHandler() Line 320 C++
xul.dll!MessageLoop::Run() Line 300 C++
xul.dll!XRE_InitChildProcess(int aArgc, char * * aArgv, const XREChildData * aChildData) Line 707 C++
xul.dll!mozilla::BootstrapImpl::XRE_InitChildProcess(int argc, char * * argv, const XREChildData * aChildData) Line 70 C++
firefox.exe!content_process_main(mozilla::Bootstrap * bootstrap, int argc, char * * argv) Line 63 C++
firefox.exe!NS_internal_main(int argc, char * * argv, char * * envp) Line 280 C++
firefox.exe!wmain(int argc, wchar_t * * argv) Line 111 C++
[External Code]
The stack shows the path that reaches the operator. PresShell::UpdateApproximateFrameVisibility() runs on a scheduler runnable, calls DoUpdateApproximateFrameVisibility(), which calls RebuildApproximateFrameVisibility(). That function calls SwapElements() on an nsTHashtable<nsPtrHashKey<nsIFrame>>, which calls SwapElements() on an nsTHashtable<detail::VoidPtrHashKey>, which calls mozilla::Swap<PLDHashTable>, which invokes the PLDHashTable move constructor, which calls the move assignment operator. The breakpoint lands on line 228, the explicit destructor call.
This confirms that the operator is used in normal browsing, not only in the gtest file that DXR pointed to.
Step 2: consider the crash reports
The researcher raises the question of whether this bug is behind some of the numerous PLDHashTable-related crashes that have been reported, linking to a Bugzilla quicksearch for PLDHashTable:
https://bugzilla.mozilla.org/buglist.cgi?quicksearch=PLDHashTable
That is posed as a question, not established as fact.
Root cause
The move assignment operator destroys this with an explicit destructor call and then reads and writes non-static members of the destroyed object: mOps and mEntrySize in the release assertions, then mHashShift, mEntryCount, mRemovedCount, mEntryStore and mGeneration, and in debug builds mChecker. It also returns *this and leaves the object to be destroyed again later. Under C++11 section 3.8, the object's lifetime ends when the destructor call starts, so all of those accesses are undefined behaviour.
The design intent is visible in the comments: mOps and mEntrySize are const, so they cannot be assigned, and the code instead asserts that they match between source and destination. The researcher's point is that this reasoning does not make the post-destruction access legal; the object is already gone when the assertions and the moves run.
The existing checks did not prevent the bug. The self-assignment guard at the top only handles this == &aOther; it does nothing about the lifetime problem. The release assertions compare members of a destroyed object, so they are themselves part of the undefined behaviour rather than a defence against it. Static analysis via DXR suggested the operator was effectively unused outside tests; the runtime stack shows that conclusion was wrong.
Impact
The report frames the impact as undefined behaviour that can plausibly cause crashes. The researcher asks whether the bug is behind some of the many PLDHashTable-related crashes reported in Bugzilla, but does not demonstrate a specific crash, memory corruption primitive or attacker-controlled outcome. The reachable path shown is ordinary page loading of one site, which reaches the frame visibility code. No confidentiality or integrity impact is claimed.
Fix
The report does not describe a fix or a patch. The code as quoted destroys this and then uses its members, and any correction would have to avoid using the destination object after its destructor has run, for example by restructuring the move assignment so that members are not accessed after the explicit destructor call. The report itself only identifies the defect.
Variants to test
- Look for other move assignment operators that call an explicit destructor on
thisand then touch members. A positive result is a stack or code path where the operator runs with distinct source and destination objects and the members are read or written after the destructor call. - Check containers built on top of such a type, such as
nsTHashtablespecialisations, forSwaporSwapElementspaths that reach the operator during normal browsing. A positive result is a debugger breakpoint on the destructor call hit without any test harness. - Compare static analysis results with runtime behaviour for move constructors and assignment operators. A positive result is a use that the cross-reference tool reports as test-only but that a debugger shows in production code.
- Review release assertions that read members of an object whose lifetime has ended. A positive result is an assertion whose operands are members of a destroyed object.
Hunting notes
This kind of bug hides in low-level C++ infrastructure: containers, smart pointers and utility types where move semantics and explicit destructor calls are used to implement assignment. The signal during review is an explicit this->~T() followed by any member access, return of *this, or later destruction. Static cross-reference tools can under-report uses, so a runtime breakpoint on the destructor call while loading an ordinary page is a cheap way to confirm reachability. In this case the researcher demonstrated a real call path from page load through PresShell frame visibility code into the operator.
What happened, in plain words
Firefox is a web browser. Inside Firefox there is a large amount of code written in a programming language called C++. That code is organised into layers, and one of the lowest layers is called XPCOM. XPCOM provides building blocks that the rest of the browser uses, a bit like the plumbing and wiring inside a house that you never see but that everything depends on.
One of those building blocks is a hash table. A hash table is a way of storing a collection of items so that you can find a particular item again very quickly, without checking every item one by one. Think of a cloakroom: you hand over your coat, you get a numbered ticket, and later the number takes you straight to your coat instead of you searching every hanger. The hash table in this report is called PLDHashTable, and it lives in a file called xpcom/ds/PLDHashTable.cpp.
PLDHashTable supports an operation called move assignment. Move assignment is a way of saying "take everything that belongs to object B and put it into object A, and leave B empty". It is used when the browser wants to shuffle data between two containers efficiently rather than copying it all. In C++ this operation is written as PLDHashTable::operator=(PLDHashTable&& aOther).
The problem the researcher found is that this move assignment operation first deliberately destroys the destination object (the one on the left of the equals sign), and then carries on reading and writing that same object's internal fields. In C++, once an object has been destroyed, using it is not allowed. The C++11 standard, which is the rulebook for the language, says this is undefined behaviour. Undefined behaviour means the language makes no promises at all about what the program will do: it might work, it might crash, it might do something strange. It is like reading a page of a book after you have already thrown the book in the fire: sometimes you might still be holding a loose page, but you have no right to expect anything.
This report is not about an attacker breaking into a website or stealing data over the internet in the usual sense. It is about a correctness bug in the browser's own code that can plausibly cause crashes. The weakness class recorded for the report is undefined behaviour, and the affected asset is Core: XPCOM. The report was disclosed on 13 April 2018.
Context
This report is about a C++ correctness bug in Mozilla's XPCOM layer, specifically in PLDHashTable, the hash table implementation in xpcom/ds/PLDHashTable.cpp. PLDHashTable is a low-level container used throughout Gecko, which is the engine inside Firefox that actually renders web pages. The container supports move assignment through PLDHashTable::operator=(PLDHashTable&& aOther).
The report is not about a remotely reachable memory-safety exploit in the usual web sense. It is about code that invokes undefined behaviour under the C++11 standard, with the potential to cause crashes. To unpack that: a memory-safety exploit is when an attacker can make a program read or write memory it should not, and use that to take control. This report does not claim that. It claims the code breaks the rules of the language, and that breaking those rules can lead to crashes.
Setup
The researcher worked against a Firefox build on Windows, judging by the debugger stack, which shows xul.dll and firefox.exe frames. A debugger is a tool that lets you pause a running program, look at exactly which line of code it is on, and inspect the values it is holding. It is like being able to freeze a film at any frame and examine every detail. xul.dll and firefox.exe are the names of the program files on Windows: .exe is a runnable program, and .dll is a shared library of code that the program loads.
The tool used was a debugger attached to Firefox. The test case was simply loading a public website:
https://www.washingtonpost.com
This is an ordinary web address for a news website. There is nothing special about it: no strange characters, no hidden parameters, no trick. Loading it showed that the buggy code runs during normal browsing.
No accounts, special configuration or crafted input are described. The precondition for the bug to matter is that the move assignment operator is actually reached at runtime with a source object that is not the destination. In plain words: the buggy operation has to actually run, and it has to run with two different objects (one being emptied into the other), not with an object being assigned to itself. Static analysis suggested otherwise, but the researcher found a real usage. Static analysis means examining the code without running it, the way you might proofread a recipe rather than cook it. It can miss things that only show up when the program actually runs.
Finding it
The report explains that PLDHashTable::operator=() destroys this and then keeps using the destroyed object's non-static member variables. Two terms need unpacking here. this is C++ shorthand for "the object this code belongs to", the destination object in an assignment. A member variable is a field stored inside an object, like the individual drawers inside a filing cabinet. "Non-static" means the field belongs to each individual object rather than being shared by all objects of that type.
The relevant code, as quoted in the report, is:
220: PLDHashTable&
221: PLDHashTable::operator=(PLDHashTable&& aOther)
222: {
223: if (this == &aOther) {
224: return *this;
225: }
226:
227: // Destruct |this|.
228: this->~PLDHashTable();
229:
230: // |mOps| and |mEntrySize| are const so we can't assign them. Instead, we
231: // require that they are equal. The justification for this is that they're
232: // conceptually part of the type -- indeed, if PLDHashTable was a templated
233: // type like nsTHashtable, they *would* be part of the type -- so it only
234: // makes sense to assign in cases where they match.
235: MOZ_RELEASE_ASSERT(mOps == aOther.mOps);
236: MOZ_RELEASE_ASSERT(mEntrySize == aOther.mEntrySize);
237:
238: // Move non-const pieces over.
239: mHashShift = Move(aOther.mHashShift);
240: mEntryCount = Move(aOther.mEntryCount);
241: mRemovedCount = Move(aOther.mRemovedCount);
242: mEntryStore.Set(aOther.mEntryStore.Get(), &mGeneration);
243: #ifdef DEBUG
244: mChecker = Move(aOther.mChecker);
245: #endif
246:
247: // Clear up |aOther| so its destruction will be a no-op.
248: {
249: #ifdef DEBUG
250: AutoDestructorOp op(mChecker);
251: #endif
252: aOther.mEntryStore.Set(nullptr, &aOther.mGeneration);
253: }
254:
255: return *this;
256: }
Line by line, in plain words:
- Line 220 says the function returns a reference to a
PLDHashTable. A reference is another name for an existing object, not a copy. - Line 221 is the function signature: this is the move assignment operator, taking another
PLDHashTablecalledaOtheras its source. - Lines 223 to 225 are a safety check for the case where someone assigns an object to itself. If
thisandaOtherare the same object, it simply returns immediately. This is the self-assignment guard. - Line 227 is a comment saying the next line destroys
this. - Line 228 is the explicit destructor call. A destructor is the special function that runs when an object is being cleaned up. Calling it by hand like this means "destroy this object right now".
- Lines 230 to 234 are a comment explaining that
mOpsandmEntrySizeareconst, meaning they cannot be changed after creation, so the code cannot copy them across. Instead it requires that they already match. - Lines 235 and 236 are assertions that check
mOpsandmEntrySizeare equal between the two objects. An assertion is a check that stops the program if something unexpected is true.MOZ_RELEASE_ASSERTis Mozilla's version that stays active even in release builds, not just debug builds. - Lines 238 to 242 copy the remaining fields across:
mHashShift,mEntryCount,mRemovedCount, and the entry store along withmGeneration.Moveis a helper that transfers a value efficiently. - Lines 243 to 245 do the same for
mChecker, but only in debug builds, because of the#ifdef DEBUG. - Lines 247 to 253 tidy up the source object so that when it is later destroyed normally, that destruction does nothing harmful.
- Line 255 returns the destination object.
The problem is on lines 235, 236 and 239 onwards, and on every later reference to a non-static member variable of the destination object, including the delete call that ultimately destroys it. In other words, after line 228 has destroyed the object, the code keeps opening its drawers.
The report cites C++11 section 3.8, which states that the lifetime of an object of a class type with a non-trivial destructor ends when the destructor call starts. A non-trivial destructor is one that actually has work to do, rather than doing nothing. After that point, a pointer to the storage may be used only in limited ways, and the program has undefined behaviour if the pointer is used to access a non-static data member or to call a non-static member function of the object. The report reproduces the standard text and emphasises that clause.
The researcher also checked whether the operator is reachable. Reachable means there is a real path through the program that gets to this code. DXR, Mozilla's source cross-reference tool, indicated that operator=(&&) is called only by the PLDHashTable move constructor, which DXR in turn said is used only by xpcom/tests/gtest/TestPLDHash.cpp. A move constructor is the close cousin of move assignment: it builds a new object by taking another object's contents. A test file is code written only to check that things work, not code that ships to users. So static analysis was saying, in effect, "this code only runs in the test suite". The researcher notes that DXR sometimes misses uses, and set out to verify at runtime.
Exploitation
Step 1: attach a debugger and load a page
The researcher attached a debugger to Firefox and loaded the Washington Post site. The move assignment operator was hit. The stack captured was:
> xul.dll!PLDHashTable::operator=(PLDHashTable && aOther) Line 228 C++
xul.dll!PLDHashTable::PLDHashTable(PLDHashTable && aOther) Line 301 C++
xul.dll!mozilla::Swap<PLDHashTable>(PLDHashTable & aX, PLDHashTable & aY) Line 232 C++
xul.dll!nsTHashtable<detail::VoidPtrHashKey>::SwapElements(nsTHashtable<detail::VoidPtrHashKey> & aOther) Line 331 C++
xul.dll!nsTHashtable<nsPtrHashKey<nsIFrame> >::SwapElements(nsTHashtable<nsPtrHashKey<nsIFrame> > & aOther) Line 623 C++
xul.dll!mozilla::PresShell::RebuildApproximateFrameVisibility(nsRect * aRect, bool aRemoveOnly) Line 6069 C++
xul.dll!mozilla::PresShell::DoUpdateApproximateFrameVisibility(bool aRemoveOnly) Line 6112 C++
xul.dll!mozilla::PresShell::UpdateApproximateFrameVisibility() Line 6090 C++
xul.dll!mozilla::detail::RunnableMethodArguments<>::applyImpl<mozilla::PresShell,void (__cdecl mozilla::PresShell::*)(void) __ptr64>(mozilla::PresShell * o, void(mozilla::PresShell::*)() m, mozilla::Tuple<> & args, mozilla::IndexSequence<> __formal) Line 1143 C++
xul.dll!mozilla::detail::RunnableMethodArguments<>::apply<mozilla::PresShell,void (__cdecl mozilla::PresShell::*)(void) __ptr64>(mozilla::PresShell * o, void(mozilla::PresShell::*)() m) Line 1150 C++
xul.dll!mozilla::detail::RunnableMethodImpl<mozilla::PresShell * __ptr64,void (__cdecl mozilla::PresShell::*)(void) __ptr64,1,0>::Run() Line 1195 C++
xul.dll!mozilla::SchedulerGroup::Runnable::Run() Line 396 C++
xul.dll!nsThread::ProcessNextEvent(bool aMayWait, bool * aResult) Line 1038 C++
xul.dll!NS_ProcessNextEvent(nsIThread * aThread, bool aMayWait) Line 513 C++
xul.dll!mozilla::ipc::MessagePump::Run(base::MessagePump::Delegate * aDelegate) Line 97 C++
xul.dll!mozilla::ipc::MessagePumpForChildProcess::Run(base::MessagePump::Delegate * aDelegate) Line 302 C++
xul.dll!MessageLoop::RunInternal() Line 327 C++
xul.dll!MessageLoop::RunHandler() Line 320 C++
xul.dll!MessageLoop::Run() Line 300 C++
xul.dll!nsBaseAppShell::Run() Line 161 C++
xul.dll!nsAppShell::Run() Line 230 C++
xul.dll!XRE_RunAppShell() Line 877 C++
xul.dll!mozilla::ipc::MessagePumpForChildProcess::Run(base::MessagePump::Delegate * aDelegate) Line 269 C++
xul.dll!MessageLoop::RunInternal() Line 327 C++
xul.dll!MessageLoop::RunHandler() Line 320 C++
xul.dll!MessageLoop::Run() Line 300 C++
xul.dll!XRE_InitChildProcess(int aArgc, char * * aArgv, const XREChildData * aChildData) Line 707 C++
xul.dll!mozilla::BootstrapImpl::XRE_InitChildProcess(int argc, char * * argv, const XREChildData * aChildData) Line 70 C++
firefox.exe!content_process_main(mozilla::Bootstrap * bootstrap, int argc, char * * argv) Line 63 C++
firefox.exe!NS_internal_main(int argc, char * * argv, char * * envp) Line 280 C++
firefox.exe!wmain(int argc, wchar_t * * argv) Line 111 C++
[External Code]
A stack (or call stack) is the list of functions that are currently running, one calling the next. It is like a stack of letters where each letter says "I asked the letter below me to do this". The top line is where the program is paused; each line below is the function that called it. Reading from top to bottom tells you how the program got there.
Line by line, in plain words:
- The top line,
PLDHashTable::operator=(PLDHashTable && aOther) Line 228, is the buggy function, paused on line 228, the explicit destructor call. This is where the breakpoint was set. - The next line,
PLDHashTable::PLDHashTable(PLDHashTable && aOther) Line 301, is the move constructor calling the move assignment operator. mozilla::Swap<PLDHashTable>is a helper that swaps two objects by using move operations.nsTHashtable<detail::VoidPtrHashKey>::SwapElementsandnsTHashtable<nsPtrHashKey<nsIFrame> >::SwapElementsare two hash tables built on top ofPLDHashTablethat are swapping their contents.nsIFrameis a frame in the page layout, one of the boxes that make up what you see on screen.mozilla::PresShell::RebuildApproximateFrameVisibility,DoUpdateApproximateFrameVisibilityandUpdateApproximateFrameVisibilityare functions in the part of the browser that decides which parts of a page are visible on screen. This is a routine housekeeping task that runs while you browse.- The
RunnableMethod...lines andSchedulerGroup::Runnable::Runshow that this work was queued up to run later, like a task on a to-do list, rather than happening instantly. nsThread::ProcessNextEvent,NS_ProcessNextEvent,MessagePump::Runand theMessageLooplines are the browser's event loop: the endless cycle of "wait for something to happen, handle it, repeat".nsBaseAppShell::Run,nsAppShell::Run,XRE_RunAppShellandXRE_InitChildProcessare the startup and main loop of the browser process.content_process_main,NS_internal_mainandwmainare the very bottom of the program, where Windows starts it.[External Code]means the debugger could not see the code below that point.
The stack shows the path that reaches the operator. PresShell::UpdateApproximateFrameVisibility() runs on a scheduler runnable, calls DoUpdateApproximateFrameVisibility(), which calls RebuildApproximateFrameVisibility(). That function calls SwapElements() on an nsTHashtable<nsPtrHashKey<nsIFrame>>, which calls SwapElements() on an nsTHashtable<detail::VoidPtrHashKey>, which calls mozilla::Swap<PLDHashTable>, which invokes the PLDHashTable move constructor, which calls the move assignment operator. The breakpoint lands on line 228, the explicit destructor call.
This confirms that the operator is used in normal browsing, not only in the gtest file that DXR pointed to. In other words, the static analysis was wrong: the code really does run when you visit an ordinary page.
Step 2: consider the crash reports
The researcher raises the question of whether this bug is behind some of the numerous PLDHashTable-related crashes that have been reported, linking to a Bugzilla quicksearch for PLDHashTable:
https://bugzilla.mozilla.org/buglist.cgi?quicksearch=PLDHashTable
This is a web address that searches Mozilla's bug tracker, Bugzilla, for bugs mentioning PLDHashTable. A bug tracker is a database where developers record known problems. The researcher is asking whether the undefined behaviour is the hidden cause of crashes that were reported separately, without knowing their root cause. That is posed as a question, not established as fact.
Root cause
The move assignment operator destroys this with an explicit destructor call and then reads and writes non-static members of the destroyed object: mOps and mEntrySize in the release assertions, then mHashShift, mEntryCount, mRemovedCount, mEntryStore and mGeneration, and in debug builds mChecker. It also returns *this and leaves the object to be destroyed again later. Under C++11 section 3.8, the object's lifetime ends when the destructor call starts, so all of those accesses are undefined behaviour.
The design intent is visible in the comments: mOps and mEntrySize are const, so they cannot be assigned, and the code instead asserts that they match between source and destination. The researcher's point is that this reasoning does not make the post-destruction access legal; the object is already gone when the assertions and the moves run.
The existing checks did not prevent the bug. The self-assignment guard at the top only handles this == &aOther; it does nothing about the lifetime problem. The release assertions compare members of a destroyed object, so they are themselves part of the undefined behaviour rather than a defence against it. Static analysis via DXR suggested the operator was effectively unused outside tests; the runtime stack shows that conclusion was wrong.
Impact
The report frames the impact as undefined behaviour that can plausibly cause crashes. The researcher asks whether the bug is behind some of the many PLDHashTable-related crashes reported in Bugzilla, but does not demonstrate a specific crash, memory corruption primitive or attacker-controlled outcome. A memory corruption primitive is a reliable way for an attacker to make a program misbehave in a chosen way; the report does not show one. The reachable path shown is ordinary page loading of one site, which reaches the frame visibility code. No confidentiality or integrity impact is claimed, meaning the report does not say that data could be stolen or altered.
Fix
The code as quoted destroys this and then uses its members, and any correction would have to avoid using the destination object after its destructor has run, for example by restructuring the move assignment so that members are not accessed after the explicit destructor call. The report itself only identifies the defect.
Variants to test
- Look for other move assignment operators that call an explicit destructor on
thisand then touch members. A positive result is a stack or code path where the operator runs with distinct source and destination objects and the members are read or written after the destructor call. - Check containers built on top of such a type, such as
nsTHashtablespecialisations, forSwaporSwapElementspaths that reach the operator during normal browsing. A positive result is a debugger breakpoint on the destructor call hit without any test harness. - Compare static analysis results with runtime behaviour for move constructors and assignment operators. A positive result is a use that the cross-reference tool reports as test-only but that a debugger shows in production code.
- Review release assertions that read members of an object whose lifetime has ended. A positive result is an assertion whose operands are members of a destroyed object.
Hunting notes
This kind of bug hides in low-level C++ infrastructure: containers, smart pointers and utility types where move semantics and explicit destructor calls are used to implement assignment. The signal during review is an explicit this->~T() followed by any member access, return of *this, or later destruction. Static cross-reference tools can under-report uses, so a runtime breakpoint on the destructor call while loading an ordinary page is a cheap way to confirm reachability. In this case the researcher demonstrated a real call path from page load through PresShell frame visibility code into the operator.
Glossary
- C++: a programming language used to build large, performance-sensitive programs such as web browsers.
- XPCOM: a low-level layer of Mozilla code that provides reusable building blocks for the rest of the browser.
- Gecko: the engine inside Firefox that renders web pages.
- Hash table: a way of storing items so a particular item can be found quickly, like a cloakroom ticket that takes you straight to your coat.
- PLDHashTable: the hash table implementation in
xpcom/ds/PLDHashTable.cppdiscussed in this report. - Move assignment: an operation that transfers the contents of one object into another, leaving the source empty.
- Move constructor: an operation that builds a new object by taking another object's contents.
- Operator: a function attached to a symbol such as
=, so that the symbol does what the programmer defines. this: C++ shorthand for the object the current code belongs to.- Member variable: a field stored inside an object, like a drawer in a filing cabinet.
- Non-static: belonging to each individual object rather than shared by all objects of that type.
- Destructor: the special function that runs when an object is cleaned up.
- Non-trivial destructor: a destructor that actually has work to do rather than doing nothing.
- Undefined behaviour: a situation where the language makes no promises about what the program will do; it may work, crash or do something strange.
- C++11 section 3.8: the part of the C++11 standard that defines when an object's lifetime begins and ends.
- Assertion: a check that stops the program if something unexpected is true.
MOZ_RELEASE_ASSERT: Mozilla's assertion that stays active even in release builds.const: a promise that a value will not be changed after it is set.- Debug build: a version of the program built with extra checks and information for developers.
- Reference: another name for an existing object, not a copy.
- Pointer: a value that records where an object lives in memory.
- Debugger: a tool that pauses a running program so you can inspect exactly what it is doing.
- Stack (call stack): the list of functions currently running, each having called the next.
- Breakpoint: a marker that tells the debugger to pause when the program reaches a particular line.
- Static analysis: examining code without running it, like proofreading a recipe instead of cooking it.
- DXR: Mozilla's source cross-reference tool, which maps where code is defined and used.
- Reachable: having a real path through the program that gets to a piece of code.
- Test file / gtest: code written only to check that things work, not code that ships to users.
nsTHashtable: a hash table type built on top ofPLDHashTable.Swap/SwapElements: helpers that exchange the contents of two objects or containers.nsIFrame: a frame in the page layout, one of the boxes that make up what you see on screen.PresShell: the part of the browser that manages the presentation of a page, including which parts are visible.- Event loop: the browser's endless cycle of waiting for something to happen, handling it, and repeating.
- Runnable: a task queued up to run later.
- Bugzilla: Mozilla's bug tracker, a database where developers record known problems.
- Memory corruption primitive: a reliable way for an attacker to make a program misbehave in a chosen way.
- Confidentiality impact: harm where data could be stolen.
- Integrity impact: harm where data could be altered.
- Patch: a change to the code that fixes a problem.
- Smart pointer: a C++ type that manages memory automatically, like a self-emptying container.
- Move semantics: language features that let a program transfer data instead of copying it, for efficiency.