Skip to content

A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.

[FIX] Stop native Linux Zoom games (#6221)

Flávio Fearn5a30fe49bb3f
diff --git a/src/backend/storeManagers/zoom/__tests__/stop.test.ts b/src/backend/storeManagers/zoom/__tests__/stop.test.ts
index f74771f6d..5b3609b65 100644
--- a/src/backend/storeManagers/zoom/__tests__/stop.test.ts
+++ b/src/backend/storeManagers/zoom/__tests__/stop.test.ts
@@ -1,4 +1,37 @@
-import { stoppedGameStatus, stopNeedsWineShutdown } from '../stop'
+import {
+ chmodSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync
+} from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+jest.mock('node:fs', (): typeof import('node:fs') => ({
+ ...jest.requireActual<typeof import('node:fs')>('node:fs'),
+ readdirSync: jest.fn()
+}))
+
+import {
+ findNativeGamePids,
+ readNativeProcesses,
+ stoppedGameStatus,
+ stopNeedsWineShutdown,
+ stopNativeGame,
+ type NativeProcess
+} from '../stop'
+
+function nativeProcess(
+ pid: number,
+ ppid: number,
+ cmdline: string[],
+ options: { cwd?: string; executable?: string } = {}
+): NativeProcess {
+ return { pid, ppid, cmdline, ...options }
+}
describe('zoom stop', () => {
it('only shuts Wine down for non-native launches', () => {
@@ -14,3 +47,224 @@ describe('zoom stop', () => {
})
})
})
+
+// POSIX permissions and symlinks decide the match, so these cases do not
+// apply on Windows.
+const describePosix = process.platform === 'win32' ? describe.skip : describe
+const readdirSyncMock = jest.mocked(readdirSync)
+
+describePosix('findNativeGamePids', () => {
+ let root: string
+ let install: string
+ let linkedInstall: string
+ let script: string
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'zoom-stop-'))
+ install = join(root, 'Games', 'Foo')
+ mkdirSync(install, { recursive: true })
+ script = join(install, 'start.sh')
+ writeFileSync(script, '#!/bin/sh\n', { mode: 0o755 })
+ symlinkSync(join(root, 'Games'), join(root, 'GamesLink'))
+ linkedInstall = join(root, 'GamesLink', 'Foo')
+ })
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true })
+ })
+
+ it('finds the launcher script and its children', () => {
+ const processes = [
+ nativeProcess(100, 1, ['/bin/bash', script], {
+ cwd: install,
+ executable: '/usr/bin/bash'
+ }),
+ nativeProcess(101, 100, [join(install, 'bin', 'game')], {
+ cwd: join(install, 'bin'),
+ executable: join(install, 'bin', 'game')
+ }),
+ nativeProcess(200, 1, ['/usr/bin/unrelated'], {
+ cwd: root,
+ executable: '/usr/bin/unrelated'
+ })
+ ]
+
+ expect(findNativeGamePids(processes, 'start.sh', install)).toEqual([
+ 100, 101
+ ])
+ })
+
+ it('finds a child that was reparented after the script was aborted', () => {
+ const processes = [
+ nativeProcess(101, 1, [join(install, 'bin', 'game')], {
+ cwd: join(install, 'bin'),
+ executable: join(install, 'bin', 'game')
+ })
+ ]
+
+ expect(findNativeGamePids(processes, 'start.sh', install)).toEqual([101])
+ })
+
+ it('finds an interpreter with cwd inside the install and no game argv', () => {
+ const processes = [
+ nativeProcess(301, 1, ['/usr/bin/python3'], {
+ cwd: install,
+ executable: '/usr/bin/python3'
+ })
+ ]
+
+ expect(findNativeGamePids(processes, 'start.sh', install)).toEqual([301])
+ })
+
+ it('finds a script that is not executable when an interpreter runs it', () => {
+ chmodSync(script, 0o644)
+ const processes = [
+ nativeProcess(300, 1, ['/usr/bin/python3', script], {
+ cwd: root,
+ executable: '/usr/bin/python3'
+ })
+ ]
+
+ expect(findNativeGamePids(processes, 'start.sh', install)).toEqual([300])
+ })
+
+ it('matches the script through a symlinked install path', () => {
+ const processes = [
+ nativeProcess(400, 1, ['/bin/bash', join(linkedInstall, 'start.sh')], {
+ cwd: linkedInstall,
+ executable: '/usr/bin/bash'
+ })
+ ]
+
+ expect(findNativeGamePids(processes, 'start.sh', linkedInstall)).toEqual([
+ 400
+ ])
+ })
+
+ it('ignores a media file passed to another program', () => {
+ const soundtrack = join(install, 'soundtrack.ogg')
+ writeFileSync(soundtrack, 'audio')
+
+ const processes = [
+ nativeProcess(500, 1, ['/usr/bin/mpv', soundtrack], {
+ cwd: root,
+ executable: '/usr/bin/mpv'
+ })
+ ]
+
+ expect(findNativeGamePids(processes, 'start.sh', install)).toEqual([])
+ })
+
+ it('does not match a sibling folder with the same prefix', () => {
+ const sibling = join(root, 'Games', 'Foobar')
+ mkdirSync(sibling, { recursive: true })
+ const siblingScript = join(sibling, 'start.sh')
+ writeFileSync(siblingScript, '#!/bin/sh\n', { mode: 0o755 })
+
+ const processes = [
+ nativeProcess(700, 1, ['/bin/bash', siblingScript], {
+ cwd: sibling,
+ executable: '/usr/bin/bash'
+ })
+ ]
+
+ expect(findNativeGamePids(processes, 'start.sh', install)).toEqual([])
+ })
+
+ it('returns no processes when proc cannot be read', () => {
+ readdirSyncMock.mockImplementationOnce(() => {
+ throw new Error('denied')
+ })
+
+ expect(readNativeProcesses('/proc')).toEqual([])
+ })
+
+ it('ignores processes outside the install path', () => {
+ const outside = join(root, 'Bar', 'game.love')
+ mkdirSync(join(root, 'Bar'), { recursive: true })
+ writeFileSync(outside, '')
+
+ const processes = [
+ nativeProcess(600, 1, ['/usr/bin/love', outside], {
+ cwd: root,
+ executable: '/usr/bin/love'
+ })
+ ]
+
+ expect(findNativeGamePids(processes, 'start.sh', install)).toEqual([])
+ })
+
+ it('terminates the matched processes', () => {
+ const kill = jest.fn()
+ const killed = stopNativeGame('start.sh', install, {
+ readProcesses: () => [
+ nativeProcess(100, 1, ['/bin/bash', script], {
+ cwd: install,
+ executable: '/usr/bin/bash'
+ }),
+ nativeProcess(101, 100, [join(install, 'bin', 'game')], {
+ cwd: join(install, 'bin'),
+ executable: join(install, 'bin', 'game')
+ })
+ ],
+ kill
+ })
+
+ expect(kill).toHaveBeenCalledTimes(2)
+ expect(kill).toHaveBeenCalledWith(100, 'SIGTERM')
+ expect(kill).toHaveBeenCalledWith(101, 'SIGTERM')
+ expect([...killed].sort((a, b) => a - b)).toEqual([100, 101])
+ })
+
+ it('ignores processes that already exited', () => {
+ const kill = jest.fn((pid: number) => {
+ if (pid === 101) {
+ throw new Error('kill ESRCH')
+ }
+ })
+
+ const killed = stopNativeGame('start.sh', install, {
+ readProcesses: () => [
+ nativeProcess(100, 1, ['/bin/bash', script], {
+ cwd: install,
+ executable: '/usr/bin/bash'
+ }),
+ nativeProcess(101, 100, [join(install, 'bin', 'game')], {
+ cwd: join(install, 'bin'),
+ executable: join(install, 'bin', 'game')
+ })
+ ],
+ kill
+ })
+
+ expect(killed).toEqual([100])
+ })
+
+ it('survives an unreadable process table', () => {
+ readdirSyncMock.mockImplementation(() => {
+ throw Object.assign(new Error('EACCES'), { code: 'EACCES' })
+ })
+ const kill = jest.fn()
+
+ const killed = stopNativeGame('start.sh', install, { kill })
+
+ expect(killed).toEqual([])
+ expect(kill).not.toHaveBeenCalled()
+ })
+
+ it('never terminates Heroic itself', () => {
+ const kill = jest.fn()
+ const killed = stopNativeGame('start.sh', install, {
+ readProcesses: () => [
+ nativeProcess(process.pid, 1, ['/bin/bash', script], {
+ cwd: install,
+ executable: '/usr/bin/node'
+ })
+ ],
+ kill
+ })
+
+ expect(kill).not.toHaveBeenCalled()
+ expect(killed).toEqual([])
+ })
+})
diff --git a/src/backend/storeManagers/zoom/__tests__/stopGame.test.ts b/src/backend/storeManagers/zoom/__tests__/stopGame.test.ts
new file mode 100644
index 000000000..ea87f8708
--- /dev/null
+++ b/src/backend/storeManagers/zoom/__tests__/stopGame.test.ts
@@ -0,0 +1,87 @@
+import { GameInfo, GameSettings } from 'common/types'
+
+import ZoomGame from '../games'
+import { stopNativeGame } from '../stop'
+import { sendGameStatusUpdate, shutdownWine } from 'backend/utils'
+
+jest.mock('node:fs/promises', (): typeof import('node:fs/promises') => ({
+ ...jest.requireActual<typeof import('node:fs/promises')>('node:fs/promises'),
+ rm: jest.fn(),
+ writeFile: jest.fn()
+}))
+jest.mock('backend/logger', () => ({
+ logError: jest.fn(),
+ logInfo: jest.fn(),
+ logWarning: jest.fn(),
+ logDebug: jest.fn(),
+ createGameLogWriter: jest.fn(),
+ LogPrefix: { Zoom: 'Zoom', Backend: 'Backend' }
+}))
+jest.mock('backend/constants/environment', () => ({
+ isLinux: true,
+ isMac: false,
+ isWindows: false
+}))
+jest.mock('backend/utils', (): typeof import('backend/utils') => ({
+ ...jest.requireActual<typeof import('backend/utils')>('backend/utils'),
+ shutdownWine: jest.fn(),
+ sendGameStatusUpdate: jest.fn()
+}))
+jest.mock('../stop', (): typeof import('../stop') => ({
+ ...jest.requireActual<typeof import('../stop')>('../stop'),
+ stopNativeGame: jest.fn()
+}))
+
+const stopNativeGameMock = jest.mocked(stopNativeGame)
+const shutdownWineMock = jest.mocked(shutdownWine)
+const sendGameStatusUpdateMock = jest.mocked(sendGameStatusUpdate)
+
+function mockGame(platform: string) {
+ const game = new ZoomGame('zoom-1')
+ const gameInfo = {
+ install: {
+ platform,
+ executable: 'start.sh',
+ install_path: '/games/foo'
+ }
+ } as unknown as GameInfo
+
+ jest.spyOn(game, 'getGameInfo').mockReturnValue(gameInfo)
+ jest
+ .spyOn(game, 'getSettings')
+ .mockResolvedValue({} as unknown as GameSettings)
+
+ return game
+}
+
+describe('ZoomGame.stop', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ it('kills the native process tree on Linux without shutting Wine down', async () => {
+ stopNativeGameMock.mockReturnValue([100, 101])
+
+ await mockGame('linux').stop()
+
+ expect(stopNativeGameMock).toHaveBeenCalledWith('start.sh', '/games/foo')
+ expect(shutdownWineMock).not.toHaveBeenCalled()
+ expect(sendGameStatusUpdateMock).toHaveBeenCalledWith({
+ appName: 'zoom-1',
+ runner: 'zoom',
+ status: 'done'
+ })
+ })
+
+ it('shuts Wine down for a Wine game and does not kill native processes', async () => {
+ await mockGame('windows').stop()
+
+ expect(shutdownWineMock).toHaveBeenCalled()
+ expect(stopNativeGameMock).not.toHaveBeenCalled()
+ expect(sendGameStatusUpdateMock).toHaveBeenCalledWith({
+ appName: 'zoom-1',
+ runner: 'zoom',
+ status: 'done'
+ })
+ })
+})
diff --git a/src/backend/storeManagers/zoom/games.ts b/src/backend/storeManagers/zoom/games.ts
index 86ed93154..e8eef9d36 100644
--- a/src/backend/storeManagers/zoom/games.ts
+++ b/src/backend/storeManagers/zoom/games.ts
@@ -58,7 +58,11 @@ import { findBatchLauncher, parseBatchLauncher } from './install'
import { missingInstallersError } from './errors'
import { resolveZoomInstallSelection } from './selection'
import { ZoomFileGroups, zoomFilesBytes } from 'common/zoomFiles'
-import { stoppedGameStatus, stopNeedsWineShutdown } from './stop'
+import {
+ stoppedGameStatus,
+ stopNeedsWineShutdown,
+ stopNativeGame
+} from './stop'
import { t } from 'i18next'
import { showDialogBoxModalAuto } from '../../dialog/dialog'
import { sendFrontendMessage } from '../../ipc'
@@ -1009,14 +1013,28 @@ export default class ZoomGame implements Game {
async stop(): Promise<void> {
logInfo(`Stopping ${this.id}`, LogPrefix.Zoom)
+ const isNative = this.isNative()
- if (stopNeedsWineShutdown(this.isNative())) {
+ if (stopNeedsWineShutdown(isNative)) {
const gameSettings = await this.getSettings()
try {
await shutdownWine(gameSettings)
} catch (error) {
logError(['Error shutting down Wine:', error], LogPrefix.Zoom)
}
+ } else if (isLinux) {
+ const gameInfo = this.getGameInfo()
+ const { executable, install_path: installPath } = gameInfo.install
+
+ if (executable && installPath) {
+ const killed = stopNativeGame(executable, installPath)
+ if (killed.length) {
+ logInfo(
+ `Stopped ${killed.length} native process(es) for ${this.id}`,
+ LogPrefix.Zoom
+ )
+ }
+ }
}
sendGameStatusUpdate(stoppedGameStatus(this.id))
diff --git a/src/backend/storeManagers/zoom/stop.ts b/src/backend/storeManagers/zoom/stop.ts
index 0bb9e1134..ab946fdb2 100644
--- a/src/backend/storeManagers/zoom/stop.ts
+++ b/src/backend/storeManagers/zoom/stop.ts
@@ -1,3 +1,14 @@
+import {
+ accessSync,
+ constants,
+ readdirSync,
+ readFileSync,
+ readlinkSync,
+ realpathSync,
+ statSync
+} from 'node:fs'
+import { basename, isAbsolute, join, resolve, sep } from 'node:path'
+
import { GameStatus } from 'common/types'
// Native Zoom games are spawned through callRunner with the app name as the
@@ -10,3 +21,270 @@ export function stopNeedsWineShutdown(isNative: boolean): boolean {
export function stoppedGameStatus(appName: string): GameStatus {
return { appName, runner: 'zoom', status: 'done' }
}
+
+export interface NativeProcess {
+ pid: number
+ ppid: number
+ cmdline: string[]
+ cwd?: string
+ executable?: string
+}
+
+function stripDeletedSuffix(path: string): string {
+ return path.replace(/ \(deleted\)$/, '')
+}
+
+/**
+ * Reads the process table from /proc. Only own processes are readable, which
+ * is enough: the game runs as the same user as Heroic.
+ */
+export function readNativeProcesses(procRoot = '/proc'): NativeProcess[] {
+ const processes: NativeProcess[] = []
+
+ let entries: string[]
+ try {
+ entries = readdirSync(procRoot)
+ } catch {
+ return processes
+ }
+
+ for (const entry of entries) {
+ if (!/^\d+$/.test(entry)) {
+ continue
+ }
+
+ const pid = Number(entry)
+ const base = join(procRoot, entry)
+
+ try {
+ const status = readFileSync(join(base, 'status'), 'utf-8')
+ const ppid = Number(/^PPid:\s+(\d+)$/m.exec(status)?.[1])
+ if (!Number.isFinite(ppid)) {
+ continue
+ }
+
+ const cmdline = readFileSync(join(base, 'cmdline'), 'utf-8')
+ .split('\0')
+ .filter(Boolean)
+
+ let cwd: string | undefined
+ try {
+ cwd = readlinkSync(join(base, 'cwd'))
+ } catch {
+ // Process may have exited or belong to another user.
+ }
+
+ let executable: string | undefined
+ try {
+ executable = stripDeletedSuffix(readlinkSync(join(base, 'exe')))
+ } catch {
+ // Same as above.
+ }
+
+ processes.push({ pid, ppid, cmdline, cwd, executable })
+ } catch {
+ // Process vanished while we were reading it.
+ }
+ }
+
+ return processes
+}
+
+function resolveArgument(argument: string, cwd?: string): string {
+ return isAbsolute(argument)
+ ? resolve(argument)
+ : resolve(cwd ?? '/', argument)
+}
+
+function resolveExistingPath(path: string): string {
+ try {
+ return realpathSync(path)
+ } catch {
+ return resolve(path)
+ }
+}
+
+function isRegularFile(path: string): boolean {
+ try {
+ return statSync(path).isFile()
+ } catch {
+ return false
+ }
+}
+
+function isExecutableFile(path: string): boolean {
+ try {
+ accessSync(path, constants.X_OK)
+ return true
+ } catch {
+ return false
+ }
+}
+
+// Scripts can be run without the executable bit when they are handed to an
+// interpreter, for example `bash /path/install/start.sh`.
+const scriptInterpreters = new Set([
+ 'bash',
+ 'sh',
+ 'dash',
+ 'zsh',
+ 'ksh',
+ 'fish',
+ 'csh',
+ 'tcsh',
+ 'python',
+ 'python3',
+ 'perl',
+ 'ruby',
+ 'php',
+ 'node',
+ 'java',
+ 'mono',
+ 'love',
+ 'env'
+])
+
+function isScriptInterpreter(command: string | undefined): boolean {
+ return Boolean(command && scriptInterpreters.has(basename(command)))
+}
+
+function isInsideInstallPath(path: string | undefined, installPath: string) {
+ if (!path) {
+ return false
+ }
+
+ return path === installPath || path.startsWith(`${installPath}${sep}`)
+}
+
+/**
+ * Finds the native game's processes. Heroic aborts the direct child first, so
+ * a launcher script may already be gone and its children reparented; matching
+ * by executable path and script argument still finds them.
+ */
+export function findNativeGamePids(
+ processes: NativeProcess[],
+ executable: string,
+ installPath: string
+): number[] {
+ const installDir = resolveExistingPath(installPath)
+ const executablePath = resolveExistingPath(
+ resolveArgument(executable, installDir)
+ )
+
+ const matches = (process: NativeProcess) => {
+ const executableUnderInstall = process.executable
+ ? resolveExistingPath(process.executable)
+ : undefined
+ if (isInsideInstallPath(executableUnderInstall, installDir)) {
+ return true
+ }
+
+ const [argv0, argv1] = process.cmdline
+ if (!argv0) {
+ return false
+ }
+
+ for (const argument of [argv0, argv1]) {
+ if (!argument) {
+ continue
+ }
+
+ const resolved = resolveExistingPath(
+ resolveArgument(argument, process.cwd)
+ )
+ if (
+ resolved !== executablePath &&
+ !isInsideInstallPath(resolved, installDir)
+ ) {
+ continue
+ }
+
+ if (!isRegularFile(resolved)) {
+ continue
+ }
+
+ if (isExecutableFile(resolved) || isScriptInterpreter(argv0)) {
+ return true
+ }
+ }
+
+ if (
+ process.cwd &&
+ isInsideInstallPath(resolveExistingPath(process.cwd), installDir) &&
+ isScriptInterpreter(argv0)
+ ) {
+ return true
+ }
+
+ return false
+ }
+
+ const roots = processes.filter(matches).map((process) => process.pid)
+ if (!roots.length) {
+ return []
+ }
+
+ const children = new Map<number, number[]>()
+ for (const process of processes) {
+ const siblings = children.get(process.ppid) ?? []
+ siblings.push(process.pid)
+ children.set(process.ppid, siblings)
+ }
+
+ const pids = new Set(roots)
+ const queue = [...roots]
+ while (queue.length) {
+ const pid = queue.shift()!
+ for (const child of children.get(pid) ?? []) {
+ if (!pids.has(child)) {
+ pids.add(child)
+ queue.push(child)
+ }
+ }
+ }
+
+ return [...pids].sort((a, b) => a - b)
+}
+
+interface StopNativeGameOptions {
+ readProcesses?: () => NativeProcess[]
+ kill?: (pid: number, signal?: NodeJS.Signals) => void
+}
+
+/**
+ * Terminates every process of a native Linux game. Returns the pids that were
+ * signalled. A process that already exited is ignored.
+ */
+export function stopNativeGame(
+ executable: string,
+ installPath: string,
+ options: StopNativeGameOptions = {}
+): number[] {
+ const readProcesses = options.readProcesses ?? readNativeProcesses
+ const kill =
+ options.kill ??
+ ((pid: number, signal?: NodeJS.Signals) => process.kill(pid, signal))
+ let pids: number[] = []
+ try {
+ pids = findNativeGamePids(readProcesses(), executable, installPath)
+ } catch {
+ // An unreadable process table must not keep the game stuck in playing.
+ pids = []
+ }
+
+ const killed: number[] = []
+ for (const pid of [...pids].reverse()) {
+ if (pid === process.pid) {
+ continue
+ }
+
+ try {
+ kill(pid, 'SIGTERM')
+ killed.push(pid)
+ } catch {
+ // Already gone.
+ }
+ }
+
+ return killed
+}