Skip to content
This repository was archived by the owner on Jan 6, 2023. It is now read-only.

Fix DesktopCapture crash on Mac OS X - #418

Merged
zcbenz merged 2 commits into
electron:masterfrom
i2x-gmbh:master
Jan 9, 2018
Merged

zcbenz merged 2 commits into
electron:masterfrom
i2x-gmbh:master

Conversation

@ilya-eder

@ilya-eder ilya-eder commented Dec 15, 2017 •

Copy link
Copy Markdown
Contributor

Fixes crash described in electron/electron#9600, electron/electron#11304.

The root cause of the observed crashes was a concurrency bug. Another possible cause for this kind of behavior could be a NULL pointer returned from a RWLock factory.

@alexeykuzmin
alexeykuzmin self-requested a review December 15, 2017 15:25

@alexeykuzmin alexeykuzmin left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ilya-edrenkin please do not change "device/bluetooth/bluetooth_adapter_mac.mm".
Build with 10.13 SDK is not supported yet.

@ilya-eder

Copy link
Copy Markdown
Contributor Author

please do not change "device/bluetooth/bluetooth_adapter_mac.mm".
Build with 10.13 SDK is not supported yet.

@alexeykuzmin I can do that, but are you 100% sure?
It does not break anything;
https://chromium.googlesource.com/chromium/src/+/master/docs/mac_build_instructions.md#system-requirements claims that "Building with a newer SDK works too".

Also it seems to enable correct behavior of bluetooth devices (which is overlooked by earlier SDKs).

@ilya-eder

Copy link
Copy Markdown
Contributor Author

Reverted it for now. I propose to keep it in the repo history though so that people can still build with SDK 10.13, which seems to be officially supported (at least if we choose to believe the Chromium documentation).

@alexeykuzmin

Copy link
Copy Markdown
Contributor

@ilya-edrenkin, yes, I'm sure.

It does not break anything.

We cannot be 100% sure, patching Chromium code we always risk breaking something.
And there is a maintenance cost for every patch we have.
Since your patch is not really necessary for the project it will be easier for us to not have it at all.
I appreciate your intention to help though =)

Reverted it for now.

Thanks!

@alexeykuzmin

Copy link
Copy Markdown
Contributor

Fixes crash described in electron/electron#9600, electron/electron#11304.

Is it possible to write a test in Electron to reproduce the crash?

@ilya-eder

Copy link
Copy Markdown
Contributor Author

Is it possible to write a test in Electron to reproduce the crash?

It would be really nice to have, but the behavior is non-deterministic. https://github.com/Ajeey/electron-crash-demo provides an example app that reliably crashes eventually, but researching the exact triggering sequence of events requires diving deep into the webrtc code.

@ilya-eder

Copy link
Copy Markdown
Contributor Author

While trying to pinpoint the problem further to automate testing, got a new kind of backtrace:

* thread #1, name = 'CrBrowserMain', queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x18)
    frame #0: 0x00000001006295f6 Electron Framework`webrtc::WriteLockScoped::~WriteLockScoped(this=0x00007fff5fbf3a60) at rw_lock_wrapper.h:59
    frame #1: 0x00000001006290f5 Electron Framework`webrtc::WriteLockScoped::~WriteLockScoped(this=0x00007fff5fbf3a60) at rw_lock_wrapper.h:58
  * frame #2: 0x0000000100629167 Electron Framework`webrtc::ScreenCapturerHelper::InvalidateRegion(this=0x000000011833a518, invalid_region=0x00007fff5fbf3ae0) at screen_capturer_helper.cc:35
    frame #3: 0x0000000100631b7a Electron Framework`webrtc::(anonymous namespace)::ScreenCapturerMac::ScreenRefresh(this=0x000000011833a480, count=7, rect_array=(origin = (x = 1482, y = 608), size = (width = 144, height = 34)), display_origin=(x_ = 0, y_ = 0)) at screen_capturer_mac.mm:1017
    frame #4: 0x000000010063125f Electron Framework`::___ZN6webrtc12_GLOBAL__N_117ScreenCapturerMac30RegisterRefreshAndMoveHandlersEv_block_invoke(.block_descriptor=<unavailable>, status=0, display_time=210683729269529, frame_surface=0x000000011838bd10, updateRef=0x0000000118132ef0) at screen_capturer_mac.mm:966
    frame #5: 0x00007fffa2ee4e33 SkyLight`CGYDisplayStreamNotification_server + 1464
    frame #6: 0x00007fffa2dfa1ea SkyLight`display_stream_runloop_callout + 46
    frame #7: 0x00007fff9130a1ed CoreFoundation`__CFMachPortPerform + 253
    frame #8: 0x00007fff9130a0d9 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
    frame #9: 0x00007fff9130a051 CoreFoundation`__CFRunLoopDoSource1 + 465
    frame #10: 0x00007fff91301cc5 CoreFoundation`__CFRunLoopRun + 2389
    frame #11: 0x00007fff91301114 CoreFoundation`CFRunLoopRunSpecific + 420
    frame #12: 0x00007fff90861ebc HIToolbox`RunCurrentEventLoopInMode + 240
    frame #13: 0x00007fff90861cf1 HIToolbox`ReceiveNextEventCommon + 432
    frame #14: 0x00007fff90861b26 HIToolbox`_BlockUntilNextEventMatchingListInModeWithFilter + 71
    frame #15: 0x00007fff8edf8a54 AppKit`_DPSNextEvent + 1120
    frame #16: 0x00007fff8f5747ee AppKit`-[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 2796
    frame #17: 0x00007fff8eded3db AppKit`-[NSApplication run] + 926
    frame #18: 0x00000001042cd73c libbase.dylib`___lldb_unnamed_symbol4062$$libbase.dylib + 300
    frame #19: 0x00000001042cb6ee libbase.dylib`base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 110
    frame #20: 0x00000001042bc50b libbase.dylib`base::MessageLoop::Run() + 299
    frame #21: 0x00000001043a39dd libbase.dylib`base::RunLoop::Run() + 125
    frame #22: 0x000000010cbb9b97 libcontent.dylib`content::BrowserMainLoop::MainMessageLoopRun() + 263
    frame #23: 0x000000010cbb9948 libcontent.dylib`content::BrowserMainLoop::RunMainMessageLoopParts() + 488
    frame #24: 0x000000010cbc2fab libcontent.dylib`___lldb_unnamed_symbol112318$$libcontent.dylib + 59
    frame #25: 0x000000010cbadacd libcontent.dylib`content::BrowserMain(content::MainFunctionParams const&) + 397
    frame #26: 0x000000010f000125 libcontent.dylib`___lldb_unnamed_symbol254292$$libcontent.dylib + 581
    frame #27: 0x000000010f00190c libcontent.dylib`___lldb_unnamed_symbol254300$$libcontent.dylib + 1260
    frame #28: 0x000000010effe73d libcontent.dylib`___lldb_unnamed_symbol254266$$libcontent.dylib + 61
    frame #29: 0x000000011122021f libembedder.dylib`service_manager::Main(service_manager::MainParams const&) + 1903
    frame #30: 0x000000010efffe99 libcontent.dylib`content::ContentMain(content::ContentMainParams const&) + 89
    frame #31: 0x0000000100091ef9 Electron Framework`::AtomMain(argc=2, argv=0x00007fff5fbffa88) at atom_library_main.mm:24
    frame #32: 0x0000000100000f02 Electron`main(argc=2, argv=0x00007fff5fbffa88) at atom_main.cc:186
    frame #33: 0x00007fffa6a87235 libdyld.dylib`start + 1
    frame #34: 0x00007fffa6a87235 libdyld.dylib`start + 1

Although it seemes be a separate issue, I thought the root cause is likely the same. However, I have found that the invalid_region_lock_ field of ScreenCapturerHelper was nullptr.

(lldb) f 2
frame #2: 0x0000000100629167 Electron Framework`webrtc::ScreenCapturerHelper::InvalidateRegion(this=0x000000011833a518, invalid_region=0x00007fff5fbf3ae0) at screen_capturer_helper.cc:35
(lldb) p *this
(webrtc::ScreenCapturerHelper) $4 = {
  invalid_region_ = {
    rows_ = size=0 {}
  }
  invalid_region_lock_ = {
    __ptr_ = {
      std::__1::__compressed_pair_elem<webrtc::RWLockWrapper *, 0, false> = (__value_ = 0x0000000000000000)
    }
  }
  size_most_recent_ = (width_ = 2880, height_ = 1800)
  log_grid_size_ = 0
}

As far as I can see, it could only stem from failure in the constructor:

ScreenCapturerHelper::ScreenCapturerHelper()
    : invalid_region_lock_(RWLockWrapper::CreateRWLock()),
      log_grid_size_(0) {
}

Digging deeper, it seems to be the result of pthread_rwlock_init failure:

RWLockPosix* RWLockPosix::Create() {
  RWLockPosix* ret_val = new RWLockPosix();
  if (!ret_val->Init()) {
    delete ret_val;
    return NULL; // <<<<<<<<<<------------------
  }
  return ret_val;
}

bool RWLockPosix::Init() {
  return pthread_rwlock_init(&lock_, 0) == 0;
}

Unfortunately, I couldn't find out why the pthread_rwlock_init failed (and if it was indeed the case); presumably, frequent requests to create rwlock increase the probability of lack of resources (or attempt to reinitialize existing one). The errno was already overwritten at this core dump.

However, I believe that we should just account for the fact that RWLockWrapper::CreateRWLock() might return NULL. The easiest workaround I can see is simply do busy waiting until it returns a properly constructed rwlock; in the worst-case it will freeze the thread, but still won't crash the whole program.

Thoughts/suggestions?

@ilya-eder ilya-eder changed the title Fix DesktopCapture crash on Mac OS X WIP: Fix DesktopCapture crash on Mac OS X Dec 15, 2017
@ilya-eder

Copy link
Copy Markdown
Contributor Author

Add a fix: https://github.com/electron/libchromiumcontent/pull/418/files#diff-d500a33e8c0b81ff56ee86256406d0b9

If the system refuses to return a valid rwlock, we wait with a random backoff (to prevent contention) and then retry. Note: the backoff parameters were not tuned, for this I would likely need fuzzing on a variety of systems which I don't have; probably it's better to leave this to WebRTC maintainers.

With this fix, I don't observe any more crashes on MacOS X 10.12.6 with a long-running Electron-crash-demo program from @Ajeey, even when making screenshots etc. This is not a proof that this will never happen though. I have checked the WebRTC code for other unsafe return values; AlignedMalloc could be one candidate, however it's probably not much we can do if malloc returned 0. I decided not to fix it until we observe any problems involving it.

I still don't understand the root cause of the problem fixed in the first commit. As far as I can see, display_stream_manager_ is only assigned once on creation display_stream_manager_ = new DisplayStreamManager;. I don't see nothrow here, therefore I would expect std::bad_alloc rather than NULL on failure, but maybe things just work differently on Mac (couldn't find any evidence of that in the documentation though).

@ilya-eder ilya-eder changed the title WIP: Fix DesktopCapture crash on Mac OS X Fix DesktopCapture crash on Mac OS X Dec 16, 2017
@ilya-eder ilya-eder changed the title Fix DesktopCapture crash on Mac OS X WIP: Fix DesktopCapture crash on Mac OS X Dec 16, 2017
@ilya-eder

ilya-eder commented Dec 16, 2017 •

Copy link
Copy Markdown
Contributor Author

OK, some good news: finally I was able to obtain my own coredump for the original problem.

* thread #32, name = 'TaskSchedulerForegroundBlockingWorker2', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
    frame #0: 0x000000010062e251 Electron Framework`webrtc::(anonymous namespace)::DisplayStreamManager::UnregisterActiveStreams() [inlined] bool std::__1::__tree_is_left_child<std::__1::__tree_node_base<void*>*>(__x=0x0000000118394b48) at __tree:84
    frame #1: 0x000000010062e23f Electron Framework`webrtc::(anonymous namespace)::DisplayStreamManager::UnregisterActiveStreams() [inlined] std::__1::__tree_end_node<std::__1::__tree_node_base<void*>*>* std::__1::__tree_next_iter<std::__1::__tree_end_node<std::__1::__tree_node_base<void*>*>*, std::__1::__tree_node_base<void*>*>(__x=0x0000000118394b48) at __tree:187
    frame #2: 0x000000010062e1c7 Electron Framework`webrtc::(anonymous namespace)::DisplayStreamManager::UnregisterActiveStreams() [inlined] std::__1::__tree_iterator<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, std::__1::__tree_node<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, void*>*, long>::operator++(this=0x000070000f9da920) at __tree:840
    frame #3: 0x000000010062e1bd Electron Framework`webrtc::(anonymous namespace)::DisplayStreamManager::UnregisterActiveStreams() [inlined] std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, std::__1::__tree_node<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, void*>*, long> >::operator++(this=0x000070000f9da920) at map:709
  * frame #4: 0x000000010062e1bd Electron Framework`webrtc::(anonymous namespace)::DisplayStreamManager::UnregisterActiveStreams(this=0x0000000118394b40) at screen_capturer_mac.mm:94
    frame #5: 0x000000010062dd02 Electron Framework`webrtc::(anonymous namespace)::ScreenCapturerMac::UnregisterRefreshAndMoveHandlers(this=0x00000001183984f0) at screen_capturer_mac.mm:989
    frame #6: 0x000000010062db11 Electron Framework`webrtc::(anonymous namespace)::ScreenCapturerMac::~ScreenCapturerMac(this=0x00000001183984f0) at screen_capturer_mac.mm:393
    frame #7: 0x000000010062aea5 Electron Framework`webrtc::(anonymous namespace)::ScreenCapturerMac::~ScreenCapturerMac(this=0x00000001183984f0) at screen_capturer_mac.mm:391
    frame #8: 0x000000010062aec9 Electron Framework`webrtc::(anonymous namespace)::ScreenCapturerMac::~ScreenCapturerMac(this=0x00000001183984f0) at screen_capturer_mac.mm:391
    frame #9: 0x0000000100495615 Electron Framework`NativeDesktopMediaList::Worker::Refresh(gfx::Size const&, long) [inlined] std::__1::default_delete<webrtc::DesktopCapturer>::operator(this=0x0000000118399248, __ptr=0x00000001183984f0)(webrtc::DesktopCapturer*) const at memory:2233
    frame #10: 0x00000001004955f0 Electron Framework`NativeDesktopMediaList::Worker::Refresh(gfx::Size const&, long) [inlined] std::__1::unique_ptr<webrtc::DesktopCapturer, std::__1::default_delete<webrtc::DesktopCapturer> >::reset(this=0x0000000118399248, __p=0x0000000000000000) at memory:2546
    frame #11: 0x0000000100495580 Electron Framework`NativeDesktopMediaList::Worker::Refresh(this=0x0000000118399230, thumbnail_size=0x0000000118396368, view_dialog_id=-1) at native_desktop_media_list.cc:218
    frame #12: 0x00000001004a1570 Electron Framework`void base::internal::FunctorTraits<void (NativeDesktopMediaList::Worker::*)(gfx::Size const&, long), void>::Invoke<NativeDesktopMediaList::Worker*, gfx::Size const&, long const&>(method=60 34 49 00 01 00 00 00 00 00 00 00 00 00 00 00, receiver_ptr=0x000070000f9dbb90, args=0x0000000118396368, args=0x0000000118396370)(gfx::Size const&, long), NativeDesktopMediaList::Worker*&&, gfx::Size const&&&, long const&&&) at bind_internal.h:209
    frame #13: 0x00000001004a146a Electron Framework`void base::internal::InvokeHelper<false, void>::MakeItSo<void (functor=0x0000000118396350, args=0x000070000f9dbb90, args=0x0000000118396368, args=0x0000000118396370)(gfx::Size const&, long), NativeDesktopMediaList::Worker*, gfx::Size const&, long const&>(void (NativeDesktopMediaList::Worker::* const&&&)(gfx::Size const&, long), NativeDesktopMediaList::Worker*&&, gfx::Size const&&&, long const&&&) at bind_internal.h:275
    frame #14: 0x00000001004a13dd Electron Framework`void base::internal::Invoker<base::internal::BindState<void (NativeDesktopMediaList::Worker::*)(gfx::Size const&, long), base::internal::UnretainedWrapper<NativeDesktopMediaList::Worker>, gfx::Size, long>, void ()>::RunImpl<void (functor=0x0000000118396350, bound=0x0000000118396360, (null)=IndexSequence<0, 1, 2> @ 0x000070000f9dbba8)(gfx::Size const&, long), std::__1::tuple<base::internal::UnretainedWrapper<NativeDesktopMediaList::Worker>, gfx::Size, long> const&, 0ul, 1ul, 2ul>(void (NativeDesktopMediaList::Worker::* const&&&)(gfx::Size const&, long), std::__1::tuple<base::internal::UnretainedWrapper<NativeDesktopMediaList::Worker>, gfx::Size, long> const&&&, base::IndexSequence<0ul, 1ul, 2ul>) at bind_internal.h:351
    frame #15: 0x00000001004a12ac Electron Framework`base::internal::Invoker<base::internal::BindState<void (NativeDesktopMediaList::Worker::*)(gfx::Size const&, long), base::internal::UnretainedWrapper<NativeDesktopMediaList::Worker>, gfx::Size, long>, void ()>::Run(base=0x0000000118396330) at bind_internal.h:329
    frame #16: 0x000000010419d42f libbase.dylib`___lldb_unnamed_symbol233$$libbase.dylib + 95
    frame #17: 0x00000001041fe5b0 libbase.dylib`base::debug::TaskAnnotator::RunTask(char const*, base::PendingTask*) + 1040
    frame #18: 0x0000000104485db3 libbase.dylib`base::internal::TaskTracker::PerformRunTask(std::__1::unique_ptr<base::internal::Task, std::__1::default_delete<base::internal::Task> >, base::internal::Sequence*) + 3027
    frame #19: 0x0000000104487f0d libbase.dylib`base::internal::TaskTrackerPosix::PerformRunTask(std::__1::unique_ptr<base::internal::Task, std::__1::default_delete<base::internal::Task> >, base::internal::Sequence*) + 445
    frame #20: 0x0000000104484a3b libbase.dylib`base::internal::TaskTracker::RunNextTask(base::internal::Sequence*) + 667
    frame #21: 0x000000010446e509 libbase.dylib`___lldb_unnamed_symbol8094$$libbase.dylib + 1993
    frame #22: 0x0000000104493d48 libbase.dylib`___lldb_unnamed_symbol8445$$libbase.dylib + 632
    frame #23: 0x00007fffa6ca093b libsystem_pthread.dylib`_pthread_body + 180
    frame #24: 0x00007fffa6ca0887 libsystem_pthread.dylib`_pthread_start + 286
    frame #25: 0x00007fffa6ca008d libsystem_pthread.dylib`thread_start + 13

(lldb) f 5
frame #5: 0x000000010062dd02 Electron Framework`webrtc::(anonymous namespace)::ScreenCapturerMac::UnregisterRefreshAndMoveHandlers(this=0x00000001183984f0) at screen_capturer_mac.mm:989
   986
   987 	void ScreenCapturerMac::UnregisterRefreshAndMoveHandlers() {
   988 	  if (display_stream_manager_) {
-> 989 	    display_stream_manager_->UnregisterActiveStreams();
   990 	  }
   991 	}
   992
(lldb) p *this
(webrtc::(anonymous namespace)::ScreenCapturerMac) $18 = {
  callback_ = 0x0000000118399230
  cgl_context_ = 0x0000000000000000
  pixel_buffer_object_ = {
    cgl_context_ = 0x0000000000000000
    pixel_buffer_object_ = 0
  }
  queue_ = {
    current_ = 0
    frames_ = {
      [0] = {
        __ptr_ = {
          std::__1::__compressed_pair_elem<webrtc::SharedDesktopFrame *, 0, false> = {
            __value_ = 0x0000000000000000
          }
        }
      }
      [1] = {
        __ptr_ = {
          std::__1::__compressed_pair_elem<webrtc::SharedDesktopFrame *, 0, false> = {
            __value_ = 0x0000000000000000
          }
        }
      }
    }
  }
  desktop_config_ = {
    bounds = (left_ = 0, top_ = 0, right_ = 1440, bottom_ = 900)
    pixel_bounds = (left_ = 0, top_ = 0, right_ = 2880, bottom_ = 1800)
    dip_to_pixel_scale = 2
    displays = size=0 {}
  }
  current_display_ = 69733632
  screen_pixel_bounds_ = (left_ = 0, top_ = 0, right_ = 2880, bottom_ = 1800)
  dip_to_pixel_scale_ = 2
  helper_ = {
    invalid_region_ = {
      rows_ = size=0 {}
    }
    invalid_region_lock_ = {
      __ptr_ = {
        std::__1::__compressed_pair_elem<webrtc::RWLockWrapper *, 0, false> = (__value_ = 0x0000000118398620)
      }
    }
    size_most_recent_ = (width_ = 2880, height_ = 1800)
    log_grid_size_ = 0
  }
  last_invalid_region_ = {
    rows_ = size=0 {}
  }
  desktop_config_monitor_ = {
    ptr_ = 0x0000000118399410
  }
  app_services_library_ = 0x0000000000000000
  cg_display_base_address_ = 0x0000000000000000
  cg_display_bytes_per_row_ = 0x0000000000000000
  cg_display_bits_per_pixel_ = 0x0000000000000000
  opengl_library_ = 0x0000000000000000
  cgl_set_full_screen_ = 0x0000000000000000
  excluded_window_ = 0
  display_stream_manager_ = 0x0000000118394b40
}

This means that the proposed nullptr-check for display_stream_manager_ is actually irrelevant. That resolves the mystery how it became null; probably it just didn't.

However, what happens next is really interesting:

(lldb) f 4
frame #4: 0x000000010062e1bd Electron Framework`webrtc::(anonymous namespace)::DisplayStreamManager::UnregisterActiveStreams(this=0x0000000118394b40) at screen_capturer_mac.mm:94
   91  	  }
   92
   93  	  void UnregisterActiveStreams() {
-> 94  	    for (auto& pair : display_stream_wrappers_) {
   95  	      DisplayStreamWrapper& wrapper = pair.second;
   96  	      if (wrapper.active) {
   97  	        wrapper.active = false;
(lldb) p *this
(webrtc::(anonymous namespace)::DisplayStreamManager) $25 = {
  display_stream_wrappers_ = size=0 {}
  unique_id_generator_ = 1
  ready_for_self_destruction_ = false
}

(lldb) frame variable
(webrtc::(anonymous namespace)::DisplayStreamManager *) this = 0x0000000118394b40
(std::__1::map<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper, std::__1::less<int>, std::__1::allocator<std::__1::pair<const int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper> > > &) __range = size=0 {}
(std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, std::__1::__tree_node<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, void *> *, long> >) __begin = {
  first = -1407216576
  second = (stream = 0x00007fffaf973a80, active = true)
}
(std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, std::__1::__tree_node<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, void *> *, long> >) __end = {
  first = 1
  second = (stream = 0x000000011839a340, active = true)
}

We see that the state of display_stream_wrappers_ map is invalid at this point. The first element has -1407216576 as the key, which seems like garbage rather than a result of integer overflow; these IDs are generated from unique_id_generator_ field of DisplayStreamManager, which is initialized to 0 and incremented on each subsequent call. Signed integer overflow is UB, therefore the observed behavior could be a byproduct of some compiler optimization, however it seems that the event of overflow in this setup is highly unlikely.

This could happen if the DisplayStreamManager was already invalidated by the moment when DisplayStreamManager::GetUniqueId() was called, s.t. the field unique_id_generator_ contains garbage. In our dump we see unique_id_generator_ = 1, which seem to make sense.

DisplayStreamManager indeed has function DestroyStream that calls delete this; and is invoked from a callback handler; however, delete this should only occur when ready_for_self_destruction_ == true. We have seen that it was set to false on frame 4. Moreover, it is only set to true in display_stream_manager_->PrepareForSelfDestruction(), which is called after the UnregisterRefreshAndMoveHandlers() call -- the call that actually fails. So it is very unlikely that DestroyStream() is guilty: at this point of execution it could not possibly destroy the manager.

I should probably stop guesswork and just rebuild with ASan (the main problem is that chromium builds take enormous amount of time on the only Mac machine I currently have access to, and the bug itself takes random amount of time to reproduce).

@ilya-eder

Copy link
Copy Markdown
Contributor Author

So far my hypothesis is that display_stream_wrappers_ is being concurrently modified by DestroyStream in a callback (which presumably runs in a separate thread, but I don't really know anything about the OS X API) and SaveStream in RegisterRefreshAndMoveHandlers. This breaks the structure of the underlying RBTree (therefore we observe the crash) and turns the data into garbage (therefore the contents of the map look strange, although other fields of the manager object look sane).

The loop for (const auto& config : desktop_config_.displays) both registers callbacks and calls SaveStream. If some callbacks trigger before the loop exits and try to write to display_stream_wrappers_, it's a race condition. An obvious solution would be to lock-guard the manager. It will help to avoid UB on concurrent read/writes between the main thread and the callback thread(s) on all fields of the manager, not only the display_stream_wrappers_. However, it comes with a performance cost.

@ilya-eder ilya-eder changed the title WIP: Fix DesktopCapture crash on Mac OS X Fix DesktopCapture crash on Mac OS X Dec 18, 2017
@ilya-eder

Copy link
Copy Markdown
Contributor Author

@alexeykuzmin Finally pinpointed and fixed the root causes. Please review.

@alexeykuzmin

alexeykuzmin commented Dec 19, 2017 •

Copy link
Copy Markdown
Contributor

@ilya-edrenkin If you believe that RWLockWrapper::CreateRWLock doesn't work properly all the time, the best place to fix it is not libcc, but WebRTC itself. libcc patches should contains only the stuff that cannot be possible upstreamed.
The same applies not only for RWLockWrapper::CreateRWLock but for everything that is not Electron-specific.

It would be great if you could submit a patch for the WebRTC repo. Here is a contributor guide https://webrtc.org/contributing/

@ilya-eder

ilya-eder commented Dec 19, 2017 •

Copy link
Copy Markdown
Contributor Author

@alexeykuzmin I have mentioned it in a corresponding issue: https://bugs.chromium.org/p/webrtc/issues/detail?id=8646#c2
Thanks for the link -- I need to follow their guidelines of patch submission. It will probably take a while before the WebRTC maintainers review and merge this.

If you believe that RWLockWrapper::CreateRWLock doesn't work properly all the time

That's not entirely true. The return value of RWLockWrapper::CreateRWLock is not safe, and in an (unlikely) event of contention on system resources it might return NULL which inevitably leads to crash on dereference. It makes sense to provide a defense from this.

However, what causes most of the observed crashes is just concurrency bugs.

@alexeykuzmin

Copy link
Copy Markdown
Contributor

@alexeykuzmin I have mentioned it in a corresponding issue: https://bugs.chromium.org/p/webrtc/issues/detail?id=8646#c2
Thanks for the link -- I need to follow their guidelines of patch submission.

Thank you!

It will probably take a while before the WebRTC maintainers review and merge this.

But they can give much better advice about how it should be done properly.

@ilya-eder

ilya-eder commented Dec 20, 2017 •

Copy link
Copy Markdown
Contributor Author

Basically, the WebRTC developers blame the fact that NativeDesktopMediaList is heavily modified in Electron (https://bugs.chromium.org/p/webrtc/issues/detail?id=8646#c5):

Note, the NativeDesktopMediaList in Electron (https://github.com/electron/electron/blob/c18afc924b7218555e529c0583773f58e1015cbe/chromium_src/chrome/browser/media/native_desktop_media_list.cc#L218) is heavily modified and breaks the design pattern of DesktopCapturer implementations. Basically all public functions of DesktopCapturer implementations should only be called in one thread, include destructor.

@zcbenz When you have time, could you please pay some attention to this feedback from WebRTC developers? It would be really great to know your opinion on that.

I can understand why it leads to race condition between the ScreenCapturerMac::~ScreenCapturerMac and the callback (which explains the error #418 (comment), and explains why locking fixes it).

However, I currently cannot see how this could explain the crash #418 (comment). Here we quite clearly observe a broken std::map display_stream_wrappers_:

(std::__1::map<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper, std::__1::less<int>, std::__1::allocator<std::__1::pair<const int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper> > > &) __range = size=0 {}
(std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, std::__1::__tree_node<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, void *> *, long> >) __begin = {
  first = -1407216576
  second = (stream = 0x00007fffaf973a80, active = true)
}
(std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, std::__1::__tree_node<std::__1::__value_type<int, webrtc::(anonymous namespace)::DisplayStreamManager::DisplayStreamWrapper>, void *> *, long> >) __end = {
  first = 1
  second = (stream = 0x000000011839a340, active = true)
}

The only two functions that modify this map are SaveStream (which gets called only inScreenCapturerMac::RegisterRefreshAndMoveHandlers) and DestroyStream which gets called only in the callback in the run loop. If there is a race between these two functions, it would also affect the upstream code. If there is no race (e.g. if the OS X somehow handles callbacks in the same thread in cooperative manner, and writing to the map can be never preempted) -- then I currently have no idea how this could possibly happen.

@Ajeey

Ajeey commented Dec 20, 2017

Copy link
Copy Markdown

@ilya-edrenkin Thanks a ton for looking into this crash bug. This specific issue is turning out to be a show stopper for us in terms of picking electron vs node-webkit. I hope this PR gets pulled into electron soon :)

@zcbenz

zcbenz commented Dec 21, 2017

Copy link
Copy Markdown
Contributor

@ilya-edrenkin Thanks for looking into this, I'll see if it is possible to avoid the race condition on Electron's side according to webrtc developers' description. If not I think we should probably add this patch.

@ilya-eder

Copy link
Copy Markdown
Contributor Author

@zcbenz Thanks for the feedback!

Re the patch:

  1. Introducing locking should fix the observed problem.
    By the way, I've also realized how we can explain the corrupted RBTree in the 2nd stacktrace: it could also be a race between the ScreenCapturerMac::~ScreenCapturerMac and the callback. DisplayStreamManager::UnregisterActiveStreams, which is called from the destructor (thread 32 in the coredump above), reads from this map; the same map can be concurrently modified by the DestroyStream in the callback on CFRunLoop (should be in thread 1). Unfortunately, I've already deleted the associated coredump, but the explanation looks plausible.

  2. NativeDesktopMediaList seems to be platform-independent. Googlers say:

Basically all public functions of DesktopCapturer implementations should only be called in one thread, include destructor.

Even if we fix this problem on Mac, aren't there problems on other platforms hiding out there? If there exist other DesktopCapturer crashes on Electron, that could have something to do with it.

  1. Re the RWLock return value: webrtc developers told me that the return value of RWLock should not be checked, because if it returns NULL it is already an emergency situation / kernel bug, and crash on null ptr dereference is actually the desired behavior. This makes sense, although I cannot fully agree with this approach (why not throw a critical exception with a human-readable error explicitly?).
    I can either remove this part of patch altogether, change it to throw an exception, or leave as-is. I'd rather remove it to reduce the maintenance cost for you.

@zcbenz

zcbenz commented Jan 8, 2018

Copy link
Copy Markdown
Contributor

I have looked into the implementation in upstream Chromium, and the NativeDesktopMediaList in Chromium has the same problem: the ScreenCapturerMac is allocated on UI thread but destroyed on IO thread. I don't think having ScreenCapturerMac allocated on IO thread would fix the crash, since the race condition happened between the destructor and the handler to capture frame.

I think Chromium does not (or rarely) have this problem because they are using NativeDesktopMediaList in a different way from us: in Electron the NativeDesktopMediaList is allocated and destroyed for every single capture, while in Chromium usually only one NativeDesktopMediaList is created and it is reused for refreshing the thumbnails.

So having this patch merged seems to be the best solution to the crash.

@zcbenz

zcbenz commented Jan 8, 2018

Copy link
Copy Markdown
Contributor

I'm rebasing this branch on master

@zcbenz
zcbenz merged commit 8320c96 into electron:master Jan 9, 2018
@Ajeey

Ajeey commented Jan 12, 2018

Copy link
Copy Markdown

@zcbenz Any approx timeline on when this will be pulled into electron?

@zcbenz

zcbenz commented Jan 18, 2018

Copy link
Copy Markdown
Contributor

It will be in next major/minor release, we don't have an estimate date yet.

@Ajeey

Ajeey commented May 2, 2018

Copy link
Copy Markdown

@zcbenz In which version of electron is this fix landed? Could not find this fix on the release page.

@zcbenz

zcbenz commented May 2, 2018

Copy link
Copy Markdown
Contributor

@Ajeey I think it is in 2.0, we probably forgot to add this item in changelog.

@Ajeey

Ajeey commented May 2, 2018

Copy link
Copy Markdown

Thank you 👍

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants