<html>
    <head>
      <base href="https://bugs.webkit.org/" />
    </head>
    <body>
      <p>
        <div>
            <b><a class="bz_bug_link 
          bz_status_RESOLVED  bz_closed"
   title="RESOLVED FIXED - Media Session: Active participating elements can change while being iterated"
   href="https://bugs.webkit.org/show_bug.cgi?id=145978#c7">Comment # 7</a>
              on <a class="bz_bug_link 
          bz_status_RESOLVED  bz_closed"
   title="RESOLVED FIXED - Media Session: Active participating elements can change while being iterated"
   href="https://bugs.webkit.org/show_bug.cgi?id=145978">bug 145978</a>
              from <span class="vcard"><a class="email" href="mailto:darin&#64;apple.com" title="Darin Adler &lt;darin&#64;apple.com&gt;"> <span class="fn">Darin Adler</span></a>
</span></b>
        <pre>Comment on <span class=""><a href="attachment.cgi?id=254883&amp;action=diff" name="attach_254883" title="Patch">attachment 254883</a> <a href="attachment.cgi?id=254883&amp;action=edit" title="Patch">[details]</a></span>
Patch

View in context: <a href="https://bugs.webkit.org/attachment.cgi?id=254883&amp;action=review">https://bugs.webkit.org/attachment.cgi?id=254883&amp;action=review</a>

<span class="quote">&gt; Source/WebCore/Modules/mediasession/MediaSession.cpp:99
&gt; +    HashSet&lt;HTMLMediaElement*&gt; activeParticipatingElementsCopy = m_activeParticipatingElements;
&gt; +
&gt; +    for (auto* element : activeParticipatingElementsCopy) {</span >

This pattern almost always leads to serious bugs. Once you have copied the HTMLMediaElement set, elements from the set could be deleted as a side effect of the operations below, and then you could use an element pointer of a deleted object.

One technique is removing each element from the set as we iterate instead of using a for loop, using the HashSet::takeAny function. Then also making sure that when an element is removed from the “real” set it’s also removed from the set currently being iterated. That pattern is used in DisplayRefreshMonitor::displayDidRefresh.

Another technique is to use Vector&lt;RefPtr&lt;HTMLMediaElement&gt;&gt; instead of HashSet&lt;MediaElement*&gt; for the elements we are iterating. That guarantees the elements are not deallocated, but we might not want to toggle the state of an element that has been removed from the document tree, for example.

I know we have run into the same problem elsewhere and solved it multiple ways. But this code is not safe.</pre>
        </div>
      </p>
      <hr>
      <span>You are receiving this mail because:</span>
      
      <ul>
          <li>You are the assignee for the bug.</li>
      </ul>
    </body>
</html>