Skip to content

Run the listener's teardown on the GUI thread (fixes #82) - #84

Open
omnimaxxing wants to merge 1 commit into
asivery:masterfrom
omnimaxxing:fix-close-race
Open

omnimaxxing wants to merge 1 commit into
asivery:masterfrom
omnimaxxing:fix-close-race

Conversation

@omnimaxxing

Copy link
Copy Markdown

Fixes #82.

Problem

When an app's backend disconnects, its listener thread calls terminate(). That erases from the unlocked sockets map and then runs closeUIInstance() → coordinator->unload(), which emits the coordinator's QML signals and unregisters the app's resources. All of this runs off the GUI thread. If the frontend closes the app at the same time (Close tapped, unloading() → terminate()), both threads tear the same app down: the iterator race @gfr-g describes in #82, plus QML changes from a non-GUI thread. On a Paper Pure this crashes xochitl, as double free or corruption or SIGSEGV.

Change

The listener no longer tears down on its own thread. It queues the teardown onto the GUI thread with QMetaObject::invokeMethod(qApp, …, Qt::QueuedConnection):

  • If the backend went away by itself, the queued call runs terminate() on the GUI thread as before, so the UI still closes when a backend dies.
  • If the GUI already terminated the app, its sockets entry is gone and the queued call does nothing. Before, the listener ran closeUIInstance(id, true) a second time.
  • The pipe's read end is closed in the queued call too, so a terminate() on the GUI thread never writes to a pipe whose reader is already closed.

So sockets is only erased, and apps only unloaded, on the GUI thread, without new locks or refcounts.

Not in this PR

  • _registerSocket() still inserts into sockets from the listener thread, and broadcastMessageToControllers() reads endpoints there. Both are less likely to collide (they happen at connect time and per message), but they belong in the same follow-up if you want the maps fully single-threaded.

Testing

On a reMarkable Paper Pure, firmware 3.29.1.0, with appload.so built by this repo's release workflow (aarch64 toolchain image):

AppLoad Closes xochitl crashes
0.6.0 (Vellum package) 1 1 (SIGSEGV)
df974a6 + this change 25 0

The repro is @gfr-g's recipe from #82: a minimal app whose frontend, on tap, sends its backend a message and calls close(). The backend exits the moment it reads any message, without waiting for AppLoad to close the socket. management.cpp, AppLoadCoordinator.cpp and library.cpp are the same in 0.6.0 and df974a6, so the two builds take the same shutdown path.

Repro app (manifest id close-race, loadsBackend: true)

ui/main.qml:

import QtQuick
import net.asivery.AppLoad 1.0

// Repro for asivery/rm-appload#82. Tapping anywhere asks the backend to exit
// (message 1) and terminates through AppLoad in the same instant, so the
// listener thread and the GUI thread tear the app down together.
Rectangle {
    id: root
    anchors.fill: parent
    color: "white"
    signal close
    function unloading() {
        endpoint.terminate();
    }
    AppLoad {
        id: endpoint
        applicationID: "close-race"
        onMessageReceived: (type, contents) => {}
    }
    Text {
        anchors.centerIn: parent
        text: "Close Race: tap to close"
        font.pixelSize: 64
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            endpoint.sendMessage(1, "exit");
            root.close();
        }
    }
}

backend/main.go (built with CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build):

// Backend for the rm-appload#82 repro: exits the moment it gets message 1
// from the frontend or AppLoad's terminate (-1), without waiting for AppLoad
// to close its end of the socket.
package main

import (
	"encoding/binary"
	"net"
	"os"
	"time"
)

func main() {
	addr := &net.UnixAddr{Name: os.Args[1], Net: "unixpacket"}
	var c *net.UnixConn
	var err error
	for range 100 { // AppLoad starts us before it listens
		if c, err = net.DialUnix("unixpacket", nil, addr); err == nil {
			break
		}
		time.Sleep(30 * time.Millisecond)
	}
	if err != nil {
		os.Exit(1)
	}
	buf := make([]byte, 1<<20)
	for {
		n, err := c.Read(buf) // one packet: a header, or a body
		if err != nil {
			os.Exit(0)
		}
		if n == 8 {
			if typ := int32(binary.LittleEndian.Uint32(buf[0:])); typ == 1 || typ == -1 {
				os.Exit(0)
			}
		}
	}
}

With this change I also checked:

  • Killing an app's backend while it's open still closes its UI. The QProcess handlers terminate it on the GUI thread, and the queued call then finds nothing left to do.
  • A regular app opens and closes cleanly. "Unloading frontends of …" is logged once per close, where 0.6.0 often logs it twice.

Side note: xovi/make.sh currently exits 141 in the release workflow (rcc | sed -n '/#ifdef/q;p' gets SIGPIPE under pipefail), for both toolchain images. For these test builds I wrote rcc's output to a file first; that change isn't part of this PR.

When a backend disconnects, the listener thread called terminate(), which
erases from the unlocked `sockets` map and then runs closeUIInstance():
coordinator->unload() changes QML properties and unregisters resources.
Both race the GUI thread when the frontend closes the app at the same
time, which can crash xochitl (seen as "double free or corruption").

The listener now queues that teardown onto the GUI thread. It skips it
when the GUI already terminated the app, and closes the pipe's read end
there, after any terminate() that might still write to it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Race condition during application close can lead to a crash

1 participant