[Linux] fix: make textures thread-safe on linux by Kingtous · Pull Request #40478 · flutter/engine

2 min read Original article ↗

We've encountered some memory corruption when developing RustDesk, which is an open-source remote desktop built with Flutter, and it uses the texture API provided by Flutter to provide the remote screen to clients.

Both Windows and macOS work well, except for Linux. Sometimes random crashes will show and print different stack traces in these conditions:

  • after registering a new texture
  • preparing a RGBA data and markAvaliable

The runtime often complains double free or corruption.
One of the stack traces using lldb-10:
image

We checked the implementation of calling textures API on Linux several times, but have no luck.

We've noticed that on Linux, textures are organized by g_hash_table, which is not the thread-safe hashtable and we should ensure synchronization on different threads. Also, we noticed the textures map on Windows already has the synchronization (for example

{
std::lock_guard<std::mutex> lock(map_mutex_);
auto it = textures_.find(texture_id);
if (it != textures_.end()) {

). So the implementation on Linux lacks this synchronization on textures management.

We add the synchronization by declaring a GMutex, which is a mutex provided by GTK, in this PR. It can make g_hash_table thread-safe in different threads(ui, raster, etc).

Pre-launch Checklist

  • I read the Contributor Guide and followed the process outlined there for submitting PRs.
  • I read the Tree Hygiene wiki page, which explains my responsibilities.
  • I read and followed the Flutter Style Guide and the C++, Objective-C, Java style guides.
  • I listed at least one issue that this PR fixes in the description above.
  • I added new tests to check the change I am making or feature I am adding, or Hixie said the PR is test-exempt. See testing the engine for instructions on writing and running engine tests.
  • I updated/added relevant documentation (doc comments with ///).
  • I signed the CLA.
  • All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel on Discord.