From 14fcb8adce6687bd9be20b9d7039b66c5f56156f Mon Sep 17 00:00:00 2001 From: vii Date: Tue, 1 Dec 2026 03:09:22 -0600 Subject: [PATCH 1/2] fix(graphics): pick working Vulkan drivers on AMD and Intel and fall back to OpenGL without one - Fix VK_LOADER_DRIVERS_DISABLE syntax (comma globs) so lavapipe is really filtered; a user-pinned VK_DRIVER_FILES list is left alone. - Pin ANV and hasvk together on Intel, accept AMDVLK, skip GPUs bound to vfio-pci and similar, and search XDG data dirs and /run/opengl-driver. - With no pinned driver, probe devices in a forked child (5 s cap) and switch to OpenGL when there is no hardware Vulkan device. - Gate ANV_SYS_MEM_LIMIT and the Mesa submit thread on Intel, and keep Mesa's device selector for pinned AMD/Intel ICDs. - Read the clipboard outside the text editor lock and drop the paste if focus moved meanwhile. - Retry the initial Wayland sync and continue instead of quitting. --- CHANGELOG.md | 12 + CMakeLists.txt | 1 + include/runtime/graphics_launch_policy.h | 33 ++- include/runtime/roblox_text_editor.h | 3 +- include/runtime/runtime_config.h | 4 + src/main.cc | 2 +- src/runtime/graphics_launch_policy.cc | 336 +++++++++++++++++++---- src/runtime/roblox_text_editor.cc | 53 +++- src/window/window.cc | 34 ++- tests/roblox_text_editor_test.cc | 81 ++++++ tests/supported_launch_policy_test.cc | 121 +++++++- tests/vulkan_icd_selection_test.cc | 74 +++++ 12 files changed, 664 insertions(+), 90 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b2ec3634..31359bf87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,18 @@ Release notes on GitHub are taken from the matching section here. where the driver is slow to destroy the old swapchain. Nightcap now waits at most 100 ms for a destroy and finishes slow ones in the background, so the first resize no longer freezes either. Quick resizes and window rebuilds no longer wait for those background destroys. +- With Vulkan, Nightcap no longer lands on the slow software renderer (lavapipe) when it cannot pin a GPU + driver. If no hardware Vulkan device exists at all, it starts with the OpenGL backend instead of + showing a blank window; `VK_DRIVER_FILES` forces Vulkan. +- Older Intel GPUs (Haswell, Broadwell) get a Vulkan device when both ANV and hasvk are installed. + Nightcap also finds GPU drivers on NixOS and in Flatpak, accepts AMDVLK, and skips a GPU passed + through to a VM. +- On AMD and Intel, `DRI_PRIME` and Mesa's GPU choice on laptops with two GPUs work again, and + Intel-only Mesa settings are no longer applied to AMD. +- Pasting into a Roblox TextBox no longer stalls the game while the program that owns the clipboard is + slow to answer. +- On a busy Wayland compositor, or with a Sway or Hyprland window rule, Nightcap no longer quits when the + window takes longer than usual to appear. - On FreeBSD, Roblox downloads no longer fail with "error adding trust anchors" in a Fedora userspace. - On FreeBSD, sound plays through `/dev/dsp` without an `asound.conf`, once `alsa-plugins-oss` is installed in the Linux userspace. An existing `~/.asoundrc` or `/etc/asound.conf` is still used. diff --git a/CMakeLists.txt b/CMakeLists.txt index 9d3380f7e..b5544496d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -367,6 +367,7 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND endif() target_link_libraries(mocktail_runtime PUBLIC Threads::Threads) target_link_libraries(mocktail_runtime PRIVATE + Vulkan::Headers OpenSSL::Crypto CURL::libcurl nlohmann_json::nlohmann_json diff --git a/include/runtime/graphics_launch_policy.h b/include/runtime/graphics_launch_policy.h index 79b172a1a..1d155842b 100644 --- a/include/runtime/graphics_launch_policy.h +++ b/include/runtime/graphics_launch_policy.h @@ -25,24 +25,49 @@ struct HostGpu { }; struct VulkanIcdSelection { - std::string manifest; // Empty when no GPU has a usable driver. + // Empty when no GPU has a usable driver. Intel pins ANV and hasvk together + // (colon-separated): each claims only its own GPU generations. + std::string manifest; + unsigned int vendor = 0; std::vector skipped; // Why each passed-over GPU was skipped. }; // ICD manifest for the first GPU whose bound kernel driver has an installed // Vulkan driver. NVIDIA and AMD cards are tried before Intel when // `prefer_discrete` is set, and after it otherwise. A GPU with an unknown -// kernel driver is matched by vendor alone. +// kernel driver is matched by vendor alone; one bound to a non-graphics +// driver (vfio-pci, pci-stub) is skipped. VulkanIcdSelection SelectHostVulkanIcd( const std::vector& gpus, const std::vector& directories, bool prefer_discrete); +std::vector VulkanIcdDirectories( + const char* xdg_data_home, const char* xdg_data_dirs, const char* home); + +enum class HostVulkanDevices { kHardware, kSoftwareOnly, kNone, kUnknown }; + +// Enumerates host Vulkan devices in a short-lived child process, so a driver +// that crashes or hangs on instance teardown never touches this process. +// kUnknown when the probe could not run or timed out. +HostVulkanDevices ProbeHostVulkanDevices(); + +using HostVulkanProbe = HostVulkanDevices (*)(); + +// GPUs listed under /sys/class/drm. +std::vector DetectHostGpus(); + +using HostGpuDetector = std::vector (*)(); + // Publishes the resolved graphics backend before the managed payload updater // starts. OpenGL is a strict system EGL/GLES path; it never silently retries // through ANGLE/Vulkan or accepts a window without a real graphics context. -bool ApplyGraphicsLaunchPolicy(const RuntimeConfig& config, - std::string* error = nullptr); +// When direct Vulkan has no pinned driver and `probe` finds no hardware +// device, `config` is switched to OpenGL. +bool ApplyGraphicsLaunchPolicy(RuntimeConfig* config, + std::string* error = nullptr, + HostVulkanProbe probe = ProbeHostVulkanDevices, + HostGpuDetector detect_gpus = DetectHostGpus); } // namespace runtime } // namespace mocktail diff --git a/include/runtime/roblox_text_editor.h b/include/runtime/roblox_text_editor.h index 6371285f0..4e77b978c 100644 --- a/include/runtime/roblox_text_editor.h +++ b/include/runtime/roblox_text_editor.h @@ -168,7 +168,8 @@ class RobloxTextEditor final { bool extend_selection); RobloxTextEditResult SelectAllLocked(); RobloxTextEditResult CopySelectionLocked(bool cut); - RobloxTextEditResult PasteLocked(); + RobloxTextEditResult PasteLocked(const Status& clipboard_status, + std::string* clipboard_text); RobloxTextEditResult FinishLocked(); RobloxTextEditResult ReleaseLocked(); Status SyncLocked(); diff --git a/include/runtime/runtime_config.h b/include/runtime/runtime_config.h index f7f483892..c70e2dfc1 100644 --- a/include/runtime/runtime_config.h +++ b/include/runtime/runtime_config.h @@ -143,6 +143,10 @@ class RuntimeConfig { const std::string& graphics_backend_name() const { return graphics_backend_name_; } + void UseGraphicsBackend(std::string name) { + graphics_backend_ = ParseGraphicsBackend(name); + graphics_backend_name_ = std::move(name); + } const WindowConfig& window() const { return window_; } const std::string& theme_mode() const { return theme_mode_; } bool theme_mode_valid() const { diff --git a/src/main.cc b/src/main.cc index 58cb5e6a6..85ee01258 100644 --- a/src/main.cc +++ b/src/main.cc @@ -786,7 +786,7 @@ int main(int argc, char* argv[]) { return EXIT_FAILURE; } if (command_line.options.mode == mocktail::runtime::CommandMode::kRun && - !mocktail::runtime::ApplyGraphicsLaunchPolicy(runtime_config.config, + !mocktail::runtime::ApplyGraphicsLaunchPolicy(&runtime_config.config, &command_line_error)) { std::cerr << "[FATAL] " << command_line_error << '\n'; return EXIT_FAILURE; diff --git a/src/runtime/graphics_launch_policy.cc b/src/runtime/graphics_launch_policy.cc index 3ae1e3157..4c2d89cce 100644 --- a/src/runtime/graphics_launch_policy.cc +++ b/src/runtime/graphics_launch_policy.cc @@ -2,7 +2,15 @@ #include "runtime/frame_rate_policy.h" +#include +#include +#include +#include +#include + #include +#include +#include #include #include #include @@ -11,10 +19,13 @@ #include #include #include -#include +#include #include #include +#define VK_NO_PROTOTYPES +#include + namespace mocktail { namespace runtime { namespace { @@ -34,15 +45,16 @@ constexpr const char* kIcdDirectories[] = { constexpr char kNativeArchitecture[] = "aarch64"; constexpr const char* kForeignArchitectures[] = { - "i686", "i586", "i486", "i386", "x86_64", "x86.", - "amd64", "armhf", "armv7", "ppc64", "riscv64", "s390x", + "i686", "i586", "i486", "i386", "x86_64", "x86.", "amd64", + "armhf", "armv7", "ppc64", "riscv64", "s390x", "icd32", }; #else constexpr char kNativeArchitecture[] = "x86_64"; +// icd32: AMDVLK's 32-bit manifest (amd_icd32.json). constexpr const char* kForeignArchitectures[] = { - "i686", "i586", "i486", "i386", "x86.", "aarch64", - "arm64", "armhf", "armv7", "ppc64", "riscv64", "s390x", + "i686", "i586", "i486", "i386", "x86.", "aarch64", "arm64", + "armhf", "armv7", "ppc64", "riscv64", "s390x", "icd32", }; #endif @@ -109,6 +121,8 @@ bool ParsePciVendor(const std::string& raw, unsigned int* vendor) { return true; } +} // namespace + std::vector DetectHostGpus() { std::vector gpus; for (int index = 0; index < 16; ++index) { @@ -131,6 +145,8 @@ std::vector DetectHostGpus() { return gpus; } +namespace { + const char* VendorName(unsigned int vendor) { switch (vendor) { case kPciVendorAmd: @@ -145,25 +161,32 @@ const char* VendorName(unsigned int vendor) { } // ICD manifest names that can drive `gpu`, best first. Empty when the bound -// kernel driver has no Vulkan driver at all. +// kernel driver has no Vulkan driver at all (radeon, vfio-pci, pci-stub). +// An unknown kernel driver (no sysfs link in a sandbox) matches by vendor. std::vector VulkanIcdsFor(const HostGpu& gpu) { + const std::string& driver = gpu.kernel_driver; switch (gpu.vendor) { case kPciVendorNvidia: - if (gpu.kernel_driver == "nvidia") { + if (driver == "nvidia") { return {"nvidia_icd"}; } - if (gpu.kernel_driver == "nouveau") { + if (driver == "nouveau") { return {"nouveau_icd"}; } - return {"nvidia_icd", "nouveau_icd"}; + if (driver.empty()) { + return {"nvidia_icd", "nouveau_icd"}; + } + return {}; case kPciVendorAmd: - // RADV needs the amdgpu kernel driver. - if (gpu.kernel_driver == "radeon") { - return {}; + if (driver == "amdgpu" || driver.empty()) { + return {"radeon_icd", "amd_icd", "amd_pro_icd"}; } - return {"radeon_icd"}; + return {}; case kPciVendorIntel: - return {"intel_icd", "intel_hasvk_icd"}; + if (driver == "i915" || driver == "xe" || driver.empty()) { + return {"intel_icd", "intel_hasvk_icd"}; + } + return {}; default: return {}; } @@ -201,47 +224,205 @@ const char* AnvSysMemLimitPercent() { return "50"; } +bool EnvSet(const char* name) { + const char* value = std::getenv(name); + return value != nullptr && value[0] != '\0'; +} + +struct VulkanIcdPolicy { + unsigned int vendor = 0; // Vendor of the pinned ICD; 0 when none pinned. + bool user_pinned = false; +}; + bool ApplyVulkanIcdPolicy(const std::vector& gpus, - std::string* error) { - // Drop software/emulation ICDs even when the user already pinned a driver - // list. Old loaders ignore this variable. - if (!SetDefault("VK_LOADER_DRIVERS_DISABLE", - "lvp_icd:dzn_icd:virtio_icd", error)) { - return false; - } - const char* existing_files = std::getenv("VK_DRIVER_FILES"); - const char* existing_icds = std::getenv("VK_ICD_FILENAMES"); - if ((existing_files != nullptr && existing_files[0] != '\0') || - (existing_icds != nullptr && existing_icds[0] != '\0')) { + VulkanIcdPolicy* policy, std::string* error) { + // A user-pinned driver list is used as given, lavapipe included. + if (EnvSet("VK_DRIVER_FILES") || EnvSet("VK_ICD_FILENAMES")) { + policy->user_pinned = true; return true; } - std::vector directories; - for (const char* directory : kIcdDirectories) { - directories.emplace_back(directory); + // The loader matches comma-separated globs against the manifest file name; + // old loaders ignore this variable. + if (!SetDefault("VK_LOADER_DRIVERS_DISABLE", "*lvp_icd*,*dzn_icd*", + error)) { + return false; } const bool prefer_discrete = !EnvIsOff("DRI_PRIME") && !EnvIsOff("__NV_PRIME_RENDER_OFFLOAD"); - const VulkanIcdSelection selection = - SelectHostVulkanIcd(gpus, directories, prefer_discrete); + const VulkanIcdSelection selection = SelectHostVulkanIcd( + gpus, + VulkanIcdDirectories(std::getenv("XDG_DATA_HOME"), + std::getenv("XDG_DATA_DIRS"), std::getenv("HOME")), + prefer_discrete); for (const std::string& reason : selection.skipped) { std::fprintf(stderr, " [runtime] vulkan: %s\n", reason.c_str()); } if (selection.manifest.empty()) { - if (!selection.skipped.empty()) { - std::fprintf(stderr, - " [runtime] vulkan: no GPU here can run Vulkan; set " - "graphics.backend: opengl in the config\n"); - } return true; } std::fprintf(stderr, " [runtime] vulkan ICD=%s\n", selection.manifest.c_str()); + policy->vendor = selection.vendor; return SetDefault("VK_DRIVER_FILES", selection.manifest, error) && SetDefault("VK_ICD_FILENAMES", selection.manifest, error); } +constexpr int kProbeHardware = 10; +constexpr int kProbeSoftwareOnly = 11; +constexpr int kProbeNone = 12; + +// Runs in the forked child. Never destroys the instance: the child exits +// straight away, and some drivers crash on teardown. +int ProbeHostVulkanDevicesInChild() { + void* loader = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL); + if (loader == nullptr) { + return kProbeNone; + } + const auto get_instance_proc = reinterpret_cast( + dlsym(loader, "vkGetInstanceProcAddr")); + if (get_instance_proc == nullptr) { + return kProbeNone; + } + const auto create_instance = reinterpret_cast( + get_instance_proc(nullptr, "vkCreateInstance")); + VkApplicationInfo application{}; + application.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + application.apiVersion = VK_API_VERSION_1_0; + VkInstanceCreateInfo create_info{}; + create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + create_info.pApplicationInfo = &application; + VkInstance instance = VK_NULL_HANDLE; + if (create_instance == nullptr || + create_instance(&create_info, nullptr, &instance) != VK_SUCCESS) { + return kProbeNone; + } + const auto enumerate = reinterpret_cast( + get_instance_proc(instance, "vkEnumeratePhysicalDevices")); + const auto properties = reinterpret_cast( + get_instance_proc(instance, "vkGetPhysicalDeviceProperties")); + uint32_t count = 0; + if (enumerate == nullptr || properties == nullptr || + enumerate(instance, &count, nullptr) < VK_SUCCESS || count == 0) { + return kProbeNone; + } + std::vector devices(count); + if (enumerate(instance, &count, devices.data()) < VK_SUCCESS) { + return kProbeNone; + } + for (uint32_t index = 0; index < count; ++index) { + VkPhysicalDeviceProperties device{}; + properties(devices[index], &device); + if (device.deviceType != VK_PHYSICAL_DEVICE_TYPE_CPU) { + return kProbeHardware; + } + } + return kProbeSoftwareOnly; +} + +const char* HostVulkanDevicesName(HostVulkanDevices devices) { + switch (devices) { + case HostVulkanDevices::kHardware: + return "hardware"; + case HostVulkanDevices::kSoftwareOnly: + return "software only"; + case HostVulkanDevices::kNone: + return "none"; + case HostVulkanDevices::kUnknown: + break; + } + return "unknown"; +} + } // namespace +std::vector VulkanIcdDirectories( + const char* xdg_data_home, const char* xdg_data_dirs, const char* home) { + std::vector directories; + const auto add = [&directories](const std::filesystem::path& data_dir) { + if (!data_dir.is_absolute()) { + return; + } + std::filesystem::path directory = data_dir / "vulkan/icd.d"; + if (std::find(directories.begin(), directories.end(), directory) == + directories.end()) { + directories.push_back(std::move(directory)); + } + }; + for (const char* directory : kIcdDirectories) { + directories.emplace_back(directory); + } + if (xdg_data_home != nullptr && xdg_data_home[0] != '\0') { + add(xdg_data_home); + } else if (home != nullptr && home[0] != '\0') { + add(std::filesystem::path(home) / ".local/share"); + } + std::string_view data_dirs = + xdg_data_dirs != nullptr && xdg_data_dirs[0] != '\0' + ? xdg_data_dirs + : "/usr/local/share:/usr/share"; + while (!data_dirs.empty()) { + const std::size_t colon = data_dirs.find(':'); + add(std::filesystem::path(data_dirs.substr(0, colon))); + if (colon == std::string_view::npos) { + break; + } + data_dirs.remove_prefix(colon + 1); + } + add("/run/opengl-driver/share"); + return directories; +} + +HostVulkanDevices ProbeHostVulkanDevices() { + std::fflush(nullptr); + const pid_t child = fork(); + if (child < 0) { + return HostVulkanDevices::kUnknown; + } + if (child == 0) { + // Keep driver chatter out of the session log. + const int null_fd = open("/dev/null", O_WRONLY | O_CLOEXEC); + if (null_fd >= 0) { + dup2(null_fd, STDOUT_FILENO); + dup2(null_fd, STDERR_FILENO); + } + _exit(ProbeHostVulkanDevicesInChild()); + } + constexpr auto kTimeout = std::chrono::seconds(5); + const auto deadline = std::chrono::steady_clock::now() + kTimeout; + int status = 0; + pid_t waited = 0; + for (;;) { + waited = waitpid(child, &status, WNOHANG); + if (waited < 0 && errno == EINTR) { + continue; + } + if (waited != 0 || std::chrono::steady_clock::now() >= deadline) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + if (waited <= 0) { + // Timed out, or waitpid failed: never leave a hung probe behind. + kill(child, SIGKILL); + while (waitpid(child, &status, 0) < 0 && errno == EINTR) { + } + return HostVulkanDevices::kUnknown; + } + if (!WIFEXITED(status)) { + return HostVulkanDevices::kUnknown; + } + switch (WEXITSTATUS(status)) { + case kProbeHardware: + return HostVulkanDevices::kHardware; + case kProbeSoftwareOnly: + return HostVulkanDevices::kSoftwareOnly; + case kProbeNone: + return HostVulkanDevices::kNone; + default: + return HostVulkanDevices::kUnknown; + } +} + VulkanIcdSelection SelectHostVulkanIcd( const std::vector& gpus, const std::vector& directories, @@ -253,17 +434,30 @@ VulkanIcdSelection SelectHostVulkanIcd( VulkanIcdSelection selection; for (const unsigned int vendor : prefer_discrete ? kDiscreteFirst : kIntegratedFirst) { + // ANV and hasvk each claim only their own Intel generations. + const bool pin_every_driver = vendor == kPciVendorIntel; for (const HostGpu& gpu : gpus) { if (gpu.vendor != vendor) { continue; } const std::vector icds = VulkanIcdsFor(gpu); for (const char* icd : icds) { - selection.manifest = SelectVulkanIcdManifest(directories, icd); + const std::string manifest = SelectVulkanIcdManifest(directories, icd); + if (manifest.empty()) { + continue; + } if (!selection.manifest.empty()) { - return selection; + selection.manifest += ':'; + } + selection.manifest += manifest; + if (!pin_every_driver) { + break; } } + if (!selection.manifest.empty()) { + selection.vendor = vendor; + return selection; + } selection.skipped.push_back(SkipReason(gpu, icds)); } } @@ -312,8 +506,10 @@ std::string SelectVulkanIcdManifest( return {}; } -bool ApplyGraphicsLaunchPolicy(const RuntimeConfig& config, - std::string* error) { +bool ApplyGraphicsLaunchPolicy(RuntimeConfig* runtime_config, + std::string* error, HostVulkanProbe probe, + HostGpuDetector detect_gpus) { + const RuntimeConfig& config = *runtime_config; if (!RuntimeConfig::IsValidPresentMode(config.present_mode())) { if (error != nullptr) *error = "cannot apply an invalid present mode"; return false; @@ -346,23 +542,55 @@ bool ApplyGraphicsLaunchPolicy(const RuntimeConfig& config, return false; } - if (direct_vulkan) { - const std::vector gpus = DetectHostGpus(); - if (!SetDefault("MOCKTAIL_CLIENT_SETTINGS_OVERRIDES_JSON", - kVulkanClientSettingsOverrides, error) || - !SetDefault("ANV_SYS_MEM_LIMIT", AnvSysMemLimitPercent(), error) || - (config.present_mode() == "auto" && - !SetDefault("MESA_VK_WSI_PRESENT_MODE", - UnthrottledPresentation(config) ? "immediate" : "mailbox", - error)) || - // Move GEM_EXECBUFFER2 off the application thread onto Mesa's submit - // worker so the render thread is not stuck in i915 ioctl. - !SetDefault("MESA_VK_ENABLE_SUBMIT_THREAD", "1", error) || - !ApplyVulkanIcdPolicy(gpus, error)) { - return false; + if (!direct_vulkan) { + return true; + } + const std::vector gpus = detect_gpus(); + VulkanIcdPolicy icd; + if (!ApplyVulkanIcdPolicy(gpus, &icd, error)) { + return false; + } + if (icd.vendor == 0 && !icd.user_pinned && probe != nullptr) { + const auto probe_started = std::chrono::steady_clock::now(); + const HostVulkanDevices devices = probe(); + const long long probe_ms = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - probe_started) + .count(); + std::fprintf(stderr, " [runtime] vulkan devices=%s (probe %lld ms)\n", + HostVulkanDevicesName(devices), probe_ms); + if (devices == HostVulkanDevices::kNone || + devices == HostVulkanDevices::kSoftwareOnly) { + std::fprintf(stderr, + " [runtime] vulkan: no hardware Vulkan device; using the " + "OpenGL backend (set VK_DRIVER_FILES to force Vulkan)\n"); + runtime_config->UseGraphicsBackend("opengl"); + return ApplyGraphicsLaunchPolicy(runtime_config, error, nullptr, + detect_gpus); } } - return true; + const bool intel = + icd.vendor == kPciVendorIntel || + (icd.vendor == 0 && + std::any_of(gpus.begin(), gpus.end(), [](const HostGpu& gpu) { + return gpu.vendor == kPciVendorIntel; + })); + // Mesa's device-select layer is what honours DRI_PRIME and orders an + // iGPU+dGPU pair on one Mesa ICD; keep it for a pinned AMD or Intel ICD. + const bool mesa_pinned = + icd.vendor == kPciVendorAmd || icd.vendor == kPciVendorIntel; + return SetDefault("MOCKTAIL_CLIENT_SETTINGS_OVERRIDES_JSON", + kVulkanClientSettingsOverrides, error) && + (!intel || + SetDefault("ANV_SYS_MEM_LIMIT", AnvSysMemLimitPercent(), error)) && + (config.present_mode() != "auto" || + SetDefault("MESA_VK_WSI_PRESENT_MODE", + UnthrottledPresentation(config) ? "immediate" : "mailbox", + error)) && + // Move GEM_EXECBUFFER2 off the application thread onto Mesa's submit + // worker so the render thread is not stuck in i915 ioctl. + (!intel || SetDefault("MESA_VK_ENABLE_SUBMIT_THREAD", "1", error)) && + (mesa_pinned || SetDefault("NODEVICE_SELECT", "1", error)); } } // namespace runtime diff --git a/src/runtime/roblox_text_editor.cc b/src/runtime/roblox_text_editor.cc index a4bee318e..fc90a04ef 100644 --- a/src/runtime/roblox_text_editor.cc +++ b/src/runtime/roblox_text_editor.cc @@ -348,12 +348,37 @@ RobloxTextEditResult RobloxTextEditor::HandleTextEditing( RobloxTextEditResult RobloxTextEditor::HandleKey( const platform::KeyEvent& event) { + const auto scancode = static_cast(event.scancode); + // Read the clipboard before taking mutex_: on Wayland SDL waits on the + // owning client's pipe for up to 5 s, and the engine thread needs the + // editor meanwhile. + std::string clipboard_text; + struct ClearClipboardText { + std::string* text; + ~ClearClipboardText() { SecureClear(text); } + } clear_clipboard_text{&clipboard_text}; + Status clipboard_status = Status::Ok(); + bool clipboard_read = false; + int64_t clipboard_textbox = 0; + uint64_t clipboard_generation = 0; + if (clipboard_ != nullptr && event.pressed && + ShortcutBit(scancode) == kShortcutPaste && + (event.modifiers & static_cast(SDL_KMOD_CTRL)) != 0 && + (event.modifiers & static_cast(SDL_KMOD_ALT)) == 0) { + std::lock_guard lock(mutex_); + clipboard_read = snapshot_.focused && !composition_active_; + clipboard_textbox = snapshot_.textbox_handle; + clipboard_generation = snapshot_.generation; + } + if (clipboard_read) { + clipboard_status = clipboard_->ReadText(&clipboard_text); + } + std::lock_guard lock(mutex_); if (!snapshot_.focused) { return Result(false, false, false); } - const auto scancode = static_cast(event.scancode); const uint32_t shortcut_bit = ShortcutBit(scancode); const bool ctrl_pressed = (event.modifiers & static_cast(SDL_KMOD_CTRL)) != 0; @@ -398,7 +423,12 @@ RobloxTextEditResult RobloxTextEditor::HandleKey( return CopySelectionLocked(false); } if (shortcut_bit == kShortcutPaste) { - return PasteLocked(); + // Drop text read for a TextBox that lost focus during the read. + if (!clipboard_read || snapshot_.textbox_handle != clipboard_textbox || + snapshot_.generation != clipboard_generation) { + return Result(true, false, false); + } + return PasteLocked(clipboard_status, &clipboard_text); } if (shortcut_bit == kShortcutCut) { return CopySelectionLocked(true); @@ -639,25 +669,18 @@ RobloxTextEditResult RobloxTextEditor::CopySelectionLocked(bool cut) { return ReplaceLocked(begin, end, ""); } -RobloxTextEditResult RobloxTextEditor::PasteLocked() { - if (clipboard_ == nullptr) { - return Result(true, false, false); - } - std::string clipboard_text; - const Status clipboard_status = clipboard_->ReadText(&clipboard_text); +RobloxTextEditResult RobloxTextEditor::PasteLocked( + const Status& clipboard_status, std::string* clipboard_text) { const std::size_t begin = SelectionBeginLocked(); const std::size_t end = SelectionEndLocked(); - const bool valid = clipboard_status.ok() && !clipboard_text.empty() && - clipboard_text.size() <= + const bool valid = clipboard_status.ok() && !clipboard_text->empty() && + clipboard_text->size() <= kMaximumTextBytes - (text_.size() - (end - begin)) && - Layout(clipboard_text).valid; + Layout(*clipboard_text).valid; if (!valid) { - SecureClear(&clipboard_text); return Result(true, false, false); } - RobloxTextEditResult result = ReplaceLocked(begin, end, clipboard_text); - SecureClear(&clipboard_text); - return result; + return ReplaceLocked(begin, end, *clipboard_text); } RobloxTextEditResult RobloxTextEditor::FinishLocked() { diff --git a/src/window/window.cc b/src/window/window.cc index 83406487e..6f9bd8bd5 100644 --- a/src/window/window.cc +++ b/src/window/window.cc @@ -676,10 +676,12 @@ bool ConfigureGraphicsBackendBeforeSDL() { SDL_SetHint(SDL_HINT_VIDEO_FORCE_EGL, "1"); if (ShouldUseAngleVulkanBackend() || ShouldUseNativeVulkanBackend()) { + setenv("DISABLE_LAYER_MESA_ANTI_LAG", "1", 0); + } + if (ShouldUseAngleVulkanBackend()) { // Mesa's implicit device selector can crash in the Android Vulkan path; // its supported opt-out is NODEVICE_SELECT=1. setenv("NODEVICE_SELECT", "1", 0); - setenv("DISABLE_LAYER_MESA_ANTI_LAG", "1", 0); } const VideoDriverChoice video_driver_choice = @@ -1221,17 +1223,25 @@ bool Init(int width, int height, const char* title) { } const char* active_video_driver = SDL_GetCurrentVideoDriver(); if (DirectVulkanWindowRequiresInitialSync( - active_video_driver != nullptr ? active_video_driver : "") && - !SDL_SyncWindow(g_state.sdl_window)) { - fprintf(stderr, - " [window] SDL_SyncWindow timed out waiting for the initial " - "Wayland configure\n"); - SDL_DestroyWindow(g_state.sdl_window); - g_state.sdl_window = nullptr; - SDL_Quit(); - g_state.direct_vulkan = false; - g_state.initialised = false; - return false; + active_video_driver != nullptr ? active_video_driver : "")) { + // A busy compositor or a workspace rule (Sway, Hyprland) can delay the + // first configure past one sync; a late configure still reaches the + // surface lifecycle, so keep going rather than abort the launch. + constexpr int kInitialSyncAttempts = 3; + bool synced = false; + for (int attempt = 0; attempt < kInitialSyncAttempts && !synced; + ++attempt) { + synced = SDL_SyncWindow(g_state.sdl_window); + if (!synced) { + SDL_PumpEvents(); + } + } + if (!synced) { + fprintf(stderr, + " [window] SDL_SyncWindow timed out %d times waiting for the " + "initial Wayland configure; continuing\n", + kInitialSyncAttempts); + } } int pixel_width = 0; int pixel_height = 0; diff --git a/tests/roblox_text_editor_test.cc b/tests/roblox_text_editor_test.cc index b6e0a7822..1ed9ab47e 100644 --- a/tests/roblox_text_editor_test.cc +++ b/tests/roblox_text_editor_test.cc @@ -4,6 +4,9 @@ #include #include +#include +#include +#include #include #include #include @@ -77,6 +80,9 @@ class ClipboardProbe final : public platform::TextClipboard { public: Status ReadText(std::string* text) override { ++read_calls; + if (on_read) { + on_read(); + } if (fail_read) { return Status::Error(StatusCode::kPlatformError, "injected clipboard read failure"); @@ -101,6 +107,7 @@ class ClipboardProbe final : public platform::TextClipboard { int write_calls = 0; bool fail_read = false; bool fail_write = false; + std::function on_read; }; Status Record(Probe* probe, Call call) { @@ -473,6 +480,80 @@ TEST(RobloxTextEditorTest, CtrlVReplacesSelectionWithUtf8ClipboardText) { EXPECT_FALSE(key_up.dispatched); } +// A hung Wayland clipboard owner can hold SDL_GetClipboardText for seconds; +// the engine thread must still reach the editor meanwhile. +TEST(RobloxTextEditorTest, ClipboardReadDoesNotHoldTheEditorLock) { + Probe probe; + ClipboardProbe clipboard; + clipboard.read_text = "pasted"; + RobloxTextEditor editor(Sink(&probe), {}, &clipboard); + ASSERT_TRUE(editor.BeginFocusSession(Session(42, 7, "")).ok()); + bool engine_reached_editor = false; + std::promise reached; + std::thread engine; + clipboard.on_read = [&] { + std::future done = reached.get_future(); + engine = std::thread([&editor, &reached] { + (void)editor.Snapshot(); + reached.set_value(); + }); + engine_reached_editor = + done.wait_for(std::chrono::seconds(2)) == std::future_status::ready; + }; + + const auto paste = editor.HandleKey(Shortcut(SDL_SCANCODE_V)); + if (engine.joinable()) { + engine.join(); + } + EXPECT_TRUE(engine_reached_editor); + ASSERT_TRUE(paste.status.ok()); + EXPECT_TRUE(paste.dispatched); + EXPECT_EQ(clipboard.read_calls, 1); + ASSERT_FALSE(probe.calls.empty()); + EXPECT_EQ(probe.calls.back().text, "pasted"); +} + +TEST(RobloxTextEditorTest, PasteOutsideAFocusedTextBoxSkipsTheClipboard) { + Probe probe; + ClipboardProbe clipboard; + RobloxTextEditor editor(Sink(&probe), {}, &clipboard); + EXPECT_FALSE(editor.HandleKey(Shortcut(SDL_SCANCODE_V)).handled); + EXPECT_EQ(clipboard.read_calls, 0); +} + +// Focus can move to another TextBox while the clipboard read is in flight. +TEST(RobloxTextEditorTest, PasteIsDroppedWhenFocusMovesDuringTheClipboardRead) { + Probe probe; + ClipboardProbe clipboard; + clipboard.read_text = "pasted"; + RobloxTextEditor editor(Sink(&probe), {}, &clipboard); + ASSERT_TRUE(editor.BeginFocusSession(Session(42, 7, "")).ok()); + clipboard.on_read = [&] { + ASSERT_TRUE(editor.EndFocusSession(42, 7, false).ok()); + ASSERT_TRUE(editor.BeginFocusSession(Session(43, 8, "other")).ok()); + }; + + const auto paste = editor.HandleKey(Shortcut(SDL_SCANCODE_V)); + EXPECT_TRUE(paste.handled); + EXPECT_FALSE(paste.dispatched); + EXPECT_EQ(clipboard.read_calls, 1); + for (const auto& call : probe.calls) { + EXPECT_EQ(call.text.find("pasted"), std::string::npos); + } +} + +TEST(RobloxTextEditorTest, PasteDuringCompositionSkipsTheClipboard) { + Probe probe; + ClipboardProbe clipboard; + clipboard.read_text = "pasted"; + RobloxTextEditor editor(Sink(&probe), {}, &clipboard); + ASSERT_TRUE(editor.BeginFocusSession(Session(42, 7, "")).ok()); + ASSERT_TRUE(editor.HandleTextEditing({"候補", 2, 0}).status.ok()); + + EXPECT_TRUE(editor.HandleKey(Shortcut(SDL_SCANCODE_V)).handled); + EXPECT_EQ(clipboard.read_calls, 0); +} + TEST(RobloxTextEditorTest, ShiftSelectionRespectsGraphemesAndCommittedTextReplacesIt) { Probe probe; diff --git a/tests/supported_launch_policy_test.cc b/tests/supported_launch_policy_test.cc index 4f97acdb9..55abfe2b3 100644 --- a/tests/supported_launch_policy_test.cc +++ b/tests/supported_launch_policy_test.cc @@ -161,6 +161,33 @@ TEST(SupportedLaunchPolicyTest, PreservesCandidateManifestOverPackagedDefault) { ExpectPackagedManifestProbe(true); } +HostVulkanDevices HardwareVulkan() { return HostVulkanDevices::kHardware; } +HostVulkanDevices NoVulkan() { return HostVulkanDevices::kNone; } +HostVulkanDevices SoftwareVulkan() { + return HostVulkanDevices::kSoftwareOnly; +} +std::vector NoGpus() { return {}; } +std::vector UnpinnedIntelGpu() { return {{0x8086, "i915"}}; } + +bool ClearGraphicsEnvironment() { + for (const char* name : { + "MOCKTAIL_GRAPHICS_BACKEND", + "MOCKTAIL_PRELOAD_VULKAN_SHIM", + "MOCKTAIL_DISABLE_AUTO_ANGLE_FALLBACK", + "MOCKTAIL_SOFTWARE_WINDOW_FALLBACK", + "MOCKTAIL_REQUIRE_REAL_GRAPHICS", + "MOCKTAIL_CLIENT_SETTINGS_OVERRIDES_JSON", + "ANV_SYS_MEM_LIMIT", + "MESA_VK_ENABLE_SUBMIT_THREAD", + "NODEVICE_SELECT", + "VK_DRIVER_FILES", + "VK_ICD_FILENAMES", + }) { + if (unsetenv(name) != 0) return false; + } + return true; +} + int RunGraphicsPolicyProbe(const char* backend) { for (const char* name : { "MOCKTAIL_GRAPHICS_BACKEND", @@ -179,9 +206,12 @@ int RunGraphicsPolicyProbe(const char* backend) { return 21; } const ProcessEnvironment environment; - const RuntimeConfig config = RuntimeConfig::FromEnvironment(environment); + RuntimeConfig config = RuntimeConfig::FromEnvironment(environment); std::string error; - if (!ApplyGraphicsLaunchPolicy(config, &error)) return 22; + if (!ApplyGraphicsLaunchPolicy(&config, &error, HardwareVulkan, + UnpinnedIntelGpu)) { + return 22; + } const bool open_gl = backend != nullptr && std::string(backend) == "opengl"; const char* resolved = getenv("MOCKTAIL_GRAPHICS_BACKEND"); @@ -283,7 +313,8 @@ TEST(GraphicsLaunchPolicyTest, KeepsMesaPresentDefaultsUnlessModeIsExplicit) { if (std::string(test.mode) == "auto") { unsetenv("MESA_VK_WSI_PRESENT_MODE"); } - if (!ApplyGraphicsLaunchPolicy(RuntimeConfig::FromEnvironment(environment))) + RuntimeConfig config = RuntimeConfig::FromEnvironment(environment); + if (!ApplyGraphicsLaunchPolicy(&config, nullptr, HardwareVulkan)) std::_Exit(40); const char* actual = getenv("MESA_VK_WSI_PRESENT_MODE"); if (test.expected == nullptr ? actual != nullptr @@ -299,6 +330,90 @@ TEST(GraphicsLaunchPolicyTest, KeepsMesaPresentDefaultsUnlessModeIsExplicit) { EXPECT_EQ(WEXITSTATUS(status), 0); } +int RunVulkanFallbackProbe(HostVulkanProbe probe) { + if (!ClearGraphicsEnvironment() || + setenv("MOCKTAIL_GRAPHICS_BACKEND", "direct-vulkan", 1) != 0) { + return 30; + } + const ProcessEnvironment environment; + RuntimeConfig config = RuntimeConfig::FromEnvironment(environment); + if (!ApplyGraphicsLaunchPolicy(&config, nullptr, probe, NoGpus)) return 31; + const char* backend = getenv("MOCKTAIL_GRAPHICS_BACKEND"); + const char* preload = getenv("MOCKTAIL_PRELOAD_VULKAN_SHIM"); + const bool vulkan = probe == HardwareVulkan; + if (backend == nullptr || preload == nullptr || + std::string(backend) != (vulkan ? "direct-vulkan" : "opengl") || + std::string(preload) != (vulkan ? "1" : "0") || + config.graphics_backend_name() != backend) { + return 32; + } + if (vulkan) { + // Unpinned, so Mesa's device selector stays off, and no Intel GPU. + const char* no_select = getenv("NODEVICE_SELECT"); + return no_select != nullptr && std::string(no_select) == "1" && + getenv("ANV_SYS_MEM_LIMIT") == nullptr && + getenv("MESA_VK_ENABLE_SUBMIT_THREAD") == nullptr + ? 0 + : 33; + } + return getenv("MOCKTAIL_CLIENT_SETTINGS_OVERRIDES_JSON") == nullptr && + getenv("MOCKTAIL_DISABLE_AUTO_ANGLE_FALLBACK") != nullptr + ? 0 + : 34; +} + +void ExpectVulkanFallbackProbe(HostVulkanProbe probe) { + const pid_t child = fork(); + ASSERT_GE(child, 0); + if (child == 0) { + std::_Exit(RunVulkanFallbackProbe(probe)); + } + int status = 0; + ASSERT_EQ(waitpid(child, &status, 0), child); + ASSERT_TRUE(WIFEXITED(status)); + EXPECT_EQ(WEXITSTATUS(status), 0); +} + +TEST(GraphicsLaunchPolicyTest, FallsBackToOpenGlWithoutAVulkanDevice) { + ExpectVulkanFallbackProbe(NoVulkan); +} + +TEST(GraphicsLaunchPolicyTest, FallsBackToOpenGlOnSoftwareVulkanOnly) { + ExpectVulkanFallbackProbe(SoftwareVulkan); +} + +TEST(GraphicsLaunchPolicyTest, KeepsVulkanWhenTheProbeFindsAGpu) { + ExpectVulkanFallbackProbe(HardwareVulkan); +} + +TEST(GraphicsLaunchPolicyTest, UserPinnedDriversAreNotFiltered) { + const pid_t child = fork(); + ASSERT_GE(child, 0); + if (child == 0) { + if (!ClearGraphicsEnvironment() || + unsetenv("VK_LOADER_DRIVERS_DISABLE") != 0 || + setenv("MOCKTAIL_GRAPHICS_BACKEND", "direct-vulkan", 1) != 0 || + setenv("VK_DRIVER_FILES", "/usr/share/vulkan/icd.d/lvp_icd.json", 1) != + 0) { + std::_Exit(50); + } + const ProcessEnvironment environment; + RuntimeConfig config = RuntimeConfig::FromEnvironment(environment); + // NoVulkan would switch to OpenGL if the probe ran; a pinned list skips it. + if (!ApplyGraphicsLaunchPolicy(&config, nullptr, NoVulkan, NoGpus)) { + std::_Exit(51); + } + std::_Exit(getenv("VK_LOADER_DRIVERS_DISABLE") == nullptr && + config.graphics_backend_name() == "direct-vulkan" + ? 0 + : 52); + } + int status = 0; + ASSERT_EQ(waitpid(child, &status, 0), child); + ASSERT_TRUE(WIFEXITED(status)); + EXPECT_EQ(WEXITSTATUS(status), 0); +} + } // namespace } // namespace runtime } // namespace mocktail diff --git a/tests/vulkan_icd_selection_test.cc b/tests/vulkan_icd_selection_test.cc index b6b2db5ff..16436f8f6 100644 --- a/tests/vulkan_icd_selection_test.cc +++ b/tests/vulkan_icd_selection_test.cc @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -204,6 +205,79 @@ TEST(HostVulkanIcdTest, PrefersTheIntelChipWhenTheDiscreteCardIsNotWanted) { (temporary.root() / "intel_icd.json").string()); } +TEST(HostVulkanIcdTest, IntelPinsAnvAndHasvkTogether) { + TemporaryDirectory temporary; + WriteManifest(temporary.root() / "intel_icd.json"); + WriteManifest(temporary.root() / "intel_hasvk_icd.json"); + + const VulkanIcdSelection selection = + SelectHostVulkanIcd({{kIntel, "i915"}}, {temporary.root()}, true); + EXPECT_EQ(selection.manifest, + (temporary.root() / "intel_icd.json").string() + ":" + + (temporary.root() / "intel_hasvk_icd.json").string()); + EXPECT_EQ(selection.vendor, kIntel); +} + +TEST(HostVulkanIcdTest, IntelWithOnlyHasvkSelectsHasvk) { + TemporaryDirectory temporary; + WriteManifest(temporary.root() / "intel_hasvk_icd.json"); + + EXPECT_EQ( + SelectHostVulkanIcd({{kIntel, "i915"}}, {temporary.root()}, true).manifest, + (temporary.root() / "intel_hasvk_icd.json").string()); +} + +TEST(HostVulkanIcdTest, PassthroughCardFallsBackToTheHostGpu) { + TemporaryDirectory temporary; + WriteManifest(temporary.root() / "nvidia_icd.json"); + WriteManifest(temporary.root() / "radeon_icd.json"); + + const VulkanIcdSelection selection = SelectHostVulkanIcd( + {{kNvidia, "vfio-pci"}, {kAmd, "amdgpu"}}, {temporary.root()}, true); + EXPECT_EQ(selection.manifest, + (temporary.root() / "radeon_icd.json").string()); + EXPECT_EQ(selection.vendor, kAmd); + ASSERT_EQ(selection.skipped.size(), 1u); + EXPECT_NE(selection.skipped[0].find("vfio-pci"), std::string::npos); +} + +TEST(HostVulkanIcdTest, AmdPrefersRadvThenAcceptsAmdvlk) { + TemporaryDirectory temporary; + WriteManifest(temporary.root() / "amd_icd64.json"); + WriteManifest(temporary.root() / "amd_icd32.json"); + + EXPECT_EQ( + SelectHostVulkanIcd({{kAmd, "amdgpu"}}, {temporary.root()}, true).manifest, + (temporary.root() / "amd_icd64.json").string()); + + WriteManifest(temporary.root() / "radeon_icd.json"); + EXPECT_EQ( + SelectHostVulkanIcd({{kAmd, "amdgpu"}}, {temporary.root()}, true).manifest, + (temporary.root() / "radeon_icd.json").string()); +} + +TEST(VulkanIcdDirectoriesTest, AddsXdgAndNixDirectoriesAfterTheSystemOnes) { + const std::vector directories = + VulkanIcdDirectories("/data/home", "/flatpak/GL:/usr/share", "/h"); + const std::vector expected = { + "/usr/share/vulkan/icd.d", + "/etc/vulkan/icd.d", + "/usr/local/share/vulkan/icd.d", + "/data/home/vulkan/icd.d", + "/flatpak/GL/vulkan/icd.d", + "/run/opengl-driver/share/vulkan/icd.d", + }; + EXPECT_EQ(directories, expected); +} + +TEST(VulkanIcdDirectoriesTest, DefaultsXdgDataHomeToHome) { + const std::vector directories = + VulkanIcdDirectories(nullptr, nullptr, "/h"); + EXPECT_NE(std::find(directories.begin(), directories.end(), + std::filesystem::path("/h/.local/share/vulkan/icd.d")), + directories.end()); +} + TEST(HostVulkanIcdTest, NoKnownCardSelectsNothingAndSkipsNothing) { TemporaryDirectory temporary; WriteManifest(temporary.root() / "nvidia_icd.json"); From 95702d21bfc52ca165b827ef059256bddedf6fb7 Mon Sep 17 00:00:00 2001 From: vii Date: Tue, 1 Dec 2026 03:15:48 -0600 Subject: [PATCH 2/2] test(updater): pin a Vulkan driver list so the backend test is host-independent --- tests/updater_launch_environment_test.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/updater_launch_environment_test.py b/tests/updater_launch_environment_test.py index 352f6ba6d..33eaeda4f 100644 --- a/tests/updater_launch_environment_test.py +++ b/tests/updater_launch_environment_test.py @@ -38,6 +38,9 @@ def main(): "MOCKTAIL_TEST_UPDATE_EXIT": "7", "MOCKTAIL_DISABLE_FAILURE_DIALOG": "1", "MOCKTAIL_DISABLE_SUPPORT_BUNDLE": "1", + # A pinned driver list skips the Vulkan device probe, which + # would switch a GPU-less CI runner to OpenGL. + "VK_DRIVER_FILES": str(case / "pinned_icd.json"), }) completed = subprocess.run( [binary, "--headless", *arguments], env=environment, cwd=case,