소스 검색

Fix findings from the static analysis review

Hardening of the file readers and parsers:
  - size and count caps in the package, texture, model and JSON readers
  - finite-float and combo value checks for wrong-typed JSON
  - MDL fuzz tool with a morph wrap fix
  - script limits and ArrayBuffer cap, isolated A8-4 state

  Audio fixes:
  - shared static packet size crash in AudioStream
  - one-shot EOF deadlock
  - several script audio buffer bugs

  Lifetime and leak fixes:
  - ShaderVariable leak
  - model freed when no longer used
  - stale layer release
  - stale KWin scripts cleaned up with a janitor helper

  Behaviour fixes:
  - setuid handling for chrome-sandbox in the release scripts
  - several wrong-behaviour cases
  - release packaging and smoke test script updates

  Adds tools/static_analysis.py for the review harness.
UwU 1 개월 전
부모
커밋
1345c6be39
100개의 변경된 파일과 3476개의 추가작업 그리고 444개의 파일을 삭제
  1. 73 2
      CMakeLists.txt
  2. 53 9
      CMakeModules/DownloadCEF.cmake
  3. 1 1
      README.md
  4. 37 0
      nix/package.nix
  5. 84 25
      src/Steam/FileSystem/FileSystem.cpp
  6. 13 9
      src/WallpaperEngine/Application/ApplicationContext.cpp
  7. 3 1
      src/WallpaperEngine/Application/ApplicationState.h
  8. 15 0
      src/WallpaperEngine/Application/ControlFileOwner.h
  9. 185 53
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  10. 14 0
      src/WallpaperEngine/Application/WallpaperApplication.h
  11. 56 10
      src/WallpaperEngine/Audio/AudioStream.cpp
  12. 5 3
      src/WallpaperEngine/Audio/AudioStream.h
  13. 6 9
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp
  14. 2 2
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h
  15. 13 12
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp
  16. 40 8
      src/WallpaperEngine/Data/JSON.h
  17. 28 0
      src/WallpaperEngine/Data/Parsers/ComboValue.h
  18. 3 2
      src/WallpaperEngine/Data/Parsers/EffectParser.cpp
  19. 43 8
      src/WallpaperEngine/Data/Parsers/MaterialParser.cpp
  20. 3 1
      src/WallpaperEngine/Data/Parsers/ModelParser.cpp
  21. 8 7
      src/WallpaperEngine/Data/Parsers/ObjectParser.cpp
  22. 8 0
      src/WallpaperEngine/Data/Parsers/PackageParser.cpp
  23. 80 6
      src/WallpaperEngine/Data/Parsers/ProjectParser.cpp
  24. 4 0
      src/WallpaperEngine/Data/Parsers/ProjectParser.h
  25. 18 3
      src/WallpaperEngine/Data/Parsers/PropertyParser.cpp
  26. 57 1
      src/WallpaperEngine/Data/Parsers/TextureParser.cpp
  27. 36 6
      src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp
  28. 61 7
      src/WallpaperEngine/Data/Utils/BinaryReader.cpp
  29. 8 0
      src/WallpaperEngine/Data/Utils/BinaryReader.h
  30. 20 0
      src/WallpaperEngine/Data/Utils/FiniteFloat.h
  31. 3 1
      src/WallpaperEngine/Desktop/GnomeShell.cpp
  32. 205 13
      src/WallpaperEngine/Desktop/KWinScript.cpp
  33. 14 1
      src/WallpaperEngine/Desktop/KWinScript.h
  34. 3 1
      src/WallpaperEngine/Desktop/PowerMonitor.cpp
  35. 5 1
      src/WallpaperEngine/Desktop/UserShortcut.cpp
  36. 13 4
      src/WallpaperEngine/FileSystem/Adapters/Directory.cpp
  37. 14 1
      src/WallpaperEngine/FileSystem/Adapters/Package.cpp
  38. 12 5
      src/WallpaperEngine/Logging/Log.cpp
  39. 13 2
      src/WallpaperEngine/Logging/Log.h
  40. 18 0
      src/WallpaperEngine/Logging/ThreadGuard.h
  41. 5 1
      src/WallpaperEngine/Media/CoverDownloader.cpp
  42. 39 4
      src/WallpaperEngine/Render/CTexture.cpp
  43. 4 1
      src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.cpp
  44. 1 0
      src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.cpp
  45. 6 0
      src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.cpp
  46. 1 0
      src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.h
  47. 21 3
      src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
  48. 2 0
      src/WallpaperEngine/Render/FBOProvider.cpp
  49. 2 0
      src/WallpaperEngine/Render/FBOProvider.h
  50. 6 2
      src/WallpaperEngine/Render/GifAnimation.cpp
  51. 19 5
      src/WallpaperEngine/Render/Objects/CMesh.cpp
  52. 26 5
      src/WallpaperEngine/Render/Objects/CParticle.cpp
  53. 4 0
      src/WallpaperEngine/Render/Objects/CParticle.h
  54. 17 10
      src/WallpaperEngine/Render/Objects/CSound.cpp
  55. 2 1
      src/WallpaperEngine/Render/Objects/Effects/CPass.cpp
  56. 22 2
      src/WallpaperEngine/Render/Objects/PuppetMeshFile.cpp
  57. 17 2
      src/WallpaperEngine/Render/Objects/PuppetRig.cpp
  58. 4 0
      src/WallpaperEngine/Render/RenderContext.cpp
  59. 2 0
      src/WallpaperEngine/Render/RenderContext.h
  60. 1 1
      src/WallpaperEngine/Render/Shaders/GLSLContext.cpp
  61. 0 1
      src/WallpaperEngine/Render/Shaders/Shader.h
  62. 31 14
      src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp
  63. 2 0
      src/WallpaperEngine/Render/Shaders/ShaderUnit.h
  64. 6 1
      src/WallpaperEngine/Render/TextureCache.cpp
  65. 7 0
      src/WallpaperEngine/Render/TextureCache.h
  66. 209 27
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  67. 19 4
      src/WallpaperEngine/Render/Wallpapers/CScene.h
  68. 19 3
      src/WallpaperEngine/Render/Wallpapers/CSplat.cpp
  69. 34 3
      src/WallpaperEngine/Render/Wallpapers/CWeb.cpp
  70. 3 0
      src/WallpaperEngine/Render/Wallpapers/CWeb.h
  71. 125 61
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp
  72. 20 4
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h
  73. 34 0
      src/WallpaperEngine/Scripting/AnimationSystem.cpp
  74. 3 0
      src/WallpaperEngine/Scripting/AnimationSystem.h
  75. 14 6
      src/WallpaperEngine/Scripting/EngineObject.cpp
  76. 55 0
      src/WallpaperEngine/Scripting/ErrorRepeatFilter.h
  77. 91 0
      src/WallpaperEngine/Scripting/HandleTable.h
  78. 55 0
      src/WallpaperEngine/Scripting/JS.cpp
  79. 9 1
      src/WallpaperEngine/Scripting/JS.h
  80. 51 0
      src/WallpaperEngine/Scripting/LimitedAllocator.cpp
  81. 21 0
      src/WallpaperEngine/Scripting/LimitedAllocator.h
  82. 245 45
      src/WallpaperEngine/Scripting/ScriptEngine.cpp
  83. 47 0
      src/WallpaperEngine/Scripting/ScriptEngine.h
  84. 50 9
      src/WallpaperEngine/Scripting/ScriptPropertiesObject.cpp
  85. 19 3
      src/WallpaperEngine/Scripting/ScriptPropertiesObject.h
  86. 65 0
      src/WallpaperEngine/Scripting/ScriptWatchdog.cpp
  87. 43 0
      src/WallpaperEngine/Scripting/ScriptWatchdog.h
  88. 12 10
      src/WallpaperEngine/Scripting/ScriptableObject.cpp
  89. 6 1
      src/WallpaperEngine/Scripting/ScriptableObject.h
  90. 7 0
      src/WallpaperEngine/Splat/SogLoader.cpp
  91. 21 0
      src/WallpaperEngine/Testing/Cases/AuthoringJson.cpp
  92. 46 0
      src/WallpaperEngine/Testing/Cases/ControlFileOwner.cpp
  93. 30 0
      src/WallpaperEngine/Testing/Cases/DirectoryAdapter.cpp
  94. 54 0
      src/WallpaperEngine/Testing/Cases/ErrorRepeatFilter.cpp
  95. 87 0
      src/WallpaperEngine/Testing/Cases/HandleTable.cpp
  96. 125 0
      src/WallpaperEngine/Testing/Cases/KWinScriptFiles.cpp
  97. 84 0
      src/WallpaperEngine/Testing/Cases/NumericGuards.cpp
  98. 17 0
      src/WallpaperEngine/Testing/Cases/PropertyParser.cpp
  99. 43 0
      src/WallpaperEngine/Testing/Cases/PuppetMeshFile.cpp
  100. 189 0
      src/WallpaperEngine/Testing/Cases/ReaderLimits.cpp

+ 73 - 2
CMakeLists.txt

@@ -49,6 +49,8 @@ set(KISSFFT_TEST OFF)
 set(KISSFFT_TOOLS OFF)
 
 set(CEF_VERSION "135.0.17+gcbc1c5b+chromium-135.0.7049.52")
+# SHA256 of the archives for that version, a CEF_SHA256_<platform> per distribution that is pinned (bump with CEF_VERSION)
+set(CEF_SHA256_linux64_minimal "24ac1980e62be7b1aea2c337d6bd4bc770dccd8b37e47c6db94b397f13ec4dc6")
 # debug builds use the standard CEF distribution, release builds the minimal one
 if(CMAKE_BUILD_TYPE STREQUAL "Debug")
     set(default_cef_dist "standard")
@@ -140,8 +142,10 @@ add_subdirectory(${CEF_LIBCEF_DLL_WRAPPER_PATH} libcef_dll_wrapper)
 add_subdirectory(src/External/glslang-WallpaperEngine glslang)
 # SPIRV-Cross and kissfft want CMake < 3.13, the options set above only stick with CMP0077 NEW
 set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
-add_subdirectory(src/External/SPIRV-Cross-WallpaperEngine spirv-cross)
-add_subdirectory(src/External/kissfft kissfft)
+# EXCLUDE_FROM_ALL keeps their install rules (headers, cmake and pkg-config files, SPIRV-Cross' libraries and CLI) out of
+# the prefix, the targets we link still get built
+add_subdirectory(src/External/SPIRV-Cross-WallpaperEngine spirv-cross EXCLUDE_FROM_ALL)
+add_subdirectory(src/External/kissfft kissfft EXCLUDE_FROM_ALL)
 unset(CMAKE_POLICY_DEFAULT_CMP0077)
 # only msdfgen's core is needed, its own CMake project pulls in vcpkg/skia/tinyxml
 file(GLOB MSDFGEN_CORE_SOURCES src/External/msdfgen/core/*.cpp)
@@ -693,6 +697,9 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Scripting/ScriptPropertiesObject.h
     src/WallpaperEngine/Scripting/ScriptPropertiesObject.cpp
     src/WallpaperEngine/Scripting/ScriptEngine.cpp
+    src/WallpaperEngine/Scripting/LimitedAllocator.h
+    src/WallpaperEngine/Scripting/LimitedAllocator.cpp
+    src/WallpaperEngine/Scripting/ScriptWatchdog.cpp
     src/WallpaperEngine/Scripting/ScriptableObject.h
     src/WallpaperEngine/Scripting/ScriptableObject.cpp
     src/WallpaperEngine/Scripting/AnimationSystem.h
@@ -738,13 +745,31 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/PowerSupply.cpp
         src/WallpaperEngine/Testing/Cases/EncodedImages.cpp
         src/WallpaperEngine/Testing/Cases/AuthoringJson.cpp
+        src/WallpaperEngine/Testing/Cases/ReaderLimits.cpp
+        src/WallpaperEngine/Testing/Cases/SteamLibraries.cpp
+        src/WallpaperEngine/Testing/Cases/ErrorRepeatFilter.cpp
+        src/WallpaperEngine/Testing/Cases/WebTestHooks.cpp
+        src/WallpaperEngine/Testing/Cases/DirectoryAdapter.cpp
+        src/WallpaperEngine/Testing/Cases/ControlFileOwner.cpp
+        src/WallpaperEngine/Testing/Cases/HandleTable.cpp
         src/WallpaperEngine/Testing/Cases/PuppetMeshFile.cpp
         src/WallpaperEngine/Testing/Cases/ScriptLocalStorage.cpp
+        src/WallpaperEngine/Testing/Cases/KWinScriptFiles.cpp
+        src/WallpaperEngine/Testing/Cases/NumericGuards.cpp
+        src/WallpaperEngine/Testing/Cases/ThreadGuard.cpp
+        src/WallpaperEngine/Testing/Cases/ScriptCallbackGuard.cpp
+        src/WallpaperEngine/Testing/Cases/WeJsonTypes.cpp
+        src/WallpaperEngine/Testing/Cases/ScriptLimits.cpp
+        src/WallpaperEngine/Testing/Cases/ShaderUniforms.cpp
+        src/WallpaperEngine/Testing/Cases/ScriptWatchdog.cpp
         src/WallpaperEngine/Testing/Cases/WebFrameSlots.cpp
         src/WallpaperEngine/Testing/Cases/AlbumArtworkUpload.cpp
         src/WallpaperEngine/Testing/Cases/SplitLayout.cpp)
 endif()
 
+# the one file that derives from a V8 class: libnode is built without RTTI and exports no typeinfo of V8's classes
+set_source_files_properties(src/WallpaperEngine/Scripting/LimitedAllocator.cpp PROPERTIES COMPILE_OPTIONS -fno-rtti)
+
 add_library(
     linux-wallpaperengine-lib SHARED
 
@@ -893,6 +918,16 @@ target_link_libraries(linux-wallpaperengine-web-helper PRIVATE
 add_dependencies(linux-wallpaperengine-web-helper libcef_dll_wrapper)
 REPLACED_SET_EXECUTABLE_TARGET_PROPERTIES(linux-wallpaperengine-web-helper)
 
+# unloads the engine's KWin scripts once the engine is gone, however it went; libdbus only (the engine is over 100 MB
+# resident), next to the engine like the web helper
+if(KDE_FEATURES_ENABLED)
+    add_executable(linux-wallpaperengine-kwin-janitor src/kwin_janitor.cpp)
+    target_include_directories(linux-wallpaperengine-kwin-janitor PRIVATE ${DBUS_INCLUDE_DIRS})
+    target_link_libraries(linux-wallpaperengine-kwin-janitor PRIVATE ${DBUS_LIBRARIES})
+    set_target_properties(linux-wallpaperengine-kwin-janitor PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${TARGET_OUTPUT_DIRECTORY})
+    add_dependencies(linux-wallpaperengine linux-wallpaperengine-kwin-janitor)
+endif()
+
 # GNOME 45-48 helper spawned by the Shell extension, static so it also runs on the host for Flatpak
 include(CheckCSourceCompiles)
 set(CMAKE_REQUIRED_LINK_OPTIONS -static)
@@ -916,9 +951,14 @@ add_dependencies(linux-wallpaperengine gnome-shell-extension)
 install(TARGETS linux-wallpaperengine linux-wallpaperengine-web-helper
     RUNTIME DESTINATION .
 )
+if(KDE_FEATURES_ENABLED)
+    install(TARGETS linux-wallpaperengine-kwin-janitor RUNTIME DESTINATION .)
+endif()
 install(TARGETS linux-wallpaperengine-lib
     LIBRARY DESTINATION .
 )
+include(GNUInstallDirs)
+install(TARGETS kissfft LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
 
 # icon and a hidden desktop entry for the engine's windows
 install(DIRECTORY resources/icons/hicolor DESTINATION share/icons)
@@ -927,5 +967,36 @@ install(FILES resources/linux-wallpaperengine.desktop DESTINATION share/applicat
 install(DIRECTORY ${TARGET_OUTPUT_DIRECTORY}/ DESTINATION . USE_SOURCE_PERMISSIONS
     PATTERN "linux-wallpaperengine" EXCLUDE
     PATTERN "linux-wallpaperengine-web-helper" EXCLUDE
+    PATTERN "linux-wallpaperengine-kwin-janitor" EXCLUDE
     PATTERN "liblinux-wallpaperengine-lib.so" EXCLUDE
+    PATTERN "glslang" EXCLUDE
+    PATTERN "glslangValidator" EXCLUDE
+    PATTERN "spirv-cross" EXCLUDE
+    PATTERN "spirv-remap" EXCLUDE
+    PATTERN "tests" EXCLUDE
+    PATTERN "lwe-resample-bin" EXCLUDE
+    PATTERN "lwe-sound-bin" EXCLUDE
 )
+
+# Chromium's sandbox helper only works setuid root. Only root can set that up (as another user the bit would run it as
+# that user, and the engine ignores a chrome-sandbox that root doesn't own). Under fakeroot (packages) id -u says 0 too
+install(CODE [[
+    execute_process(COMMAND id -u OUTPUT_VARIABLE lwe_uid OUTPUT_STRIP_TRAILING_WHITESPACE)
+    set(lwe_sandbox "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/chrome-sandbox")
+
+    if(EXISTS "${lwe_sandbox}")
+        if(lwe_uid STREQUAL "0")
+            execute_process(COMMAND chown 0:0 "${lwe_sandbox}" RESULT_VARIABLE lwe_chown)
+            execute_process(COMMAND chmod 4755 "${lwe_sandbox}" RESULT_VARIABLE lwe_chmod)
+
+            if(lwe_chown OR lwe_chmod)
+                message(WARNING "Could not make ${lwe_sandbox} setuid root, web wallpapers need user namespaces")
+            else()
+                message(STATUS "Set chrome-sandbox setuid root: ${lwe_sandbox}")
+            endif()
+        else()
+            message(STATUS "chrome-sandbox is not setuid (not installing as root), web wallpapers need user namespaces: "
+                "chown root:root chrome-sandbox; chmod 4755 chrome-sandbox")
+        endif()
+    endif()
+]])

+ 53 - 9
CMakeModules/DownloadCEF.cmake

@@ -17,27 +17,71 @@ function(DownloadCEF platform version download_dir)
   if(NOT IS_DIRECTORY "${CEF_ROOT}")
     set(CEF_DOWNLOAD_FILENAME "${CEF_DISTRIBUTION}.tar.bz2")
     set(CEF_DOWNLOAD_PATH "${CEF_DOWNLOAD_DIR}/${CEF_DOWNLOAD_FILENAME}")
+
+    # an archive left in the download directory is checked before it is unpacked, against the hash pinned in
+    # CMakeLists.txt or else the .sha1 that came with it
+    if(EXISTS "${CEF_DOWNLOAD_PATH}")
+      set(CEF_ARCHIVE_OK TRUE)
+
+      if(DEFINED CEF_SHA256_${platform})
+        file(SHA256 "${CEF_DOWNLOAD_PATH}" CEF_ARCHIVE_SHA256)
+
+        if(NOT CEF_ARCHIVE_SHA256 STREQUAL "${CEF_SHA256_${platform}}")
+          set(CEF_ARCHIVE_OK FALSE)
+        endif()
+      elseif(EXISTS "${CEF_DOWNLOAD_PATH}.sha1")
+        file(READ "${CEF_DOWNLOAD_PATH}.sha1" CEF_ARCHIVE_EXPECTED_SHA1)
+        string(STRIP "${CEF_ARCHIVE_EXPECTED_SHA1}" CEF_ARCHIVE_EXPECTED_SHA1)
+        file(SHA1 "${CEF_DOWNLOAD_PATH}" CEF_ARCHIVE_SHA1)
+
+        if(NOT CEF_ARCHIVE_SHA1 STREQUAL CEF_ARCHIVE_EXPECTED_SHA1)
+          set(CEF_ARCHIVE_OK FALSE)
+        endif()
+      endif()
+
+      if(NOT CEF_ARCHIVE_OK)
+        message(WARNING "${CEF_DOWNLOAD_PATH} does not match its checksum, downloading it again")
+        file(REMOVE "${CEF_DOWNLOAD_PATH}" "${CEF_DOWNLOAD_PATH}.sha1")
+      endif()
+    endif()
+
     if(NOT EXISTS "${CEF_DOWNLOAD_PATH}")
       set(CEF_DOWNLOAD_URL "https://cef-builds.spotifycdn.com/${CEF_DOWNLOAD_FILENAME}")
       string(REPLACE "+" "%2B" CEF_DOWNLOAD_URL_ESCAPED ${CEF_DOWNLOAD_URL})
 
-      message(STATUS "Downloading ${CEF_DOWNLOAD_PATH}.sha1 from ${CEF_DOWNLOAD_URL_ESCAPED}...")
-      file(DOWNLOAD "${CEF_DOWNLOAD_URL_ESCAPED}.sha1" "${CEF_DOWNLOAD_PATH}.sha1")
-      file(READ "${CEF_DOWNLOAD_PATH}.sha1" CEF_SHA1)
+      if(DEFINED CEF_SHA256_${platform})
+        message(STATUS "Downloading ${CEF_DOWNLOAD_PATH}...")
+        file(
+          DOWNLOAD "${CEF_DOWNLOAD_URL_ESCAPED}" "${CEF_DOWNLOAD_PATH}"
+          EXPECTED_HASH SHA256=${CEF_SHA256_${platform}}
+          SHOW_PROGRESS
+          )
+      else()
+        message(WARNING "No pinned SHA256 for CEF ${platform}, trusting the .sha1 from the download server")
+        message(STATUS "Downloading ${CEF_DOWNLOAD_PATH}.sha1 from ${CEF_DOWNLOAD_URL_ESCAPED}...")
+        file(DOWNLOAD "${CEF_DOWNLOAD_URL_ESCAPED}.sha1" "${CEF_DOWNLOAD_PATH}.sha1")
+        file(READ "${CEF_DOWNLOAD_PATH}.sha1" CEF_SHA1)
+        string(STRIP "${CEF_SHA1}" CEF_SHA1)
 
-      message(STATUS "Downloading ${CEF_DOWNLOAD_PATH}...")
-      file(
-        DOWNLOAD "${CEF_DOWNLOAD_URL_ESCAPED}" "${CEF_DOWNLOAD_PATH}"
-        EXPECTED_HASH SHA1=${CEF_SHA1}
-        SHOW_PROGRESS
-        )
+        message(STATUS "Downloading ${CEF_DOWNLOAD_PATH}...")
+        file(
+          DOWNLOAD "${CEF_DOWNLOAD_URL_ESCAPED}" "${CEF_DOWNLOAD_PATH}"
+          EXPECTED_HASH SHA1=${CEF_SHA1}
+          SHOW_PROGRESS
+          )
+      endif()
     endif()
 
     message(STATUS "Extracting ${CEF_DOWNLOAD_PATH}...")
     execute_process(
       COMMAND ${CMAKE_COMMAND} -E tar xzf "${CEF_DOWNLOAD_DIR}/${CEF_DOWNLOAD_FILENAME}"
       WORKING_DIRECTORY ${CEF_DOWNLOAD_DIR}
+      RESULT_VARIABLE CEF_EXTRACT_RESULT
       )
+
+    if(NOT CEF_EXTRACT_RESULT EQUAL 0)
+      message(FATAL_ERROR "Could not extract ${CEF_DOWNLOAD_PATH}")
+    endif()
   endif()
 endfunction()
 

+ 1 - 1
README.md

@@ -199,7 +199,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--hwdec <backend>` | mpv hardware decoding for videos: `auto` (default), `no`, `vaapi-copy`, `nvdec-copy`, ... Try `no` if videos crash on NVIDIA |
 | `--video-start <time>`, `--video-end <time>` | Video wallpapers only: loop just this part of the video, in seconds, `m:ss` or `h:mm:ss` (either one alone leaves that side at the video's start/end) |
 | `--video-segments <start-end,...>` | Video wallpapers only: play these parts one after the other and skip everything between them, e.g. `"2:00-3:00,4:00-5:00"`; an empty side is the video's start/end (`"4:00-"`) |
-| `--control-file <path>` | File the `SIGUSR1` hotswap request is read from, one per engine when several run. Default `$XDG_RUNTIME_DIR/lwe-control` |
+| `--control-file <path>` | File the `SIGUSR1` hotswap request is read from, one per engine when several run. Default `$XDG_RUNTIME_DIR/lwe-control`, `/tmp/lwe-control-<uid>` without it |
 | `--post-processing <mode>` | `disabled` (no bloom), `enabled` (default), `ultra` (HDR rendering and HDR bloom for scenes with bloom + hdr) or `displayhdr` (highlights up to the HDR output's peak, with `--hdr`) |
 | `--shadows <quality>`, `--volumetrics <quality>` | `disabled`, `low`, `medium` (default), `high`, `ultra` |
 | `--msaa <none/x2/x4/x8>` | Wallpaper Engine's anti-aliasing, only for scenes with 3D models like in Wallpaper Engine |

+ 37 - 0
nix/package.nix

@@ -35,8 +35,11 @@
   cups,
   at-spi2-atk,
   at-spi2-core,
+  atk,
   libdrm,
   mesa,
+  libgbm,
+  systemdLibs,
   alsa-lib,
   pango,
   cairo,
@@ -60,6 +63,36 @@ let
     doInstallCheck = false;
   });
 
+  # the web helper links nothing but libcef.so, and ld finds the libraries libcef.so needs only through -rpath-link
+  cefLibraries = lib.makeLibraryPath (
+    [
+      glib
+      nss
+      nspr
+      dbus
+      atk
+      at-spi2-atk
+      at-spi2-core
+      cups
+      libgbm
+      expat
+      libxkbcommon
+      pango
+      cairo
+      alsa-lib
+      systemdLibs
+    ]
+    ++ (with xorg; [
+      libX11
+      libXcomposite
+      libXdamage
+      libXext
+      libXfixes
+      libXrandr
+      libxcb
+    ])
+  );
+
   # the version CMakeLists.txt pins, CMake's DownloadCEF finds the archive already in its folder
   cefVersion = "135.0.17+gcbc1c5b+chromium-135.0.7049.52";
   cefArchive = "cef_binary_${cefVersion}_linux64_minimal.tar.bz2";
@@ -108,8 +141,11 @@ stdenv.mkDerivation {
     cups
     at-spi2-atk
     at-spi2-core
+    atk
     libdrm
     mesa
+    libgbm
+    systemdLibs
     alsa-lib
     pango
     cairo
@@ -149,6 +185,7 @@ stdenv.mkDerivation {
     (lib.cmakeFeature "V8_INCLUDE_DIR" "${libnode}/include/node")
     # relative, package_release.sh installs into a prefix of its own
     (lib.cmakeFeature "CMAKE_INSTALL_LIBDIR" "lib")
+    (lib.cmakeFeature "CMAKE_EXE_LINKER_FLAGS" "-Wl,-rpath-link,${cefLibraries}")
   ];
 
   # the CEF wrapper library builds with -Werror and defines its own _FORTIFY_SOURCE

+ 84 - 25
src/Steam/FileSystem/FileSystem.cpp

@@ -1,23 +1,16 @@
 #include "FileSystem.h"
 #include "WallpaperEngine/Logging/Log.h"
-#include <climits>
+#include <algorithm>
 #include <cstdlib>
 #include <filesystem>
-#include <sstream>
-#include <sys/stat.h>
-
-std::vector<std::string> appDirectoryPaths = {
-    ".steam/steam/steamapps/common",
-    ".local/share/Steam/steamapps/common",
-    ".var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps/common",
-    "snap/steam/common/.local/share/Steam/steamapps/common",
-};
-
-std::vector<std::string> workshopDirectoryPaths = {
-    ".local/share/Steam/steamapps/workshop/content",
-    ".steam/steam/steamapps/workshop/content",
-    ".var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps/workshop/content",
-    "snap/steam/common/.local/share/Steam/steamapps/workshop/content",
+#include <fstream>
+#include <regex>
+
+std::vector<std::string> steamRootPaths = {
+    ".steam/steam",
+    ".local/share/Steam",
+    ".var/app/com.valvesoftware.Steam/.local/share/Steam",
+    "snap/steam/common/.local/share/Steam",
 };
 
 std::filesystem::path detectHomepath () {
@@ -36,11 +29,79 @@ std::filesystem::path detectHomepath () {
     return path;
 }
 
-std::filesystem::path Steam::FileSystem::workshopDirectory (int appID, const std::string& contentID) {
-    auto homepath = detectHomepath ();
+namespace {
+// the "path" entries of Steam's libraryfolders.vdf, one per library folder on any disk
+std::vector<std::filesystem::path> libraryFoldersOf (const std::filesystem::path& steamRoot) {
+    static const std::regex entry (R"re("path"\s+"((?:[^"\\]|\\.)*)")re");
+    std::vector<std::filesystem::path> folders;
+
+    for (const auto& vdf : { steamRoot / "steamapps/libraryfolders.vdf", steamRoot / "config/libraryfolders.vdf" }) {
+	std::ifstream file (vdf);
+
+	if (!file.is_open ()) {
+	    continue;
+	}
+
+	const std::string text ((std::istreambuf_iterator<char> (file)), std::istreambuf_iterator<char> ());
+
+	for (auto it = std::sregex_iterator (text.begin (), text.end (), entry); it != std::sregex_iterator (); ++it) {
+	    const std::string raw = (*it)[1].str ();
+	    std::string value;
 
-    for (const auto& current : workshopDirectoryPaths) {
-	auto currentpath = std::filesystem::path (homepath) / current / std::to_string (appID) / contentID;
+	    for (size_t i = 0; i < raw.size (); i++) {
+		if (raw[i] == '\\' && i + 1 < raw.size ()) {
+		    i++;
+		}
+
+		value += raw[i];
+	    }
+
+	    if (!value.empty ()) {
+		folders.emplace_back (value);
+	    }
+	}
+    }
+
+    return folders;
+}
+
+// every Steam install and the library folders they list, each once, in lookup order
+std::vector<std::filesystem::path> steamLibraries () {
+    const auto home = detectHomepath ();
+    std::vector<std::filesystem::path> libraries;
+    std::error_code error;
+
+    const auto add = [&] (const std::filesystem::path& folder) {
+	if (!std::filesystem::is_directory (folder, error)) {
+	    return;
+	}
+
+	const auto canonical = std::filesystem::weakly_canonical (folder, error);
+
+	if (std::ranges::find (libraries, canonical) == libraries.end ()) {
+	    libraries.push_back (canonical);
+	}
+    };
+
+    for (const auto& root : steamRootPaths) {
+	add (home / root);
+    }
+
+    const auto installs = libraries;
+
+    for (const auto& install : installs) {
+	for (const auto& folder : libraryFoldersOf (install)) {
+	    add (folder);
+	}
+    }
+
+    return libraries;
+}
+} // namespace
+
+std::filesystem::path Steam::FileSystem::workshopDirectory (int appID, const std::string& contentID) {
+    for (const auto& library : steamLibraries ()) {
+	auto currentpath = library / "steamapps/workshop/content" / std::to_string (appID) / contentID;
 
 	if (!std::filesystem::exists (currentpath) || !std::filesystem::is_directory (currentpath)) {
 	    continue;
@@ -53,10 +114,8 @@ std::filesystem::path Steam::FileSystem::workshopDirectory (int appID, const std
 }
 
 std::filesystem::path Steam::FileSystem::appDirectory (const std::string& appDirectory, const std::string& path) {
-    auto homepath = detectHomepath ();
-
-    for (const auto& current : appDirectoryPaths) {
-	auto currentpath = std::filesystem::path (homepath) / current / appDirectory / path;
+    for (const auto& library : steamLibraries ()) {
+	auto currentpath = library / "steamapps/common" / appDirectory / path;
 
 	if (!std::filesystem::exists (currentpath) || !std::filesystem::is_directory (currentpath)) {
 	    continue;
@@ -66,4 +125,4 @@ std::filesystem::path Steam::FileSystem::appDirectory (const std::string& appDir
     }
 
     sLog.exception ("Cannot find directory for steam app ", appDirectory, ": ", path);
-}
+}

+ 13 - 9
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -2,6 +2,7 @@
 
 #include "Steam/FileSystem/FileSystem.h"
 #include "WallpaperEngine/Data/JSON.h"
+#include "WallpaperEngine/Data/Utils/FiniteFloat.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/CFBO.h"
 #include "WallpaperEngine/Render/Wallpapers/CVideo.h"
@@ -21,6 +22,8 @@
 
 #include <argparse/argparse.hpp>
 
+using WallpaperEngine::Data::Utils::parseFiniteFloat;
+
 #define WORKSHOP_APP_ID 431960
 #define APP_DIRECTORY "wallpaper_engine"
 
@@ -726,7 +729,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    float zoom;
 
 	    try {
-		zoom = std::stof (value);
+		zoom = parseFiniteFloat (value);
 	    } catch (const std::exception&) {
 		sLog.exception ("Invalid zoom value: ", value);
 	    }
@@ -762,8 +765,8 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    glm::vec2 offset;
 
 	    try {
-		offset.x = std::stof (value.substr (0, comma));
-		offset.y = std::stof (value.substr (comma + 1));
+		offset.x = parseFiniteFloat (value.substr (0, comma));
+		offset.y = parseFiniteFloat (value.substr (comma + 1));
 	    } catch (const std::exception&) {
 		sLog.exception ("Invalid offset value: ", value);
 	    }
@@ -790,7 +793,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 		float parsed;
 
 		try {
-		    parsed = std::stof (value);
+		    parsed = parseFiniteFloat (value);
 		} catch (const std::exception&) {
 		    sLog.exception ("Invalid ", name, " value: ", value);
 		}
@@ -884,7 +887,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 	float result;
 
 	try {
-	    result = std::stof (value);
+	    result = parseFiniteFloat (value);
 	} catch (const std::exception&) {
 	    sLog.exception ("Invalid ", name, " value: ", value);
 	}
@@ -1076,7 +1079,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    float speed;
 
 	    try {
-		speed = std::stof (value);
+		speed = parseFiniteFloat (value);
 	    } catch (const std::exception&) {
 		sLog.exception ("Invalid speed value: ", value);
 	    }
@@ -1289,7 +1292,8 @@ void ApplicationContext::loadSettingsFromArgv () {
     configurationGroup.add_argument ("--control-file")
 	.help (
 	    "File the SIGUSR1 hotswap request is read from. Give every engine its own when several run at once, "
-	    "otherwise they all read the same one. Default: $XDG_RUNTIME_DIR/lwe-control"
+	    "otherwise they all read the same one. Default: $XDG_RUNTIME_DIR/lwe-control, /tmp/lwe-control-<uid> "
+	    "without it"
 	)
 	.action ([this] (const std::string& value) -> void {
 	    if (!value.empty ()) {
@@ -1500,7 +1504,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    const std::string multiplierStr = value.substr (equals + 1);
 
 	    try {
-		this->settings.general.audioSensitivity[target] = std::stof (multiplierStr);
+		this->settings.general.audioSensitivity[target] = parseFiniteFloat (multiplierStr);
 	    } catch (const std::exception&) {
 		sLog.exception ("--audio-sensitivity: '" + multiplierStr + "' is not a valid number");
 	    }
@@ -1525,7 +1529,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    const std::string volumeStr = value.substr (equals + 1);
 
 	    try {
-		this->settings.general.soundVolume[target] = std::stof (volumeStr);
+		this->settings.general.soundVolume[target] = parseFiniteFloat (volumeStr);
 	    } catch (const std::exception&) {
 		sLog.exception ("--sound-volume: '" + volumeStr + "' is not a valid number");
 	    }

+ 3 - 1
src/WallpaperEngine/Application/ApplicationState.h

@@ -1,5 +1,7 @@
 #pragma once
 
+#include <atomic>
+
 #include "ApplicationContext.h"
 
 namespace WallpaperEngine::Application {
@@ -12,7 +14,7 @@ enum class XrayMode {
 class ApplicationState {
 public:
     struct {
-	bool keepRunning;
+	std::atomic<bool> keepRunning;
     } general {};
 
     struct {

+ 15 - 0
src/WallpaperEngine/Application/ControlFileOwner.h

@@ -0,0 +1,15 @@
+#pragma once
+
+#include <filesystem>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+namespace WallpaperEngine::Application {
+/** Whether something owned by someone other than user sits at path: lstat, so a link someone else planted counts by
+ * its own owner and not by what it points to. A path that is not there is nobody's */
+inline bool belongsToAnotherUser (const std::filesystem::path& path, uid_t user) {
+    struct stat info {};
+
+    return lstat (path.c_str (), &info) == 0 && info.st_uid != user;
+}
+} // namespace WallpaperEngine::Application

+ 185 - 53
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -1,4 +1,5 @@
 #include "WallpaperApplication.h"
+#include "ControlFileOwner.h"
 
 #include <cstdlib>
 
@@ -6,8 +7,10 @@
 #include "WallpaperEngine/Application/ApplicationState.h"
 #include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h"
+#include "WallpaperEngine/Data/Utils/FiniteFloat.h"
 #include "WallpaperEngine/FileSystem/Container.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Logging/ThreadGuard.h"
 #include "WallpaperEngine/Render/Drivers/VideoFactories.h"
 #include "WallpaperEngine/Render/RenderContext.h"
 #include "WallpaperEngine/Render/Shaders/ShaderCache.h"
@@ -47,12 +50,15 @@
 #include <numeric>
 #include <ranges>
 #include <string_view>
+#include <sys/stat.h>
 #include <unistd.h>
 #define STB_IMAGE_WRITE_IMPLEMENTATION
 #include <stb_image_write.h>
 #include <thread>
 #include <utility>
 
+using WallpaperEngine::Data::Utils::parseFiniteFloat;
+
 // microseconds, for usleep ()
 #define FULLSCREEN_CHECK_WAIT_TIME 250000
 
@@ -222,6 +228,11 @@ WallpaperApplication::ProjectSource WallpaperApplication::openProjectSource (con
     const auto dependency = json.at ("dependency");
     const auto dependencyId = dependency.is_string () ? dependency.get<std::string> () : dependency.dump ();
 
+    if (dependencyId.empty () || dependencyId == "." || dependencyId == ".."
+	|| dependencyId.find ('/') != std::string::npos) {
+	sLog.exception ("Preset ", path, " has an invalid dependency '", dependencyId, "'");
+    }
+
     std::filesystem::path presetDir = path;
 
     if (!presetDir.has_filename ()) {
@@ -254,7 +265,7 @@ std::optional<float> presetNumber (const WallpaperEngine::Data::JSON::JSON& pres
 
     if (it->is_string ()) {
 	try {
-	    return std::stof (it->get<std::string> ());
+	    return parseFiniteFloat (it->get<std::string> ());
 	} catch (const std::exception&) { }
     }
 
@@ -330,8 +341,18 @@ void WallpaperApplication::applyPreset (
 
 	// file and directory properties hold paths relative to the preset folder, pages expect an absolute one
 	if (const auto* file = dynamic_cast<const PropertyFile*> (property->second.get ());
-	    file != nullptr && !text.empty () && std::filesystem::path (text).is_relative ()) {
-	    const auto candidate = presetDir / text;
+	    file != nullptr && !text.empty ()) {
+	    std::error_code pathError;
+	    const auto folder = std::filesystem::weakly_canonical (presetDir, pathError);
+	    const auto candidate = std::filesystem::weakly_canonical (folder / text, pathError);
+	    const auto inside = candidate.lexically_relative (folder);
+
+	    // a preset is someone else's content, its files are in its own folder: "/" or "../.." must not open the
+	    // user's disk to a web page
+	    if (pathError || inside.empty () || *inside.begin () == "..") {
+		sLog.error ("Preset value for ", entry.key (), " is outside the preset's folder, ignored: ", text);
+		continue;
+	    }
 
 	    if (file->isDirectory () ? std::filesystem::is_directory (candidate)
 				     : std::filesystem::is_regular_file (candidate)) {
@@ -356,7 +377,7 @@ void WallpaperApplication::applyPreset (
     }
 }
 
-ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) {
+ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) try {
     auto [container, json, preset, directory] = this->openProjectSource (bg);
 
     // reset screenshot state so a background change (e.g. playlist advance) can screenshot again
@@ -399,6 +420,8 @@ ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) {
     }
 
     return project;
+} catch (const std::exception& e) {
+    throw std::runtime_error ("Cannot load wallpaper '" + bg + "': " + e.what ());
 }
 
 std::vector<std::size_t>
@@ -540,8 +563,13 @@ void WallpaperApplication::advancePlaylist (
 
     playlist.orderIndex = (playlist.orderIndex + 1) % playlist.order.size ();
 
-    if (playlist.orderIndex == 0 && playlist.definition.settings.order == "random") {
-	std::shuffle (playlist.order.begin (), playlist.order.end (), this->m_playlistRng);
+    // an item that failed gets another chance in every round
+    if (playlist.orderIndex == 0) {
+	playlist.failedIndices.clear ();
+
+	if (playlist.definition.settings.order == "random") {
+	    std::shuffle (playlist.order.begin (), playlist.order.end (), this->m_playlistRng);
+	}
     }
 
     std::size_t candidateOrderIndex = playlist.orderIndex;
@@ -550,6 +578,7 @@ void WallpaperApplication::advancePlaylist (
 	sLog.error ("All playlist items failed for ", screen, ", keeping current wallpaper");
 	const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
 	playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
+	playlist.failedIndices.clear ();
 	return;
     }
 
@@ -563,6 +592,7 @@ void WallpaperApplication::advancePlaylist (
 	    sLog.error ("All playlist items failed for ", screen, ", keeping current wallpaper");
 	    const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
 	    playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
+	    playlist.failedIndices.clear ();
 	    return;
 	}
     }
@@ -607,13 +637,14 @@ void WallpaperApplication::advancePlaylist (
 	loaded = true;
     } catch (const std::exception& e) {
 	sLog.error ("Failed to advance playlist on ", screen, ": ", e.what ());
+    } catch (...) {
+	sLog.error ("Failed to advance playlist on ", screen, ": unknown error");
     }
 
     if (!loaded) {
 	playlist.failedIndices.insert (playlist.order[playlist.orderIndex]);
 
-	// keep the position, the next tick retries
-	sLog.error ("Failed to load wallpaper for ", screen, ", will retry on next cycle");
+	sLog.error ("Failed to load wallpaper for ", screen, ", skipping it until the playlist comes round again");
     }
 
     const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
@@ -832,7 +863,7 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	    float amount;
 
 	    try {
-		amount = std::clamp (std::stof (value), 0.0f, 100.0f);
+		amount = std::clamp (parseFiniteFloat (value), 0.0f, 100.0f);
 	    } catch (const std::exception&) {
 		sLog.error ("Hotswap: ignoring invalid ", key, " value: ", value);
 		continue;
@@ -913,10 +944,19 @@ void WallpaperApplication::checkHotswapRequest () {
     }
 
     const char* runtimeDir = getenv ("XDG_RUNTIME_DIR");
+    const bool sharedTmp
+	= !this->m_context.settings.general.controlFile.has_value () && (runtimeDir == nullptr || *runtimeDir == '\0');
     const auto controlFile = this->m_context.settings.general.controlFile.value_or (
-	std::filesystem::path (runtimeDir != nullptr ? runtimeDir : "/tmp") / "lwe-control"
+	sharedTmp ? std::filesystem::path ("/tmp/lwe-control-" + std::to_string (geteuid ()))
+		  : std::filesystem::path (runtimeDir) / "lwe-control"
     );
 
+    // /tmp is shared, a file another user left there is not a request
+    if (sharedTmp && belongsToAnotherUser (controlFile, geteuid ())) {
+	sLog.error ("Hotswap requested but the control file belongs to another user: ", controlFile.string ());
+	return;
+    }
+
     std::ifstream file (controlFile);
 
     if (!file.is_open ()) {
@@ -950,11 +990,49 @@ void WallpaperApplication::checkHotswapRequest () {
 	return;
     }
 
+    // before anything changes: a wallpaper that can't load leaves the running one with everything it had
+    if (request.path.has_value () && !this->preflightWallpaper (*request.path)) {
+	sLog.error ("Hotswap failed, invalid wallpaper at ", *request.path);
+	return;
+    }
+
+    // what a wallpaper that parses but fails to load puts back
+    struct OverrideSnapshot {
+	std::vector<std::string> disabledObjects, enabledObjects, disabledEffects, enabledEffects;
+	std::map<std::string, std::string> properties;
+	std::map<std::string, float> audioSensitivity, soundVolume;
+	Data::Model::ImageAdjustments windowImageAdjustments;
+	VideoPlayback::VideoSegments videoSegments;
+	std::map<std::string, Data::Model::ImageAdjustments> screenImageAdjustments;
+	std::map<std::string, VideoPlayback::VideoSegments> screenVideoSegments;
+	std::vector<Data::Model::ImageAdjustments> spanImageAdjustments;
+    };
+
+    std::optional<OverrideSnapshot> previousOverrides;
+
     // overrides belong to the wallpaper they were set for (ids and generic property names collide), a new one only gets
     // what this request carries
     if (request.path.has_value ()) {
 	auto& general = this->m_context.settings.general;
 
+	previousOverrides = OverrideSnapshot {
+	    .disabledObjects = general.disabledObjects,
+	    .enabledObjects = general.enabledObjects,
+	    .disabledEffects = general.disabledEffects,
+	    .enabledEffects = general.enabledEffects,
+	    .properties = general.properties,
+	    .audioSensitivity = general.audioSensitivity,
+	    .soundVolume = general.soundVolume,
+	    .windowImageAdjustments = this->m_context.settings.render.window.imageAdjustments,
+	    .videoSegments = this->m_context.settings.render.videoSegments,
+	    .screenImageAdjustments = general.screenImageAdjustments,
+	    .screenVideoSegments = general.screenVideoSegments,
+	};
+
+	for (const auto& spanGroup : general.spanGroups) {
+	    previousOverrides->spanImageAdjustments.push_back (spanGroup.imageAdjustments);
+	}
+
 	general.disabledObjects.clear ();
 	general.enabledObjects.clear ();
 	general.disabledEffects.clear ();
@@ -1135,7 +1213,7 @@ void WallpaperApplication::checkHotswapRequest () {
     if (request.audioSensitivityProvided) {
 	for (const auto& [target, value] : request.audioSensitivity) {
 	    try {
-		this->m_context.settings.general.audioSensitivity[target] = std::stof (value);
+		this->m_context.settings.general.audioSensitivity[target] = parseFiniteFloat (value);
 	    } catch (const std::exception&) {
 		sLog.error ("Hotswap: ignoring invalid audio-sensitivity value: ", value);
 	    }
@@ -1155,13 +1233,35 @@ void WallpaperApplication::checkHotswapRequest () {
 	return;
     }
 
-    if (request.path.has_value () && !this->preflightWallpaper (*request.path)) {
-	sLog.error ("Hotswap failed, invalid wallpaper at ", *request.path);
-	return;
-    }
+    // the request's own settings are applied by now, a failure from here on puts the old ones back
+    const auto restoreOverrides = [&] {
+	if (!previousOverrides.has_value ()) {
+	    return;
+	}
+
+	auto& general = this->m_context.settings.general;
+
+	general.disabledObjects = previousOverrides->disabledObjects;
+	general.enabledObjects = previousOverrides->enabledObjects;
+	general.disabledEffects = previousOverrides->disabledEffects;
+	general.enabledEffects = previousOverrides->enabledEffects;
+	general.properties = previousOverrides->properties;
+	general.audioSensitivity = previousOverrides->audioSensitivity;
+	general.soundVolume = previousOverrides->soundVolume;
+	this->m_context.settings.render.window.imageAdjustments = previousOverrides->windowImageAdjustments;
+	this->m_context.settings.render.videoSegments = previousOverrides->videoSegments;
+	general.screenImageAdjustments = previousOverrides->screenImageAdjustments;
+	general.screenVideoSegments = previousOverrides->screenVideoSegments;
+
+	for (size_t index = 0;
+	     index < general.spanGroups.size () && index < previousOverrides->spanImageAdjustments.size (); index++) {
+	    general.spanGroups[index].imageAdjustments = previousOverrides->spanImageAdjustments[index];
+	}
+    };
 
     if (!this->makeAnyViewportCurrent ()) {
 	sLog.error ("Hotswap failed, no active viewport");
+	restoreOverrides ();
 	return;
     }
 
@@ -1171,6 +1271,8 @@ void WallpaperApplication::checkHotswapRequest () {
 	sLog.out ("Hotswapping wallpaper layers");
     }
 
+    bool swapped = false;
+
     // the outgoing project must outlive setWallpaper(), the old wallpaper keeps a reference into it
     for (auto& [screen, background] : this->m_backgrounds) {
 	if (!this->hotswapReaches (target, screen)) {
@@ -1205,6 +1307,8 @@ void WallpaperApplication::checkHotswapRequest () {
 		throw;
 	    }
 
+	    swapped = true;
+
 	    if (request.path.has_value ()) {
 		if (screen.starts_with ("span:")) {
 		    for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
@@ -1218,12 +1322,19 @@ void WallpaperApplication::checkHotswapRequest () {
 	    }
 	} catch (const std::exception& e) {
 	    sLog.error ("Hotswap failed for screen ", screen, ": ", e.what ());
+	} catch (...) {
+	    sLog.error ("Hotswap failed for screen ", screen, ": unknown error");
 	}
     }
 
+    if (!swapped) {
+	// every screen kept its wallpaper, so it keeps what it was set up with as well
+	restoreOverrides ();
+    }
+
     this->applyAudioPolicy ();
 
-    if (request.path.has_value () && !request.screen.has_value ()) {
+    if (swapped && request.path.has_value () && !request.screen.has_value ()) {
 	this->m_context.settings.general.defaultBackground = *request.path;
     }
 }
@@ -1572,7 +1683,7 @@ void WallpaperApplication::applyZoomHotswap (const HotswapTarget& target, const
     float zoom;
 
     try {
-	zoom = std::stof (value);
+	zoom = parseFiniteFloat (value);
     } catch (const std::exception&) {
 	sLog.error ("Hotswap: ignoring invalid zoom value: ", value);
 	return;
@@ -1600,8 +1711,8 @@ void WallpaperApplication::applyOffsetHotswap (const HotswapTarget& target, cons
     glm::vec2 offset;
 
     try {
-	offset.x = std::stof (value.substr (0, comma));
-	offset.y = std::stof (value.substr (comma + 1));
+	offset.x = parseFiniteFloat (value.substr (0, comma));
+	offset.y = parseFiniteFloat (value.substr (comma + 1));
     } catch (const std::exception&) {
 	sLog.error ("Hotswap: ignoring invalid offset value: ", value);
 	return;
@@ -1627,7 +1738,7 @@ void WallpaperApplication::applyAlignmentHotswap (const HotswapTarget& target, c
 
     try {
 	while (count < values.size () && std::getline (stream, part, ',')) {
-	    values[count++] = std::stof (part);
+	    values[count++] = parseFiniteFloat (part);
 	}
     } catch (const std::exception&) {
 	count = 0;
@@ -1715,7 +1826,7 @@ void WallpaperApplication::applySpeedHotswap (const std::string& value) {
     float speed;
 
     try {
-	speed = std::stof (value);
+	speed = parseFiniteFloat (value);
     } catch (const std::exception&) {
 	sLog.error ("Hotswap: ignoring invalid speed value: ", value);
 	return;
@@ -2184,7 +2295,7 @@ void WallpaperApplication::setupSoundVolume () {
 void WallpaperApplication::applySoundVolumeHotswap (const std::map<std::string, std::string>& targets) {
     for (const auto& [target, value] : targets) {
 	try {
-	    this->m_context.settings.general.soundVolume[target] = std::stof (value);
+	    this->m_context.settings.general.soundVolume[target] = parseFiniteFloat (value);
 	} catch (const std::exception&) {
 	    sLog.error ("Hotswap: ignoring invalid sound-volume value: ", value);
 	}
@@ -2535,7 +2646,7 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
     const std::string extStr = extension.string ();
 
     // process and save off the render thread
-    std::thread ([captures, width, height, vflip, extStr, filename] () {
+    const auto encode = [captures, width, height, vflip, extStr, filename] () {
 	auto* bitmap = new uint8_t[width * height * 3] { 0 };
 
 	for (const auto& capture : captures) {
@@ -2588,16 +2699,36 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
 	    delete[] capture.buffer;
 	}
 
-	if (extStr == ".bmp") {
-	    stbi_write_bmp (filename.c_str (), width, height, 3, bitmap);
-	} else if (extStr == ".png") {
-	    stbi_write_png (filename.c_str (), width, height, 3, bitmap, width * 3);
-	} else if (extStr == ".jpg" || extStr == ".jpeg") {
-	    stbi_write_jpg (filename.c_str (), width, height, 3, bitmap, 100);
+	const auto write = [&] (const std::filesystem::path& target) {
+	    if (extStr == ".bmp") {
+		return stbi_write_bmp (target.c_str (), width, height, 3, bitmap) != 0;
+	    }
+
+	    if (extStr == ".png") {
+		return stbi_write_png (target.c_str (), width, height, 3, bitmap, width * 3) != 0;
+	    }
+
+	    if (extStr == ".jpg" || extStr == ".jpeg") {
+		return stbi_write_jpg (target.c_str (), width, height, 3, bitmap, 100) != 0;
+	    }
+
+	    return false;
+	};
+
+	// whoever waits for the file never sees half of it
+	const std::filesystem::path partial = filename.string () + ".partial";
+	std::error_code error;
+
+	if (!write (partial) || (std::filesystem::rename (partial, filename, error), error)) {
+	    std::filesystem::remove (partial, error);
+	    write (filename);
 	}
 
 	delete[] bitmap;
-    }).detach ();
+    };
+
+    this->m_screenshotWriter
+	= std::jthread ([encode] { WallpaperEngine::Logging::guardThread ("Screenshot writer", encode); });
 }
 
 void WallpaperApplication::setupOutput () {
@@ -2688,7 +2819,7 @@ const ApplicationContext::SpanGroup* WallpaperApplication::findSpanGroup (const
 
 void WallpaperApplication::installWallpaper (
     const std::string& screen, const Project& project, const std::filesystem::path& path, const bool holdPrevious
-) {
+) try {
     const auto& general = this->m_context.settings.general;
     const auto& window = this->m_context.settings.render.window;
     const auto* spanGroup = this->findSpanGroup (screen);
@@ -2764,6 +2895,8 @@ void WallpaperApplication::installWallpaper (
     for (const auto& name : spanGroup->screens) {
 	this->m_renderContext->setWallpaper (name, wallpaper, holdPrevious);
     }
+} catch (const std::exception& e) {
+    throw std::runtime_error ("Cannot set up wallpaper '" + path.string () + "' on " + screen + ": " + e.what ());
 }
 
 void WallpaperApplication::prepareOutputs () {
@@ -2820,17 +2953,15 @@ void WallpaperApplication::setup () {
 	sLog.exception ("Demo mode only supports one background");
     }
 
-    int width = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferWidth ();
-    int height = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferHeight ();
-    std::vector<uint8_t> pixels (width * height * 3);
-    bool initialized = false;
-    int frame = 0;
+    this->m_demo.width = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferWidth ();
+    this->m_demo.height = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferHeight ();
+    this->m_demo.pixels.assign (static_cast<size_t> (this->m_demo.width) * this->m_demo.height * 3, 0);
+    this->m_demo.initialized = false;
+    this->m_demo.frame = 0;
 #endif /* DEMOMODE */
 }
 
 void WallpaperApplication::render () {
-    static time_t seconds;
-    static struct tm* timeinfo;
     static float rawTimeLast = 0.0f;
 
     if (this->m_isPaused) {
@@ -2863,9 +2994,10 @@ void WallpaperApplication::render () {
 
 	this->m_isPaused = false;
     } else {
-	time (&seconds);
-	timeinfo = localtime (&seconds);
-	g_Daytime = static_cast<float> ((timeinfo->tm_hour * 60) + timeinfo->tm_min) / (24.0f * 60.0f);
+	const time_t seconds = time (nullptr);
+	struct tm timeinfo {};
+	localtime_r (&seconds, &timeinfo);
+	g_Daytime = static_cast<float> ((timeinfo.tm_hour * 60) + timeinfo.tm_min) / (24.0f * 60.0f);
 
 	// LWE_FIXED_TIMESTEP=<seconds>: same step every frame so frame N always shows the same moment (regression
 	// renders)
@@ -2950,12 +3082,12 @@ void WallpaperApplication::render () {
 #if DEMOMODE
 	// wait a full render cycle before starting, giving video/web decoders time to set up
 	if (m_videoDriver->getFrameCounter () > (uint32_t)this->m_context.settings.render.maximumFPS) {
-	    if (!initialized) {
-		width = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferWidth ();
-		height = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferHeight ();
-		pixels.reserve (width * height * 3);
-		init_encoder ("output.webm", width, height);
-		initialized = true;
+	    if (!this->m_demo.initialized) {
+		this->m_demo.width = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferWidth ();
+		this->m_demo.height = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferHeight ();
+		this->m_demo.pixels.assign (static_cast<size_t> (this->m_demo.width) * this->m_demo.height * 3, 0);
+		init_encoder ("output.webm", this->m_demo.width, this->m_demo.height);
+		this->m_demo.initialized = true;
 	    }
 
 	    glBindFramebuffer (
@@ -2963,11 +3095,13 @@ void WallpaperApplication::render () {
 	    );
 
 	    glPixelStorei (GL_PACK_ALIGNMENT, 1);
-	    glReadPixels (0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels.data ());
-	    write_video_frame (pixels.data ());
-	    frame++;
+	    glReadPixels (
+		0, 0, this->m_demo.width, this->m_demo.height, GL_RGB, GL_UNSIGNED_BYTE, this->m_demo.pixels.data ()
+	    );
+	    write_video_frame (this->m_demo.pixels.data ());
+	    this->m_demo.frame++;
 
-	    if (frame >= FRAME_COUNT) {
+	    if (this->m_demo.frame >= FRAME_COUNT) {
 		this->m_context.state.general.keepRunning = false;
 	    }
 	}
@@ -3011,8 +3145,6 @@ void WallpaperApplication::cleanup () {
 #if DEMOMODE
     close_encoder ();
 #endif /* DEMOMODE */
-
-    SDL_Quit ();
 }
 
 void WallpaperApplication::show () {

+ 14 - 0
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -24,6 +24,7 @@
 #include "WallpaperEngine/Media/MediaSource.h"
 
 #include <set>
+#include <thread>
 
 namespace WallpaperEngine::Application {
 
@@ -251,6 +252,19 @@ private:
     bool m_showFrameWhilePaused = false;
     std::unique_ptr<WallpaperEngine::Desktop::PowerMonitor> m_powerMonitor = nullptr;
     bool m_screenShotTaken = false;
+    // encodes and writes the last screenshot, joined before the next one and when the application goes
+    mutable std::jthread m_screenshotWriter;
+
+#if DEMOMODE
+    /** What the demo recording keeps between frames (setup () sizes it, render () feeds the encoder) */
+    struct {
+	int width = 0;
+	int height = 0;
+	std::vector<uint8_t> pixels;
+	bool initialized = false;
+	int frame = 0;
+    } m_demo;
+#endif /* DEMOMODE */
     uint32_t m_nextFrameScreenshot = 0;
     std::chrono::steady_clock::time_point m_pauseStart {};
     GLuint m_destinationFramebuffer = 0;

+ 56 - 10
src/WallpaperEngine/Audio/AudioStream.cpp

@@ -1,5 +1,6 @@
 #include "AudioStream.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Logging/ThreadGuard.h"
 #include <algorithm>
 #include <cassert>
 #include <cmath>
@@ -145,12 +146,10 @@ AudioStream::AudioStream (AudioContext& audioContext, AVCodecContext* context) :
 AudioStream::~AudioStream () {
     this->stop ();
 
-    if (this->m_audioThread != nullptr) {
-	SDL_WaitThread (this->m_audioThread, nullptr);
+    if (this->m_audioThread.joinable ()) {
+	this->m_audioThread.join ();
     }
 
-    this->m_audioThread = nullptr;
-
     if (this->m_swrctx != nullptr && swr_is_initialized (this->m_swrctx) == true) {
 	swr_close (this->m_swrctx);
     }
@@ -164,17 +163,40 @@ AudioStream::~AudioStream () {
 	av_frame_free (&this->m_decodeFrame);
     }
     if (this->m_queue != nullptr && this->m_queue->packetList != nullptr) {
+	// the packets the decoder never took
+	MyAVPacketList entry {};
+
 #if FF_API_FIFO_OLD_API
+	while (av_fifo_size (this->m_queue->packetList) >= static_cast<int> (sizeof (entry))
+	       && av_fifo_generic_read (this->m_queue->packetList, &entry, sizeof (entry), nullptr) >= 0) {
+	    av_packet_free (&entry.packet);
+	}
+
 	av_fifo_free (this->m_queue->packetList);
 	this->m_queue->packetList = nullptr;
 #else
+	while (av_fifo_read (this->m_queue->packetList, &entry, 1) >= 0) {
+	    av_packet_free (&entry.packet);
+	}
+
 	av_fifo_freep2 (&this->m_queue->packetList);
 #endif /* FF_API_FIFO_OLD_API */
     }
 
+    if (this->m_queue != nullptr) {
+	SDL_DestroyMutex (this->m_queue->mutex);
+	SDL_DestroyCond (this->m_queue->wait);
+    }
+
     delete this->m_queue;
 
     if (this->m_formatContext != nullptr) {
+	// avformat_free_context leaves the IO context made for the reader's stream
+	if (this->m_buffer != nullptr && this->m_formatContext->pb != nullptr) {
+	    av_freep (&this->m_formatContext->pb->buffer);
+	    avio_context_free (&this->m_formatContext->pb);
+	}
+
 	avformat_free_context (this->m_formatContext);
     }
 
@@ -223,7 +245,10 @@ void AudioStream::loadCustomContent (const char* filename) {
 
     this->initialize ();
 
-    this->m_audioThread = SDL_CreateThread (audio_read_thread, filename, this);
+    this->m_audioThread = std::thread ([this] {
+	WallpaperEngine::Logging::guardThread ("Audio reader", [this] { audio_read_thread (this); });
+	this->markReaderFinished ();
+    });
 }
 
 void AudioStream::initialize () {
@@ -231,6 +256,9 @@ void AudioStream::initialize () {
     this->m_queue->packetList = av_fifo_alloc (sizeof (MyAVPacketList));
 #else
     this->m_queue->packetList = av_fifo_alloc2 (1, sizeof (MyAVPacketList), AV_FIFO_FLAG_AUTO_GROW);
+
+    // the default limit is 1 MB (131072 entries), tiny packets reach MAX_QUEUE_SIZE with many more
+    av_fifo_auto_grow_limit (this->m_queue->packetList, MAX_QUEUE_SIZE / sizeof (MyAVPacketList) + 1);
 #endif
 
 #if FF_API_OLD_CHANNEL_LAYOUT
@@ -302,7 +330,7 @@ void AudioStream::queuePacket (AVPacket* pkt) {
     AVPacket* clone = av_packet_alloc ();
 
     if (clone == nullptr) {
-	av_packet_unref (clone);
+	av_packet_unref (pkt);
 	return;
     }
 
@@ -313,7 +341,7 @@ void AudioStream::queuePacket (AVPacket* pkt) {
     SDL_UnlockMutex (this->m_queue->mutex);
 
     if (!gotQueued) {
-	av_packet_free (&pkt);
+	av_packet_free (&clone);
     }
 }
 
@@ -440,9 +468,21 @@ ReadStreamSharedPtr& AudioStream::getBuffer () { return this->m_buffer; }
 
 SDL_cond* AudioStream::getWaitCondition () const { return this->m_queue->wait; }
 
-size_t AudioStream::getQueueSize () const { return this->m_queue->size; }
+size_t AudioStream::getQueueSize () const {
+    SDL_LockMutex (this->m_queue->mutex);
+    const size_t size = this->m_queue->size;
+    SDL_UnlockMutex (this->m_queue->mutex);
+
+    return size;
+}
 
-int AudioStream::getQueuePacketCount () const { return this->m_queue->nb_packets; }
+int AudioStream::getQueuePacketCount () const {
+    SDL_LockMutex (this->m_queue->mutex);
+    const int count = this->m_queue->nb_packets;
+    SDL_UnlockMutex (this->m_queue->mutex);
+
+    return count;
+}
 
 AVRational AudioStream::getTimeBase () const {
     if (this->m_audioStream == NO_AUDIO_STREAM) {
@@ -452,7 +492,13 @@ AVRational AudioStream::getTimeBase () const {
     return this->m_formatContext->streams[this->m_audioStream]->time_base;
 }
 
-int64_t AudioStream::getQueueDuration () const { return this->m_queue->duration; }
+int64_t AudioStream::getQueueDuration () const {
+    SDL_LockMutex (this->m_queue->mutex);
+    const int64_t duration = this->m_queue->duration;
+    SDL_UnlockMutex (this->m_queue->mutex);
+
+    return duration;
+}
 
 void AudioStream::stop () {
     if (!this->isInitialized ()) {

+ 5 - 3
src/WallpaperEngine/Audio/AudioStream.h

@@ -2,6 +2,7 @@
 
 #include <atomic>
 #include <string>
+#include <thread>
 #include <vector>
 
 extern "C" {
@@ -107,8 +108,8 @@ private:
 
     SwrContext* m_swrctx = nullptr;
     AudioContext& m_audioContext;
-    bool m_initialized = false;
-    bool m_repeat = false;
+    std::atomic<bool> m_initialized = false;
+    std::atomic<bool> m_repeat = false;
     /** Set once the reader thread has exited, so nothing waits for packets that will never come */
     std::atomic<bool> m_readerFinished = false;
     AVCodecContext* m_context = nullptr;
@@ -146,6 +147,7 @@ private:
 	SDL_cond* wait = nullptr;
     }* m_queue {};
 
-    SDL_Thread* m_audioThread = nullptr;
+    // std::thread, not SDL_Thread: SDL_WaitThread doesn't join anymore once SDL_Quit ran (sdl2-compat)
+    std::thread m_audioThread;
 };
 } // namespace WallpaperEngine::Audio

+ 6 - 9
src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp

@@ -1,5 +1,6 @@
 #include "PulseAudioPlaybackRecorder.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Logging/ThreadGuard.h"
 #include <algorithm>
 #include <chrono>
 #include <cmath>
@@ -245,8 +246,9 @@ PulseAudioPlaybackRecorder::PulseAudioPlaybackRecorder () :
 
     // capture on its own thread: pumped from the render loop a slow frame stalled it and the server force-dropped the
     // backlog
-    this->m_captureThread
-	= SDL_CreateThread (&PulseAudioPlaybackRecorder::captureThreadEntry, "lwe-audiocapture", this);
+    this->m_captureThread = std::thread ([this] {
+	WallpaperEngine::Logging::guardThread ("Audio capture", [this] { this->captureLoop (); });
+    });
 }
 
 PulseAudioPlaybackRecorder::~PulseAudioPlaybackRecorder () {
@@ -255,8 +257,8 @@ PulseAudioPlaybackRecorder::~PulseAudioPlaybackRecorder () {
 	// unblocks the pa_mainloop_poll() the capture thread may be waiting in
 	pa_mainloop_wakeup (this->m_mainloop);
     }
-    if (this->m_captureThread) {
-	SDL_WaitThread (this->m_captureThread, nullptr);
+    if (this->m_captureThread.joinable ()) {
+	this->m_captureThread.join ();
     }
 
     if (m_captureData.captureStream) {
@@ -277,11 +279,6 @@ PulseAudioPlaybackRecorder::~PulseAudioPlaybackRecorder () {
 void PulseAudioPlaybackRecorder::lock () const { SDL_LockMutex (this->m_dataMutex); }
 void PulseAudioPlaybackRecorder::unlock () const { SDL_UnlockMutex (this->m_dataMutex); }
 
-int PulseAudioPlaybackRecorder::captureThreadEntry (void* userdata) {
-    static_cast<PulseAudioPlaybackRecorder*> (userdata)->captureLoop ();
-    return 0;
-}
-
 void PulseAudioPlaybackRecorder::captureLoop () {
     bool cleared = false;
 

+ 2 - 2
src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h

@@ -7,6 +7,7 @@
 #include <chrono>
 #include <pulse/pulseaudio.h>
 #include <string>
+#include <thread>
 
 namespace WallpaperEngine::Audio::Drivers::Recorders {
 class PlaybackRecorder;
@@ -31,7 +32,6 @@ public:
     void dropBlock ();
 
 private:
-    static int captureThreadEntry (void* userdata);
     void captureLoop ();
     void clearCaptured ();
 
@@ -45,7 +45,7 @@ private:
     std::chrono::steady_clock::time_point m_lastSamples = std::chrono::steady_clock::now ();
 
     // own thread so capture keeps draining however long a frame takes
-    SDL_Thread* m_captureThread = nullptr;
+    std::thread m_captureThread;
     mutable SDL_mutex* m_dataMutex = nullptr;
     std::atomic<bool> m_running { true };
 };

+ 13 - 12
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp

@@ -349,22 +349,23 @@ SDLAudioDriver::SDLAudioDriver (
 }
 
 SDLAudioDriver::~SDLAudioDriver () {
-    if (!this->m_initialized) {
-	return;
-    }
+    if (this->m_initialized) {
+	if (this->m_deviceID != 0) {
+	    SDL_CloseAudioDevice (this->m_deviceID);
+	}
 
-    if (this->m_deviceID != 0) {
-	SDL_CloseAudioDevice (this->m_deviceID);
-    }
+	// streams still fading out belong to the driver
+	for (const auto* buffer : this->m_streams | std::views::values) {
+	    delete buffer;
+	}
 
-    // streams still fading out belong to the driver
-    for (const auto* buffer : this->m_streams | std::views::values) {
-	delete buffer;
-    }
+	this->m_streams.clear ();
 
-    this->m_streams.clear ();
+	SDL_QuitSubSystem (SDL_INIT_AUDIO);
+    }
 
-    SDL_QuitSubSystem (SDL_INIT_AUDIO);
+    // made before the audio system starts, so it is there on every path out of the constructor
+    SDL_DestroyMutex (this->m_streamListMutex);
 }
 
 int SDLAudioDriver::addStream (AudioStream* stream, int volume, float left, float right) {

+ 40 - 8
src/WallpaperEngine/Data/JSON.h

@@ -75,7 +75,7 @@ public:
 	}
     }
     [[nodiscard]] base_type require (const std::string& key, const std::string& message) const {
-	auto base = this->base ();
+	const auto& base = this->base ();
 	const auto it = base.find (key);
 
 	if (it == base.end ()) {
@@ -85,17 +85,22 @@ public:
 	return *it;
     }
     template <typename T> [[nodiscard]] T require (const std::string& key, const std::string& message) const {
-	auto base = this->base ();
+	const auto& base = this->base ();
 	const auto it = base.find (key);
 
 	if (it == base.end ()) {
 	    sLog.exception (message, ". Contents: ", base.dump ());
 	}
 
-	return (*it);
+	try {
+	    return (*it);
+	} catch (const std::exception& e) {
+	    reportMistyped (key, *it, e, true);
+	    throw;
+	}
     }
     [[nodiscard]] std::optional<base_type> optional (const std::string& key) const noexcept {
-	auto base = this->base ();
+	const auto& base = this->base ();
 	const auto it = base.find (key);
 	auto result = std::optional<base_type> {};
 
@@ -105,25 +110,37 @@ public:
 
 	return result;
     }
+    // a value of the wrong type (a bool written as 1, a number where text goes) counts as missing: these are noexcept,
+    // the conversion's type_error used to end the process
     template <typename T> [[nodiscard]] std::optional<T> optional (const std::string& key) const noexcept {
-	auto base = this->base ();
+	const auto& base = this->base ();
 	const auto it = base.find (key);
 
 	if (it == base.end () || it->is_null ()) {
 	    return std::nullopt;
 	}
 
-	return *it;
+	try {
+	    return *it;
+	} catch (const std::exception& e) {
+	    reportMistyped (key, *it, e);
+	    return std::nullopt;
+	}
     }
     template <typename T> [[nodiscard]] T optional (const std::string& key, T defaultValue) const noexcept {
-	auto base = this->base ();
+	const auto& base = this->base ();
 	const auto it = base.find (key);
 
 	if (it == base.end () || it->is_null ()) {
 	    return defaultValue;
 	}
 
-	return (*it);
+	try {
+	    return (*it);
+	} catch (const std::exception& e) {
+	    reportMistyped (key, *it, e);
+	    return defaultValue;
+	}
     }
     [[nodiscard]] UserSettingUniquePtr user (const std::string& key, const Properties& properties) const;
     template <typename T>
@@ -174,6 +191,21 @@ public:
 
 private:
     [[nodiscard]] const base_type& base () const { return *static_cast<const base_type*> (this); }
+
+    static void reportMistyped (
+	const std::string& key, const base_type& value, const std::exception& error, bool required = false
+    ) noexcept {
+	try {
+	    auto text = value.dump ();
+
+	    if (text.size () > 80) {
+		text.resize (80);
+		text += "...";
+	    }
+
+	    sLog.error (required ? "Cannot use required '" : "Ignoring '", key, "' (", text, "): ", error.what ());
+	} catch (...) { }
+    }
 };
 
 } // namespace WallpaperEngine::Data::JSON

+ 28 - 0
src/WallpaperEngine/Data/Parsers/ComboValue.h

@@ -0,0 +1,28 @@
+#pragma once
+
+#include <cstdint>
+
+#include "WallpaperEngine/Data/JSON.h"
+
+namespace WallpaperEngine::Data::Parsers {
+// an effect instance's combo as WE reads it for conditions (sub_1401E63B0): a number, cut to an integer, and anything
+// else counts as 0
+inline int comboValue (const WallpaperEngine::Data::JSON::JSON& value) {
+    if (value.is_number_float ()) {
+	return static_cast<int> (value.get<double> ());
+    }
+
+    return value.is_number () ? static_cast<int> (value.get<int64_t> ()) : 0;
+}
+
+// a material pass's combos and an effect pass override's (merged into the pass by sub_140153200, read by
+// sub_140154480): asInt without a type test, so null is 0, a real is cut and a bool is 0 or 1. Text, arrays and objects
+// abort WE there, 0 here
+inline int passComboValue (const WallpaperEngine::Data::JSON::JSON& value) {
+    if (value.is_boolean ()) {
+	return value.get<bool> () ? 1 : 0;
+    }
+
+    return comboValue (value);
+}
+} // namespace WallpaperEngine::Data::Parsers

+ 3 - 2
src/WallpaperEngine/Data/Parsers/EffectParser.cpp

@@ -224,8 +224,9 @@ std::vector<EffectPassUniquePtr> EffectParser::parseEffectPasses (const JSON& it
 	result.push_back (
 	    std::make_unique<EffectPass> (EffectPass {
 		.conditions = conditions.has_value () ? parseConditions (*conditions) : EffectConditions {},
-		.material = material.has_value () ? MaterialParser::load (project, *material)
-						  : std::optional<MaterialUniquePtr> {},
+		.material = material.has_value ()
+		    ? MaterialParser::load (project, material->is_string () ? material->get<std::string> () : "")
+		    : std::optional<MaterialUniquePtr> {},
 		.binds = binds.has_value () ? parseBinds (binds.value ()) : std::map<int, std::string> {},
 		.command = command.has_value () ? (command.value () == "copy" ? Command_Copy : Command_Swap)
 						: std::optional<PassCommandType> {},

+ 43 - 8
src/WallpaperEngine/Data/Parsers/MaterialParser.cpp

@@ -1,5 +1,6 @@
 #include "MaterialParser.h"
 
+#include "ComboValue.h"
 #include "TextureParser.h"
 #include "WallpaperEngine/Data/Model/Material.h"
 #include "WallpaperEngine/Data/Model/Project.h"
@@ -38,19 +39,43 @@ MaterialUniquePtr MaterialParser::parse (const JSON& it, const std::string& file
     });
 }
 
+namespace {
+// sub_1401587D0 and its siblings (blending, alphawriting, depthtest, depthwrite, cullmode): a member that is there is
+// looked up by its text in that property's table, and anything that isn't text (a number, null) or isn't in the table
+// takes the table's first entry. Only a member that is missing leaves the material's own default.
+std::optional<std::string> modeName (const JSON& pass, const char* key) {
+    const auto member = pass.find (key);
+
+    if (member == pass.end ()) {
+	return std::nullopt;
+    }
+
+    if (member->is_string ()) {
+	return member->get<std::string> ();
+    }
+
+    sLog.error ("Ignoring '", key, "' (", member->dump (), "): not text");
+
+    return std::string ();
+}
+} // namespace
+
 MaterialPassUniquePtr MaterialParser::parsePass (const JSON& it, const Project& project) {
     const auto textures = it.optional ("textures");
     const auto usertextures = it.optional ("usertextures");
     const auto combos = it.optional ("combos");
     const auto constants = it.optional ("constantshadervalues");
+    const auto cullmode = modeName (it, "cullmode");
+    const auto depthtest = modeName (it, "depthtest");
+    const auto depthwrite = modeName (it, "depthwrite");
 
     return std::make_unique<MaterialPass> (MaterialPass {
 	// TODO: avoid this std::string construction
 	.blending = parseBlendMode (it.optional ("blending", std::string ("normal"))),
 	// left unknown when missing, which draws like nocull/disabled, 3D models pick their own defaults
-	.cullmode = it.contains ("cullmode") ? parseCullMode (it["cullmode"]) : CullingMode_Unknown,
-	.depthtest = it.contains ("depthtest") ? parseDepthtestMode (it["depthtest"]) : DepthtestMode_Unknown,
-	.depthwrite = it.contains ("depthwrite") ? parseDepthwriteMode (it["depthwrite"]) : DepthwriteMode_Unknown,
+	.cullmode = cullmode.has_value () ? parseCullMode (*cullmode) : CullingMode_Unknown,
+	.depthtest = depthtest.has_value () ? parseDepthtestMode (*depthtest) : DepthtestMode_Unknown,
+	.depthwrite = depthwrite.has_value () ? parseDepthwriteMode (*depthwrite) : DepthwriteMode_Unknown,
 	// no shader falls back to WE's "error" shader too (sub_140154480)
 	.shader = it.optional<std::string> ("shader", "error"),
 	.textures = textures.has_value () ? TextureParser::parseTextureMap (*textures) : TextureMap {},
@@ -69,7 +94,7 @@ std::map<std::string, int> MaterialParser::parseCombos (const JSON& it) {
     }
 
     for (const auto& cur : it.items ()) {
-	result.emplace (cur.key (), cur.value ());
+	result.emplace (cur.key (), passComboValue (cur.value ()));
     }
 
     return result;
@@ -105,8 +130,12 @@ CullingMode MaterialParser::parseCullMode (const std::string& mode) {
 	return CullingMode_Normal;
     }
 
-    sLog.error ("Unknown culling mode: ", mode, " defaulting to nocull");
-    return CullingMode_Disable;
+    // the first entry of WE's table
+    if (!mode.empty ()) {
+	sLog.error ("Unknown culling mode: ", mode, " defaulting to normal");
+    }
+
+    return CullingMode_Normal;
 }
 
 DepthtestMode MaterialParser::parseDepthtestMode (const std::string& mode) {
@@ -118,7 +147,10 @@ DepthtestMode MaterialParser::parseDepthtestMode (const std::string& mode) {
 	return DepthtestMode_Enabled;
     }
 
-    sLog.error ("Unknown depthtest mode: ", mode, " defaulting to disabled");
+    if (!mode.empty ()) {
+	sLog.error ("Unknown depthtest mode: ", mode, " defaulting to disabled");
+    }
+
     return DepthtestMode_Disabled;
 }
 
@@ -131,6 +163,9 @@ DepthwriteMode MaterialParser::parseDepthwriteMode (const std::string& mode) {
 	return DepthwriteMode_Enabled;
     }
 
-    sLog.error ("Unknown depthwrite mode: ", mode, " defaulting to disabled");
+    if (!mode.empty ()) {
+	sLog.error ("Unknown depthwrite mode: ", mode, " defaulting to disabled");
+    }
+
     return DepthwriteMode_Disabled;
 }

+ 3 - 1
src/WallpaperEngine/Data/Parsers/ModelParser.cpp

@@ -17,7 +17,9 @@ ModelUniquePtr ModelParser::load (const Project& project, const std::string& fil
 }
 
 ModelUniquePtr ModelParser::parse (const JSON& file, const Project& project, const std::string& filename) {
-    const auto material = file.require<std::string> ("material", "Model must have a material");
+    const auto materialNode = file.require ("material", "Model must have a material");
+    // not text counts as a material that can't be opened, see MaterialParser::load
+    const auto material = materialNode.is_string () ? materialNode.get<std::string> () : std::string ();
 
     return std::make_unique<ModelStruct> (ModelStruct {
 	.filename = filename,

+ 8 - 7
src/WallpaperEngine/Data/Parsers/ObjectParser.cpp

@@ -1,4 +1,5 @@
 #include "ObjectParser.h"
+#include "ComboValue.h"
 #include "DynamicValueParser.h"
 #include "EffectParser.h"
 #include "MaterialParser.h"
@@ -844,7 +845,11 @@ std::vector<ImageEffectUniquePtr> ObjectParser::parseEffects (const JSON& it, co
     std::vector<ImageEffectUniquePtr> result = {};
 
     for (const auto& cur : it) {
-	result.push_back (parseEffect (cur, project));
+	try {
+	    result.push_back (parseEffect (cur, project));
+	} catch (const std::exception& e) {
+	    sLog.error ("Skipping an effect that cannot be loaded: ", e.what ());
+	}
     }
 
     return result;
@@ -857,11 +862,7 @@ ImageEffectUniquePtr ObjectParser::parseEffect (const JSON& it, const Project& p
     // non-numbers count as 0 (sub_1401E63B0)
     if (const auto found = it.find ("combos"); found != it.end () && found->is_object ()) {
 	for (const auto& [name, value] : found->items ()) {
-	    combos.emplace (
-		name,
-		value.is_number_float () ? static_cast<int> (value.get<double> ())
-					 : (value.is_number () ? static_cast<int> (value.get<int64_t> ()) : 0)
-	    );
+	    combos.emplace (name, comboValue (value));
 	}
     }
 
@@ -915,7 +916,7 @@ ComboMap ObjectParser::parseComboMap (const JSON& it) {
     ComboMap result = {};
 
     for (const auto& cur : it.items ()) {
-	result.emplace (cur.key (), cur.value ());
+	result.emplace (cur.key (), passComboValue (cur.value ()));
     }
 
     return result;

+ 8 - 0
src/WallpaperEngine/Data/Parsers/PackageParser.cpp

@@ -7,6 +7,7 @@
 
 #include <fstream>
 #include <memory>
+#include <tuple>
 
 using namespace WallpaperEngine::Data::Parsers;
 using namespace WallpaperEngine::Data::Assets;
@@ -25,6 +26,8 @@ PackageUniquePtr PackageParser::parse (ReadStreamSharedPtr stream) {
 
     result->files = parseFileList (*result->file);
     result->baseOffset = result->file->base ().tellg ();
+    // looked up once here, the adapter's bounds checks reuse it
+    std::ignore = result->file->size ();
 
     return result;
 }
@@ -33,6 +36,11 @@ FileEntryList PackageParser::parseFileList (const BinaryReader& stream) {
     FileEntryList result = {};
     const uint32_t filesCount = stream.nextUInt32 ();
 
+    // each entry is a name length, a name, an offset and a length: the count can't be more than the file holds
+    if (!stream.fits (filesCount, 3 * sizeof (uint32_t))) {
+	sLog.exception ("Package lists ", filesCount, " files, more than it can hold");
+    }
+
     result.reserve (filesCount);
 
     for (uint32_t i = 0; i < filesCount; i++) {

+ 80 - 6
src/WallpaperEngine/Data/Parsers/ProjectParser.cpp

@@ -19,7 +19,8 @@ ProjectUniquePtr ProjectParser::parse (const JSON& data, AssetLocatorUniquePtr c
     const auto general = data.optional ("general");
     const auto workshopId = data.optional ("workshopid");
     auto actualWorkshopId = std::to_string (--backgroundId);
-    auto type = data.require<std::string> ("type", "Project type missing");
+    // read as text here, a number or an object would otherwise fail later without saying which key it was
+    const auto mainFile = data.require<std::string> ("file", "Project's main file missing");
 
     if (workshopId.has_value ()) {
 	if (workshopId->is_number ()) {
@@ -31,22 +32,95 @@ ProjectUniquePtr ProjectParser::parse (const JSON& data, AssetLocatorUniquePtr c
 	}
     }
 
-    std::ranges::transform (type, type.begin (), tolower);
-
     auto result = std::make_unique<Project> (Project {
-	.title = data.require<std::string> ("title", "Project title missing"),
-	.type = parseType (type),
+	.title = data.optional<std::string> ("title", ""),
+	.type = determineType (data, mainFile),
 	.workshopId = actualWorkshopId,
 	.supportsAudioProcessing = general.has_value () && general.value ().optional ("supportsaudioprocessing", false),
 	.properties = parseProperties (general),
 	.assetLocator = std::move (container),
     });
 
-    result->wallpaper = WallpaperParser::parse (data.require ("file", "Project's main file missing"), *result);
+    result->wallpaper = WallpaperParser::parse (JSON (mainFile), *result);
 
     return result;
 }
 
+// sub_14011D7D0 / sub_14011E520: Wallpaper Engine never reads the "type" key, it works the type out of the main file's
+// extension (.json .pkg .gif scene, .html web, .exe application, .mp4 .wmv .avi .m4v .mov .webm .mkv video) and writes
+// that into the key. The declared type is only used here for a file it has no rule for.
+std::optional<Project::Type> ProjectParser::typeOfFile (const std::string& file) {
+    const auto dot = file.rfind ('.');
+
+    if (dot == std::string::npos) {
+	return std::nullopt;
+    }
+
+    auto extension = file.substr (dot);
+    std::ranges::transform (extension, extension.begin (), tolower);
+
+    if (extension == ".json" || extension == ".pkg" || extension == ".gif") {
+	return Project::Type_Scene;
+    }
+
+    if (extension == ".html") {
+	return Project::Type_Web;
+    }
+
+    if (extension == ".mp4" || extension == ".wmv" || extension == ".avi" || extension == ".m4v" || extension == ".mov"
+	|| extension == ".webm" || extension == ".mkv") {
+	return Project::Type_Video;
+    }
+
+    return std::nullopt;
+}
+
+Project::Type ProjectParser::determineType (const JSON& data, const std::string& file) {
+    const auto declared = data.optional<std::string> ("type");
+    const auto derived = typeOfFile (file);
+
+    if (derived.has_value ()) {
+	if (declared.has_value ()) {
+	    auto name = *declared;
+	    std::ranges::transform (name, name.begin (), tolower);
+
+	    // a wrong declaration is reported, the file decides like in WE
+	    if (const auto known = typeOfName (name); !known.has_value () || *known != *derived) {
+		sLog.error (
+		    "Project type '", *declared, "' does not match its main file '", file, "', using the file's"
+		);
+	    }
+	}
+
+	return *derived;
+    }
+
+    if (!declared.has_value ()) {
+	sLog.exception ("Project type missing and the main file '", file, "' does not tell it");
+    }
+
+    auto name = *declared;
+    std::ranges::transform (name, name.begin (), tolower);
+
+    return parseType (name);
+}
+
+std::optional<Project::Type> ProjectParser::typeOfName (const std::string& type) {
+    if (type == "scene") {
+	return Project::Type_Scene;
+    }
+
+    if (type == "video") {
+	return Project::Type_Video;
+    }
+
+    if (type == "web") {
+	return Project::Type_Web;
+    }
+
+    return std::nullopt;
+}
+
 Project::Type ProjectParser::parseType (const std::string& type) {
     if (type == "scene") {
 	return Project::Type_Scene;

+ 4 - 0
src/WallpaperEngine/Data/Parsers/ProjectParser.h

@@ -15,8 +15,12 @@ using namespace WallpaperEngine::Data::Model;
 class ProjectParser {
 public:
     static ProjectUniquePtr parse (const JSON& data, AssetLocatorUniquePtr container);
+    /** The type Wallpaper Engine takes from a main file's extension, nothing for an extension it has no rule for */
+    static std::optional<Project::Type> typeOfFile (const std::string& file);
 
 private:
+    static Project::Type determineType (const JSON& data, const std::string& file);
+    static std::optional<Project::Type> typeOfName (const std::string& type);
     static Project::Type parseType (const std::string& type);
     static Properties parseProperties (const std::optional<JSON>& data);
 };

+ 18 - 3
src/WallpaperEngine/Data/Parsers/PropertyParser.cpp

@@ -1,6 +1,8 @@
 #include "PropertyParser.h"
 #include "../Model/Property.h"
 
+#include <filesystem>
+
 using namespace WallpaperEngine::Data::Parsers;
 using namespace WallpaperEngine::Data::Model;
 
@@ -80,12 +82,18 @@ PropertySharedPtr PropertyParser::parseCombo (const JSON& it, const std::string&
 }
 
 PropertySharedPtr PropertyParser::parseColor (const JSON& it, const std::string& name) {
+    const auto value = it.require ("value", "Property must have a value");
+
+    if (!value.is_string ()) {
+	sLog.error ("Color property ", name, " has a value that is not text (", value.dump (), "), using white");
+    }
+
     return std::make_shared<PropertyColor> (
 	PropertyData {
 	    .name = name,
 	    .text = it.optional<std::string> ("text", ""),
 	},
-	it.require ("value", "Property must have a value")
+	value.is_string () ? value.get<std::string> () : std::string ("1 1 1")
     );
 }
 
@@ -134,13 +142,20 @@ PropertySharedPtr PropertyParser::parseSceneTexture (const JSON& it, const std::
 }
 
 PropertySharedPtr PropertyParser::parseFile (const JSON& it, const std::string& name) {
+    auto value = it.optional<std::string> ("value", "");
+
+    // a default can't name a place on the user's disk, only the user does ("/" would open the whole filesystem to a
+    // web wallpaper's page)
+    if (std::filesystem::path (value).is_absolute ()) {
+	value.clear ();
+    }
+
     return std::make_shared<PropertyFile> (
 	PropertyData {
 	    .name = name,
 	    .text = it.optional<std::string> ("text", ""),
 	},
-	it.optional<std::string> ("value", ""), it.optional<std::string> ("type", "") == "directory",
-	it.optional<std::string> ("fileType", "")
+	value, it.optional<std::string> ("type", "") == "directory", it.optional<std::string> ("fileType", "")
     );
 }
 

+ 57 - 1
src/WallpaperEngine/Data/Parsers/TextureParser.cpp

@@ -1,3 +1,4 @@
+#include <algorithm>
 #include <cmath>
 #include <cstdlib>
 #include <cstring>
@@ -69,6 +70,21 @@ MipmapSharedPtr TextureParser::parseMipmap (const BinaryReader& file, const Text
 	result->uncompressedSize = result->compressedSize;
     }
 
+    // the sizes are the file's word, don't allocate (up to 2 GB) what it can't back. An LZ4 block never expands past
+    // 255:1, so a bigger claim is a lie too
+    const bool compressed = (result->compression & 1) != 0;
+
+    if (result->compressedSize < 0 || result->uncompressedSize < 0
+	|| !file.fits (static_cast<uint64_t> (result->compressedSize), 1)
+	|| (compressed
+	    && static_cast<uint64_t> (result->uncompressedSize)
+		> static_cast<uint64_t> (result->compressedSize) * 255 + 1024)) {
+	sLog.exception (
+	    "Texture mipmap claims ", result->compressedSize, " bytes (", result->uncompressedSize,
+	    " unpacked), the file holds ", file.remaining ()
+	);
+    }
+
     result->uncompressedData = std::unique_ptr<char[]> (new char[result->uncompressedSize]);
 
     if (result->compression & 1) {
@@ -92,9 +108,18 @@ MipmapSharedPtr TextureParser::parseMipmap (const BinaryReader& file, const Text
 void TextureParser::parseMipmapPatches (Mipmap& mipmap, const BinaryReader& file) {
     const uint32_t groupCount = file.nextUInt32 ();
 
+    if (!file.fits (groupCount, sizeof (uint32_t))) {
+	sLog.exception ("Texture lists ", groupCount, " patch groups, more than the file holds");
+    }
+
     for (uint32_t group = 0; group < groupCount; group++) {
 	const uint32_t patchCount = file.nextUInt32 ();
 
+	// a patch is eight numbers and its data's length
+	if (!file.fits (patchCount, 8 * sizeof (uint32_t))) {
+	    sLog.exception ("Texture group lists ", patchCount, " patches, more than the file holds");
+	}
+
 	for (uint32_t index = 0; index < patchCount; index++) {
 	    MipmapPatch patch;
 
@@ -105,7 +130,14 @@ void TextureParser::parseMipmapPatches (Mipmap& mipmap, const BinaryReader& file
 	    patch.width = file.nextUInt32 ();
 	    patch.height = file.nextUInt32 ();
 	    patch.format = file.nextInt ();
-	    patch.data.resize (file.nextUInt32 ());
+
+	    const uint32_t dataSize = file.nextUInt32 ();
+
+	    if (!file.fits (dataSize, 1)) {
+		sLog.exception ("Texture patch claims ", dataSize, " bytes, the file holds ", file.remaining ());
+	    }
+
+	    patch.data.resize (dataSize);
 	    file.next (patch.data.data (), patch.data.size ());
 	    mipmap.patches.push_back (std::move (patch));
 	}
@@ -211,6 +243,14 @@ void TextureParser::parseContainer (Texture& header, const BinaryReader& file, c
 
     const uint32_t conditionCount = version >= 4 ? file.nextUInt32 () : 0;
 
+    // three numbers and a text each, at least its terminator
+    if (!file.fits (conditionCount, 3 * sizeof (uint32_t) + 1) || !file.fits (header.imageCount, sizeof (uint32_t))) {
+	sLog.exception (
+	    "Texture claims ", header.imageCount, " images and ", conditionCount,
+	    " conditions, more than the file holds"
+	);
+    }
+
     for (uint32_t index = 0; index < conditionCount; index++) {
 	TextureCondition condition;
 
@@ -225,6 +265,11 @@ void TextureParser::parseContainer (Texture& header, const BinaryReader& file, c
 	const uint32_t mipmapCount = file.nextUInt32 ();
 	MipmapList mipmaps;
 
+	// width, height and a size at least
+	if (!file.fits (mipmapCount, 3 * sizeof (uint32_t))) {
+	    sLog.exception ("Texture image lists ", mipmapCount, " mipmaps, more than the file holds");
+	}
+
 	for (uint32_t mipmap = 0; mipmap < mipmapCount; mipmap++) {
 	    mipmaps.emplace_back (parseMipmap (file, header));
 
@@ -236,6 +281,12 @@ void TextureParser::parseContainer (Texture& header, const BinaryReader& file, c
 
 	header.images.emplace (image, mipmaps);
     }
+
+    // every consumer starts from the first mipmap of image 0
+    if (header.images.empty ()
+	|| std::ranges::any_of (header.images, [] (const auto& image) { return image.second.empty (); })) {
+	sLog.exception ("Texture has no image data");
+    }
 }
 
 // sub_14015E1D0: v1 has integer frame rects, v3+ stores the frame size after the count
@@ -244,6 +295,11 @@ void TextureParser::parseAnimations (Texture& header, const BinaryReader& file,
 
     uint32_t frameCount = file.nextUInt32 ();
 
+    // a frame is eight numbers
+    if (!file.fits (frameCount, 8 * sizeof (uint32_t))) {
+	sLog.exception ("Texture lists ", frameCount, " animation frames, more than the file holds");
+    }
+
     if (version >= 3) {
 	header.gifWidth = file.nextUInt32 ();
 	header.gifHeight = file.nextUInt32 ();

+ 36 - 6
src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp

@@ -319,10 +319,40 @@ SceneUniquePtr WallpaperParser::parseScene (const JSON& file, Project& project)
     const auto scene = JSON::parseAsset (project.assetLocator->readString (file));
     const auto camera = scene.require ("camera", "Scenes must have a camera section");
     const auto general = scene.require ("general", "Scenes must have a general section");
-    // null (or missing) means a perspective camera, a 3D scene
+    // sub_140186C90: the scene is orthographic only when the member is an object that says "auto": true or has a numeric
+    // width and height, neither of them 0. Anything else (missing, null, text, a number, a half written block) leaves the
+    // scene perspective, a 3D one, and loads
     const auto projectionIt = general.find ("orthogonalprojection");
-    const bool perspective = projectionIt == general.end () || projectionIt->is_null ();
-    const JSON projection = perspective ? JSON::object () : JSON (*projectionIt);
+    bool perspective = true;
+    int projectionWidth = 0;
+    int projectionHeight = 0;
+
+    if (projectionIt != general.end () && projectionIt->is_object ()) {
+	const auto autoIt = projectionIt->find ("auto");
+	const auto widthIt = projectionIt->find ("width");
+	const auto heightIt = projectionIt->find ("height");
+
+	if (autoIt != projectionIt->end () && autoIt->is_boolean () && autoIt->get<bool> ()) {
+	    perspective = false;
+	} else if (widthIt != projectionIt->end () && heightIt != projectionIt->end () && widthIt->is_number ()
+		   && heightIt->is_number ()) {
+	    projectionWidth = widthIt->get<int> ();
+	    projectionHeight = heightIt->get<int> ();
+
+	    if (projectionWidth != 0 && projectionHeight != 0) {
+		// a negative canvas is the one case WE draws nonsense from, nothing here to match
+		if (projectionWidth < 0 || projectionHeight < 0) {
+		    sLog.exception ("Projection size must be positive: ", projectionWidth, "x", projectionHeight);
+		}
+
+		perspective = false;
+	    } else {
+		projectionWidth = projectionHeight = 0;
+	    }
+	}
+    }
+
+    const bool sizedByContent = perspective || projectionWidth == 0;
     const auto objects = scene.require ("objects", "Scenes must have an objects section");
     const auto& properties = project.properties;
     // particles read it while the objects get parsed below
@@ -390,9 +420,9 @@ SceneUniquePtr WallpaperParser::parseScene (const JSON& file, Project& project)
                 },
                 .paths = parseCameraPaths (camera, project),
                 .projection = {
-                    .width  = perspective || projection.optional ("auto", false) ? 0 : projection.require <int> ("width",  "Projection must have a width"),
-                    .height = perspective || projection.optional ("auto", false) ? 0 : projection.require <int> ("height", "Projection must have a height"),
-                    .isAuto = perspective || projection.optional ("auto", false),
+                    .width  = projectionWidth,
+                    .height = projectionHeight,
+                    .isAuto = sizedByContent,
                     .isPerspective = perspective,
                     .nearz = general.user ("nearz", properties, 0.1f),
                     .farz = general.user ("farz", properties, 10000.0f),

+ 61 - 7
src/WallpaperEngine/Data/Utils/BinaryReader.cpp

@@ -9,8 +9,9 @@ using namespace WallpaperEngine::Data::Utils;
 
 BinaryReader::BinaryReader (ReadStreamSharedPtr file) : m_input (std::move (file)) { }
 
+// a read that comes up short leaves zeros for the missing bytes (and the stream's failbit for callers that look)
 uint32_t BinaryReader::nextUInt32 () const {
-    char buffer[4];
+    char buffer[4] = {};
 
     this->m_input->read (buffer, 4);
 
@@ -22,7 +23,7 @@ uint32_t BinaryReader::nextUInt32 () const {
 }
 
 int BinaryReader::nextInt () const {
-    char buffer[4];
+    char buffer[4] = {};
 
     this->m_input->read (buffer, 4);
 
@@ -34,7 +35,7 @@ int BinaryReader::nextInt () const {
 }
 
 float BinaryReader::nextFloat () const {
-    float result;
+    float result = 0.0f;
     static_assert (std::endian::native == std::endian::little, "Only little endian is supported for floats");
 
     this->m_input->read (reinterpret_cast<char*> (&result), sizeof (result));
@@ -45,7 +46,8 @@ float BinaryReader::nextFloat () const {
 std::string BinaryReader::nextNullTerminatedString () const {
     std::string output;
 
-    while (const auto c = this->next ()) {
+    // the end of the data ends the string too, there is no terminator to wait for
+    for (char c = this->next (); this->m_input->good () && c != '\0'; c = this->next ()) {
 	output += c;
     }
 
@@ -53,7 +55,14 @@ std::string BinaryReader::nextNullTerminatedString () const {
 }
 
 std::string BinaryReader::nextSizedString () const {
-    uint32_t length = this->nextUInt32 ();
+    const uint32_t length = this->nextUInt32 ();
+
+    // a length the file can't hold would allocate it (up to 4 GB) for nothing
+    if (length > this->remaining ()) {
+	this->m_input->setstate (std::ios::failbit);
+	return {};
+    }
+
     std::string output (length, '\0');
 
     this->m_input->read (output.data (), length);
@@ -61,12 +70,57 @@ std::string BinaryReader::nextSizedString () const {
     return output;
 }
 
-void BinaryReader::next (char* out, size_t size) const { this->m_input->read (out, size); }
+void BinaryReader::next (char* out, size_t size) const {
+    this->m_input->read (out, static_cast<std::streamsize> (size));
+
+    if (const auto got = static_cast<size_t> (this->m_input->gcount ()); got < size) {
+	memset (out + got, 0, size - got);
+    }
+}
 
 char BinaryReader::next () const {
-    char buffer;
+    char buffer = 0;
     this->m_input->read (&buffer, 1);
     return buffer;
 }
 
 std::istream& BinaryReader::base () const { return *this->m_input; }
+
+uint64_t BinaryReader::size () const {
+    if (this->m_size < 0) {
+	const auto here = this->m_input->tellg ();
+
+	if (here < 0) {
+	    return 0;
+	}
+
+	// relative moves only, MemoryStream has no absolute seek
+	this->m_input->seekg (0, std::ios::end);
+	const auto end = this->m_input->tellg ();
+	this->m_input->seekg (here - end, std::ios::cur);
+	this->m_size = static_cast<int64_t> (end);
+    }
+
+    return static_cast<uint64_t> (this->m_size);
+}
+
+uint64_t BinaryReader::remaining () const {
+    const auto here = this->m_input->tellg ();
+
+    if (here < 0) {
+	return 0;
+    }
+
+    const uint64_t total = this->size ();
+
+    return total > static_cast<uint64_t> (here) ? total - static_cast<uint64_t> (here) : 0;
+}
+
+bool BinaryReader::fits (const uint64_t count, const uint64_t recordBytes) const {
+    if (count == 0 || recordBytes == 0) {
+	return true;
+    }
+
+    // count * recordBytes without wrapping
+    return count <= this->remaining () / recordBytes;
+}

+ 8 - 0
src/WallpaperEngine/Data/Utils/BinaryReader.h

@@ -22,8 +22,16 @@ public:
 
     [[nodiscard]] std::istream& base () const;
 
+    /** Length of the whole stream, what the parsers check the sizes and counts a file claims against */
+    [[nodiscard]] uint64_t size () const;
+    /** Bytes after the read position, 0 once a read failed */
+    [[nodiscard]] uint64_t remaining () const;
+    /** Whether count records of at least recordBytes each can still be in the rest of the stream */
+    [[nodiscard]] bool fits (uint64_t count, uint64_t recordBytes) const;
+
 private:
     ReadStreamSharedPtr m_input;
+    mutable int64_t m_size = -1;
 };
 
 using BinaryReaderUniquePtr = std::unique_ptr<BinaryReader>;

+ 20 - 0
src/WallpaperEngine/Data/Utils/FiniteFloat.h

@@ -0,0 +1,20 @@
+#pragma once
+
+#include <cmath>
+#include <stdexcept>
+#include <string>
+
+namespace WallpaperEngine::Data::Utils {
+/** std::stof for what a user types: "nan" and "inf" parse, pass every range check (a comparison with NaN is false) and
+ * end up as a flat red frame (--speed nan) or a black one (--zoom nan). Throws std::invalid_argument like stof does for
+ * text that isn't a number, so the callers' catch blocks take it */
+inline float parseFiniteFloat (const std::string& text) {
+    const float value = std::stof (text);
+
+    if (!std::isfinite (value)) {
+	throw std::invalid_argument ("not a finite number: " + text);
+    }
+
+    return value;
+}
+} // namespace WallpaperEngine::Data::Utils

+ 3 - 1
src/WallpaperEngine/Desktop/GnomeShell.cpp

@@ -11,6 +11,7 @@
 #include <sys/socket.h>
 #include <sys/stat.h>
 #include <sys/un.h>
+#include <system_error>
 #include <unistd.h>
 
 using namespace WallpaperEngine::Desktop;
@@ -171,7 +172,8 @@ int GnomeShell::openWaylandSocket () {
     umask (mask);
 
     if (!bound) {
-	this->m_reason = "cannot listen on " + path + ": " + std::strerror (errno);
+	this->m_reason
+	    = "cannot listen on " + path + ": " + std::error_code (errno, std::generic_category ()).message ();
 	if (listener >= 0) {
 	    close (listener);
 	}

+ 205 - 13
src/WallpaperEngine/Desktop/KWinScript.cpp

@@ -3,8 +3,19 @@
 
 #include "WallpaperEngine/Logging/Log.h"
 
+#include <algorithm>
+#include <cctype>
+#include <cerrno>
+#include <csignal>
 #include <cstdio>
-#include <fstream>
+#include <cstdlib>
+#include <cstring>
+#include <fcntl.h>
+#include <spawn.h>
+#include <sys/file.h>
+#include <unistd.h>
+
+extern char** environ;
 
 using namespace WallpaperEngine::Desktop;
 
@@ -19,8 +30,180 @@ DBusMessage* callKWin (DBusConnection* connection, DBusMessage* call, const char
 
     return reply;
 }
+
+constexpr const char* SCRIPT_PREFIX = "lwe-";
+
+void unloadScript (DBusConnection* connection, const std::string& pluginName) {
+    DBusMessage* unload
+	= dbus_message_new_method_call ("org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting", "unloadScript");
+    const char* nameArg = pluginName.c_str ();
+    dbus_message_append_args (unload, DBUS_TYPE_STRING, &nameArg, DBUS_TYPE_INVALID);
+
+    if (DBusMessage* reply = callKWin (connection, unload, "unloadScript"); reply != nullptr) {
+	dbus_message_unref (reply);
+    }
+}
+
+bool writeAll (int descriptor, const std::string& text) {
+    for (size_t done = 0; done < text.size ();) {
+	const ssize_t wrote = ::write (descriptor, text.data () + done, text.size () - done);
+
+	if (wrote < 0 && errno == EINTR) {
+	    continue;
+	}
+
+	if (wrote <= 0) {
+	    return false;
+	}
+
+	done += static_cast<size_t> (wrote);
+    }
+
+    return true;
+}
+
+/** The kwin janitor helper of this engine: unloads its scripts once the pipe to it closes, however the engine ended:
+ * the destructors never run for a SIGKILL, and a script of a dead engine makes KWin call a service that isn't there at
+ * every cursor move */
+class Janitor {
+public:
+    static Janitor& instance () {
+	static Janitor janitor;
+	return janitor;
+    }
+
+    void watch (const std::string& pluginName, const std::string& path) {
+	this->send ("+" + pluginName + "\t" + path + "\n");
+    }
+
+    void forget (const std::string& pluginName) { this->send ("-" + pluginName + "\n"); }
+
+private:
+    void start () {
+	this->m_started = true;
+
+	// next to the engine like the web helper, the engine itself is far too big for a watcher (112 MB resident)
+	std::error_code error;
+	const auto helper = std::filesystem::read_symlink ("/proc/self/exe", error).parent_path ()
+	    / "linux-wallpaperengine-kwin-janitor";
+
+	if (error || !std::filesystem::exists (helper, error)) {
+	    return;
+	}
+
+	int channel[2];
+
+	if (pipe2 (channel, O_CLOEXEC) != 0) {
+	    return;
+	}
+
+	posix_spawn_file_actions_t actions;
+	posix_spawn_file_actions_init (&actions);
+	// dup2 clears the close-on-exec flag of the copy, the write end must not reach the helper or anything else
+	posix_spawn_file_actions_adddup2 (&actions, channel[0], STDIN_FILENO);
+	posix_spawn_file_actions_addopen (&actions, STDOUT_FILENO, "/dev/null", O_WRONLY, 0);
+	posix_spawn_file_actions_addopen (&actions, STDERR_FILENO, "/dev/null", O_WRONLY, 0);
+
+	// its own session: a kill of the engine's process group (or a Ctrl-C) must not take it along
+	posix_spawnattr_t attributes;
+	posix_spawnattr_init (&attributes);
+	posix_spawnattr_setflags (&attributes, POSIX_SPAWN_SETSID);
+
+	const std::string program = helper.string ();
+	char* const arguments[] = { const_cast<char*> (program.c_str ()), nullptr };
+	pid_t child = 0;
+	const int result = posix_spawn (&child, program.c_str (), &actions, &attributes, arguments, environ);
+
+	posix_spawnattr_destroy (&attributes);
+	posix_spawn_file_actions_destroy (&actions);
+	close (channel[0]);
+
+	if (result != 0) {
+	    close (channel[1]);
+	    return;
+	}
+
+	this->m_pipe = channel[1];
+    }
+
+    void send (const std::string& line) {
+	if (!this->m_started) {
+	    this->start ();
+	}
+
+	if (this->m_pipe >= 0 && !writeAll (this->m_pipe, line)) {
+	    close (this->m_pipe);
+	    this->m_pipe = -1;
+	}
+    }
+
+    int m_pipe = -1;
+    bool m_started = false;
+};
 } // namespace
 
+std::vector<std::string>
+KWinScript::findStale (const std::filesystem::path& directory, std::chrono::seconds minimumAge) {
+    std::vector<std::string> stale;
+    std::error_code error;
+
+    for (const auto& entry : std::filesystem::directory_iterator (directory, error)) {
+	const std::string name = entry.path ().stem ().string ();
+
+	if (!entry.is_regular_file (error) || entry.path ().extension () != ".js"
+	    || !name.starts_with (SCRIPT_PREFIX)) {
+	    continue;
+	}
+
+	const auto modified = entry.last_write_time (error);
+
+	if (!error && std::filesystem::file_time_type::clock::now () - modified < minimumAge) {
+	    continue;
+	}
+
+	// an engine from before the lock existed has none: its name ends in its pid, which tells while it runs in this
+	// pid namespace (a Flatpak's "<instance>_<pid>" doesn't parse and relies on the lock)
+	const auto tag = name.substr (name.find_last_of ('-') + 1);
+
+	if (!tag.empty () && std::ranges::all_of (tag, [] (unsigned char c) { return std::isdigit (c); })) {
+	    const auto pid = std::strtol (tag.c_str (), nullptr, 10);
+
+	    if (pid > 0 && (kill (static_cast<pid_t> (pid), 0) == 0 || errno == EPERM)) {
+		continue;
+	    }
+	}
+
+	// a running engine holds a shared lock on its file for as long as it lives, wherever its pid namespace is
+	const int file = open (entry.path ().c_str (), O_RDONLY | O_CLOEXEC);
+
+	if (file < 0) {
+	    continue;
+	}
+
+	if (flock (file, LOCK_EX | LOCK_NB) == 0) {
+	    stale.push_back (name);
+	}
+
+	close (file);
+    }
+
+    return stale;
+}
+
+void KWinScript::unloadStale (DBusConnection* connection) {
+    const std::string dir = runtimeDirectory ();
+
+    if (dir.empty ()) {
+	return;
+    }
+
+    for (const auto& name : findStale (dir)) {
+	sLog.out ("Unloading the KWin script ", name, " of an engine that is gone");
+	unloadScript (connection, name);
+	std::remove ((dir + "/" + name + ".js").c_str ());
+    }
+}
+
 KWinScript::KWinScript (DBusConnection* connection, std::string pluginName, const std::string& source) :
     m_connection (connection), m_pluginName (std::move (pluginName)) {
     const std::string dir = runtimeDirectory ();
@@ -30,18 +213,24 @@ KWinScript::KWinScript (DBusConnection* connection, std::string pluginName, cons
 	return;
     }
 
+    // scripts of engines that were killed since the last start
+    unloadStale (this->m_connection);
+
     this->m_path = dir + "/" + this->m_pluginName + ".js";
-    std::ofstream out (this->m_path, std::ios::trunc);
+    this->m_lock = open (this->m_path.c_str (), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
 
-    if (!out.is_open ()) {
+    if (this->m_lock < 0 || flock (this->m_lock, LOCK_SH) != 0 || !writeAll (this->m_lock, source)) {
 	sLog.error ("KWin script: could not write ", this->m_path);
 	this->m_path.clear ();
+
+	if (this->m_lock >= 0) {
+	    close (this->m_lock);
+	    this->m_lock = -1;
+	}
+
 	return;
     }
 
-    out << source;
-    out.close ();
-
     DBusMessage* load
 	= dbus_message_new_method_call ("org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting", "loadScript");
     const char* pathArg = this->m_path.c_str ();
@@ -65,6 +254,7 @@ KWinScript::KWinScript (DBusConnection* connection, std::string pluginName, cons
 
     // the destructor unloads it even if run fails
     this->m_registered = true;
+    Janitor::instance ().watch (this->m_pluginName, this->m_path);
 
     // KWin 6 puts the script at /Scripting/Script<id>, KWin 5 at /<id>
     std::string error;
@@ -85,17 +275,19 @@ KWinScript::KWinScript (DBusConnection* connection, std::string pluginName, cons
 
 KWinScript::~KWinScript () {
     if (this->m_registered && this->m_connection != nullptr) {
-	DBusMessage* unload
-	    = dbus_message_new_method_call ("org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting", "unloadScript");
-	const char* nameArg = this->m_pluginName.c_str ();
-	dbus_message_append_args (unload, DBUS_TYPE_STRING, &nameArg, DBUS_TYPE_INVALID);
+	unloadScript (this->m_connection, this->m_pluginName);
+    }
 
-	if (DBusMessage* reply = callKWin (this->m_connection, unload, "unloadScript"); reply != nullptr) {
-	    dbus_message_unref (reply);
-	}
+    if (this->m_registered) {
+	Janitor::instance ().forget (this->m_pluginName);
     }
 
     if (!this->m_path.empty ()) {
 	std::remove (this->m_path.c_str ());
     }
+
+    // the lock goes with the descriptor, after the file is gone
+    if (this->m_lock >= 0) {
+	close (this->m_lock);
+    }
 }

+ 14 - 1
src/WallpaperEngine/Desktop/KWinScript.h

@@ -1,10 +1,14 @@
 #pragma once
 
+#include <chrono>
 #include <dbus/dbus.h>
+#include <filesystem>
 #include <string>
+#include <vector>
 
 namespace WallpaperEngine::Desktop {
-/** A KWin script loaded over D-Bus for the lifetime of this object */
+/** A KWin script loaded over D-Bus for the lifetime of this object. Its source file stays locked while this process
+ * lives, so whatever the process leaves behind when it is killed can be told from the scripts of live engines */
 class KWinScript {
 public:
     KWinScript (DBusConnection* connection, std::string pluginName, const std::string& source);
@@ -16,10 +20,19 @@ public:
     /** loaded and started */
     [[nodiscard]] bool isLoaded () const { return this->m_running; }
 
+    /** Plugin names of the scripts in directory whose engine is gone: the file is not locked by anyone, not new (a
+     * starting engine creates and locks it a moment later) and its pid, where the name has one, is not running */
+    [[nodiscard]] static std::vector<std::string>
+    findStale (const std::filesystem::path& directory, std::chrono::seconds minimumAge = std::chrono::seconds (2));
+    /** Unloads those from KWin and removes their files. A killed engine's script goes on calling its dead D-Bus
+     * service at every cursor move otherwise */
+    static void unloadStale (DBusConnection* connection);
+
 private:
     DBusConnection* m_connection;
     std::string m_pluginName;
     std::string m_path;
+    int m_lock = -1;
     bool m_registered = false;
     bool m_running = false;
 };

+ 3 - 1
src/WallpaperEngine/Desktop/PowerMonitor.cpp

@@ -15,6 +15,7 @@
 
 #include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Logging/ThreadGuard.h"
 
 #ifdef ENABLE_WAYLAND
 #include "WallpaperEngine/Desktop/HostWayland.h"
@@ -342,7 +343,8 @@ PowerMonitor::PowerMonitor () : m_wakeFd (eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK
     }
 #endif /* ENABLE_WAYLAND */
 
-    this->m_thread = std::thread ([this] { this->run (); });
+    this->m_thread
+	= std::thread ([this] { WallpaperEngine::Logging::guardThread ("Power monitor", [this] { this->run (); }); });
 }
 
 PowerMonitor::~PowerMonitor () {

+ 5 - 1
src/WallpaperEngine/Desktop/UserShortcut.cpp

@@ -11,6 +11,7 @@
 #include <sstream>
 #include <sys/stat.h>
 #include <sys/wait.h>
+#include <system_error>
 #include <unistd.h>
 #include <vector>
 
@@ -344,7 +345,10 @@ bool spawnDetached (std::vector<std::string> arguments, const std::string& worki
     close (errorPipe[0]);
 
     if (failed) {
-	sLog.error ("User shortcut: cannot start ", arguments.front (), ": ", strerror (failure));
+	sLog.error (
+	    "User shortcut: cannot start ", arguments.front (), ": ",
+	    std::error_code (failure, std::generic_category ()).message ()
+	);
 	return false;
     }
 

+ 13 - 4
src/WallpaperEngine/FileSystem/Adapters/Directory.cpp

@@ -18,6 +18,15 @@ static bool equalsIgnoreCase (const std::string& a, const std::string& b) {
 	   });
 }
 
+// a prefix of the base's text is not enough: /a/pack-secret is not inside /a/pack
+static bool isInside (const std::filesystem::path& base, const std::filesystem::path& file) {
+    const std::string& root = base.native ();
+    const std::string& target = file.native ();
+
+    return target.starts_with (root)
+	&& (target.size () == root.size () || root.empty () || root.back () == '/' || target[root.size ()] == '/');
+}
+
 // scenes are authored on Windows, so missing path components fall back to a case-insensitive search
 static std::filesystem::path resolveCase (const std::filesystem::path& base, const std::filesystem::path& relative) {
     std::error_code ec;
@@ -55,7 +64,7 @@ static std::filesystem::path resolveCase (const std::filesystem::path& base, con
 ReadStreamSharedPtr DirectoryAdapter::open (const std::filesystem::path& path) const {
     auto finalpath = std::filesystem::canonical (resolveCase (this->basepath, path));
 
-    if (finalpath.string ().find (this->basepath.string ()) != 0) {
+    if (!isInside (this->basepath, finalpath)) {
 	throw std::filesystem::filesystem_error ("Cannot find file", path, std::error_code ());
     }
 
@@ -76,7 +85,7 @@ bool DirectoryAdapter::exists (const std::filesystem::path& path) const {
     try {
 	const auto finalpath = std::filesystem::canonical (resolveCase (this->basepath, path));
 
-	if (finalpath.string ().find (this->basepath.string ()) != 0) {
+	if (!isInside (this->basepath, finalpath)) {
 	    return false;
 	}
 
@@ -99,7 +108,7 @@ bool DirectoryAdapter::exists (const std::filesystem::path& path) const {
 std::filesystem::path DirectoryAdapter::physicalPath (const std::filesystem::path& path) const {
     auto finalpath = std::filesystem::canonical (resolveCase (this->basepath, path));
 
-    if (finalpath.string ().find (this->basepath.string ()) != 0) {
+    if (!isInside (this->basepath, finalpath)) {
 	throw std::filesystem::filesystem_error ("Cannot find file", path, std::error_code ());
     }
 
@@ -149,7 +158,7 @@ std::vector<std::string> DirectoryAdapter::listFiles (const std::filesystem::pat
     std::error_code ec;
     const auto finalpath = std::filesystem::weakly_canonical (resolveCase (this->basepath, dir), ec);
 
-    if (ec || finalpath.string ().find (this->basepath.string ()) != 0) {
+    if (ec || !isInside (this->basepath, finalpath)) {
 	return names;
     }
 

+ 14 - 1
src/WallpaperEngine/FileSystem/Adapters/Package.cpp

@@ -41,9 +41,22 @@ ReadStreamSharedPtr PackageAdapter::open (const std::filesystem::path& path) con
 	throw std::filesystem::filesystem_error ("Cannot find file", path, std::error_code ());
     }
 
+    const uint64_t start = static_cast<uint64_t> (it->get ()->offset) + this->package->baseOffset;
+
+    // the stream is shared by every file of the package, nothing an earlier read left behind may carry over
+    this->package->file->base ().clear ();
+
+    // an entry that runs past the end (corrupt or truncated package) must not allocate its claimed size
+    if (start + it->get ()->length > this->package->file->size ()) {
+	throw std::filesystem::filesystem_error (
+	    "Package entry runs past the end of the package", path,
+	    std::make_error_code (std::errc::result_out_of_range)
+	);
+    }
+
     auto buffer = std::make_unique<char[]> (it->get ()->length);
 
-    this->package->file->base ().seekg (it->get ()->offset + this->package->baseOffset, std::ios::beg);
+    this->package->file->base ().seekg (static_cast<std::streamoff> (start), std::ios::beg);
     this->package->file->next (buffer.get (), it->get ()->length);
 
     return std::make_shared<MemoryStream> (std::move (buffer), it->get ()->length);

+ 12 - 5
src/WallpaperEngine/Logging/Log.cpp

@@ -8,15 +8,22 @@ using namespace WallpaperEngine::Logging;
 Log::Log () { assert (this->sInstance == nullptr); }
 
 Log& Log::get () {
-    if (sInstance == nullptr) {
+    static Log* const instance = [] {
 	sInstance = std::unique_ptr<Log> (new Log ());
-    }
+	return sInstance.get ();
+    }();
 
-    return *sInstance;
+    return *instance;
 }
 
-void Log::addOutput (std::ostream* stream) { this->mOutputs.push_back (stream); }
+void Log::addOutput (std::ostream* stream) {
+    const std::lock_guard lock (this->mMutex);
+    this->mOutputs.push_back (stream);
+}
 
-void Log::addError (std::ostream* stream) { this->mErrors.push_back (stream); }
+void Log::addError (std::ostream* stream) {
+    const std::lock_guard lock (this->mMutex);
+    this->mErrors.push_back (stream);
+}
 
 std::unique_ptr<Log> Log::sInstance = nullptr;

+ 13 - 2
src/WallpaperEngine/Logging/Log.h

@@ -2,6 +2,7 @@
 
 #include <iostream>
 #include <memory>
+#include <mutex>
 #include <ostream>
 #include <sstream>
 #include <vector>
@@ -14,6 +15,7 @@ public:
 
     template <typename... Data> void out (Data... data) {
 	std::string str = this->buildBuffer (data...);
+	const std::lock_guard lock (this->mMutex);
 
 	for (const auto cur : this->mOutputs) {
 	    *cur << str << '\n' << std::flush;
@@ -23,6 +25,7 @@ public:
     template <typename... Data> void debug (Data... data) {
 #if (!NDEBUG) && (!ERRORONLY)
 	std::string str = this->buildBuffer (data...);
+	const std::lock_guard lock (this->mMutex);
 
 	for (const auto cur : this->mOutputs) {
 	    *cur << str << '\n';
@@ -33,6 +36,7 @@ public:
     template <typename... Data> void debugerror (Data... data) {
 #if (!NDEBUG) && (ERRORONLY)
 	std::string str = this->buildBuffer (data...);
+	const std::lock_guard lock (this->mMutex);
 
 	for (const auto cur : this->mOutputs) {
 	    *cur << str << '\n';
@@ -42,6 +46,7 @@ public:
 
     template <typename... Data> void error (Data... data) {
 	std::string str = this->buildBuffer (data...);
+	const std::lock_guard lock (this->mMutex);
 
 	for (const auto cur : this->mErrors) {
 	    *cur << str << '\n' << std::flush;
@@ -50,8 +55,13 @@ public:
 
     template <class EX, typename... Data> [[noreturn]] void exception (Data... data) {
 	std::string str = this->buildBuffer (data...);
-	for (const auto cur : this->mErrors) {
-	    *cur << str << '\n';
+
+	{
+	    const std::lock_guard lock (this->mMutex);
+
+	    for (const auto cur : this->mErrors) {
+		*cur << str << '\n';
+	    }
 	}
 
 	throw EX (str);
@@ -75,6 +85,7 @@ private:
 	return buffer.str ();
     }
 
+    std::mutex mMutex;
     std::vector<std::ostream*> mOutputs = {};
     std::vector<std::ostream*> mErrors = {};
     static std::unique_ptr<Log> sInstance;

+ 18 - 0
src/WallpaperEngine/Logging/ThreadGuard.h

@@ -0,0 +1,18 @@
+#pragma once
+
+#include <exception>
+
+#include "WallpaperEngine/Logging/Log.h"
+
+namespace WallpaperEngine::Logging {
+// an exception that leaves a thread's function ends the whole process, this logs it and lets that thread end alone
+template <typename Body> void guardThread (const char* name, Body&& body) noexcept {
+    try {
+	body ();
+    } catch (const std::exception& e) {
+	sLog.error (name, " stopped: ", e.what ());
+    } catch (...) {
+	sLog.error (name, " stopped by an unknown error");
+    }
+}
+} // namespace WallpaperEngine::Logging

+ 5 - 1
src/WallpaperEngine/Media/CoverDownloader.cpp

@@ -2,6 +2,7 @@
 
 #include "CoverImage.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Logging/ThreadGuard.h"
 
 #include <algorithm>
 #include <chrono>
@@ -117,7 +118,10 @@ std::optional<std::filesystem::path> CoverDownloader::request (const std::string
     auto job = std::make_unique<Job> ();
     job->url = url;
     job->target = target;
-    job->thread = std::thread ([job = job.get ()] { run (*job); });
+    job->thread = std::thread ([job = job.get ()] {
+	WallpaperEngine::Logging::guardThread ("Cover download", [job] { run (*job); });
+	job->finished = true;
+    });
     this->m_jobs.push_back (std::move (job));
 
     return std::nullopt;

+ 39 - 4
src/WallpaperEngine/Render/CTexture.cpp

@@ -4,7 +4,9 @@
 #include <algorithm>
 #include <atomic>
 #include <cstring>
+#include <exception>
 #include <lz4.h>
+#include <mutex>
 #include <thread>
 #include <vector>
 
@@ -115,9 +117,22 @@ void CTexture::uploadImages (const UploadFormat& upload) const {
 	decode (decoded.front ());
     } else if (decoded.size () > 1) {
 	std::atomic<size_t> next = 0;
-	const auto worker = [&decoded, &next, &decode] () {
-	    for (size_t i = next++; i < decoded.size (); i = next++) {
-		decode (decoded[i]);
+	std::exception_ptr failure;
+	std::mutex failureMutex;
+	// an exception leaving a thread's function ends the process, the first one goes back to the caller instead
+	const auto worker = [&decoded, &next, &decode, &failure, &failureMutex] () {
+	    try {
+		for (size_t i = next++; i < decoded.size (); i = next++) {
+		    decode (decoded[i]);
+		}
+	    } catch (...) {
+		const std::scoped_lock lock (failureMutex);
+
+		if (!failure) {
+		    failure = std::current_exception ();
+		}
+
+		next = decoded.size ();
 	    }
 	};
 	const size_t threadCount
@@ -133,10 +148,23 @@ void CTexture::uploadImages (const UploadFormat& upload) const {
 	for (auto& thread : threads) {
 	    thread.join ();
 	}
+
+	if (failure) {
+	    for (const auto& job : decoded) {
+		if (job.pixels != nullptr) {
+		    stbi_image_free (job.pixels);
+		}
+	    }
+
+	    std::rethrow_exception (failure);
+	}
     }
 
     auto nextDecoded = decoded.begin ();
     GLint previousAlignment = 4;
+    GLint maxTextureSize = 0;
+
+    glGetIntegerv (GL_MAX_TEXTURE_SIZE, &maxTextureSize);
 
     // tightly packed rows like WE's D3D pitch (sub_1400EC220)
     glGetIntegerv (GL_UNPACK_ALIGNMENT, &previousAlignment);
@@ -165,7 +193,14 @@ void CTexture::uploadImages (const UploadFormat& upload) const {
 		++nextDecoded;
 	    }
 
-	    if (upload.compressed) {
+	    if (width <= 0 || height <= 0
+		|| (maxTextureSize > 0 && (width > maxTextureSize || height > maxTextureSize))) {
+		// GL refuses it, and the zero padding below would allocate width x height from the file's word
+		sLog.error (
+		    "Texture mipmap ", width, "x", height, " is past GL_MAX_TEXTURE_SIZE (", maxTextureSize,
+		    "), skipped"
+		);
+	    } else if (upload.compressed) {
 		glCompressedTexImage2D (
 		    GL_TEXTURE_2D, level, upload.internalFormat, width, height, 0, static_cast<GLsizei> (dataSize),
 		    dataptr

+ 4 - 1
src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.cpp

@@ -75,7 +75,10 @@ GLFWOpenGLDriver::GLFWOpenGLDriver (const char* windowTitle, ApplicationContext&
 #endif
 }
 
-GLFWOpenGLDriver::~GLFWOpenGLDriver () { glfwTerminate (); }
+GLFWOpenGLDriver::~GLFWOpenGLDriver () {
+    delete this->m_output;
+    glfwTerminate ();
+}
 
 Output::Output& GLFWOpenGLDriver::getOutput () { return *this->m_output; }
 

+ 1 - 0
src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.cpp

@@ -170,6 +170,7 @@ HeadlessOpenGLDriver::HeadlessOpenGLDriver (ApplicationContext& context, Wallpap
 }
 
 HeadlessOpenGLDriver::~HeadlessOpenGLDriver () {
+    delete this->m_output;
     eglMakeCurrent (this->m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
     eglDestroySurface (this->m_display, this->m_surface);
     eglDestroyContext (this->m_display, this->m_eglContext);

+ 6 - 0
src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.cpp

@@ -29,6 +29,12 @@ GLFWWindowOutput::GLFWWindowOutput (ApplicationContext& context, VideoDriver& dr
 	= new GLFWOutputViewport { { 0, 0, this->m_fullWidth, this->m_fullHeight }, "default" };
 }
 
+GLFWWindowOutput::~GLFWWindowOutput () {
+    for (const auto& [name, viewport] : this->m_viewports) {
+	delete viewport;
+    }
+}
+
 void GLFWWindowOutput::repositionWindow () const {
     this->m_driver.resizeWindow (this->m_context.settings.render.window.geometry);
 }

+ 1 - 0
src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.h

@@ -7,6 +7,7 @@ namespace WallpaperEngine::Render::Drivers::Output {
 class GLFWWindowOutput final : public Output {
 public:
     GLFWWindowOutput (ApplicationContext& context, VideoDriver& driver);
+    ~GLFWWindowOutput () override;
 
     void reset () override;
     bool renderVFlip () const override;

+ 21 - 3
src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp

@@ -53,6 +53,10 @@ void X11Output::reset () {
 }
 
 void X11Output::free () {
+    if (this->m_display == nullptr) {
+	return;
+    }
+
     // m_viewports holds non-owning aliases, m_screens owns the objects
     for (const auto& screen : this->m_screens) {
 	delete screen;
@@ -68,11 +72,25 @@ void X11Output::free () {
 	this->m_desktopWindowMapped = false;
     }
 
-    XDestroyImage (this->m_image);
+    if (this->m_image != nullptr) {
+	XDestroyImage (this->m_image);
+	this->m_image = nullptr;
+    }
+
     this->m_imageData = nullptr;
-    XFreeGC (this->m_display, this->m_gc);
-    XFreePixmap (this->m_display, this->m_pixmap);
+
+    if (this->m_gc != None) {
+	XFreeGC (this->m_display, this->m_gc);
+	this->m_gc = None;
+    }
+
+    if (this->m_pixmap != None) {
+	XFreePixmap (this->m_display, this->m_pixmap);
+	this->m_pixmap = None;
+    }
+
     XCloseDisplay (this->m_display);
+    this->m_display = nullptr;
 }
 
 void* X11Output::getImageBuffer () const { return this->m_imageData; }

+ 2 - 0
src/WallpaperEngine/Render/FBOProvider.cpp

@@ -78,6 +78,8 @@ std::shared_ptr<CFBO> FBOProvider::alias (const std::string& newName, const std:
     return this->m_fbos[newName] = this->m_fbos[original];
 }
 
+void FBOProvider::remove (const std::string& name) { this->m_fbos.erase (name); }
+
 std::shared_ptr<CFBO> FBOProvider::find (const std::string& name) const {
     if (const auto it = this->m_fbos.find (name); it != this->m_fbos.end ()) {
 	return it->second;

+ 2 - 0
src/WallpaperEngine/Render/FBOProvider.h

@@ -21,6 +21,8 @@ public:
     );
     std::shared_ptr<CFBO> alias (const std::string& newName, const std::string& original);
     [[nodiscard]] std::shared_ptr<CFBO> find (const std::string& name) const;
+    /** Drops this provider's name for a buffer, whoever else holds it keeps it alive */
+    void remove (const std::string& name);
 
 private:
     const FBOProvider* m_parent;

+ 6 - 2
src/WallpaperEngine/Render/GifAnimation.cpp

@@ -72,8 +72,12 @@ bool GifAnimation::readHeader () {
     m_transparent = -1;
 
     // WE only stops at a failed malloc, which overcommit never gives; the canvas becomes a texture, so the GPU limit
-    // bounds it. loadNext rereads the header while the canvas is empty
-    if (m_width == 0 || m_height == 0 || exceedsMaxImageSide (m_width, m_height)) {
+    // bounds each side, and the area is bounded too (RGBA and a history byte per pixel: 16384 x 16384 would be 1.3 GB,
+    // no real GIF is near that). loadNext rereads the header while the canvas is empty
+    constexpr size_t maxCanvasPixels = 64u * 1024 * 1024;
+
+    if (m_width == 0 || m_height == 0 || exceedsMaxImageSide (m_width, m_height)
+	|| static_cast<size_t> (m_width) * m_height > maxCanvasPixels) {
 	return false;
     }
 

+ 19 - 5
src/WallpaperEngine/Render/Objects/CMesh.cpp

@@ -190,6 +190,9 @@ private:
     std::vector<FrameSharedPtr> m_frames = {};
 };
 
+// real models pack a few hundred thousand texels, 16M is a 4096 x 4096 texture
+constexpr size_t MAX_MORPH_TEXELS = 16 * 1024 * 1024;
+
 // bounds = union of the mesh boxes (sub_1402617C0), before v17 boxes are zero; no width gives +-131072
 std::vector<MdlMesh> readMdlMeshes (
     const std::vector<char>& data, glm::vec3& boundsMin, glm::vec3& boundsMax, size_t& end, uint32_t& meshCount,
@@ -300,18 +303,29 @@ void loadMorphTargets (
 	    continue;
 	}
 
-	const uint32_t vertices = static_cast<uint32_t> (mesh->vertices.size () / mesh->stride);
-	const uint32_t perTarget = vertices * targets;
-	uint32_t units = (flags & 0x400) ? perTarget * 2 : perTarget;
+	// the counts come from the file and multiply: 32 bit products wrapped, the packing loops below then wrote far
+	// past the texture's memory
+	const size_t vertices = mesh->vertices.size () / mesh->stride;
+	const size_t perTarget = vertices * targets;
+	size_t units = (flags & 0x400) ? perTarget * 2 : perTarget;
 
 	if (flags & 0x800) {
 	    units += perTarget;
 	}
 
-	const uint32_t texels = (3 * units) / 4 + ((3 * units) % 4 != 0 ? 1 : 0);
+	const size_t texels = (3 * units + 3) / 4;
+
+	if (texels > MAX_MORPH_TEXELS) {
+	    sLog.error (
+		"Skipping the morph targets of mesh ", index, ": ", targets, " targets of ", vertices,
+		" vertices don't fit a texture"
+	    );
+	    continue;
+	}
+
 	auto side = static_cast<int> (std::sqrt (static_cast<float> (texels)));
 
-	if (static_cast<uint32_t> (side * side) < texels) {
+	if (static_cast<size_t> (side) * side < texels) {
 	    side++;
 	}
 

+ 26 - 5
src/WallpaperEngine/Render/Objects/CParticle.cpp

@@ -118,7 +118,20 @@ CParticle::CParticle (Wallpapers::CScene& scene, const Particle& particle) :
 
     // the pool is maxcount big whatever the count override says, that one only binds emitter rates
     // (wallpaper64.exe sub_1401D3780 copies maxcount unscaled, sub_1402378A0 emits while alive < maxcount)
-    m_maxParticles = particle.maxCount > 0 ? particle.maxCount : DEFAULT_MAX_PARTICLES;
+    const uint32_t requestedParticles = particle.maxCount > 0 ? particle.maxCount : DEFAULT_MAX_PARTICLES;
+    const size_t floatsPerParticle = m_useRopeRenderer && m_useTrailRenderer
+	? static_cast<size_t> (m_ropeSegments) * 4 * ROPE_FLOATS_PER_VERTEX
+	: (m_useRopeRenderer ? 4 * ROPE_FLOATS_PER_VERTEX : 4 * SPRITE_FLOATS_PER_VERTEX);
+
+    m_maxParticles
+	= static_cast<uint32_t> (std::min<size_t> ({ requestedParticles, MAX_PARTICLES,
+						     MAX_VERTEX_FLOATS / std::max<size_t> (floatsPerParticle, 1) }));
+
+    if (m_maxParticles < requestedParticles) {
+	sLog.error (
+	    "Particle system ", particle.name, " asks for ", requestedParticles, " particles, using ", m_maxParticles
+	);
+    }
 
     m_particles.resize (m_maxParticles);
     m_slotUsed.assign (m_maxParticles, 0);
@@ -141,8 +154,8 @@ CParticle::CParticle (Wallpapers::CScene& scene, const Particle& particle) :
 	const int verticesPerParticle = 4;
 	const int indicesPerParticle = 6;
 
-	m_vertices.resize (m_maxParticles * verticesPerParticle * SPRITE_FLOATS_PER_VERTEX);
-	m_indices.resize (m_maxParticles * indicesPerParticle);
+	m_vertices.resize (static_cast<size_t> (m_maxParticles) * verticesPerParticle * SPRITE_FLOATS_PER_VERTEX);
+	m_indices.resize (static_cast<size_t> (m_maxParticles) * indicesPerParticle);
     }
 }
 
@@ -326,10 +339,18 @@ void CParticle::prewarm (double now) {
 
     // wallpaper64.exe sub_14022EBE0: whole fixed steps, coarser ones for big systems, and no child events meanwhile
     const float step = m_particle.maxCount < 500 ? 0.05f : 0.2f;
+    // the longest one installed is 1000 s; a file asking for more (4294967296 never got past 2^25 in the float count)
+    // would freeze the wallpaper at load
+    constexpr float MaxStartTime = 3600.0f;
+    const float startTime = std::min (m_particle.startTime, MaxStartTime);
+
+    if (startTime < m_particle.startTime) {
+	sLog.error ("Particle starttime ", m_particle.startTime, " is too long, using ", MaxStartTime);
+    }
 
     m_prewarming = true;
-    m_time = now - m_particle.startTime;
-    for (float done = 0.0f; done < m_particle.startTime; done += step) {
+    m_time = now - startTime;
+    for (float done = 0.0f; done < startTime; done += step) {
 	m_time += step;
 	update (step);
     }

+ 4 - 0
src/WallpaperEngine/Render/Objects/CParticle.h

@@ -26,6 +26,10 @@ class CImage;
 class PuppetRig;
 
 constexpr uint32_t DEFAULT_MAX_PARTICLES = 1000;
+// no installed system has more than 100000, a count a file claims past this would only be an allocation
+constexpr uint32_t MAX_PARTICLES = 1000000;
+// the vertex data a system may hold (400 MB), a rope trail keeps several quads per particle
+constexpr size_t MAX_VERTEX_FLOATS = 100000000;
 
 struct ParticleInstance {
     glm::vec3 position { 0.0f };

+ 17 - 10
src/WallpaperEngine/Render/Objects/CSound.cpp

@@ -81,18 +81,25 @@ CSound::CSound (Wallpapers::CScene& scene, const Sound& sound) :
 	= this->m_sound.volume && this->m_sound.volume->value ? this->m_sound.volume->value->getFloat () : 1.0f;
     this->m_lastMaster = this->masterVolume ();
 
-    // sub_1401F4F20, when the object is added to the scene
-    if (!this->m_startSilent) {
-	this->play ();
-    }
-
-    // a script asked for this sound before it existed
-    if (const auto request = scene.getSoundPlayRequest (sound.id); request.has_value ()) {
-	if (request.value ()) {
+    try {
+	// sub_1401F4F20, when the object is added to the scene
+	if (!this->m_startSilent) {
 	    this->play ();
-	} else {
-	    this->stop ();
 	}
+
+	// a script asked for this sound before it existed
+	if (const auto request = scene.getSoundPlayRequest (sound.id); request.has_value ()) {
+	    if (request.value ()) {
+		this->play ();
+	    } else {
+		this->stop ();
+	    }
+	}
+    } catch (...) {
+	// the destructor does not run for a constructor that throws, and the driver would go on mixing the streams of
+	// the voices that already started once the vector frees them
+	this->stopAllVoices ();
+	throw;
     }
 }
 

+ 2 - 1
src/WallpaperEngine/Render/Objects/Effects/CPass.cpp

@@ -243,7 +243,8 @@ std::optional<std::string> CPass::resolveUserTextureName (const std::string& pro
 	const auto shortcut = Desktop::UserShortcut::parse (it->second->getString ());
 	const auto icon = shortcut.has_value () ? shortcut->iconPath () : std::nullopt;
 
-	return icon.has_value () ? std::optional<std::string> ("$usershortcut:" + icon->string ()) : std::nullopt;
+	return icon.has_value () ? std::optional<std::string> (this->getContext ().iconTextureName (*icon))
+				 : std::nullopt;
     }
 
     const std::string& value = it->second->getString ();

+ 22 - 2
src/WallpaperEngine/Render/Objects/PuppetMeshFile.cpp

@@ -17,6 +17,12 @@ using namespace WallpaperEngine::Data::Utils;
 namespace {
 constexpr size_t MARKER_SIZE = 9;
 constexpr size_t MESH_HEADER_SIZE = sizeof (uint32_t) * 2;
+// the heuristic layout search only runs for a file whose header could not be read, and the first mesh's header sits in
+// the first few hundred bytes. Without these limits a damaged file of a few dozen MB took minutes: every offset is
+// tried as a mesh and every candidate with every stride
+constexpr size_t MAX_HEADER_SCAN = 64 * 1024;
+constexpr size_t MAX_LAYOUT_CANDIDATES = 64;
+constexpr size_t MAX_LAYOUT_WORK = 16 * 1024 * 1024;
 
 // offsets that could be an MDLV mesh header, stride resolved later
 std::vector<PuppetMeshBlock> findPuppetMeshBlockCandidates (
@@ -24,7 +30,9 @@ std::vector<PuppetMeshBlock> findPuppetMeshBlockCandidates (
 ) {
     std::vector<PuppetMeshBlock> candidates;
 
-    for (size_t offset = markerSize; offset + meshHeaderSize + sizeof (uint32_t) < mdlsOffset; offset++) {
+    for (size_t offset = markerSize; offset + meshHeaderSize + sizeof (uint32_t) < mdlsOffset
+	 && offset < MAX_HEADER_SCAN && candidates.size () < MAX_LAYOUT_CANDIDATES;
+	 offset++) {
 	reader.base ().seekg (static_cast<std::streamoff> (offset + sizeof (uint32_t)), std::ios::beg);
 	const uint32_t candidateVertexBytes = reader.nextUInt32 ();
 	const size_t verticesOffset = offset + meshHeaderSize;
@@ -207,9 +215,20 @@ resolvePuppetVertexLayout (const BinaryReader& reader, size_t markerSize, size_t
 
     std::optional<PuppetVertexLayout> best;
     double bestScore = std::numeric_limits<double>::max ();
+    size_t work = 0;
 
     for (const auto& block : candidates) {
 	for (size_t stride = minVertexStride; stride <= maxVertexStride; stride += strideStep) {
+	    if (block.vertexBytes % stride != 0) {
+		continue;
+	    }
+
+	    work += block.vertexBytes / stride + block.indexBytes / sizeof (uint16_t);
+
+	    if (work > MAX_LAYOUT_WORK) {
+		return best;
+	    }
+
 	    const auto data = readPuppetMeshData (reader, block, meshHeaderSize, stride);
 	    if (!data.has_value ()) {
 		continue;
@@ -288,7 +307,8 @@ std::optional<PuppetVertexLayout> readPuppetVertexLayout (const std::vector<char
     const auto texcoord = CMesh::vertexComponentOffset (header.format, 0x8);
 
     if (stride == 0 || header.vertexBytes % stride != 0 || !texcoord.has_value ()
-	|| *texcoord != stride - sizeof (GLfloat) * 2 || header.vertices + header.vertexBytes > data.size ()) {
+	|| *texcoord != stride - sizeof (GLfloat) * 2
+	|| header.vertices + header.vertexBytes + sizeof (uint32_t) + header.indexBytes > data.size ()) {
 	return std::nullopt;
     }
 

+ 17 - 2
src/WallpaperEngine/Render/Objects/PuppetRig.cpp

@@ -345,7 +345,16 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
     for (uint16_t i = 0; i < chains && reader.base ().good (); i++) {
 	PuppetIKChain chain;
 	chain.root = reader.nextUInt32 ();
-	chain.extras.resize (reader.nextUInt32 ());
+
+	const uint32_t extraCount = reader.nextUInt32 ();
+
+	// more than the section holds is a bad read, which ends the chain list like any other
+	if (!reader.fits (extraCount, sizeof (uint32_t))) {
+	    reader.base ().setstate (std::ios::failbit);
+	    break;
+	}
+
+	chain.extras.resize (extraCount);
 	for (uint32_t& extra : chain.extras) {
 	    extra = reader.nextUInt32 ();
 	}
@@ -692,7 +701,13 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 	if (version >= 3 && valid) {
 	    // g_BlendMap tracks (clip +216)
 	    const uint32_t blendTracks = reader.nextUInt32 ();
-	    clip.blendTracks.resize (blendTracks);
+
+	    // a track is two numbers and its samples
+	    if (!reader.fits (blendTracks, 2 * sizeof (uint32_t))) {
+		valid = false;
+	    } else {
+		clip.blendTracks.resize (blendTracks);
+	    }
 
 	    for (uint32_t track = 0; track < blendTracks && valid; track++) {
 		(void)reader.nextUInt32 ();

+ 4 - 0
src/WallpaperEngine/Render/RenderContext.cpp

@@ -371,6 +371,10 @@ RenderContext::resolveTexture (const std::string& name, const Data::Model::Proje
     return this->m_textureCache->resolve (name, project);
 }
 
+std::string RenderContext::iconTextureName (const std::filesystem::path& icon) const {
+    return this->m_textureCache->iconTextureName (icon);
+}
+
 std::shared_ptr<const TextureProvider>
 RenderContext::findLoadedTexture (const std::string& name, const Data::Model::Project& project) const {
     return this->m_textureCache->findLoaded (name, project);

+ 2 - 0
src/WallpaperEngine/Render/RenderContext.h

@@ -50,6 +50,8 @@ namespace Render {
 	[[nodiscard]] const Drivers::Output::Output& getOutput () const;
 	[[nodiscard]] std::shared_ptr<const TextureProvider>
 	resolveTexture (const std::string& name, const Data::Model::Project& project) const;
+	/** see TextureCache::iconTextureName */
+	[[nodiscard]] std::string iconTextureName (const std::filesystem::path& icon) const;
 	/** see TextureCache::findLoaded */
 	[[nodiscard]] std::shared_ptr<const TextureProvider>
 	findLoadedTexture (const std::string& name, const Data::Model::Project& project) const;

+ 1 - 1
src/WallpaperEngine/Render/Shaders/GLSLContext.cpp

@@ -257,7 +257,7 @@ GLSLContext::Sources GLSLContext::toGlsl (
     }
 
     // glslang/SPIRV-Cross and the options below only change with a rebuild
-    const std::string diskKey = std::string ("glsl " __DATE__ " " __TIME__ "\0") + cacheKey;
+    const std::string diskKey = std::string ("glsl " __DATE__ " " __TIME__) + '\0' + cacheKey;
 
     if (auto stored = ShaderCache::get ().loadTranslation (diskKey); stored.has_value ()) {
 	std::lock_guard lock (cacheMutex);

+ 0 - 1
src/WallpaperEngine/Render/Shaders/Shader.h

@@ -44,7 +44,6 @@ private:
     /** GS_ENABLED shaders with a .geom, like WE's particle shaders (its renderer always sets that define) */
     std::unique_ptr<ShaderUnit> m_geometry;
     std::string m_file;
-    std::vector<Variables::ShaderVariable*> m_parameters = {};
     const ComboMap& m_combos;
     const TextureMap m_passTextures;
 };

+ 31 - 14
src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp

@@ -1673,27 +1673,42 @@ void ShaderUnit::parseParameterConfiguration (
 	}
     }
 
-    Variables::ShaderVariable* parameter = nullptr;
+    std::unique_ptr<Variables::ShaderVariable> parameter;
 
+    // a uniform may name a material constant and leave "default" out (shadowcasterfoliage4.vert), the constant gives
+    // the value then and the default is only a placeholder: zero
     if (type == "vec4") {
-	parameter
-	    = new Variables::ShaderVariableVector4 (VectorBuilder::parse<glm::vec4> (defvalue->get<std::string> ()));
+	parameter = std::make_unique<Variables::ShaderVariableVector4> (
+	    defvalue.has_value () ? VectorBuilder::parse<glm::vec4> (defvalue->get<std::string> ()) : glm::vec4 (0.0f)
+	);
     } else if (type == "vec3") {
-	parameter = new Variables::ShaderVariableVector3 (VectorBuilder::parse<glm::vec3> (*defvalue));
+	parameter = std::make_unique<Variables::ShaderVariableVector3> (
+	    defvalue.has_value () ? VectorBuilder::parse<glm::vec3> (*defvalue) : glm::vec3 (0.0f)
+	);
     } else if (type == "vec2") {
-	parameter = new Variables::ShaderVariableVector2 (VectorBuilder::parse<glm::vec2> (*defvalue));
+	parameter = std::make_unique<Variables::ShaderVariableVector2> (
+	    defvalue.has_value () ? VectorBuilder::parse<glm::vec2> (*defvalue) : glm::vec2 (0.0f)
+	);
     } else if (type == "float") {
-	if (defvalue->is_string ()) {
-	    parameter = new Variables::ShaderVariableFloat (std::stoi (defvalue->get<std::string> ()));
-	} else {
-	    parameter = new Variables::ShaderVariableFloat (defvalue->get<float> ());
+	float number = 0.0f;
+
+	if (defvalue.has_value ()) {
+	    // a default written as text is a number as well ("0.1" went through stoi and became 0)
+	    number = defvalue->is_string () ? std::strtof (defvalue->get<std::string> ().c_str (), nullptr)
+					    : defvalue->get<float> ();
 	}
+
+	parameter = std::make_unique<Variables::ShaderVariableFloat> (number);
     } else if (type == "int") {
-	if (defvalue->is_string ()) {
-	    parameter = new Variables::ShaderVariableInteger (std::stoi (defvalue->get<std::string> ()));
-	} else {
-	    parameter = new Variables::ShaderVariableInteger (defvalue->get<int> ());
+	int number = 0;
+
+	if (defvalue.has_value ()) {
+	    number = defvalue->is_string ()
+		? static_cast<int> (std::strtol (defvalue->get<std::string> ().c_str (), nullptr, 10))
+		: defvalue->get<int> ();
 	}
+
+	parameter = std::make_unique<Variables::ShaderVariableInteger> (number);
     } else if (type == "sampler2D" || type == "sampler2DComparison") {
 	const auto textureName = data.find ("default");
 	const auto requireany = data.find ("requireany");
@@ -1804,12 +1819,14 @@ void ShaderUnit::parseParameterConfiguration (
 	return;
     }
 
+    // a parameter that names no material has nothing to be found by and goes with this call
     if (material.has_value () && parameter != nullptr) {
 	parameter->setIdentifierName (*material);
 	parameter->setName (name);
 	parameter->setInDegrees (data.optional ("conversion", std::string ()) == "rad2deg");
 
-	this->m_parameters.push_back (parameter);
+	this->m_parameters.push_back (parameter.get ());
+	this->m_ownedParameters.push_back (std::move (parameter));
     }
 }
 

+ 2 - 0
src/WallpaperEngine/Render/Shaders/ShaderUnit.h

@@ -104,6 +104,8 @@ private:
     std::string m_preprocessed;
     bool m_feedsGeometry { false };
     std::string m_final;
+    /** The unit owns its parameters, passes and uniforms point at them for as long as the shader lives */
+    std::vector<std::unique_ptr<Variables::ShaderVariable>> m_ownedParameters = {};
     std::vector<Variables::ShaderVariable*> m_parameters = {};
     const ComboMap& m_combos;
     const ComboMap& m_overrideCombos;

+ 6 - 1
src/WallpaperEngine/Render/TextureCache.cpp

@@ -576,12 +576,17 @@ TextureCache::findLoaded (const std::string& filename, const Project& project) c
     return found != this->m_textureCache.end () ? found->second : nullptr;
 }
 
+std::string TextureCache::iconTextureName (const std::filesystem::path& icon) {
+    return *this->m_iconNames.insert ("$usershortcut:" + icon.string ()).first;
+}
+
 std::shared_ptr<const TextureProvider> TextureCache::resolve (const std::string& filename, const Project& requester) {
     if (const auto shared = this->m_sharedTextures.find (filename); shared != this->m_sharedTextures.end ()) {
 	return shared->second;
     }
 
-    if (constexpr std::string_view prefix = "$usershortcut:"; filename.starts_with (prefix)) {
+    if (constexpr std::string_view prefix = "$usershortcut:";
+	filename.starts_with (prefix) && this->m_iconNames.contains (filename)) {
 	auto texture = std::make_shared<CTexture> (
 	    this->getContext (), buildIconTexture (std::filesystem::path (filename.substr (prefix.size ())))
 	);

+ 7 - 0
src/WallpaperEngine/Render/TextureCache.h

@@ -1,8 +1,10 @@
 #pragma once
 
+#include <filesystem>
 #include <functional>
 #include <map>
 #include <memory>
+#include <set>
 #include <string>
 #include <utility>
 
@@ -34,6 +36,10 @@ public:
     [[nodiscard]] std::shared_ptr<const TextureProvider>
     findLoaded (const std::string& filename, const Data::Model::Project& project) const;
 
+    /** The texture name of an icon the engine picked for a user shortcut; a name like it that comes from a wallpaper's
+     * own files is not an icon and resolves like any other missing texture */
+    [[nodiscard]] std::string iconTextureName (const std::filesystem::path& icon);
+
     /** Registers a texture that is shared by every project (media thumbnails and such) */
     void store (const std::string& name, std::shared_ptr<const TextureProvider> texture);
 
@@ -66,6 +72,7 @@ private:
     std::vector<std::unique_ptr<ConditionalTexture>> m_conditionalTextures = {};
     std::shared_ptr<const AlbumTexture> m_previousThumbnail = nullptr;
     std::shared_ptr<const AlbumTexture> m_currentThumbnail = nullptr;
+    std::set<std::string> m_iconNames = {};
     std::map<std::string, std::shared_ptr<const TextureProvider>> m_sharedTextures = {};
     std::map<std::pair<const Data::Model::Project*, std::string>, std::shared_ptr<const TextureProvider>> m_textureCache
 	= {};

+ 209 - 27
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -13,6 +13,7 @@
 
 #include "CScene.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
 #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
 
@@ -31,6 +32,7 @@
 #include <limits>
 #include <ranges>
 #include <regex>
+#include <unordered_map>
 
 extern float g_Time;
 extern float g_TimeLast;
@@ -209,6 +211,48 @@ CScene::CScene (
     this->m_settingsScriptsData = ObjectParser::parse ({ { "id", -1 }, { "name", "" } }, scene->project);
     this->m_settingsScripts = std::make_unique<SceneSettingsScripts> (*this, *this->m_settingsScriptsData, *scene);
 
+    // a constructor that throws never runs the destructor: the objects made so far (a sound's reader thread among
+    // them) would leak and keep running
+    struct ObjectsGuard {
+	CScene& scene;
+	bool armed = true;
+
+	~ObjectsGuard () {
+	    if (armed) {
+		scene.destroyObjects ();
+	    }
+	}
+    } objectsGuard { *this };
+
+    // a chain of parents that comes back to its start never reaches a root, and every walk along it (a layer's buffer
+    // name, its world matrix) would go on forever: break it before any object is made
+    std::unordered_map<int, const Object*> objectsById;
+
+    for (const auto& object : scene->objects) {
+	objectsById.emplace (object->id, object.get ());
+    }
+
+    for (const auto& object : scene->objects) {
+	int steps = 0;
+
+	for (auto current = object->parent; current.has_value () && steps < 4096; steps++) {
+	    if (*current == object->id) {
+		sLog.error ("Parent loop through object ", object->id, " (", object->name, "), dropping its parent");
+		object->parent.reset ();
+		object->attachment.reset ();
+		break;
+	    }
+
+	    const auto next = objectsById.find (*current);
+
+	    if (next == objectsById.end ()) {
+		break;
+	    }
+
+	    current = next->second->parent;
+	}
+    }
+
     // createObject recurses into each object's dependencies/parent first
     for (const auto& object : scene->objects) {
 	this->createObject (*object);
@@ -250,6 +294,7 @@ CScene::CScene (
 
     this->m_loading = false;
     this->m_modelFiles.clear ();
+    objectsGuard.armed = false;
 }
 
 CScene::~CScene () {
@@ -257,6 +302,12 @@ CScene::~CScene () {
 	glDeleteTextures (1, &this->m_nullTexture);
     }
 
+    this->destroyObjects ();
+
+    this->releaseMultisample ();
+}
+
+void CScene::destroyObjects () {
     for (const auto& val : this->m_objects | std::views::values) {
 	delete val;
     }
@@ -265,10 +316,15 @@ CScene::~CScene () {
 	delete object;
     }
 
+    this->m_destroyedObjects.clear ();
+
+    for (const auto& layer : this->m_releasableLayers) {
+	delete layer.object;
+    }
+
+    this->m_releasableLayers.clear ();
     this->m_objectsByRenderOrder.clear ();
     this->m_objects.clear ();
-
-    this->releaseMultisample ();
 }
 
 Render::CObject* CScene::createObject (const Object& object) {
@@ -285,8 +341,10 @@ Render::CObject* CScene::createObject (const Object& object) {
 	return nullptr;
     }
 
+    bool dependenciesReady = false;
+
     try {
-	this->createObjectDependencies (object);
+	dependenciesReady = this->createObjectDependencies (object);
     } catch (...) {
 	this->m_objectsInCreation.erase (object.id);
 	throw;
@@ -294,6 +352,10 @@ Render::CObject* CScene::createObject (const Object& object) {
 
     this->m_objectsInCreation.erase (object.id);
 
+    if (!dependenciesReady) {
+	return nullptr;
+    }
+
     renderObject = this->dispatchObjectType (object);
 
     if (renderObject != nullptr) {
@@ -303,7 +365,7 @@ Render::CObject* CScene::createObject (const Object& object) {
     return renderObject;
 }
 
-void CScene::createObjectDependencies (const Object& object) {
+bool CScene::createObjectDependencies (const Object& object) {
     for (const auto& cur : object.dependencies) {
 	// self-dependency is a possibility...
 	if (cur == object.id) {
@@ -326,15 +388,55 @@ void CScene::createObjectDependencies (const Object& object) {
 	});
 
 	if (dep == this->getScene ().objects.end ()) {
-	    sLog.exception ("Cannot find parent ", parentId, " for object ", object.id);
+	    // one object without its parent has nowhere to go, the rest of the scene still loads
+	    sLog.error (
+		"Cannot find parent ", parentId, " for object ", object.id, " (", object.name, "), skipping it"
+	    );
+	    return false;
 	}
 
 	this->createObject (**dep);
     }
+
+    return true;
 }
 
 Render::CObject* CScene::dispatchObjectType (const Object& object) {
     Render::CObject* renderObject = nullptr;
+    const auto scriptMark = this->getScriptEngine ().moduleMark ();
+
+    try {
+	renderObject = this->constructObject (object);
+    } catch (const std::exception& e) {
+	// the half built object is gone, the scripts its constructor queued still point at it
+	sLog.error ("Failed to create object ", object.id, " (", object.name, "): ", e.what ());
+	this->getScriptEngine ().dropModulesSince (scriptMark);
+
+	return nullptr;
+    }
+
+    if (renderObject == nullptr) {
+	return nullptr;
+    }
+
+    try {
+	renderObject->setup ();
+    } catch (const std::exception& e) {
+	sLog.error ("Failed to setup object ", object.id, ": ", e.what ());
+	if (auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (renderObject); scriptable != nullptr) {
+	    this->getScriptEngine ().dropObjectScripts (*scriptable);
+	}
+	std::erase (this->m_sceneCameras, renderObject);
+	delete renderObject;
+	renderObject = nullptr;
+    }
+
+    return renderObject;
+}
+
+Render::CObject* CScene::constructObject (const Object& object) {
+    Render::CObject* renderObject = nullptr;
+
     if (object.is<Image> ()) {
 	renderObject = new Objects::CImage (*this, *object.as<Image> ());
     } else if (object.is<Sound> ()) {
@@ -369,17 +471,6 @@ Render::CObject* CScene::dispatchObjectType (const Object& object) {
 	renderObject = new Scripting::ScriptableObject (*this, object);
     }
 
-    try {
-	renderObject->setup ();
-    } catch (const std::exception& e) {
-	sLog.error ("Failed to setup object ", object.id, ": ", e.what ());
-	if (auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (renderObject); scriptable != nullptr) {
-	    this->getScriptEngine ().dropObjectScripts (*scriptable);
-	}
-	delete renderObject;
-	renderObject = nullptr;
-    }
-
     return renderObject;
 }
 
@@ -1436,9 +1527,72 @@ bool CScene::isPendingDestroy (const CObject& object) const {
     return this->m_pendingDestroy.contains (const_cast<CObject*> (&object));
 }
 
+// a layer's own buffers and render object are what a script that keeps creating and destroying layers piles up (two
+// layer sized framebuffers each, which the scene's name map and the output follower list never let go)
+bool CScene::isReleasable (const CObject& object) const {
+    // only what scripts made while running: nothing in the scene file can name them. Cameras, lights and models are
+    // listed elsewhere too (m_sceneCameras, the light slots, the shadow casters)
+    return object.getId () >= DYNAMIC_LAYER_ID_BASE && !object.is<Objects::CMesh> () && !object.is<Objects::CLight> ()
+	&& !object.is<Objects::CCamera> ();
+}
+
+void CScene::releaseDestroyedLayers () {
+    // destroyed in an earlier frame: the lists, the script handles (forgotten) and the render order let go of it then
+    constexpr uint32_t gracePeriod = 2;
+    const auto due = std::ranges::stable_partition (this->m_releasableLayers, [this] (const DestroyedLayer& layer) {
+	return this->m_frameCounter - layer.frame < gracePeriod;
+    });
+
+    for (const auto& layer : due) {
+	const int id = layer.object->getId ();
+
+	this->m_transparentSorted.erase (layer.object);
+
+	// the text a layer was made from is most of what the model costs, and the model has to stay: animation clocks
+	// and script handles may still point into it
+	if (auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (layer.object); scriptable != nullptr) {
+	    scriptable->dropScriptSources ();
+	}
+
+	delete layer.object;
+	this->remove ("_rt_imageLayerComposite_" + std::to_string (id) + "_a");
+	this->remove ("_rt_imageLayerComposite_" + std::to_string (id) + "_b");
+	this->releaseLayerModel (id);
+    }
+
+    if (due.empty ()) {
+	return;
+    }
+
+    this->m_releasableLayers.erase (due.begin (), due.end ());
+    // the entries of the buffers that just went
+    std::erase_if (this->m_outputSizedBuffers, [] (const OutputSizedBuffer& buffer) { return buffer.fbo.expired (); });
+}
+
+void CScene::releaseLayerModel (int id) {
+    const auto data = this->m_dynamicObjectData.find (id);
+
+    if (data == this->m_dynamicObjectData.end ()) {
+	return;
+    }
+
+    // the timelines of its values go first, they write into them every frame
+    this->getScriptEngine ().getAnimations ().removeObject (id);
+
+    // an IEffect or IMaterial a script holds points into the model for good, those layers keep it
+    if (this->getScriptEngine ().getAdapters ().object->hasEffectHandles (*data->second)) {
+	std::string ().swap (data->second->initialConfig);
+	return;
+    }
+
+    this->m_dynamicObjectData.erase (data);
+}
+
 void CScene::destroyPendingLayers () {
-    // sub_1401909C0: children keep their transforms but lose the parent, scripts get destroy (). Stays allocated until
-    // the scene goes, others may hold its buffers
+    this->releaseDestroyedLayers ();
+
+    // sub_1401909C0: children keep their transforms but lose the parent, scripts get destroy (). A scene's own layer
+    // stays allocated until the scene goes, others may hold its buffers
     const auto pending = std::exchange (this->m_pendingDestroy, {});
 
     for (auto* object : pending) {
@@ -1457,7 +1611,14 @@ void CScene::destroyPendingLayers () {
 
 	std::erase (this->m_objectsByRenderOrder, object);
 	this->m_objects.erase (object->getId ());
-	this->m_destroyedObjects.push_back (object);
+	this->m_cursorInside.erase (object->getId ());
+	this->m_cursorPressed.erase (object->getId ());
+
+	if (this->isReleasable (*object)) {
+	    this->m_releasableLayers.push_back ({ object, this->m_frameCounter });
+	} else {
+	    this->m_destroyedObjects.push_back (object);
+	}
     }
 }
 
@@ -1471,12 +1632,17 @@ bool CScene::scriptsMayReparent () const {
     return *this->m_scriptsMayReparent;
 }
 
-int CScene::passthroughDepth (const CObject& object) const {
+int CScene::passthroughDepth (const CObject& object, const int level) const {
     const int own = isPassthroughImage (object) ? 1 : 0;
     int depth = own;
 
+    // a parent loop (A under B under A) would never end
+    if (level >= 64) {
+	return depth;
+    }
+
     for (const auto* child : this->childrenOf (object.getId ())) {
-	depth = std::max (depth, this->passthroughDepth (*child) + own);
+	depth = std::max (depth, this->passthroughDepth (*child, level + 1) + own);
     }
 
     return depth;
@@ -1505,8 +1671,13 @@ bool CScene::setObjectParent (CObject& object, const CObject* parent, int attach
 
     // itself, or more than 3 passthrough layers deep: WE drops the parent and reports the error
     int parentDepth = 0;
+    int steps = 0;
+    bool loops = false;
 
-    for (const CObject* ancestor = parent; ancestor != nullptr && parentDepth < 64;) {
+    // the chain of parents ends at a root, unless it comes back to the object (or loops among others, which only the
+    // step count stops: a loop of plain groups never raises parentDepth)
+    for (const CObject* ancestor = parent; ancestor != nullptr && parentDepth < 64 && steps < 1024; steps++) {
+	loops = loops || ancestor == &object;
 	parentDepth += isPassthroughImage (*ancestor) ? 1 : 0;
 	const auto& next = ancestor->getObject ().parent;
 	ancestor = next.has_value () ? this->getObject (*next) : nullptr;
@@ -1514,7 +1685,13 @@ bool CScene::setObjectParent (CObject& object, const CObject* parent, int attach
 
     this->detachChild (object);
 
-    if (parent == &object || parentDepth + this->passthroughDepth (object) > 3) {
+    if (loops || steps >= 1024) {
+	sLog.error (
+	    "Cannot make object ", object.getId (), " a child of ", parent->getId (), ", the parents would loop"
+	);
+    }
+
+    if (parent == &object || loops || steps >= 1024 || parentDepth + this->passthroughDepth (object) > 3) {
 	data.parent.reset ();
 	data.attachment.reset ();
 	return false;
@@ -1601,7 +1778,8 @@ void CScene::updateCameraPath (const float dt, glm::vec3& eye, glm::vec3& center
 	until = (this->m_pathKey + 1 < count ? path.keys[this->m_pathKey + 1].time : 0.0f) + key.time;
     } else if (this->m_pathKey + 1 < count) {
 	const auto& next = path.keys[this->m_pathKey + 1];
-	const float s = (time - key.time) / (next.time - key.time);
+	// two keys at one time (an editor can write them) are a jump to the second, not a division by zero
+	const float s = next.time > key.time ? (time - key.time) / (next.time - key.time) : 1.0f;
 	const float s2 = s * s;
 	const float s3 = s2 * s;
 	const float h00 = 2.0f * s3 - 3.0f * s2 + 1.0f;
@@ -1742,7 +1920,11 @@ void CScene::updateCamera () {
 
 	if (roughness > 0.001f && roughness != 1.0f) {
 	    const float length = glm::length (offset);
-	    offset *= std::pow (length, roughness) / length;
+
+	    // an offset of nothing stays nothing
+	    if (length > 0.0f) {
+		offset *= std::pow (length, roughness) / length;
+	    }
 	}
 
 	eye += offset * amplitude;
@@ -3146,7 +3328,7 @@ Render::CObject* CScene::buildLayer (JSON layerJson) {
 	return nullptr;
     }
 
-    this->m_dynamicObjectData.emplace_back (std::move (objectData));
+    this->m_dynamicObjectData.emplace (id, std::move (objectData));
     this->appendLayer (renderObject);
 
     return renderObject;
@@ -3163,7 +3345,7 @@ Render::CObject* CScene::createPlaceholderLayer () {
 	auto* renderObject = new Scripting::ScriptableObject (*this, *objectData);
 
 	this->m_objects.emplace (renderObject->getId (), renderObject);
-	this->m_dynamicObjectData.emplace_back (std::move (objectData));
+	this->m_dynamicObjectData.emplace (id, std::move (objectData));
 	this->appendLayer (renderObject);
 
 	return renderObject;

+ 19 - 4
src/WallpaperEngine/Render/Wallpapers/CScene.h

@@ -354,15 +354,19 @@ private:
     /** includes the attachment point */
     [[nodiscard]] glm::mat4 parentChainMatrix (const Data::Model::Object& object, bool scaled) const;
     /** sub_1401DDB50 */
-    [[nodiscard]] int passthroughDepth (const CObject& object) const;
+    [[nodiscard]] int passthroughDepth (const CObject& object, int level = 0) const;
     /** Back to front along the camera's view direction, WE's transparent sort (sub_1401865C0) */
     [[nodiscard]] std::vector<CObject*> sortedByDepth (std::vector<CObject*> objects) const;
     /** transparentsorting list membership, decided when the object is created (object flag 0x100, sub_14018FF60) */
     [[nodiscard]] bool isTransparentSorted (const CObject& object);
 
     Render::CObject* createObject (const Object& object);
-    void createObjectDependencies (const Object& object);
+    /** false when the object can't be created (its parent doesn't exist) */
+    bool createObjectDependencies (const Object& object);
+    /** Deletes every render object, the constructor does it too when it fails (the destructor doesn't run then) */
+    void destroyObjects ();
     Render::CObject* dispatchObjectType (const Object& object);
+    Render::CObject* constructObject (const Object& object);
     void addObjectToRenderOrder (const Object& object);
 
     std::unique_ptr<Scripting::ScriptEngine> m_scriptEngine;
@@ -417,8 +421,10 @@ private:
     std::vector<std::shared_ptr<CFBO>> m_hdrBloomLevels;
     std::vector<DynamicValue*> m_scriptedValues = {};
     // backs createLayer() objects, must outlive them
-    std::vector<ObjectUniquePtr> m_dynamicObjectData = {};
-    int m_nextDynamicLayerId = 2000000000;
+    std::map<int, ObjectUniquePtr> m_dynamicObjectData = {};
+    // ids of layers scripts create start here, past anything a scene file numbers
+    static constexpr int DYNAMIC_LAYER_ID_BASE = 2000000000;
+    int m_nextDynamicLayerId = DYNAMIC_LAYER_ID_BASE;
     std::map<std::string, std::string> m_createLayerAliases = {};
     glm::vec2 m_mousePosition = {};
     glm::vec2 m_pointerPosition = {};
@@ -485,6 +491,15 @@ private:
     std::set<CObject*> m_pendingDestroy = {};
     /** deleted with the scene */
     std::vector<CObject*> m_destroyedObjects = {};
+    /** layers a script created and destroyed, freed a couple of frames later (nothing else is left holding them) */
+    struct DestroyedLayer {
+	CObject* object;
+	uint32_t frame;
+    };
+    std::vector<DestroyedLayer> m_releasableLayers = {};
+    [[nodiscard]] bool isReleasable (const CObject& object) const;
+    void releaseDestroyedLayers ();
+    void releaseLayerModel (int id);
     void destroyPendingLayers ();
     mutable std::shared_ptr<const TextureProvider> m_missingTexture = nullptr;
     mutable GLuint m_nullTexture = GL_NONE;

+ 19 - 3
src/WallpaperEngine/Render/Wallpapers/CSplat.cpp

@@ -24,6 +24,7 @@
 #include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Logging/ThreadGuard.h"
 #include "WallpaperEngine/Splat/SogLoader.h"
 
 using namespace WallpaperEngine::Render;
@@ -36,7 +37,9 @@ class SplatSorter {
 public:
     SplatSorter (std::vector<glm::vec3> centers, std::vector<uint32_t> ids) :
 	m_centers (std::move (centers)), m_ids (std::move (ids)) {
-	this->m_worker = std::thread (&SplatSorter::run, this);
+	this->m_worker = std::thread ([this] {
+	    WallpaperEngine::Logging::guardThread ("Splat sorter", [this] { this->run (); });
+	});
     }
 
     ~SplatSorter () {
@@ -510,10 +513,23 @@ void CSplat::loadCloud () {
 	    return locator.readString (directory + "/" + name);
 	}
 
-	std::ifstream file (std::filesystem::path (directory) / name, std::ios::binary);
+	// the names come from the preset's meta: files of the data folder, not "/dev/zero" or "../../x", and no more
+	// than a splat image can be (real ones are a few MB)
+	constexpr std::uintmax_t maxFileSize = 128u * 1024 * 1024;
+	std::error_code pathError;
+	const auto folder = std::filesystem::weakly_canonical (directory, pathError);
+	const auto resolved = std::filesystem::weakly_canonical (folder / name, pathError);
+	const auto inside = resolved.lexically_relative (folder);
+
+	if (pathError || inside.empty () || *inside.begin () == ".." || !std::filesystem::is_regular_file (resolved)
+	    || std::filesystem::file_size (resolved, pathError) > maxFileSize || pathError) {
+	    sLog.exception ("Cannot read ", name, " from the splat data folder ", directory);
+	}
+
+	std::ifstream file (resolved, std::ios::binary);
 
 	if (!file) {
-	    sLog.exception ("Cannot read ", (std::filesystem::path (directory) / name).string ());
+	    sLog.exception ("Cannot read ", resolved.string ());
 	}
 
 	return { std::istreambuf_iterator<char> (file), std::istreambuf_iterator<char> () };

+ 34 - 3
src/WallpaperEngine/Render/Wallpapers/CWeb.cpp

@@ -10,6 +10,7 @@
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
 #include "WallpaperEngine/Media/ThumbnailPalette.h"
 #include "WallpaperEngine/Render/RenderContext.h"
+#include "WallpaperEngine/WebBrowser/CEF/TestHookPolicy.h"
 
 #include <atomic>
 #include <chrono>
@@ -134,6 +135,14 @@ void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
     // stream restore would hand our "Chromium" volume to the user's browser, so the host's stream opts out
     // tests only (HEADLESS_RENDER_WEB=1): LD_PRELOAD for the host alone, libcef.so before libc for its close() wrapper
     const char* preload = std::getenv ("LWE_WEB_HOST_PRELOAD");
+
+    if (preload != nullptr && preload[0] != '\0' && !WallpaperEngine::WebBrowser::CEF::trustedPreloadFile (preload)) {
+	sLog.error (
+	    "LWE_WEB_HOST_PRELOAD: ignoring ", preload, ", it must be an absolute path to a file only you can write"
+	);
+	preload = nullptr;
+    }
+
     std::vector<std::string> environment;
 
     for (char** entry = environ; *entry != nullptr; entry++) {
@@ -275,6 +284,11 @@ void CWeb::renderFrame (const glm::ivec4& viewport) {
 	return;
     }
 
+    if (*taken >= WebHostSharedMemory::FRAME_SLOTS) {
+	this->rejectFrame ();
+	return;
+    }
+
     this->m_frontSlot = *taken;
 
     const uint32_t frameWidth = this->m_shm->slotWidth[this->m_frontSlot].load (std::memory_order_relaxed);
@@ -285,6 +299,15 @@ void CWeb::renderFrame (const glm::ivec4& viewport) {
 	return;
     }
 
+    if (!WebHostSharedMemory::frameFits (
+	    this->m_frontSlot, frameWidth, frameHeight, this->m_shmMaxWidth, this->m_shmMaxHeight
+	)) {
+	this->rejectFrame ();
+	return;
+    }
+
+    uint8_t* const pixels = this->m_shm->frameBuffer (this->m_frontSlot, this->m_shmMaxWidth, this->m_shmMaxHeight);
+
     // resize the FBO with the frame, the output pass filters by its size; only reallocate on a change
     if (frameWidth != this->m_uploadedTextureWidth || frameHeight != this->m_uploadedTextureHeight) {
 	this->find ("_rt_FullFrameBuffer")->resize (frameWidth, frameHeight);
@@ -295,12 +318,11 @@ void CWeb::renderFrame (const glm::ivec4& viewport) {
     glBindTexture (GL_TEXTURE_2D, this->getWallpaperTexture ());
     glTexSubImage2D (
 	GL_TEXTURE_2D, 0, 0, 0, static_cast<GLsizei> (frameWidth), static_cast<GLsizei> (frameHeight), GL_BGRA_EXT,
-	GL_UNSIGNED_BYTE, this->m_shm->frameBuffer (this->m_frontSlot)
+	GL_UNSIGNED_BYTE, pixels
     );
     glBindTexture (GL_TEXTURE_2D, 0);
 
-    if (!this->m_pageHasContent
-	&& frameHasContent (this->m_shm->frameBuffer (this->m_frontSlot), frameWidth, frameHeight)) {
+    if (!this->m_pageHasContent && frameHasContent (pixels, frameWidth, frameHeight)) {
 	this->m_pageHasContent = true;
 
 	if (this->m_statsEnabled) {
@@ -329,6 +351,15 @@ bool CWeb::hasContent () const {
 	|| std::chrono::steady_clock::now () - this->m_created > patience;
 }
 
+void CWeb::rejectFrame () {
+    if (!this->m_badFrameLogged) {
+	sLog.error ("CWeb: the host published a frame that does not fit its shared memory, ignoring it");
+	this->m_badFrameLogged = true;
+    }
+
+    this->requestPageFrame ();
+}
+
 void CWeb::requestPageFrame () {
     const auto now = std::chrono::steady_clock::now ();
 

+ 3 - 0
src/WallpaperEngine/Render/Wallpapers/CWeb.h

@@ -65,6 +65,8 @@ private:
     void spawnHost (const std::filesystem::path& resolvedBackgroundPath);
     // asks the host for the next page frame, at most once per m_frameRequestDivisor renders
     void requestPageFrame ();
+    // a slot number or size the host wrote that doesn't fit the segment: nothing is read, the next frame is requested
+    void rejectFrame ();
 
     WallpaperEngine::WebBrowser::IPC::WebHostSharedMemory* m_shm = nullptr;
     std::string m_shmName;
@@ -96,6 +98,7 @@ private:
     bool m_mediaPublished = false;
     uint32_t m_coverVersion = 0;
     bool m_helperFailureLogged = false;
+    bool m_badFrameLogged = false;
     std::chrono::steady_clock::time_point m_created = std::chrono::steady_clock::now ();
     bool m_pageHasContent = false;
 

+ 125 - 61
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp

@@ -44,9 +44,14 @@ ScriptEngine& engineOf (const v8::FunctionCallbackInfo<v8::Value>& info) {
     return ScriptEngine::from (info.GetIsolate ());
 }
 
-// the layer a method's data points at, nullptr once it's gone
-ScriptableObject* layerObject (v8::Local<v8::Value> data) {
-    const auto* layer = JS::unwrap<Layer> (data);
+// the layer a handle in a JS object's data stands for, nullptr once it's gone
+Layer* layerFor (v8::Isolate* isolate, v8::Local<v8::Value> data) {
+    return ScriptEngine::from (isolate).getAdapters ().object->layerAt (JS::unwrap<void> (data));
+}
+
+// the object of the layer a method's data points at, nullptr once it's gone
+ScriptableObject* layerObject (v8::Isolate* isolate, v8::Local<v8::Value> data) {
+    const auto* layer = layerFor (isolate, data);
 
     return layer == nullptr ? nullptr : layer->object;
 }
@@ -168,7 +173,7 @@ IndexOrName indexOrNameArgument (v8::Isolate* isolate, v8::Local<v8::Value> valu
 
 // thisLayer.play/pause/stop/isPlaying
 void playback_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
 
     if (object == nullptr) {
 	return;
@@ -187,7 +192,7 @@ void playback_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
 // only scriptable layers can be handed to scripts, a plain group parent comes back as null
 void hierarchy_call (const v8::FunctionCallbackInfo<v8::Value>& info, int children) {
     auto& engine = engineOf (info);
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
     const auto& scene = engine.getScene ();
 
     if (object == nullptr) {
@@ -251,7 +256,7 @@ const std::vector<ImageEffectUniquePtr>* effectsOf (const Object& object) {
 // getEffectCount / getEffect: an index or an effect name (flags 0x208), null for anything else
 void effect_call (const v8::FunctionCallbackInfo<v8::Value>& info, int get) {
     auto& engine = engineOf (info);
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
     const auto* effects = object == nullptr ? nullptr : effectsOf (object->getObject ());
 
     if (get == 0) {
@@ -305,7 +310,7 @@ enum VideoTextureCall {
 
 // IVideoTexture methods (wallpaper64 2.8.42 sub_140214050, bodies sub_1401FA510..sub_1401FA730)
 void videotexture_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
-    auto* layer = JS::unwrap<Layer> (info.Data ());
+    auto* layer = layerFor (info.GetIsolate (), info.Data ());
     auto* player = layer == nullptr ? nullptr : videoPlayerOf (*layer);
     const auto context = info.GetIsolate ()->GetCurrentContext ();
 
@@ -379,15 +384,15 @@ void detachTextureAnimation (CImage& image, CImage::TextureAnimation& animation)
     animation.detached = true;
 }
 
-CImage* imageOf (v8::Local<v8::Value> data) {
-    auto* object = layerObject (data);
+CImage* imageOf (v8::Isolate* isolate, v8::Local<v8::Value> data) {
+    auto* object = layerObject (isolate, data);
 
     return object != nullptr && object->is<CImage> () ? object->as<CImage> () : nullptr;
 }
 
 // ITextureAnimation methods (wallpaper64 2.8.42 sub_1402131A0, bodies sub_1401FA330..sub_1401FA490)
 void textureanimation_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
-    auto* image = imageOf (info.Data ());
+    auto* image = imageOf (info.GetIsolate (), info.Data ());
     auto* animation = image == nullptr ? nullptr : image->getTextureAnimation ();
 
     if (animation == nullptr || call == TextureGetAnimation) {
@@ -532,7 +537,7 @@ enum BlendShapeCall { GetBlendShapeIndex, GetBlendShapeWeight, SetBlendShapeWeig
 
 // sub_140210400 / sub_1402104B0 / sub_1402105C0, non-puppets read -1 / 0 and ignore writes
 void blend_shape_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
     auto* image = object != nullptr && object->is<CImage> () ? object->as<CImage> () : nullptr;
 
     if (call == GetBlendShapeIndex) {
@@ -617,7 +622,7 @@ void applyMaterialState (WallpaperEngine::Render::Objects::Effects::CPass& pass,
 
 // emitParticles (an int argument, flag 8, the dispatcher's 0 otherwise) and getAnimation on IParticleSystemInstance
 void particle_call (const v8::FunctionCallbackInfo<v8::Value>& info, int emit) {
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
 
     if (emit != 0 && object != nullptr && object->is<CParticle> ()) {
 	object->as<CParticle> ()->emitParticles (int32Argument (info[0]).value_or (0));
@@ -719,7 +724,7 @@ WallpaperEngine::Render::Objects::PuppetRig* animationRig (ScriptableObject& obj
 void animation_layer_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
     auto& engine = engineOf (info);
     const auto context = engine.getContext ();
-    auto* object = layerObject (JS::get (context, info.Data (), 0u));
+    auto* object = layerObject (info.GetIsolate (), JS::get (context, info.Data (), 0u));
     const auto serial = static_cast<size_t> (JS::get (context, info.Data (), 1u)->IntegerValue (context).FromMaybe (0));
     auto* rig = object == nullptr ? nullptr : animationRig (*object);
     auto* clock = rig == nullptr ? nullptr : rig->findLayer (serial);
@@ -811,7 +816,7 @@ void animation_layer_call (const v8::FunctionCallbackInfo<v8::Value>& info, int
 void animation_layer_get_animation (const v8::FunctionCallbackInfo<v8::Value>& info) {
     auto& engine = engineOf (info);
     const auto context = engine.getContext ();
-    auto* object = layerObject (JS::get (context, info.Data (), 0u));
+    auto* object = layerObject (info.GetIsolate (), JS::get (context, info.Data (), 0u));
     const auto serial = static_cast<size_t> (JS::get (context, info.Data (), 1u)->IntegerValue (context).FromMaybe (0));
     std::string name;
 
@@ -849,7 +854,7 @@ v8::Local<v8::Value> WallpaperEngine::Scripting::Adapters::makeAnimationLayerHan
     const v8::Local<v8::Object> handle = v8::Object::New (isolate);
     const auto data = JS::data (
 	isolate,
-	{ JS::external (isolate, &engine.getAdapters ().object->layerOf (object)),
+	{ JS::external (isolate, engine.getAdapters ().object->layerOf (object).handle),
 	  v8::Number::New (isolate, static_cast<double> (serial)) }
     );
 
@@ -933,7 +938,7 @@ void layer_animation_layer_call (const v8::FunctionCallbackInfo<v8::Value>& info
     auto* isolate = info.GetIsolate ();
     auto& engine = engineOf (info);
     const auto context = engine.getContext ();
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
     auto* rig = object == nullptr ? nullptr : animationRig (*object);
     const auto handleFor = [&] (std::optional<size_t> serial) -> v8::Local<v8::Value> {
 	return serial.has_value () ? makeAnimationLayerHandle (engine, *object, *serial)
@@ -1011,7 +1016,7 @@ void layer_animation_layer_call (const v8::FunctionCallbackInfo<v8::Value>& info
 
 // scripts call this on image layers whose material is a video (mp4 texture), everything else gets null
 void video_texture_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
-    auto* layer = JS::unwrap<Layer> (info.Data ());
+    auto* layer = layerFor (info.GetIsolate (), info.Data ());
 
     info.GetReturnValue ().SetNull ();
 
@@ -1075,7 +1080,7 @@ void setLocalBoneAngles (glm::mat4& local, const glm::vec3& angles) {
 void bone_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
     auto& engine = engineOf (info);
     const auto context = engine.getContext ();
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
 
     const auto unset = [&] () {
 	switch (call) {
@@ -1223,7 +1228,7 @@ void bone_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
 // among this layer's animated properties (engine slot 15). undefined when there is none
 void get_animation_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
     auto& engine = engineOf (info);
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
     std::string name;
 
     if (object == nullptr) {
@@ -1247,7 +1252,7 @@ void get_animation_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
 
 // image layers with an animated texture get their ITextureAnimation, everything else null
 void texture_animation_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
-    auto* layer = JS::unwrap<Layer> (info.Data ());
+    auto* layer = layerFor (info.GetIsolate (), info.Data ());
 
     info.GetReturnValue ().SetNull ();
 
@@ -1385,7 +1390,7 @@ const CObject* layerArgument (ScriptEngine& engine, v8::Local<v8::Value> value)
 
 void set_parent_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
     auto& engine = engineOf (info);
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
 
     if (object == nullptr) {
 	return;
@@ -1418,7 +1423,7 @@ void set_parent_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
 void transform_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
     auto& engine = engineOf (info);
     const auto context = engine.getContext ();
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
 
     if (object == nullptr) {
 	return;
@@ -1545,7 +1550,7 @@ glm::mat4 layerViewProjection (const ScriptableObject& object) {
 // this layer's plane. Returns a Mat3 of texture direction and position
 void transform_attachment_to_texture_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
     auto& engine = engineOf (info);
-    auto* object = layerObject (info.Data ());
+    auto* object = layerObject (info.GetIsolate (), info.Data ());
     const auto* other = dynamic_cast<const ScriptableObject*> (layerArgument (engine, info[0]));
     std::array<float, 9> result = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f };
 
@@ -1797,7 +1802,7 @@ constexpr LayerMethod LayerMethods[] = {
 // layer properties: the object's DynamicValue when it has one, the few that aren't one, undefined otherwise
 void layer_get (v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
     auto* isolate = info.GetIsolate ();
-    auto* layer = JS::unwrap<Layer> (info.Data ());
+    auto* layer = layerFor (info.GetIsolate (), info.Data ());
 
     if (layer == nullptr || layer->object == nullptr) {
 	return;
@@ -1842,7 +1847,7 @@ void layer_get (v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8:
 // script
 void layer_set (v8::Local<v8::Name> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info) {
     auto* isolate = info.GetIsolate ();
-    auto* layer = JS::unwrap<Layer> (info.Data ());
+    auto* layer = layerFor (info.GetIsolate (), info.Data ());
 
     if (layer == nullptr || layer->object == nullptr) {
 	return;
@@ -1856,13 +1861,17 @@ void layer_set (v8::Local<v8::Name> property, v8::Local<v8::Value> value, const
 }
 
 void native_get (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info) {
-    if (const auto* property = JS::unwrap<NativeProperty> (info.Data ()); property != nullptr && property->get) {
+    if (const auto* property
+	= ScriptEngine::from (info.GetIsolate ()).getAdapters ().object->nativeAt (JS::unwrap<void> (info.Data ()));
+	property != nullptr && property->get) {
 	info.GetReturnValue ().Set (property->get ());
     }
 }
 
 void native_set (v8::Local<v8::Name>, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info) {
-    if (const auto* property = JS::unwrap<NativeProperty> (info.Data ()); property != nullptr && property->set) {
+    if (const auto* property
+	= ScriptEngine::from (info.GetIsolate ()).getAdapters ().object->nativeAt (JS::unwrap<void> (info.Data ()));
+	property != nullptr && property->set) {
 	property->set (value);
     }
 }
@@ -1886,6 +1895,7 @@ Layer& ScriptableObjectAdapter::layerOf (ScriptableObject& object) {
 
     if (layer == nullptr) {
 	layer = std::make_unique<Layer> (Layer { .object = &object });
+	layer->handle = this->m_layerHandles.insert (layer.get ());
     }
 
     return *layer;
@@ -1902,7 +1912,7 @@ v8::Local<v8::Object> ScriptableObjectAdapter::instantiate (ScriptableObject& ob
 
     const v8::Local<v8::Object> result
 	= this->m_layerConstructor.Get (isolate)->NewInstance (context).ToLocalChecked ();
-    const auto data = JS::external (isolate, &layer);
+    const auto data = JS::external (isolate, layer.handle);
     const auto members = layerMembers (object);
     const bool particle = object.getObject ().is<Particle> ();
 
@@ -1961,13 +1971,17 @@ void ScriptableObjectAdapter::forget (const ScriptableObject& object) {
 	return;
     }
 
-    it->second->object = nullptr;
-    it->second->instance.Reset ();
-    it->second->textureAnimation.Reset ();
-    it->second->particleInstance.Reset ();
-    it->second->videoTexture.Reset ();
-    it->second->videoTextureState.reset ();
-    this->m_forgotten.push_back (std::move (it->second));
+    auto& layer = *it->second;
+
+    for (void* handle : layer.nativeHandles) {
+	this->m_nativeHandles.release (handle);
+    }
+
+    this->m_layerHandles.release (layer.handle);
+    layer.instance.Reset ();
+    layer.textureAnimation.Reset ();
+    layer.particleInstance.Reset ();
+    layer.videoTexture.Reset ();
     this->m_layers.erase (it);
 }
 
@@ -1985,24 +1999,31 @@ ScriptableObject* ScriptableObjectAdapter::getObject (v8::Local<v8::Value> value
 	return nullptr;
     }
 
-    return layerObject (data);
+    return layerObject (isolate, data);
 }
 
 v8::Local<v8::Object> ScriptableObjectAdapter::makeNativeObject (
-    std::vector<NativeProperty> properties, const std::vector<std::pair<std::string, v8::Local<v8::Function>>>& methods
+    std::vector<NativeProperty> properties, const std::vector<std::pair<std::string, v8::Local<v8::Function>>>& methods,
+    Layer* owner
 ) {
     auto* isolate = this->m_engine.getIsolate ();
     const auto context = this->m_engine.getContext ();
     const v8::Local<v8::Object> result
 	= this->m_nativeConstructor.Get (isolate)->NewInstance (context).ToLocalChecked ();
-    auto& members
-	= *this->m_nativeMembers.emplace_back (std::make_unique<std::vector<NativeProperty>> (std::move (properties)));
+    auto& storage = owner == nullptr ? this->m_nativeMembers : owner->natives;
+    auto& members = *storage.emplace_back (std::make_unique<std::vector<NativeProperty>> (std::move (properties)));
 
     for (auto& property : members) {
+	void* handle = this->m_nativeHandles.insert (&property);
+
+	if (owner != nullptr) {
+	    owner->nativeHandles.push_back (handle);
+	}
+
 	result
 	    ->SetNativeDataProperty (
 		context, JS::name (isolate, property.name), native_get, property.set ? native_set : nullptr,
-		JS::external (isolate, &property), property.set ? v8::None : v8::ReadOnly
+		JS::external (isolate, handle), property.set ? v8::None : v8::ReadOnly
 	    )
 	    .Check ();
     }
@@ -2029,8 +2050,10 @@ v8::Local<v8::Value> ScriptableObjectAdapter::textureAnimation (Layer& layer) {
 
     // the members in the order WE's object lists them: properties, then methods, then IObject's getAnimation.
     // frameCount and duration are read only (+96 = 2)
-    Layer* owner = &layer;
-    const auto alive = [owner] { return owner->object != nullptr ? owner->object->as<CImage> () : nullptr; };
+    const auto alive = [this, handle = layer.handle] () -> CImage* {
+	const auto* current = this->layerAt (handle);
+	return current != nullptr && current->object != nullptr ? current->object->as<CImage> () : nullptr;
+    };
     std::vector<NativeProperty> properties = {
 	{ .name = "frameCount",
 	  .get = [isolate, alive] () -> v8::Local<v8::Value> {
@@ -2073,7 +2096,7 @@ v8::Local<v8::Value> ScriptableObjectAdapter::textureAnimation (Layer& layer) {
 	      } },
     };
 
-    const auto data = JS::external (isolate, &layer);
+    const auto data = JS::external (isolate, layer.handle);
     // every method reports length 0, like WE's
     const std::vector<std::pair<std::string, v8::Local<v8::Function>>> methods = {
 	{ "play", JS::function (context, JS::bind<textureanimation_call, TexturePlay>, data) },
@@ -2086,7 +2109,7 @@ v8::Local<v8::Value> ScriptableObjectAdapter::textureAnimation (Layer& layer) {
 	{ "getAnimation", JS::function (context, JS::bind<textureanimation_call, TextureGetAnimation>, data) },
     };
 
-    const auto result = this->makeNativeObject (std::move (properties), methods);
+    const auto result = this->makeNativeObject (std::move (properties), methods, &layer);
     layer.textureAnimation.Reset (isolate, result);
     return result;
 }
@@ -2104,21 +2127,25 @@ v8::Local<v8::Value> ScriptableObjectAdapter::videoTexture (Layer& layer) {
     // the properties keep their own values like WE's typed members: a float only takes numbers, a bool only
     // booleans (sub_1401A4B00, sub_1401A4A20), the change callback runs after every write either way
     // (sub_1401FA6D0, sub_1401FA700). duration is read only (+96 = 2)
-    Layer* owner = &layer;
+    const auto owner = [this, handle = layer.handle] () { return this->layerAt (handle); };
     std::vector<NativeProperty> properties = {
 	{ .name = "rate",
 	  .get = [isolate, owner] () -> v8::Local<v8::Value> {
-	      return v8::Number::New (isolate, owner->videoTextureState ? owner->videoTextureState->rate : 0.0f);
+	      const auto* current = owner ();
+	      return v8::Number::New (
+		  isolate, current != nullptr && current->videoTextureState ? current->videoTextureState->rate : 0.0f
+	      );
 	  },
 	  .set =
 	      [owner] (v8::Local<v8::Value> value) {
-		  auto* player = videoPlayerOf (*owner);
+		  auto* current = owner ();
+		  auto* player = current == nullptr ? nullptr : videoPlayerOf (*current);
 
-		  if (player == nullptr || owner->videoTextureState == nullptr) {
+		  if (player == nullptr || current->videoTextureState == nullptr) {
 		      return;
 		  }
 
-		  auto& state = *owner->videoTextureState;
+		  auto& state = *current->videoTextureState;
 
 		  if (value->IsNumber ()) {
 		      state.rate = static_cast<float> (value.As<v8::Number> ()->Value ());
@@ -2131,30 +2158,35 @@ v8::Local<v8::Value> ScriptableObjectAdapter::videoTexture (Layer& layer) {
 	      } },
 	{ .name = "loop",
 	  .get = [isolate, owner] () -> v8::Local<v8::Value> {
-	      return v8::Boolean::New (isolate, owner->videoTextureState && owner->videoTextureState->loop);
+	      const auto* current = owner ();
+	      return v8::Boolean::New (
+		  isolate, current != nullptr && current->videoTextureState && current->videoTextureState->loop
+	      );
 	  },
 	  .set =
 	      [owner] (v8::Local<v8::Value> value) {
-		  auto* player = videoPlayerOf (*owner);
+		  auto* current = owner ();
+		  auto* player = current == nullptr ? nullptr : videoPlayerOf (*current);
 
-		  if (player == nullptr || owner->videoTextureState == nullptr) {
+		  if (player == nullptr || current->videoTextureState == nullptr) {
 		      return;
 		  }
 
 		  if (value->IsBoolean ()) {
-		      owner->videoTextureState->loop = value.As<v8::Boolean> ()->Value ();
+		      current->videoTextureState->loop = value.As<v8::Boolean> ()->Value ();
 		  }
 
-		  player->setLoop (owner->videoTextureState->loop);
+		  player->setLoop (current->videoTextureState->loop);
 	      } },
 	{ .name = "duration",
 	  .get = [isolate, owner] () -> v8::Local<v8::Value> {
-	      auto* player = videoPlayerOf (*owner);
+	      const auto* current = owner ();
+	      auto* player = current == nullptr ? nullptr : videoPlayerOf (*current);
 	      return v8::Number::New (isolate, player == nullptr ? 0.0f : static_cast<float> (player->getDuration ()));
 	  } },
     };
 
-    const auto data = JS::external (isolate, &layer);
+    const auto data = JS::external (isolate, layer.handle);
     const std::vector<std::pair<std::string, v8::Local<v8::Function>>> methods = {
 	{ "play", JS::function (context, JS::bind<videotexture_call, VideoPlay>, data) },
 	{ "pause", JS::function (context, JS::bind<videotexture_call, VideoPause>, data) },
@@ -2165,7 +2197,7 @@ v8::Local<v8::Value> ScriptableObjectAdapter::videoTexture (Layer& layer) {
 	{ "addEndedCallback", JS::function (context, JS::bind<videotexture_call, VideoAddEndedCallback>, data) },
     };
 
-    const auto result = this->makeNativeObject (std::move (properties), methods);
+    const auto result = this->makeNativeObject (std::move (properties), methods, &layer);
     layer.videoTexture.Reset (isolate, result);
     return result;
 }
@@ -2208,6 +2240,20 @@ std::vector<v8::Local<v8::Function>> ScriptableObjectAdapter::takeDueVideoEndedC
     return due;
 }
 
+void ScriptableObjectAdapter::dropVideoEndedCallback (v8::Local<v8::Function> callback) {
+    auto* isolate = this->m_engine.getIsolate ();
+
+    for (const auto& layer : this->m_layers | std::views::values) {
+	if (layer->videoTextureState == nullptr) {
+	    continue;
+	}
+
+	std::erase_if (layer->videoTextureState->endedCallbacks, [&] (const v8::Global<v8::Function>& registered) {
+	    return registered.Get (isolate)->StrictEquals (callback);
+	});
+    }
+}
+
 v8::Local<v8::Value> ScriptableObjectAdapter::animation (int systemId, int clockId) {
     auto* isolate = this->m_engine.getIsolate ();
     const auto context = this->m_engine.getContext ();
@@ -2281,6 +2327,22 @@ v8::Local<v8::Value> ScriptableObjectAdapter::animation (int systemId, int clock
     return result;
 }
 
+bool ScriptableObjectAdapter::hasEffectHandles (const Object& object) const {
+    const auto* effects = effectsOf (object);
+
+    if (effects == nullptr) {
+	return false;
+    }
+
+    return std::ranges::any_of (*effects, [this] (const ImageEffectUniquePtr& effect) {
+	// the state entry comes first when a material handle is made, so it covers m_materials as well
+	const auto material = this->m_materialStates.lower_bound ({ effect.get (), 0 });
+
+	return this->m_effects.contains (effect.get ())
+	    || (material != this->m_materialStates.end () && material->first.first == effect.get ());
+    });
+}
+
 v8::Local<v8::Value> ScriptableObjectAdapter::effect (ImageEffect& effect) {
     auto* isolate = this->m_engine.getIsolate ();
     const auto context = this->m_engine.getContext ();
@@ -2481,8 +2543,10 @@ v8::Local<v8::Value> ScriptableObjectAdapter::particleInstance (Layer& layer) {
     }
 
     auto& engine = this->m_engine;
-    Layer* owner = &layer;
-    const auto alive = [owner] { return owner->object != nullptr ? owner->object->as<CParticle> () : nullptr; };
+    const auto alive = [this, handle = layer.handle] () -> CParticle* {
+	const auto* current = this->layerAt (handle);
+	return current != nullptr && current->object != nullptr ? current->object->as<CParticle> () : nullptr;
+    };
     const auto& instanceOverride = alive ()->getParticle ().instanceOverride;
     std::vector<NativeProperty> properties;
 
@@ -2548,10 +2612,10 @@ v8::Local<v8::Value> ScriptableObjectAdapter::particleInstance (Layer& layer) {
     addFloat ("alpha", *instanceOverride.alpha->value);
 
     const std::vector<std::pair<std::string, v8::Local<v8::Function>>> methods = {
-	{ "getAnimation", JS::function (context, JS::bind<particle_call, 0>, JS::external (isolate, &layer)) },
+	{ "getAnimation", JS::function (context, JS::bind<particle_call, 0>, JS::external (isolate, layer.handle)) },
     };
 
-    const auto result = this->makeNativeObject (std::move (properties), methods);
+    const auto result = this->makeNativeObject (std::move (properties), methods, &layer);
     layer.particleInstance.Reset (isolate, result);
     return result;
 }

+ 20 - 4
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h

@@ -3,6 +3,8 @@
 #include <v8-local-handle.h>
 #include <v8-persistent-handle.h>
 
+#include "WallpaperEngine/Scripting/HandleTable.h"
+
 #include <array>
 #include <functional>
 #include <map>
@@ -20,6 +22,7 @@ class Private;
 
 namespace WallpaperEngine::Data::Model {
 struct ImageEffect;
+class Object;
 }
 
 namespace WallpaperEngine::Render::Objects {
@@ -50,9 +53,11 @@ struct VideoTexture {
     std::vector<v8::Global<v8::Function>> endedCallbacks = {};
 };
 
-/** What scripts reach a layer through. Outlives the layer, `object` is cleared when it goes */
+/** What scripts reach a layer through. Lives as long as the layer, JS objects refer to it by `handle` and find nothing
+ * once it is gone */
 struct Layer {
     ScriptableObject* object;
+    void* handle = nullptr;
     // one JS object per layer like scenescript64 (getLayer sub_181632350 -> sub_181652380), scripts compare
     // layers, key maps by them and tag them (3378399626's widget, 3577513994's icon.clicked)
     v8::Global<v8::Object> instance;
@@ -63,6 +68,9 @@ struct Layer {
     /** IVideoTexture of an image layer with a video texture, one per layer like WE's */
     v8::Global<v8::Object> videoTexture;
     std::unique_ptr<VideoTexture> videoTextureState;
+    /** The members of the native objects made for this layer, and the handles their accessors carry */
+    std::vector<std::unique_ptr<std::vector<NativeProperty>>> natives;
+    std::vector<void*> nativeHandles;
 };
 
 /** IAnimationLayer (wallpaper64 2.8.42 sub_14026C980) for the puppet animation layer with that serial */
@@ -80,6 +88,9 @@ public:
     /** The layer a JS value produced by instantiate () stands for, nullptr for anything else or a layer that is gone */
     ScriptableObject* getObject (v8::Local<v8::Value> value) const;
     Layer& layerOf (ScriptableObject& object);
+    /** The layer a handle of its JS objects stands for, nullptr once the layer is gone */
+    [[nodiscard]] Layer* layerAt (void* handle) const { return m_layerHandles.find (handle); }
+    [[nodiscard]] NativeProperty* nativeAt (void* handle) const { return m_nativeHandles.find (handle); }
 
     void forget (const ScriptableObject& object);
 
@@ -88,6 +99,11 @@ public:
     v8::Local<v8::Value> videoTexture (Layer& layer);
     /** Steps every IVideoTexture's ended state for this frame, returns the callbacks due now (sub_1401FDF90) */
     std::vector<v8::Local<v8::Function>> takeDueVideoEndedCallbacks ();
+    /** Forgets an ended callback that ran away, so it does not stop the frame at every loop */
+    void dropVideoEndedCallback (v8::Local<v8::Function> callback);
+    /** Whether a script ever got an IEffect or IMaterial of one of the object's effects: those keep raw references into
+     * the object's model for as long as the engine lives */
+    [[nodiscard]] bool hasEffectHandles (const Data::Model::Object& object) const;
     /** IEffect of one of an image's effects, one JS object per effect */
     v8::Local<v8::Value> effect (Data::Model::ImageEffect& effect);
     /** one JS object per material, null without one */
@@ -98,7 +114,7 @@ public:
     // properties before methods, read only writes throw
     v8::Local<v8::Object> makeNativeObject (
 	std::vector<NativeProperty> properties,
-	const std::vector<std::pair<std::string, v8::Local<v8::Function>>>& methods
+	const std::vector<std::pair<std::string, v8::Local<v8::Function>>>& methods, Layer* owner = nullptr
     );
 
     ScriptEngine& getEngine () const { return m_engine; }
@@ -107,8 +123,8 @@ private:
     ScriptEngine& m_engine;
 
     std::unordered_map<const ScriptableObject*, std::unique_ptr<Layer>> m_layers;
-    // layers of objects that are gone, scripts may still hold their JS objects
-    std::vector<std::unique_ptr<Layer>> m_forgotten;
+    HandleTable<Layer> m_layerHandles;
+    HandleTable<NativeProperty> m_nativeHandles;
     std::unordered_map<int, v8::Global<v8::Object>> m_animations;
     std::unordered_map<const Data::Model::ImageEffect*, v8::Global<v8::Object>> m_effects;
     std::map<std::pair<const Data::Model::ImageEffect*, size_t>, v8::Global<v8::Object>> m_materials;

+ 34 - 0
src/WallpaperEngine/Scripting/AnimationSystem.cpp

@@ -316,6 +316,40 @@ void AnimationSystem::remove (const DynamicValue& value) {
     std::erase_if (m_entries, [&value] (const Entry& entry) { return entry.value == &value; });
 }
 
+void AnimationSystem::removeObject (int objectId) {
+    const std::string own = "obj" + std::to_string (objectId);
+    const std::string layers = "animationlayer" + std::to_string (objectId) + "[";
+    const auto ours = [&] (const std::string& group) {
+	return group == own || group.starts_with (own + "/") || group.starts_with (layers);
+    };
+
+    std::set<const DynamicValue*> gone;
+
+    for (auto* entries : { &m_pending, &m_entries }) {
+	for (const auto& entry : *entries) {
+	    if (ours (entry.group)) {
+		gone.insert (entry.value);
+	    }
+	}
+
+	std::erase_if (*entries, [&] (const Entry& entry) { return ours (entry.group); });
+    }
+
+    if (gone.empty ()) {
+	return;
+    }
+
+    std::erase_if (m_groups, [&] (const auto& group) { return ours (group.first); });
+
+    for (const auto* value : gone) {
+	m_bound.erase (value);
+	m_byValue.erase (value);
+    }
+
+    // a timeline only ever binds values of its own group, so every one of them is gone as well
+    std::erase_if (m_clocks, [&] (const auto& clock) { return gone.contains (&clock->getRootValue ()); });
+}
+
 AnimationClock* AnimationSystem::findByName (const std::string& name, const std::optional<std::string>& objectGroup) {
     if (!m_linked) {
 	this->link ();

+ 3 - 0
src/WallpaperEngine/Scripting/AnimationSystem.h

@@ -90,6 +90,9 @@ public:
     void add (const std::string& group, const std::string& key, DynamicValue& value);
     /** Drops a not-yet-linked registration, used when a later registration supersedes it */
     void remove (const DynamicValue& value);
+    /** Forgets everything registered for one object (its properties, effect constants and animation layers) with the
+     * timelines that were built from it, for an object whose values are about to be freed */
+    void removeObject (int objectId);
     void tick (float deltaSeconds);
     std::vector<PendingEvent> takeEvents ();
     AnimationClock* clockOf (const DynamicValue& value);

+ 14 - 6
src/WallpaperEngine/Scripting/EngineObject.cpp

@@ -270,9 +270,14 @@ v8::Local<v8::Object> EngineObject::registerAudioBuffers (int resolution) {
 
     for (int index = 0; index < 9; index++) {
 	if (this->m_audioBuffers[index] == nullptr) {
-	    this->m_audioBuffers[index]
-		= v8::ArrayBuffer::NewBackingStore (isolate, (16u << (index / 3)) * sizeof (float));
-	    std::fill_n (static_cast<float*> (this->m_audioBuffers[index]->Data ()), 16 << (index / 3), 0.0f);
+	    // not the isolate's allocator: that one refuses a script that holds too much, and a native allocation
+	    // failing takes the process down
+	    const size_t count = 16u << (index / 3);
+
+	    this->m_audioBuffers[index] = v8::ArrayBuffer::NewBackingStore (
+		new float[count](), count * sizeof (float),
+		[] (void* data, size_t, void*) { delete[] static_cast<float*> (data); }, nullptr
+	    );
 	}
     }
 
@@ -392,7 +397,9 @@ void EngineObject::tick () {
 	// the callback may start timers, which can move this one
 	const std::string owner = timer->owner;
 
-	if (this->m_engine.callAsModule (owner, timer->callback.Get (isolate)).IsEmpty ()) {
+	const bool failed = this->m_engine.callAsModule (owner, timer->callback.Get (isolate)).IsEmpty ();
+
+	if (failed) {
 	    logJSException (isolate, tryCatch, interval ? "setInterval" : "setTimeout");
 	}
 
@@ -403,10 +410,11 @@ void EngineObject::tick () {
 	    continue;
 	}
 
-	// a finished timeout's stop function does nothing from then on
-	if (interval) {
+	// a callback that ran away is over, it would only do it again
+	if (interval && !(failed && this->m_engine.lastCallStopped ())) {
 	    timer->remaining = timer->duration;
 	} else {
+	    // a finished timeout's stop function does nothing from then on
 	    timer->stopData.Get (isolate)->Set (context, 0, v8::Undefined (isolate)).Check ();
 	    this->m_timers.erase (timer);
 	}

+ 55 - 0
src/WallpaperEngine/Scripting/ErrorRepeatFilter.h

@@ -0,0 +1,55 @@
+#pragma once
+
+#include <algorithm>
+#include <cstddef>
+#include <deque>
+#include <map>
+#include <string>
+#include <utility>
+
+namespace WallpaperEngine::Scripting {
+/**
+ * Decides which script errors reach the log: a script that fails the same way every frame is reported once, also when
+ * it alternates between a few errors, and the next error that is shown says how many were left out. Memory stays
+ * bounded however many different errors a script makes up.
+ */
+class ErrorRepeatFilter {
+public:
+    static constexpr std::size_t REMEMBERED_PER_SCRIPT = 8;
+    static constexpr std::size_t MAX_SCRIPTS = 256;
+
+    /** Whether to log this error, suppressed gets the number of repeats dropped since the last one logged */
+    bool admit (const std::string& script, const std::string& error, std::size_t& suppressed) {
+	suppressed = 0;
+
+	if (!m_scripts.contains (script) && m_scripts.size () >= MAX_SCRIPTS) {
+	    m_scripts.clear ();
+	}
+
+	auto& recent = m_scripts[script];
+
+	if (std::ranges::find (recent.errors, error) != recent.errors.end ()) {
+	    recent.suppressed++;
+	    return false;
+	}
+
+	recent.errors.push_front (error);
+
+	if (recent.errors.size () > REMEMBERED_PER_SCRIPT) {
+	    recent.errors.pop_back ();
+	}
+
+	suppressed = std::exchange (recent.suppressed, 0);
+
+	return true;
+    }
+
+private:
+    struct Recent {
+	std::deque<std::string> errors;
+	std::size_t suppressed = 0;
+    };
+
+    std::map<std::string, Recent> m_scripts;
+};
+} // namespace WallpaperEngine::Scripting

+ 91 - 0
src/WallpaperEngine/Scripting/HandleTable.h

@@ -0,0 +1,91 @@
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <deque>
+#include <stdexcept>
+#include <vector>
+
+namespace WallpaperEngine::Scripting {
+/**
+ * Hands out values a v8::External can carry in place of a raw pointer to a native record a script may keep using after
+ * the record is gone. A released handle (and one of an earlier use of its slot) finds nothing, so the record can be
+ * freed while stale JS objects still call into it. The value stays below 2^47, which every pointer-sized External
+ * accepts, and is never 0.
+ */
+template <typename T> class HandleTable {
+public:
+    [[nodiscard]] void* insert (T* object) {
+	uint32_t index;
+
+	if (m_free.size () > REUSE_AFTER) {
+	    index = m_free.front ();
+	    m_free.pop_front ();
+	} else {
+	    if (m_slots.size () >= INDEX_MASK) {
+		throw std::length_error ("too many live script handles");
+	    }
+
+	    index = static_cast<uint32_t> (m_slots.size ());
+	    m_slots.emplace_back ();
+	}
+
+	m_slots[index].object = object;
+
+	return encode (index, m_slots[index].generation);
+    }
+
+    [[nodiscard]] T* find (void* handle) const {
+	const auto slot = decode (handle);
+
+	return slot == nullptr ? nullptr : slot->object;
+    }
+
+    void release (void* handle) {
+	const auto slot = decode (handle);
+
+	if (slot == nullptr) {
+	    return;
+	}
+
+	slot->object = nullptr;
+	slot->generation = slot->generation >= GENERATION_MASK ? 1 : slot->generation + 1;
+	m_free.push_back (static_cast<uint32_t> (slot - m_slots.data ()));
+    }
+
+    [[nodiscard]] size_t live () const { return m_slots.size () - m_free.size (); }
+
+private:
+    static constexpr uint64_t INDEX_MASK = (1u << 24) - 1;
+    static constexpr uint64_t GENERATION_MASK = (1u << 23) - 1;
+    // a slot waits behind this many others before it is used again, so a stale handle stays stale for long
+    static constexpr size_t REUSE_AFTER = 64;
+
+    struct Slot {
+	T* object = nullptr;
+	uint32_t generation = 1;
+    };
+
+    static void* encode (uint32_t index, uint32_t generation) {
+	return reinterpret_cast<void*> (
+	    static_cast<uintptr_t> ((static_cast<uint64_t> (generation) << 24) | (index + 1u))
+	);
+    }
+
+    Slot* decode (void* handle) const {
+	const auto value = static_cast<uint64_t> (reinterpret_cast<uintptr_t> (handle));
+	const uint64_t index = value & INDEX_MASK;
+
+	if (index == 0 || index > m_slots.size ()) {
+	    return nullptr;
+	}
+
+	auto* slot = const_cast<Slot*> (&m_slots[index - 1]);
+
+	return slot->object != nullptr && slot->generation == (value >> 24) ? slot : nullptr;
+    }
+
+    std::vector<Slot> m_slots;
+    std::deque<uint32_t> m_free;
+};
+} // namespace WallpaperEngine::Scripting

+ 55 - 0
src/WallpaperEngine/Scripting/JS.cpp

@@ -4,10 +4,14 @@
 
 #include <libplatform/libplatform.h>
 
+#include <array>
 #include <cstdlib>
+#include <exception>
 #include <filesystem>
 #include <fstream>
+#include <mutex>
 #include <string>
+#include <utility>
 
 // embedders skip node's ICU setup, without it Fedora's libnode has no time zone data. Weak for nodes without Intl
 namespace node::i18n {
@@ -16,6 +20,28 @@ namespace node::i18n {
 
 namespace WallpaperEngine::Scripting::JS {
 namespace {
+    // the callbacks the stand-ins call, written before a stand-in is handed out and only read by the script thread
+    constexpr size_t GuardSlots = 1024;
+    std::array<v8::FunctionCallback, GuardSlots> guardedCallbacks {};
+
+    template <size_t Slot> void guarded (const v8::FunctionCallbackInfo<v8::Value>& info) {
+	try {
+	    guardedCallbacks[Slot](info);
+	} catch (const std::exception& e) {
+	    sLog.error ("Script API call failed: ", e.what ());
+	    info.GetIsolate ()->ThrowException (v8::Exception::Error (string (info.GetIsolate (), e.what ())));
+	} catch (...) {
+	    sLog.error ("Script API call failed: unknown error");
+	    info.GetIsolate ()->ThrowException (v8::Exception::Error (string (info.GetIsolate (), "unknown error")));
+	}
+    }
+
+    template <size_t... Slot> constexpr auto makeGuards (std::index_sequence<Slot...>) {
+	return std::array<v8::FunctionCallback, sizeof...(Slot)> { &guarded<Slot>... };
+    }
+
+    constexpr auto guards = makeGuards (std::make_index_sequence<GuardSlots> ());
+
     // node's lookup: NODE_ICU_DATA, then the build's default directory if installed
     std::string icuDataDirectory () {
 	if (const char* env = std::getenv ("NODE_ICU_DATA"); env != nullptr) {
@@ -118,4 +144,33 @@ void useNamedTimeZone () {
 	setenv ("TZ", name.c_str (), 1);
     }
 }
+v8::FunctionCallback guard (v8::FunctionCallback callback) {
+    static std::mutex mutex;
+    static size_t used = 0;
+    static bool warned = false;
+    const std::lock_guard lock (mutex);
+
+    if (callback == nullptr) {
+	return callback;
+    }
+
+    for (size_t i = 0; i < used; i++) {
+	if (guardedCallbacks[i] == callback) {
+	    return guards[i];
+	}
+    }
+
+    if (used == GuardSlots) {
+	if (!warned) {
+	    warned = true;
+	    sLog.error ("More script API callbacks than guards (", GuardSlots, "), the rest run without one");
+	}
+
+	return callback;
+    }
+
+    guardedCallbacks[used] = callback;
+
+    return guards[used++];
+}
 } // namespace WallpaperEngine::Scripting::JS

+ 9 - 1
src/WallpaperEngine/Scripting/JS.h

@@ -71,11 +71,19 @@ inline v8::Local<v8::Value> dataAt (const v8::FunctionCallbackInfo<v8::Value>& i
     return info.Data ().As<v8::Array> ()->Get (info.GetIsolate ()->GetCurrentContext (), index).ToLocalChecked ();
 }
 
+/**
+ * The callback with a net around it: scripts call native code through generated code the unwinder cannot cross, so a
+ * C++ exception that leaves a callback ends the process. The returned stand-in turns it into a JavaScript Error (and
+ * logs it). One per distinct callback, taken from a fixed pool; past the pool the callback is returned as it is.
+ */
+v8::FunctionCallback guard (v8::FunctionCallback callback);
+
 /** A native function the way scenescript64 hands them out: no name, length as given (0 for WE's own methods) */
 inline v8::Local<v8::Function> function (
     v8::Local<v8::Context> context, v8::FunctionCallback callback, v8::Local<v8::Value> data = {}, int length = 0
 ) {
-    return v8::Function::New (context, callback, data, length, v8::ConstructorBehavior::kThrow).ToLocalChecked ();
+    return v8::Function::New (context, guard (callback), data, length, v8::ConstructorBehavior::kThrow)
+	.ToLocalChecked ();
 }
 
 /** The same callback for every `magic` value, so one switch can serve several methods */

+ 51 - 0
src/WallpaperEngine/Scripting/LimitedAllocator.cpp

@@ -0,0 +1,51 @@
+#include "LimitedAllocator.h"
+
+#include <atomic>
+
+namespace WallpaperEngine::Scripting {
+namespace {
+    class LimitedAllocator final : public v8::ArrayBuffer::Allocator {
+    public:
+	explicit LimitedAllocator (size_t limit) :
+	    m_backing (v8::ArrayBuffer::Allocator::NewDefaultAllocator ()), m_limit (limit) { }
+
+	void* Allocate (size_t length) override {
+	    return this->take (length, [&] { return this->m_backing->Allocate (length); });
+	}
+
+	void* AllocateUninitialized (size_t length) override {
+	    return this->take (length, [&] { return this->m_backing->AllocateUninitialized (length); });
+	}
+
+	void Free (void* data, size_t length) override {
+	    this->m_backing->Free (data, length);
+	    this->m_used -= length;
+	}
+
+    private:
+	template <typename Allocate> void* take (size_t length, Allocate allocate) {
+	    if (this->m_used.fetch_add (length) + length > this->m_limit && this->m_limit > 0) {
+		this->m_used -= length;
+		return nullptr;
+	    }
+
+	    void* data = allocate ();
+
+	    // the system refused it: what was counted for it goes back
+	    if (data == nullptr) {
+		this->m_used -= length;
+	    }
+
+	    return data;
+	}
+
+	std::unique_ptr<v8::ArrayBuffer::Allocator> m_backing;
+	size_t m_limit;
+	std::atomic<size_t> m_used = 0;
+    };
+} // namespace
+
+std::unique_ptr<v8::ArrayBuffer::Allocator> makeLimitedAllocator (size_t limit) {
+    return std::make_unique<LimitedAllocator> (limit);
+}
+} // namespace WallpaperEngine::Scripting

+ 21 - 0
src/WallpaperEngine/Scripting/LimitedAllocator.h

@@ -0,0 +1,21 @@
+#pragma once
+
+#include <cstddef>
+#include <memory>
+
+#include <v8-array-buffer.h>
+
+namespace WallpaperEngine::Scripting {
+/**
+ * The isolate's ArrayBuffer allocator with a cap on what scripts can hold. ArrayBuffer memory lives outside V8's heap
+ * and its limit, a script keeping Float64Arrays around would grow the process until the machine runs out. Past the
+ * limit the allocation fails and the script gets V8's RangeError; a limit of 0 means none. Nothing native may allocate
+ * through it, V8 aborts the process when ArrayBuffer::New fails (EngineObject keeps its own memory).
+ *
+ * A function and not the class: libnode is built without RTTI and does not export typeinfo for V8's classes, and
+ * depending on the V8 version a class derived from ArrayBuffer::Allocator needs it ("undefined reference to typeinfo
+ * for v8::ArrayBuffer::Allocator" at link time). LimitedAllocator.cpp is the one file that derives from it and is
+ * compiled without RTTI, like V8 itself.
+ */
+std::unique_ptr<v8::ArrayBuffer::Allocator> makeLimitedAllocator (size_t limit);
+} // namespace WallpaperEngine::Scripting

+ 245 - 45
src/WallpaperEngine/Scripting/ScriptEngine.cpp

@@ -5,6 +5,7 @@
 
 #include "Adapters/ScriptableObjectAdapter.h"
 #include "JS.h"
+#include "LimitedAllocator.h"
 #include "ScriptPropertiesObject.h"
 #include "ScriptableObject.h"
 #include "WallpaperEngine/Audio/AudioContext.h"
@@ -22,6 +23,7 @@
 
 #include <algorithm>
 #include <array>
+#include <atomic>
 #include <cctype>
 #include <cerrno>
 #include <chrono>
@@ -30,10 +32,12 @@
 #include <cstring>
 #include <ctime>
 #include <filesystem>
+#include <functional>
 #include <future>
 #include <map>
 #include <optional>
 #include <ranges>
+#include <set>
 #include <sstream>
 #include <string_view>
 #include <vector>
@@ -349,6 +353,122 @@ void ScriptEngine::assignPropertyJsValue (v8::Local<v8::Value> val, DynamicValue
     }
 }
 
+namespace {
+constexpr long DEFAULT_CALL_BUDGET_MS = 5000;
+constexpr long DEFAULT_HEAP_LIMIT_MB = 512;
+constexpr long DEFAULT_BUFFER_LIMIT_MB = 512;
+// room V8 gets past the limit to unwind a script it terminated
+constexpr size_t HEAP_UNWIND_ROOM = 64 * 1024 * 1024;
+
+long envNumber (const char* name, long fallback) {
+    const char* text = std::getenv (name);
+    char* end = nullptr;
+
+    if (text == nullptr) {
+	return fallback;
+    }
+
+    const long value = std::strtol (text, &end, 10);
+
+    return end != text && *end == '\0' && value >= 0 ? value : fallback;
+}
+} // namespace
+
+ScriptEngine::RunLimit::RunLimit (ScriptEngine& engine) : m_engine (engine) {
+    if (engine.m_runDepth++ > 0) {
+	return;
+    }
+
+    engine.m_runawayReported = false;
+
+    if (engine.m_callBudget.count () > 0 && engine.m_watchdog != nullptr) {
+	engine.m_watchdog->begin (engine.m_callBudget);
+    }
+}
+
+ScriptEngine::RunLimit::~RunLimit () {
+    if (--this->m_engine.m_runDepth > 0) {
+	return;
+    }
+
+    // a termination that came in as the call finished is still pending and would stop the next script that runs
+    const bool timedOut = this->m_engine.m_watchdog != nullptr && this->m_engine.m_watchdog->end ();
+
+    if (timedOut || this->m_engine.m_heapExhausted) {
+	this->m_engine.m_isolate->CancelTerminateExecution ();
+	this->m_engine.m_heapExhausted = false;
+    }
+}
+
+size_t ScriptEngine::nearHeapLimit (void* data, size_t currentLimit, size_t) {
+    auto& engine = *static_cast<ScriptEngine*> (data);
+
+    // script code allocates inside a RunLimit, anything else (the engine's own startup) just gets room
+    if (engine.m_runDepth > 0) {
+	engine.m_heapExhausted = true;
+	engine.m_isolate->TerminateExecution ();
+    }
+
+    engine.m_heapLimitRaised = true;
+
+    return currentLimit + HEAP_UNWIND_ROOM;
+}
+
+void ScriptEngine::stopRunaway (const LoadedModule* culprit, const char* what, std::string_view owner) {
+    // our own record of why it was stopped: when V8 clears its termination state differs between versions
+    const bool stopped = this->m_heapExhausted || (this->m_watchdog != nullptr && this->m_watchdog->fired ());
+
+    // the innermost call that sees it blames its module, the ones around it only unwind
+    if (!stopped || this->m_runawayReported) {
+	return;
+    }
+
+    this->m_runawayReported = true;
+
+    // looked up by address, the entry may have been rebound while the script ran
+    LoadedModule* module = nullptr;
+
+    for (auto& entry : this->m_scriptModules | std::views::values) {
+	if (&entry == culprit) {
+	    module = &entry;
+	    break;
+	}
+    }
+
+    const std::string limit = this->m_heapExhausted
+	? "went over the " + std::to_string (this->m_heapLimit / (1024 * 1024)) + " MB script memory limit"
+	: "ran longer than " + std::to_string (this->m_callBudget.count ()) + " ms";
+
+    std::string name (owner.empty () ? "script" : owner);
+
+    if (module != nullptr) {
+	name = module->key;
+    }
+
+    sLog.error (
+	"ScriptEngine [", name, "]: ", what, " ", limit,
+	module != nullptr ? ", the script is switched off" : ", it was stopped"
+    );
+
+    if (module != nullptr) {
+	module->dropped = true;
+	this->retireScript (module->key);
+    }
+}
+
+void ScriptEngine::restoreHeapLimit () {
+    if (!this->m_heapLimitRaised) {
+	return;
+    }
+
+    this->m_heapLimitRaised = false;
+
+    // whatever the script held goes before the limit is lowered again, V8 keeps it above what is still alive
+    this->m_isolate->LowMemoryNotification ();
+    this->m_isolate->RemoveNearHeapLimitCallback (&ScriptEngine::nearHeapLimit, this->m_heapLimit);
+    this->m_isolate->AddNearHeapLimitCallback (&ScriptEngine::nearHeapLimit, this);
+}
+
 ScriptEngine::Scope::Scope (const ScriptEngine& engine) :
     m_isolateScope (engine.m_isolate), m_handleScope (engine.m_isolate),
     m_contextScope (engine.m_context.Get (engine.m_isolate)) { }
@@ -369,13 +489,28 @@ ScriptEngine::ScriptEngine (Wallpapers::CScene& scene, Media::MediaSource& media
 
     JS::platform ();
 
-    this->m_allocator.reset (v8::ArrayBuffer::Allocator::NewDefaultAllocator ());
+    // WE has no limits, these only catch a script that never comes back or never stops allocating, which would
+    // otherwise freeze the wallpaper or take the whole process down at V8's own heap limit
+    this->m_allocator = makeLimitedAllocator (
+	static_cast<size_t> (envNumber ("LWE_SCRIPT_BUFFER_MB", DEFAULT_BUFFER_LIMIT_MB)) * 1024 * 1024
+    );
+    this->m_callBudget = std::chrono::milliseconds (envNumber ("LWE_SCRIPT_TIMEOUT_MS", DEFAULT_CALL_BUDGET_MS));
+    this->m_heapLimit = static_cast<size_t> (envNumber ("LWE_SCRIPT_HEAP_MB", DEFAULT_HEAP_LIMIT_MB)) * 1024 * 1024;
 
     v8::Isolate::CreateParams params;
     params.array_buffer_allocator = this->m_allocator.get ();
 
+    if (this->m_heapLimit > 0) {
+	params.constraints.set_max_old_generation_size_in_bytes (this->m_heapLimit);
+    }
+
     this->m_isolate = v8::Isolate::New (params);
     this->m_isolate->SetData (0, this);
+    this->m_watchdog = std::make_unique<ScriptWatchdog> (this->m_isolate);
+
+    if (this->m_heapLimit > 0) {
+	this->m_isolate->AddNearHeapLimitCallback (&ScriptEngine::nearHeapLimit, this);
+    }
 
     const v8::Isolate::Scope isolateScope (this->m_isolate);
     const v8::HandleScope handleScope (this->m_isolate);
@@ -426,6 +561,9 @@ ScriptEngine::~ScriptEngine () {
     this->m_unregisterMediaUpdateCallback ();
     this->m_unregisterAlbumArtUpdateCallback ();
 
+    // its thread talks to the isolate
+    this->m_watchdog.reset ();
+
     // every handle has to go before the isolate does
     this->m_scriptModules.clear ();
     this->m_animationLayerEndedCallbacks.clear ();
@@ -493,9 +631,6 @@ void logException (
     v8::Isolate* isolate, v8::Local<v8::Value> exception, v8::Local<v8::Message> message, const char* context,
     const std::optional<std::string>& source
 ) {
-    // scripts that fail every tick would otherwise print the same error every frame
-    static std::map<std::string, std::string> lastReported;
-
     if (exception.IsEmpty ()) {
 	sLog.error ("ScriptEngine [", context, "]: script execution was terminated");
 	return;
@@ -516,13 +651,16 @@ void logException (
 	    + std::to_string (message->GetStartColumn (jsContext).FromMaybe (0) + 1);
     }
 
-    auto& last = lastReported[context];
+    // scripts that fail every tick would otherwise print the same error every frame
+    std::size_t suppressed = 0;
 
-    if (last == text + stack) {
+    if (!ScriptEngine::from (isolate).errorFilter ().admit (context, text + stack, suppressed)) {
 	return;
     }
 
-    last = text + stack;
+    if (suppressed > 0) {
+	sLog.error ("ScriptEngine [", context, "]: ", suppressed, " repeats of earlier errors not shown");
+    }
 
     sLog.error ("ScriptEngine [", context, "]: ", text);
 
@@ -541,6 +679,11 @@ void logException (
 void WallpaperEngine::Scripting::logJSException (
     v8::Isolate* isolate, const v8::TryCatch& tryCatch, const char* context, const std::optional<std::string>& source
 ) {
+    // stopRunaway () reports it, and cancelling the termination leaves nothing in the TryCatch
+    if (!tryCatch.HasCaught () && ScriptEngine::from (isolate).lastCallStopped ()) {
+	return;
+    }
+
     if (!tryCatch.HasCaught ()) {
 	sLog.error ("ScriptEngine [", context, "]: a native call failed without setting an exception");
 	return;
@@ -655,6 +798,7 @@ ScriptLayerHandle ScriptEngine::createLayerScript (
 	<< "  };\n"
 	<< "})();\n";
 
+    const RunLimit limit (*this);
     const v8::TryCatch tryCatch (this->m_isolate);
     v8::ScriptOrigin origin = JS::origin (this->m_isolate, "<layer-script>", false);
     v8::Local<v8::Script> script;
@@ -663,6 +807,7 @@ ScriptLayerHandle ScriptEngine::createLayerScript (
 	&& !script->Run (context).IsEmpty ();
 
     if (!ok) {
+	this->stopRunaway (nullptr, "createLayerScript");
 	logJSException (this->m_isolate, tryCatch, "createLayerScript");
     }
 
@@ -706,11 +851,21 @@ void ScriptEngine::tickLayer (ScriptLayerHandle handle, double time, double delt
     }
 
     const auto callHook = [&] (const char* property, const char* tag) {
+	const RunLimit limit (*this);
 	const v8::TryCatch tryCatch (this->m_isolate);
 	const auto function = JS::get (context, layer, property);
 
 	if (function->IsFunction () && function.As<v8::Function> ()->Call (context, layer, 0, nullptr).IsEmpty ()) {
-	    logJSException (this->m_isolate, tryCatch, tag);
+	    this->stopRunaway (nullptr, tag);
+
+	    if (!this->m_runawayReported) {
+		logJSException (this->m_isolate, tryCatch, tag);
+		return;
+	    }
+
+	    // it would be stopped again every frame
+	    JS::set (context, layer.As<v8::Object> (), "_init", v8::Null (this->m_isolate));
+	    JS::set (context, layer.As<v8::Object> (), "_tick", v8::Null (this->m_isolate));
 	}
     };
 
@@ -749,10 +904,12 @@ void ScriptEngine::destroyLayer (ScriptLayerHandle handle) {
     const auto layer = this->textLayer (handle);
 
     if (layer->IsObject ()) {
+	const RunLimit limit (*this);
 	const v8::TryCatch tryCatch (this->m_isolate);
 	const auto function = JS::get (context, layer, "_destroy");
 
 	if (function->IsFunction () && function.As<v8::Function> ()->Call (context, layer, 0, nullptr).IsEmpty ()) {
+	    this->stopRunaway (nullptr, "layer.destroy");
 	    logJSException (this->m_isolate, tryCatch, "layer.destroy");
 	}
     }
@@ -783,7 +940,14 @@ ScriptEngine::call (const LoadedModule& module, const char* name, int argc, v8::
 	return v8::Undefined (this->m_isolate);
     }
 
-    return function.As<v8::Function> ()->Call (context, exports, argc, argv);
+    const RunLimit limit (*this);
+    const auto result = function.As<v8::Function> ()->Call (context, exports, argc, argv);
+
+    if (result.IsEmpty ()) {
+	this->stopRunaway (&module, name);
+    }
+
+    return result;
 }
 
 void ScriptEngine::retireScript (const std::string& key) { this->m_retiredScriptKeys.push_back (key); }
@@ -833,6 +997,21 @@ void ScriptEngine::dropObjectScripts (const ScriptableObject& object) {
     }
 }
 
+void ScriptEngine::dropModulesSince (const uint64_t mark) {
+    std::set<const ScriptableObject*> owners;
+
+    for (const auto& module : this->m_scriptModules | std::views::values) {
+	if (module.order >= mark && module.object != nullptr) {
+	    owners.insert (module.object);
+	}
+    }
+
+    // the owners are freed already, dropObjectScripts () only compares their addresses
+    for (const auto* owner : owners) {
+	this->dropObjectScripts (*owner);
+    }
+}
+
 bool ScriptEngine::rebindScript (const std::string& key, DynamicValue& newValue) {
     const auto it = this->m_scriptModules.find (key);
 
@@ -848,6 +1027,7 @@ bool ScriptEngine::rebindScript (const std::string& key, DynamicValue& newValue)
 			       .propertyName = it->second.propertyName,
 			       .order = it->second.order,
 			       .key = key };
+    this->m_scriptPropertiesObject->rebind (it->second.value, newValue);
     this->m_scriptModules.erase (it);
     const auto inserted = this->m_scriptModules.emplace (key, std::move (replacement));
     this->m_runningModule = &inserted.first->second;
@@ -855,6 +1035,17 @@ bool ScriptEngine::rebindScript (const std::string& key, DynamicValue& newValue)
     return true;
 }
 
+void ScriptEngine::eraseModule (const std::string& key) {
+    const auto it = this->m_scriptModules.find (key);
+
+    if (it == this->m_scriptModules.end ()) {
+	return;
+    }
+
+    this->m_scriptPropertiesObject->release (it->second.value);
+    this->m_scriptModules.erase (it);
+}
+
 void ScriptEngine::queueScript (
     const std::string& key, DynamicValue& currentValue, ScriptableObject& object, const std::string& propertyName
 ) {
@@ -906,17 +1097,23 @@ void ScriptEngine::queueScript (
     this->bindThisLayer (object, this->m_runningModule);
 
     const auto fail = [&] (v8::Local<v8::Value> exception) {
-	if (tryCatch.HasCaught ()) {
+	if (this->m_runawayReported) {
+	    // stopRunaway () reported it
+	} else if (tryCatch.HasCaught ()) {
 	    logJSException (this->m_isolate, tryCatch, key.c_str (), source);
 	} else {
 	    logException (this->m_isolate, exception, {}, key.c_str (), source);
 	}
 
 	this->m_runningModule = nullptr;
-	this->m_scriptModules.erase (key);
+	this->eraseModule (key);
     };
 
+    // the imports a module names are evaluated while it is instantiated
+    const RunLimit limit (*this);
+
     if (!compiled->InstantiateModule (context, resolveModule).FromMaybe (false)) {
+	this->stopRunaway (nullptr, "import", key);
 	fail ({});
 	return;
     }
@@ -928,6 +1125,10 @@ void ScriptEngine::queueScript (
     const bool evaluated = !compiled->Evaluate (context).IsEmpty ();
     this->m_evaluatingModuleBody = wasEvaluatingModuleBody;
 
+    if (!evaluated) {
+	this->stopRunaway (nullptr, "module body", key);
+    }
+
     // 3378399626's weather widget stores its offsets in shared at the top level from the defaults and only
     // picks the user's location up in applyUserProperties
     this->m_scriptPropertiesObject->deliverValues (currentValue);
@@ -1291,6 +1492,7 @@ void ScriptEngine::dispatchAnimationLayerEnded (const ScriptableObject& owner, s
 	}
 
 	const v8::HandleScope handleScope (this->m_isolate);
+	const RunLimit limit (*this);
 	const v8::TryCatch tryCatch (this->m_isolate);
 	const v8::Local<v8::Function> callback = entry.callback.Get (this->m_isolate);
 
@@ -1300,11 +1502,24 @@ void ScriptEngine::dispatchAnimationLayerEnded (const ScriptableObject& owner, s
 	    this->bindThisLayer (*module->object, module);
 	}
 
-	if (callback->Call (context, v8::Undefined (this->m_isolate), 0, nullptr).IsEmpty ()) {
+	const bool failed = callback->Call (context, v8::Undefined (this->m_isolate), 0, nullptr).IsEmpty ();
+
+	this->m_runningModule = previous;
+
+	if (!failed) {
+	    continue;
+	}
+
+	this->stopRunaway (module, "animation layer ended callback");
+
+	if (!this->m_runawayReported) {
 	    logJSException (this->m_isolate, tryCatch, "animation layer ended callback");
+	    continue;
 	}
 
-	this->m_runningModule = previous;
+	// it would run away again at the next end
+	this->m_animationLayerEndedCallbacks.erase (this->m_animationLayerEndedCallbacks.begin () + index);
+	index--;
     }
 }
 
@@ -1368,9 +1583,14 @@ v8::MaybeLocal<v8::Value> ScriptEngine::callAsModule (const std::string& key, v8
 	}
     }
 
+    const RunLimit limit (*this);
     const auto result = callback->Call (this->getContext (), v8::Undefined (this->m_isolate), 0, nullptr);
     this->m_runningModule = previous;
 
+    if (result.IsEmpty ()) {
+	this->stopRunaway (module, "callback");
+    }
+
     return result;
 }
 
@@ -1440,19 +1660,29 @@ void ScriptEngine::tick () {
 	const v8::HandleScope handleScope (this->m_isolate);
 
 	for (const auto& callback : this->m_adapters.object->takeDueVideoEndedCallbacks ()) {
+	    const RunLimit limit (*this);
 	    const v8::TryCatch tryCatch (this->m_isolate);
 
 	    if (callback->Call (context, v8::Undefined (this->m_isolate), 0, nullptr).IsEmpty ()) {
-		logJSException (this->m_isolate, tryCatch, "video ended callback");
+		this->stopRunaway (nullptr, "video ended callback");
+
+		if (!this->m_runawayReported) {
+		    logJSException (this->m_isolate, tryCatch, "video ended callback");
+		    continue;
+		}
+
+		// it would run away again at the next end
+		this->m_adapters.object->dropVideoEndedCallback (callback);
 	    }
 	}
     }
 
     // safe to erase retired modules now, nothing is mid-iteration and no queueScript() is on the stack
     for (const auto& key : this->m_retiredScriptKeys) {
-	this->m_scriptModules.erase (key);
+	this->eraseModule (key);
     }
     this->m_retiredScriptKeys.clear ();
+    this->restoreHeapLimit ();
 
     // long stalls (window dragged, suspend) shouldn't skip whole animations
     this->m_animations.tick (std::clamp (g_Time - g_TimeLast, 0.0f, 0.25f));
@@ -1500,36 +1730,6 @@ void ScriptEngine::tick () {
 	    continue;
 	}
 
-	if (key.starts_with ("scale_")) {
-	    static int scaleDiagnosticCounter = 0;
-	    if (++scaleDiagnosticCounter >= 300) {
-		scaleDiagnosticCounter = 0;
-		sLog.debug (
-		    "scale script '", key, "': update() returned ",
-		    JS::toString (this->m_isolate, result->TypeOf (this->m_isolate)), ", current vec3 = (",
-		    module.value.getVec3 ().x, ", ", module.value.getVec3 ().y, ", ", module.value.getVec3 ().z, ")"
-		);
-	    }
-
-	    // timestamped pulse marker, to correlate with when the sound played
-	    static std::map<std::string, bool> wasPulsing;
-	    const bool pulsingNow = std::abs (module.value.getVec3 ().x - 1.0f) > 0.03f;
-	    if (pulsingNow && !wasPulsing[key]) {
-		const auto now = std::chrono::system_clock::now ();
-		const auto ms = std::chrono::duration_cast<std::chrono::milliseconds> (now.time_since_epoch ()) % 1000;
-		const std::time_t t = std::chrono::system_clock::to_time_t (now);
-		std::tm tmBuf {};
-		localtime_r (&t, &tmBuf);
-		char buf[16];
-		std::strftime (buf, sizeof (buf), "%H:%M:%S", &tmBuf);
-		sLog.debug (
-		    "[", buf, ".", (ms.count () < 100 ? "0" : ""), (ms.count () < 10 ? "0" : ""), ms.count (),
-		    "] scale script '", key, "': PULSE, vec3.x=", module.value.getVec3 ().x
-		);
-	    }
-	    wasPulsing[key] = pulsingNow;
-	}
-
 	this->assignPropertyJsValue (result, module.value, module.propertyName);
     }
 

+ 47 - 0
src/WallpaperEngine/Scripting/ScriptEngine.h

@@ -4,9 +4,11 @@
 #include "AnimationSystem.h"
 #include "ConsoleObject.h"
 #include "EngineObject.h"
+#include "ErrorRepeatFilter.h"
 #include "InputObject.h"
 #include "LocalStorageObject.h"
 #include "SceneObject.h"
+#include "ScriptWatchdog.h"
 
 #include <chrono>
 #include <filesystem>
@@ -126,6 +128,9 @@ public:
     v8::Local<v8::Context> getContext () const { return m_context.Get (m_isolate); }
     v8::Local<v8::Object> getGlobalThis () const { return this->getContext ()->Global (); }
     LoadedModule* getRunningModule () const { return m_runningModule; }
+    /** Whether the last outermost call into a script was stopped for running too long or using too much memory */
+    bool lastCallStopped () const { return m_runawayReported; }
+    ErrorRepeatFilter& errorFilter () { return m_errorFilter; }
     // true while a module's top level code runs, WE calls that the global scope
     bool isEvaluatingModuleBody () const { return m_evaluatingModuleBody; }
     // true while a module's update() runs
@@ -154,6 +159,12 @@ public:
     /** destroy () (export 3) where present, then dropObjectScripts () */
     void destroyObjectScripts (const ScriptableObject& object);
 
+    /** Where the next queued module will be counted from, for dropModulesSince () */
+    [[nodiscard]] uint64_t moduleMark () const { return this->m_nextModuleOrder; }
+    /** dropObjectScripts () for whatever queued modules since mark, when the object they belong to was never finished:
+     * its constructor threw, so nothing but the modules' pointers to it is left */
+    void dropModulesSince (uint64_t mark);
+
     /** Rebinds an already-running module under key to newValue in place when its script source is identical, so init()
      * does not run twice. Returns false if nothing was rebound */
     bool rebindScript (const std::string& key, DynamicValue& newValue);
@@ -233,6 +244,29 @@ public:
     v8::MaybeLocal<v8::Module> importModule (const std::string& specifier);
 
 private:
+    /**
+     * Gives the JS that runs while it lives a time budget (the outermost one arms the watchdog, a call from a script
+     * into another one shares it). A termination can still be pending when the watchdog fired as a call ended, the
+     * outermost one cancels it once nothing is left to unwind
+     */
+    class RunLimit {
+    public:
+	explicit RunLimit (ScriptEngine& engine);
+	~RunLimit ();
+	RunLimit (const RunLimit&) = delete;
+	RunLimit& operator= (const RunLimit&) = delete;
+
+    private:
+	ScriptEngine& m_engine;
+    };
+
+    /** After a call into JS came back empty: when V8 was terminating it, say why and switch off its module (nullptr for
+     * a call without one, owner then names it in the log) */
+    void stopRunaway (const LoadedModule* culprit, const char* what, std::string_view owner = {});
+    /** Collects what a switched off script left and takes back the heap room it was given to unwind */
+    void restoreHeapLimit ();
+    static size_t nearHeapLimit (void* data, size_t currentLimit, size_t initialLimit);
+
     /** Calls the module's export `name` if it is a function, undefined otherwise. Empty when it threw */
     v8::MaybeLocal<v8::Value>
     call (const LoadedModule& module, const char* name, int argc, v8::Local<v8::Value> argv[]);
@@ -264,6 +298,17 @@ private:
 
     std::unique_ptr<v8::ArrayBuffer::Allocator> m_allocator;
     v8::Isolate* m_isolate = nullptr;
+    // how long one call into a script may run and how much memory its heap may take, 0 is no limit
+    std::chrono::milliseconds m_callBudget;
+    size_t m_heapLimit;
+    std::unique_ptr<ScriptWatchdog> m_watchdog;
+    int m_runDepth = 0;
+    // the call in progress, or the last one, was stopped and reported. Reset when the next outermost call starts
+    bool m_runawayReported = false;
+    ErrorRepeatFilter m_errorFilter;
+    // the heap hit its limit during the call in progress, nearHeapLimit() terminated it
+    bool m_heapExhausted = false;
+    bool m_heapLimitRaised = false;
     v8::Global<v8::Context> m_context;
     // imports by lowercased name
     std::map<std::string, v8::Global<v8::Module>> m_imports;
@@ -275,6 +320,8 @@ private:
     std::unique_ptr<LocalStorageObject> m_localStorageObject;
     std::unique_ptr<ScriptPropertiesObject> m_scriptPropertiesObject;
 
+    /** Erases a module and what its script left in the script properties */
+    void eraseModule (const std::string& key);
     std::map<std::string, LoadedModule> m_scriptModules = {};
     uint64_t m_nextModuleOrder = 0;
     std::vector<std::string> m_retiredScriptKeys = {};

+ 50 - 9
src/WallpaperEngine/Scripting/ScriptPropertiesObject.cpp

@@ -18,7 +18,7 @@ ScriptPropertiesObject& objectOf (const v8::FunctionCallbackInfo<v8::Value>& inf
 // data is [the holder instance, the property name]
 void scriptproperty_get (const v8::FunctionCallbackInfo<v8::Value>& info) {
     auto* isolate = info.GetIsolate ();
-    auto* instance = JS::unwrap<ScriptPropertiesObject::Instance> (JS::dataAt (info, 0));
+    auto* instance = objectOf (info).instanceAt (JS::unwrap<void> (JS::dataAt (info, 0)));
     const std::string name = JS::toString (isolate, JS::dataAt (info, 1));
 
     if (instance == nullptr) {
@@ -31,7 +31,7 @@ void scriptproperty_get (const v8::FunctionCallbackInfo<v8::Value>& info) {
     }
 
     try {
-	const auto& properties = instance->value.getProperties ();
+	const auto& properties = instance->value->getProperties ();
 	if (const auto it = properties.find (name); it != properties.end ()) {
 	    info.GetReturnValue ().Set (ScriptEngine::from (isolate).dynamicToJs (*it->second->value));
 	}
@@ -42,7 +42,7 @@ void scriptproperty_get (const v8::FunctionCallbackInfo<v8::Value>& info) {
 
 void scriptproperty_set (const v8::FunctionCallbackInfo<v8::Value>& info) {
     auto* isolate = info.GetIsolate ();
-    auto* instance = JS::unwrap<ScriptPropertiesObject::Instance> (JS::dataAt (info, 0));
+    auto* instance = objectOf (info).instanceAt (JS::unwrap<void> (JS::dataAt (info, 0)));
 
     if (instance != nullptr && info.Length () > 0) {
 	instance->assigned[JS::toString (isolate, JS::dataAt (info, 1))].Reset (isolate, info[0]);
@@ -96,7 +96,7 @@ void scriptpropertiescreator_finish (const v8::FunctionCallbackInfo<v8::Value>&
 
 	instance.assigned[name].Reset (isolate, value.Get (isolate));
 
-	const auto data = JS::data (isolate, { JS::external (isolate, &instance), JS::string (isolate, name) });
+	const auto data = JS::data (isolate, { JS::external (isolate, instance.handle), JS::string (isolate, name) });
 
 	result->SetAccessorProperty (
 	    JS::name (isolate, name), JS::function (context, scriptproperty_get, data),
@@ -114,7 +114,7 @@ void scriptpropertiescreator_create (const v8::FunctionCallbackInfo<v8::Value>&
 
 void ScriptPropertiesObject::deliverValues (Data::Model::DynamicValue& value) {
     std::erase_if (this->m_undelivered, [&] (Instance* instance) {
-	if (&instance->value != &value) {
+	if (instance->value != &value) {
 	    return false;
 	}
 
@@ -126,9 +126,45 @@ void ScriptPropertiesObject::deliverValues (Data::Model::DynamicValue& value) {
     });
 }
 
+void ScriptPropertiesObject::release (const Data::Model::DynamicValue& value) {
+    std::erase_if (this->m_undelivered, [&] (const Instance* instance) { return instance->value == &value; });
+
+    std::erase_if (this->m_instances, [&] (const std::unique_ptr<Instance>& instance) {
+	if (instance->value != &value) {
+	    return false;
+	}
+
+	this->m_instanceHandles.release (instance->handle);
+	return true;
+    });
+
+    std::erase_if (this->m_creators, [&] (const std::unique_ptr<Creator>& creator) {
+	if (creator->owner != &value) {
+	    return false;
+	}
+
+	this->m_creatorHandles.release (creator->handle);
+	return true;
+    });
+}
+
+void ScriptPropertiesObject::rebind (const Data::Model::DynamicValue& from, Data::Model::DynamicValue& to) {
+    for (const auto& instance : this->m_instances) {
+	if (instance->value == &from) {
+	    instance->value = &to;
+	}
+    }
+
+    for (const auto& creator : this->m_creators) {
+	if (creator->owner == &from) {
+	    creator->owner = &to;
+	}
+    }
+}
+
 void ScriptPropertiesObject::userPropertiesChanged (const std::vector<std::string>& names) {
     for (const auto& instance : this->m_instances) {
-	for (const auto& [name, setting] : instance->value.getProperties ()) {
+	for (const auto& [name, setting] : instance->value->getProperties ()) {
 	    if (setting != nullptr && setting->property != nullptr
 		&& std::ranges::find (names, setting->property->name) != names.end ()) {
 		instance->assigned.erase (name);
@@ -172,10 +208,14 @@ v8::Local<v8::Object> ScriptPropertiesObject::newCreator () {
     auto* isolate = this->m_engine.getIsolate ();
     const auto context = this->m_engine.getContext ();
     const v8::Local<v8::Object> creator = v8::Object::New (isolate);
+    const auto* module = this->m_engine.getRunningModule ();
     auto& state = *this->m_creators.emplace_back (std::make_unique<Creator> ());
 
+    state.owner = module == nullptr ? nullptr : &module->value;
+    state.handle = this->m_creatorHandles.insert (&state);
+
     JS::setPrototype (context, creator, this->m_creatorPrototype.Get (isolate));
-    creator->SetPrivate (context, this->m_creatorKey.Get (isolate), JS::external (isolate, &state)).Check ();
+    creator->SetPrivate (context, this->m_creatorKey.Get (isolate), JS::external (isolate, state.handle)).Check ();
 
     return creator;
 }
@@ -194,12 +234,13 @@ ScriptPropertiesObject::Creator* ScriptPropertiesObject::creatorOf (v8::Local<v8
 	return nullptr;
     }
 
-    return JS::unwrap<Creator> (state);
+    return this->m_creatorHandles.find (JS::unwrap<void> (state));
 }
 
 ScriptPropertiesObject::Instance& ScriptPropertiesObject::newInstance (Data::Model::DynamicValue& value) {
-    auto& instance = *this->m_instances.emplace_back (std::make_unique<Instance> (Instance { .value = value }));
+    auto& instance = *this->m_instances.emplace_back (std::make_unique<Instance> (Instance { .value = &value }));
 
+    instance.handle = this->m_instanceHandles.insert (&instance);
     this->m_undelivered.push_back (&instance);
 
     return instance;

+ 19 - 3
src/WallpaperEngine/Scripting/ScriptPropertiesObject.h

@@ -3,6 +3,8 @@
 #include <v8-local-handle.h>
 #include <v8-persistent-handle.h>
 
+#include "HandleTable.h"
+
 #include <map>
 #include <memory>
 #include <string>
@@ -28,13 +30,17 @@ public:
      *  scene's scriptproperties don't set a name */
     struct Creator {
 	std::vector<std::pair<std::string, v8::Global<v8::Value>>> defaults;
+	/** The script value that was running when it was made, nullptr for the global scope */
+	const Data::Model::DynamicValue* owner = nullptr;
+	void* handle = nullptr;
     };
 
     /** Behind the object finish () returns */
     struct Instance {
-	Data::Model::DynamicValue& value;
+	Data::Model::DynamicValue* value;
 	/** add*() defaults and values a script assigned, WE's scriptProperties is a plain object that keeps them */
 	std::map<std::string, v8::Global<v8::Value>> assigned;
+	void* handle = nullptr;
     };
 
     ScriptPropertiesObject (ScriptEngine& engine, Render::Wallpapers::CScene& scene);
@@ -49,18 +55,28 @@ public:
     void userPropertiesChanged (const std::vector<std::string>& names);
 
     v8::Local<v8::Object> newCreator ();
-    /** The creator a JS object stands for, nullptr for anything else */
+    /** The creator a JS object stands for, nullptr for anything else or one whose script is gone */
     Creator* creatorOf (v8::Local<v8::Value> value);
     Instance& newInstance (Data::Model::DynamicValue& value);
+    /** The instance behind a handle of an accessor, nullptr once its script is gone */
+    [[nodiscard]] Instance* instanceAt (void* handle) const { return m_instanceHandles.find (handle); }
+
+    /** The script of this value is going away: its creators and instances are freed, the JS objects that still hold
+     * their handles find nothing */
+    void release (const Data::Model::DynamicValue& value);
+    /** The script goes on with another value */
+    void rebind (const Data::Model::DynamicValue& from, Data::Model::DynamicValue& to);
 
 protected:
     Render::Wallpapers::CScene& m_scene;
     ScriptEngine& m_engine;
 
-    // they live as long as the script context, a handful per script
+    // they live as long as their script
     std::vector<std::unique_ptr<Creator>> m_creators;
     std::vector<std::unique_ptr<Instance>> m_instances;
     std::vector<Instance*> m_undelivered;
+    HandleTable<Creator> m_creatorHandles;
+    HandleTable<Instance> m_instanceHandles;
 
     v8::Global<v8::Object> m_creatorPrototype;
     v8::Global<v8::Private> m_creatorKey;

+ 65 - 0
src/WallpaperEngine/Scripting/ScriptWatchdog.cpp

@@ -0,0 +1,65 @@
+#include "ScriptWatchdog.h"
+
+#include "WallpaperEngine/Logging/ThreadGuard.h"
+
+using namespace WallpaperEngine::Scripting;
+
+namespace {
+// how late a runaway script is noticed at the most, on top of its budget
+constexpr std::chrono::milliseconds PollInterval { 100 };
+} // namespace
+
+ScriptWatchdog::ScriptWatchdog (v8::Isolate* isolate) : m_isolate (isolate) {
+    this->m_thread
+	= std::thread ([this] { WallpaperEngine::Logging::guardThread ("Script watchdog", [this] { this->run (); }); });
+}
+
+ScriptWatchdog::~ScriptWatchdog () {
+    {
+	const std::lock_guard lock (this->m_mutex);
+	this->m_stop = true;
+    }
+
+    this->m_wake.notify_all ();
+    this->m_thread.join ();
+}
+
+void ScriptWatchdog::begin (const std::chrono::milliseconds budget) {
+    const std::lock_guard lock (this->m_mutex);
+
+    this->m_deadline = std::chrono::steady_clock::now () + budget;
+    this->m_armed = true;
+    this->m_fired = false;
+}
+
+bool ScriptWatchdog::fired () {
+    const std::lock_guard lock (this->m_mutex);
+
+    return this->m_fired;
+}
+
+bool ScriptWatchdog::end () {
+    const std::lock_guard lock (this->m_mutex);
+    const bool fired = this->m_fired;
+
+    this->m_armed = false;
+    this->m_fired = false;
+
+    return fired;
+}
+
+void ScriptWatchdog::run () {
+    std::unique_lock lock (this->m_mutex);
+
+    while (!this->m_stop) {
+	this->m_wake.wait_for (lock, PollInterval, [this] { return this->m_stop; });
+
+	// decided and done under the lock: a call that just ended (end ()) or began again can't be hit by a stale
+	// decision
+	if (this->m_armed && std::chrono::steady_clock::now () >= this->m_deadline) {
+	    this->m_armed = false;
+	    this->m_fired = true;
+	    this->m_isolate->TerminateExecution ();
+	}
+    }
+}

+ 43 - 0
src/WallpaperEngine/Scripting/ScriptWatchdog.h

@@ -0,0 +1,43 @@
+#pragma once
+
+#include <chrono>
+#include <condition_variable>
+#include <mutex>
+#include <thread>
+
+#include <v8-isolate.h>
+
+namespace WallpaperEngine::Scripting {
+/**
+ * Stops script code that runs too long. begin () sets a deadline for one call into a script, end () clears it, and a
+ * thread looks at it a few times a second: past the deadline it calls the isolate's TerminateExecution, which unwinds
+ * whatever the script is doing (a script can't catch it) and leaves the embedder to resume with
+ * CancelTerminateExecution. Polling keeps begin () and end () to a lock and a clock read, they run for every update ()
+ * of every script every frame.
+ */
+class ScriptWatchdog {
+public:
+    explicit ScriptWatchdog (v8::Isolate* isolate);
+    ~ScriptWatchdog ();
+    ScriptWatchdog (const ScriptWatchdog&) = delete;
+    ScriptWatchdog& operator= (const ScriptWatchdog&) = delete;
+
+    void begin (std::chrono::milliseconds budget);
+    /** Whether the thread terminated what ran since begin (), without ending the call */
+    bool fired ();
+    /** Whether the thread terminated what ran since begin () */
+    bool end ();
+
+private:
+    void run ();
+
+    v8::Isolate* m_isolate;
+    std::mutex m_mutex;
+    std::condition_variable m_wake;
+    std::chrono::steady_clock::time_point m_deadline {};
+    bool m_armed = false;
+    bool m_fired = false;
+    bool m_stop = false;
+    std::thread m_thread;
+};
+} // namespace WallpaperEngine::Scripting

+ 12 - 10
src/WallpaperEngine/Scripting/ScriptableObject.cpp

@@ -37,16 +37,6 @@ void ScriptableObject::registerRenderableProperties (
     this->registerProperty ("castshadow", *renderable.castShadow->value);
 }
 
-DynamicValue& ScriptableObject::getProperty (const std::string& name) {
-    const auto it = this->m_properties.find (name);
-
-    if (it == this->m_properties.end ()) {
-	sLog.exception ("Property '" + name + "' not found on object '" + this->getObject ().name + "'");
-    }
-
-    return it->second.value;
-}
-
 DynamicValue* ScriptableObject::tryGetProperty (const std::string& name) {
     const auto it = this->m_properties.find (name);
 
@@ -92,6 +82,8 @@ void ScriptableObject::registerProperty (
 	    return;
 	}
 
+	this->m_replacedValues.push_back (&existing->second.value);
+
 	this->getScene ().getScriptEngine ().getAnimations ().remove (existing->second.value);
 
 	// the derived class parses the same key as the base's group* fallback, so this may queue the same script again;
@@ -128,6 +120,16 @@ void ScriptableObject::registerProperty (
     );
 }
 
+void ScriptableObject::dropScriptSources () {
+    for (auto& entry : this->m_properties) {
+	entry.second.value.clearScriptSource ();
+    }
+
+    for (auto* value : this->m_replacedValues) {
+	value->clearScriptSource ();
+    }
+}
+
 namespace {
 std::string animationLayerPrefix (size_t serial) { return "animationlayers[" + std::to_string (serial) + "]."; }
 }

+ 6 - 1
src/WallpaperEngine/Scripting/ScriptableObject.h

@@ -17,7 +17,6 @@ public:
     ScriptableObject (Wallpapers::CScene& scene, const Object& object);
     virtual ~ScriptableObject () = default;
 
-    DynamicValue& getProperty (const std::string& name);
     // nullptr instead of logging and throwing, scripts probe unbacked properties (horizontalalign, size, ...)
     DynamicValue* tryGetProperty (const std::string& name);
 
@@ -38,6 +37,10 @@ public:
     /** before its settings go away */
     void unregisterAnimationLayerProperties (size_t serial);
 
+    /** Frees the script text of every registered property, for an object that is being deleted: its modules are gone,
+     * the model the values live in stays */
+    void dropScriptSources ();
+
 protected:
     void registerProperty (
 	const std::string& name, DynamicValue& value, const std::string& animationGroup = {},
@@ -53,5 +56,7 @@ protected:
 private:
     Playback m_playback = Playback::Playing;
     std::map<std::string, PropertyEntry> m_properties;
+    // values a later registration of the same name replaced, their script text goes with the rest in dropScriptSources
+    std::vector<DynamicValue*> m_replacedValues;
 };
 }

+ 7 - 0
src/WallpaperEngine/Splat/SogLoader.cpp

@@ -91,6 +91,13 @@ DecodedImage decodeWebP (const std::string& bytes) {
 	throw std::runtime_error ("Cannot decode a WebP image");
     }
 
+    // 4096 x 4096 texels, a few million splats; real ones are 1088 x 1088. Every texel costs 48 bytes of cloud arrays
+    constexpr int64_t maxTexels = 16 * 1024 * 1024;
+
+    if (frame->width <= 0 || frame->height <= 0 || static_cast<int64_t> (frame->width) * frame->height > maxTexels) {
+	throw std::runtime_error ("A SOG image is bigger than 4096 x 4096");
+    }
+
     DecodedImage image;
     image.width = frame->width;
     image.height = frame->height;

+ 21 - 0
src/WallpaperEngine/Testing/Cases/AuthoringJson.cpp

@@ -82,3 +82,24 @@ TEST_CASE ("Materials load from asset JSON, a broken one becomes WE's error pass
     REQUIRE (fallback->passes.size () == 1);
     CHECK (fallback->passes[0]->shader == "error");
 }
+
+TEST_CASE ("A value of the wrong type counts as missing instead of ending the process") {
+    const auto value = JSON::parse (
+	R"({ "flag": 1, "name": 7, "count": "12", "ratio": "x", "nested": { "a": 1 }, "ok": true, "five": 5 })"
+    );
+
+    CHECK_FALSE (value.optional ("flag", false));
+    CHECK (value.optional ("flag", true));
+    CHECK (value.optional ("name", std::string ("fallback")) == "fallback");
+    CHECK (value.optional ("count", 3) == 3);
+    CHECK (value.optional ("ratio", 0.5f) == 0.5f);
+    CHECK (value.optional ("nested", std::string ("n")) == "n");
+    CHECK_FALSE (value.optional<bool> ("flag").has_value ());
+    CHECK_FALSE (value.optional<std::string> ("name").has_value ());
+
+    // what does convert still does
+    CHECK (value.optional ("ok", false));
+    CHECK (value.optional ("five", 0.0f) == 5.0f);
+    CHECK (value.optional<int> ("five").value () == 5);
+    CHECK (value.optional ("missing", 9) == 9);
+}

+ 46 - 0
src/WallpaperEngine/Testing/Cases/ControlFileOwner.cpp

@@ -0,0 +1,46 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <filesystem>
+#include <fstream>
+#include <string>
+#include <unistd.h>
+
+#include "WallpaperEngine/Application/ControlFileOwner.h"
+
+using WallpaperEngine::Application::belongsToAnotherUser;
+
+TEST_CASE ("A control file of another user is recognised") {
+    const auto directory = std::filesystem::temp_directory_path () / ("lwe-owner-test-" + std::to_string (getpid ()));
+    std::filesystem::create_directories (directory);
+    const auto mine = directory / "mine";
+    std::ofstream (mine) << "path=/x\n";
+
+    CHECK_FALSE (belongsToAnotherUser (mine, geteuid ()));
+    CHECK (belongsToAnotherUser (mine, geteuid () + 1));
+    CHECK_FALSE (belongsToAnotherUser (directory / "missing", geteuid ()));
+
+    std::filesystem::remove_all (directory);
+}
+
+TEST_CASE ("Files that really belong to someone else are refused") {
+    if (geteuid () == 0) {
+	SKIP ("root owns /etc/passwd");
+    }
+
+    CHECK (belongsToAnotherUser ("/etc/passwd", geteuid ()));
+}
+
+TEST_CASE ("A link counts by its own owner, not by its target's") {
+    if (geteuid () == 0) {
+	SKIP ("root owns /etc/passwd");
+    }
+
+    const auto directory = std::filesystem::temp_directory_path () / ("lwe-owner-link-" + std::to_string (getpid ()));
+    std::filesystem::create_directories (directory);
+    const auto link = directory / "link";
+    std::filesystem::create_symlink ("/etc/passwd", link);
+
+    CHECK_FALSE (belongsToAnotherUser (link, geteuid ()));
+
+    std::filesystem::remove_all (directory);
+}

+ 30 - 0
src/WallpaperEngine/Testing/Cases/DirectoryAdapter.cpp

@@ -0,0 +1,30 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <filesystem>
+#include <fstream>
+#include <string>
+#include <unistd.h>
+
+#include "WallpaperEngine/FileSystem/Adapters/Directory.h"
+
+using WallpaperEngine::FileSystem::Adapters::DirectoryAdapter;
+
+TEST_CASE ("A directory adapter does not reach into a sibling that shares its name as a prefix") {
+    const auto root = std::filesystem::canonical (std::filesystem::temp_directory_path ())
+	/ ("lwe-dir-test-" + std::to_string (getpid ()));
+    std::filesystem::create_directories (root / "pack/sub");
+    std::filesystem::create_directories (root / "pack-secret");
+    std::ofstream (root / "pack/sub/inside.txt") << "inside";
+    std::ofstream (root / "pack-secret/outside.txt") << "outside";
+
+    const DirectoryAdapter adapter (root / "pack");
+
+    CHECK (adapter.exists ("sub/inside.txt"));
+    CHECK_FALSE (adapter.exists ("../pack-secret/outside.txt"));
+    CHECK_FALSE (adapter.exists ((root / "pack-secret/outside.txt").string ()));
+    CHECK_THROWS (adapter.open ("../pack-secret/outside.txt"));
+    CHECK_THROWS (adapter.physicalPath ("../pack-secret/outside.txt"));
+    CHECK_NOTHROW (adapter.physicalPath ("sub/inside.txt"));
+
+    std::filesystem::remove_all (root);
+}

+ 54 - 0
src/WallpaperEngine/Testing/Cases/ErrorRepeatFilter.cpp

@@ -0,0 +1,54 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <string>
+
+#include "WallpaperEngine/Scripting/ErrorRepeatFilter.h"
+
+using WallpaperEngine::Scripting::ErrorRepeatFilter;
+
+TEST_CASE ("A script failing the same way every frame is reported once") {
+    ErrorRepeatFilter filter;
+    std::size_t suppressed = 99;
+
+    CHECK (filter.admit ("script", "TypeError: x", suppressed));
+    CHECK (suppressed == 0);
+
+    for (int frame = 0; frame < 100; frame++) {
+	CHECK_FALSE (filter.admit ("script", "TypeError: x", suppressed));
+    }
+
+    CHECK (filter.admit ("script", "RangeError: y", suppressed));
+    CHECK (suppressed == 100);
+}
+
+TEST_CASE ("A script alternating between two errors is not reported every frame") {
+    ErrorRepeatFilter filter;
+    std::size_t suppressed = 0;
+    int reported = 0;
+
+    for (int frame = 0; frame < 50; frame++) {
+	reported += filter.admit ("script", frame % 2 == 0 ? "a" : "b", suppressed) ? 1 : 0;
+    }
+
+    CHECK (reported == 2);
+}
+
+TEST_CASE ("Scripts are told apart and memory stays bounded") {
+    ErrorRepeatFilter filter;
+    std::size_t suppressed = 0;
+
+    CHECK (filter.admit ("one", "same", suppressed));
+    CHECK (filter.admit ("two", "same", suppressed));
+    CHECK_FALSE (filter.admit ("one", "same", suppressed));
+
+    for (std::size_t i = 0; i < ErrorRepeatFilter::REMEMBERED_PER_SCRIPT * 3; i++) {
+	CHECK (filter.admit ("one", "error " + std::to_string (i), suppressed));
+    }
+
+    // the oldest ones fell out of the window
+    CHECK (filter.admit ("one", "same", suppressed));
+
+    for (std::size_t i = 0; i < ErrorRepeatFilter::MAX_SCRIPTS * 2; i++) {
+	CHECK (filter.admit ("script " + std::to_string (i), "e", suppressed));
+    }
+}

+ 87 - 0
src/WallpaperEngine/Testing/Cases/HandleTable.cpp

@@ -0,0 +1,87 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <cstdint>
+#include <set>
+#include <vector>
+
+#include "WallpaperEngine/Scripting/HandleTable.h"
+
+using WallpaperEngine::Scripting::HandleTable;
+
+TEST_CASE ("A handle finds its record until the record is released") {
+    HandleTable<int> table;
+    int first = 1;
+    int second = 2;
+
+    void* a = table.insert (&first);
+    void* b = table.insert (&second);
+
+    CHECK (a != nullptr);
+    CHECK (a != b);
+    CHECK (table.find (a) == &first);
+    CHECK (table.find (b) == &second);
+    CHECK (table.live () == 2);
+
+    table.release (a);
+
+    CHECK (table.find (a) == nullptr);
+    CHECK (table.find (b) == &second);
+    CHECK (table.live () == 1);
+
+    table.release (a);
+    CHECK (table.live () == 1);
+}
+
+TEST_CASE ("Nothing but an issued handle finds a record") {
+    HandleTable<int> table;
+    int value = 1;
+    void* handle = table.insert (&value);
+
+    CHECK (table.find (nullptr) == nullptr);
+    CHECK (table.find (&value) == nullptr);
+    CHECK (table.find (reinterpret_cast<void*> (static_cast<uintptr_t> (0xFFFFFFFFFFFFull))) == nullptr);
+    CHECK (table.find (reinterpret_cast<void*> (reinterpret_cast<uintptr_t> (handle) + (1ull << 24))) == nullptr);
+    CHECK (table.find (reinterpret_cast<void*> (reinterpret_cast<uintptr_t> (handle) + 1)) == nullptr);
+}
+
+TEST_CASE ("A released slot is used again later and the old handle stays stale") {
+    HandleTable<int> table;
+    std::vector<int> values (500);
+    std::vector<void*> handles;
+
+    for (auto& value : values) {
+	handles.push_back (table.insert (&value));
+    }
+
+    void* stale = handles[0];
+    table.release (stale);
+
+    int replacement = 7;
+    std::set<uintptr_t> seen;
+
+    for (int i = 0; i < 2000; i++) {
+	void* handle = table.insert (&replacement);
+	CHECK (table.find (stale) == nullptr);
+	CHECK (table.find (handle) == &replacement);
+	seen.insert (reinterpret_cast<uintptr_t> (handle) & 0xFFFFFF);
+	table.release (handle);
+    }
+
+    CHECK (seen.size () > 1);
+    CHECK (table.find (handles[1]) == &values[1]);
+}
+
+TEST_CASE ("Handles stay below 2^47 and nonzero however often a slot is reused") {
+    HandleTable<int> table;
+    int value = 1;
+
+    for (int i = 0; i < 300000; i++) {
+	void* handle = table.insert (&value);
+	REQUIRE (reinterpret_cast<uintptr_t> (handle) != 0);
+	REQUIRE (reinterpret_cast<uintptr_t> (handle) < (1ull << 47));
+	REQUIRE (table.find (handle) == &value);
+	table.release (handle);
+    }
+
+    CHECK (table.live () == 0);
+}

+ 125 - 0
src/WallpaperEngine/Testing/Cases/KWinScriptFiles.cpp

@@ -0,0 +1,125 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <algorithm>
+#include <chrono>
+#include <filesystem>
+#include <fstream>
+#include <string>
+
+#include <cerrno>
+#include <csignal>
+#include <fcntl.h>
+#include <sys/file.h>
+#include <unistd.h>
+
+#include "WallpaperEngine/Desktop/KWinScript.h"
+
+using WallpaperEngine::Desktop::KWinScript;
+using namespace std::chrono_literals;
+
+namespace {
+struct Directory {
+    std::filesystem::path path;
+
+    Directory () {
+	path = std::filesystem::temp_directory_path () / ("lwe-kwin-test-" + std::to_string (getpid ()));
+	std::filesystem::create_directories (path);
+    }
+
+    ~Directory () { std::filesystem::remove_all (path); }
+
+    std::filesystem::path make (const std::string& name, std::chrono::seconds age = 60s) const {
+	const auto file = path / name;
+
+	std::ofstream (file) << "// script\n";
+	std::filesystem::last_write_time (file, std::filesystem::file_time_type::clock::now () - age);
+
+	return file;
+    }
+};
+
+// a pid nothing runs under: engines' file names end in one, and the sweep spares a script whose pid is alive
+std::string deadPid (int offset = 0) {
+    for (int pid = 4000000 - offset; pid > 1000; pid--) {
+	if (kill (pid, 0) != 0 && errno == ESRCH) {
+	    return std::to_string (pid);
+	}
+    }
+
+    FAIL ("no free pid");
+    return {};
+}
+
+bool contains (const std::vector<std::string>& names, const std::string& name) {
+    return std::ranges::find (names, name) != names.end ();
+}
+} // namespace
+
+TEST_CASE ("A script file nobody holds belongs to an engine that is gone") {
+    const Directory dir;
+
+    const auto pid = deadPid ();
+
+    dir.make ("lwe-cursor-input-" + pid + ".js");
+    dir.make ("lwe-window-states-" + pid + ".js");
+
+    const auto stale = KWinScript::findStale (dir.path);
+
+    CHECK (stale.size () == 2);
+    CHECK (contains (stale, "lwe-cursor-input-" + pid));
+    CHECK (contains (stale, "lwe-window-states-" + pid));
+}
+
+TEST_CASE ("A script file a running engine holds is left alone") {
+    const Directory dir;
+    const auto pid = deadPid ();
+    const auto held = dir.make ("lwe-cursor-input-" + pid + ".js");
+
+    // what KWinScript does for as long as the engine lives
+    const int lock = open (held.c_str (), O_RDONLY);
+    REQUIRE (lock >= 0);
+    REQUIRE (flock (lock, LOCK_SH) == 0);
+
+    CHECK_FALSE (contains (KWinScript::findStale (dir.path), "lwe-cursor-input-" + pid));
+
+    // the engine ends, however it does
+    close (lock);
+
+    CHECK (contains (KWinScript::findStale (dir.path), "lwe-cursor-input-" + pid));
+}
+
+TEST_CASE ("A file an engine is still starting up with is not taken for stale") {
+    const Directory dir;
+
+    const auto pid = deadPid ();
+
+    dir.make ("lwe-cursor-input-" + pid + ".js", 0s);
+
+    CHECK (KWinScript::findStale (dir.path, 2s).empty ());
+    CHECK (contains (KWinScript::findStale (dir.path, 0s), "lwe-cursor-input-" + pid));
+}
+
+TEST_CASE ("The script of an older engine that still runs is left alone") {
+    const Directory dir;
+
+    // no lock to be seen, the pid is what says it lives (this process stands in for it)
+    dir.make ("lwe-cursor-input-" + std::to_string (getpid ()) + ".js");
+
+    CHECK (KWinScript::findStale (dir.path).empty ());
+
+    // a Flatpak's tag is not a pid and falls back on the lock alone
+    dir.make ("lwe-window-states-abc123_" + std::to_string (getpid ()) + ".js");
+
+    CHECK (contains (KWinScript::findStale (dir.path), "lwe-window-states-abc123_" + std::to_string (getpid ())));
+}
+
+TEST_CASE ("Only the engine's own script files count") {
+    const Directory dir;
+
+    dir.make ("other-script.js");
+    dir.make ("lwe-cursor-input-9.txt");
+    std::filesystem::create_directories (dir.path / "lwe-folder.js");
+
+    CHECK (KWinScript::findStale (dir.path).empty ());
+    CHECK (KWinScript::findStale (dir.path / "missing").empty ());
+}

+ 84 - 0
src/WallpaperEngine/Testing/Cases/NumericGuards.cpp

@@ -0,0 +1,84 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <memory>
+#include <stdexcept>
+#include <string>
+
+#include "WallpaperEngine/Assets/AssetLocator.h"
+#include "WallpaperEngine/Data/Model/Project.h"
+#include "WallpaperEngine/Data/Model/Wallpaper.h"
+#include "WallpaperEngine/Data/Parsers/WallpaperParser.h"
+#include "WallpaperEngine/Data/Utils/FiniteFloat.h"
+#include "WallpaperEngine/FileSystem/Container.h"
+
+using namespace WallpaperEngine;
+using namespace WallpaperEngine::Data::Utils;
+
+TEST_CASE ("Typed numbers are finite") {
+    CHECK (parseFiniteFloat ("1.5") == 1.5f);
+    CHECK (parseFiniteFloat ("-0.25") == -0.25f);
+    CHECK (parseFiniteFloat ("2e3") == 2000.0f);
+
+    // each of these parses with stof and then passes every range check, because comparisons with NaN are false
+    for (const std::string text : { "nan", "NaN", "-nan", "inf", "-inf", "infinity" }) {
+	INFO (text);
+	CHECK_THROWS_AS (parseFiniteFloat (text), std::invalid_argument);
+    }
+
+    CHECK_THROWS_AS (parseFiniteFloat ("zoom"), std::invalid_argument);
+    CHECK_THROWS_AS (parseFiniteFloat (""), std::invalid_argument);
+    CHECK_THROWS_AS (parseFiniteFloat ("1e999"), std::out_of_range);
+}
+
+namespace {
+Data::Model::WallpaperUniquePtr sceneWith (const std::string& projection) {
+    auto container = std::make_unique<FileSystem::Container> ();
+    container->getVFS ().add (
+	"scene.json",
+	R"({ "camera": { "center": "0 0 -1", "eye": "0 0 0", "up": "0 1 0" },
+	     "general": { "orthogonalprojection": )"
+	    + projection + R"( },
+	     "objects": [] })"
+    );
+
+    Data::Model::Project project {};
+    project.type = Data::Model::Project::Type_Scene;
+    project.assetLocator = std::make_unique<Assets::AssetLocator> (std::move (container));
+
+    return Data::Parsers::WallpaperParser::parse (Data::JSON::JSON ("scene.json"), project);
+}
+} // namespace
+
+TEST_CASE ("A scene is orthographic only with a usable projection, like in WE") {
+    const auto sized = sceneWith (R"({ "width": 1920, "height": 1080 })");
+
+    CHECK (sized->as<Data::Model::Scene> ()->camera.projection.width == 1920);
+    CHECK (sized->as<Data::Model::Scene> ()->camera.projection.height == 1080);
+    CHECK_FALSE (sized->as<Data::Model::Scene> ()->camera.projection.isPerspective);
+
+    // sized from its content: no numbers needed
+    const auto automatic = sceneWith (R"({ "auto": true })");
+    CHECK (automatic->as<Data::Model::Scene> ()->camera.projection.isAuto);
+    CHECK_FALSE (automatic->as<Data::Model::Scene> ()->camera.projection.isPerspective);
+
+    // sub_140186C90 sets the orthographic flag for nothing else: a canvas of no size, a size that isn't a pair of
+    // numbers, "auto" that isn't a real true, and a member that isn't an object all leave a perspective scene that
+    // loads
+    for (const std::string projection :
+	 { R"({ "width": 0, "height": 1080 })", R"({ "width": 1920, "height": 0 })",
+	   R"({ "width": 0.4, "height": 1080 })", R"({ "width": "1920", "height": 1080 })",
+	   R"({ "width": 1920, "height": null })", R"({ "width": 1920 })", R"({ "width": true, "height": true })",
+	   R"({ "auto": 1 })", R"({ "auto": "true", "width": "x" })", R"({})", "null", "7", R"("1920x1080")", "[]",
+	   "[1920, 1080]", "true" }) {
+	INFO (projection);
+	const auto scene = sceneWith (projection);
+
+	CHECK (scene->as<Data::Model::Scene> ()->camera.projection.isPerspective);
+	CHECK (scene->as<Data::Model::Scene> ()->camera.projection.width == 0);
+	CHECK (scene->as<Data::Model::Scene> ()->camera.projection.height == 0);
+    }
+
+    // a negative size is the one case WE draws nonsense from and we have nothing to match
+    CHECK_THROWS (sceneWith (R"({ "width": -1920, "height": 1080 })"));
+    CHECK_THROWS (sceneWith (R"({ "width": 1920, "height": -1 })"));
+}

+ 17 - 0
src/WallpaperEngine/Testing/Cases/PropertyParser.cpp

@@ -49,6 +49,23 @@ TEST_CASE ("Directory properties remember they are directories and what file typ
     CHECK (asFile->getFileType ().empty ());
 }
 
+TEST_CASE ("File and directory properties drop an absolute default, only the user points them at the disk") {
+    const auto root
+	= PropertyParser::parse (JSON { { "type", "directory" }, { "text", "Root" }, { "value", "/" } }, "root");
+    const auto file
+	= PropertyParser::parse (JSON { { "type", "file" }, { "text", "Image" }, { "value", "/etc/passwd" } }, "image");
+    const auto relative = PropertyParser::parse (
+	JSON { { "type", "file" }, { "text", "Image" }, { "value", "images/a.png" } }, "bundled"
+    );
+
+    REQUIRE (root != nullptr);
+    REQUIRE (file != nullptr);
+    REQUIRE (relative != nullptr);
+    CHECK (root->getString ().empty ());
+    CHECK (file->getString ().empty ());
+    CHECK (relative->getString () == "images/a.png");
+}
+
 TEST_CASE ("UI-only description lines with made up types are parsed as plain text") {
     for (const char* type : { "txt", "test", "label" }) {
 	const JSON propertyData = {

+ 43 - 0
src/WallpaperEngine/Testing/Cases/PuppetMeshFile.cpp

@@ -3,7 +3,9 @@
 #include <algorithm>
 #include <array>
 #include <bit>
+#include <chrono>
 #include <cstdint>
+#include <cstring>
 #include <optional>
 #include <string>
 #include <vector>
@@ -347,6 +349,47 @@ TEST_CASE ("Broken puppet meshes are refused without throwing") {
     }
 }
 
+TEST_CASE ("A header that declares more index bytes than the file holds is refused") {
+    auto bytes = puppet ().bytes;
+    const auto good = puppet ();
+
+    // the index byte count sits right before the three indices
+    const size_t countAt = good.indexEnd - 3 * sizeof (uint16_t) - sizeof (uint32_t);
+    uint32_t declared = 0;
+    std::memcpy (&declared, bytes.data () + countAt, sizeof (declared));
+    REQUIRE (declared == 3 * sizeof (uint16_t));
+
+    // about 2.9 GB of indices in a few hundred bytes used to be reserved before anything was read
+    const uint32_t huge = 0xAFB8C39A;
+    std::memcpy (bytes.data () + countAt, &huge, sizeof (huge));
+
+    CHECK_NOTHROW (readPuppetMeshFile (bytes));
+    CHECK_FALSE (readPuppetMeshFile (bytes).has_value ());
+}
+
+TEST_CASE ("The stride search of a damaged file gives up instead of trying every offset") {
+    // no readable header, and every word says 600000 bytes: each offset looks like a mesh that fits a dozen strides
+    // (a truncated 33 MB model ran for minutes)
+    std::vector<char> bytes (8 * 1024 * 1024);
+    const std::string tag ("MDLV0013");
+
+    std::copy (tag.begin (), tag.end (), bytes.begin ());
+
+    for (size_t offset = tag.size () + 1; offset + sizeof (uint32_t) <= bytes.size (); offset += sizeof (uint32_t)) {
+	const uint32_t word = 600000;
+	std::memcpy (bytes.data () + offset, &word, sizeof (word));
+    }
+
+    const auto start = std::chrono::steady_clock::now ();
+
+    CHECK_NOTHROW (readPuppetMeshFile (bytes));
+
+    const auto seconds = std::chrono::duration<double> (std::chrono::steady_clock::now () - start).count ();
+
+    INFO ("took " << seconds << " s");
+    CHECK (seconds < 20.0);
+}
+
 TEST_CASE ("Bad optional puppet data leaves the plain mesh") {
     // an auxiliary block shorter than one vec3 per vertex is dropped with a warning
     const auto shortAux = puppet ({ .version = 21, .auxBytes = 12 });

+ 189 - 0
src/WallpaperEngine/Testing/Cases/ReaderLimits.cpp

@@ -0,0 +1,189 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <cstdint>
+#include <cstring>
+#include <filesystem>
+#include <memory>
+#include <sstream>
+#include <string>
+
+#include "WallpaperEngine/Data/Parsers/PackageParser.h"
+#include "WallpaperEngine/Data/Parsers/TextureParser.h"
+#include "WallpaperEngine/Data/Utils/BinaryReader.h"
+#include "WallpaperEngine/FileSystem/Adapters/Package.h"
+#include "WallpaperEngine/Render/GifAnimation.h"
+
+using namespace WallpaperEngine::Data::Parsers;
+using namespace WallpaperEngine::Data::Utils;
+using namespace WallpaperEngine::FileSystem::Adapters;
+using WallpaperEngine::Render::GifAnimation;
+
+namespace {
+// the little endian byte soup a package or a texture is made of
+struct Bytes {
+    std::string data;
+
+    Bytes& u32 (const uint32_t value) {
+	for (int shift = 0; shift < 32; shift += 8) {
+	    this->data.push_back (static_cast<char> ((value >> shift) & 0xFF));
+	}
+
+	return *this;
+    }
+
+    Bytes& text (const std::string& value) {
+	this->data += value;
+	return *this;
+    }
+
+    // a NUL terminated tag, like TEXV0005
+    Bytes& tag (const std::string& value) { return this->text (value).text (std::string (1, '\0')); }
+
+    Bytes& sized (const std::string& value) { return this->u32 (static_cast<uint32_t> (value.size ())).text (value); }
+
+    [[nodiscard]] ReadStreamSharedPtr stream () const { return std::make_shared<std::istringstream> (this->data); }
+    [[nodiscard]] BinaryReader reader () const { return BinaryReader (this->stream ()); }
+};
+
+// TEXV0005 with a TEXI0001 header (a 4x4 RGBA image) and the start of a TEXB0001 container
+Bytes textureStart () {
+    Bytes bytes;
+
+    bytes.tag ("TEXV0005").tag ("TEXI0001");
+    bytes.u32 (0).u32 (0).u32 (4).u32 (4).u32 (4).u32 (4).u32 (0);
+    bytes.tag ("TEXB0001");
+
+    return bytes;
+}
+} // namespace
+
+TEST_CASE ("A read past the end gives zeros, not whatever was on the stack") {
+    Bytes bytes;
+    bytes.text (std::string ("\x01\x02", 2));
+    auto reader = bytes.reader ();
+
+    CHECK (reader.nextUInt32 () == 0x0201);
+    CHECK (reader.base ().fail ());
+    CHECK (reader.nextUInt32 () == 0);
+    CHECK (reader.nextInt () == 0);
+    CHECK (reader.nextFloat () == 0.0f);
+
+    char out[8];
+    std::memset (out, 0x7F, sizeof (out));
+    reader.next (out, sizeof (out));
+
+    for (const char byte : out) {
+	CHECK (byte == 0);
+    }
+}
+
+TEST_CASE ("A string without a terminator ends with the data") {
+    Bytes bytes;
+    bytes.text ("abc");
+
+    CHECK (bytes.reader ().nextNullTerminatedString () == "abc");
+}
+
+TEST_CASE ("A sized string longer than the data is refused without being allocated") {
+    Bytes bytes;
+    bytes.u32 (0xFFFFFFFFu).text ("ab");
+    auto reader = bytes.reader ();
+
+    CHECK (reader.nextSizedString ().empty ());
+    CHECK (reader.base ().fail ());
+}
+
+TEST_CASE ("A package that lists more files than it can hold is refused") {
+    Bytes bytes;
+    bytes.sized ("PKGV0001").u32 (0xFFFFFFFFu);
+
+    CHECK_THROWS_AS (PackageParser::parse (bytes.stream ()), std::runtime_error);
+}
+
+TEST_CASE ("A package entry past the end is refused and the entries after it still read") {
+    constexpr uint32_t headerSize = 4 + 8 + 4 + (4 + 7 + 8) + (4 + 6 + 8);
+    Bytes bytes;
+
+    bytes.sized ("PKGV0001").u32 (2);
+    bytes.sized ("bad.bin").u32 (0).u32 (0x40000000u);
+    bytes.sized ("ok.txt").u32 (0).u32 (5);
+    REQUIRE (bytes.data.size () == headerSize);
+    bytes.text ("hello");
+
+    PackageAdapter adapter (PackageParser::parse (bytes.stream ()));
+
+    CHECK_THROWS_AS (adapter.open ("bad.bin"), std::filesystem::filesystem_error);
+
+    const auto good = adapter.open ("ok.txt");
+    std::string content (5, '\0');
+    good->read (content.data (), 5);
+
+    CHECK (content == "hello");
+}
+
+TEST_CASE ("A texture that claims more mipmap data than the file holds is refused") {
+    auto bytes = textureStart ();
+
+    // one image, one mipmap of 4x4 that says it is 2 GB long
+    bytes.u32 (1).u32 (1).u32 (4).u32 (4).u32 (0x7FFFFFF0u);
+
+    auto reader = bytes.reader ();
+
+    CHECK_THROWS_AS (TextureParser::parse (reader), std::runtime_error);
+}
+
+TEST_CASE ("A texture without any mipmap is refused") {
+    auto bytes = textureStart ();
+
+    bytes.u32 (1).u32 (0);
+
+    auto reader = bytes.reader ();
+
+    CHECK_THROWS_AS (TextureParser::parse (reader), std::runtime_error);
+}
+
+TEST_CASE ("A texture that claims billions of images is refused") {
+    auto bytes = textureStart ();
+
+    bytes.u32 (0x7FFFFFFFu);
+
+    auto reader = bytes.reader ();
+
+    CHECK_THROWS_AS (TextureParser::parse (reader), std::runtime_error);
+}
+
+TEST_CASE ("A texture with room for what it claims still loads") {
+    auto bytes = textureStart ();
+
+    // one image, one 4x4 mipmap of 64 raw bytes
+    bytes.u32 (1).u32 (1).u32 (4).u32 (4).u32 (64).text (std::string (64, 'x'));
+
+    auto reader = bytes.reader ();
+    const auto texture = TextureParser::parse (reader);
+
+    REQUIRE (texture != nullptr);
+    REQUIRE (texture->images.size () == 1);
+    REQUIRE (texture->images.at (0).size () == 1);
+    CHECK (texture->images.at (0).front ()->uncompressedSize == 64);
+}
+
+TEST_CASE ("A GIF whose header claims a canvas of billions of pixels is refused") {
+    // GIF89a, 65535 x 65535, no color table
+    const uint8_t header[] = { 'G', 'I', 'F', '8', '9', 'a', 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00 };
+    const auto gif = GifAnimation::open (header, sizeof (header));
+
+    REQUIRE (gif != nullptr);
+    CHECK_FALSE (gif->advance (0.0f));
+}
+
+TEST_CASE ("A one pixel GIF still plays") {
+    const uint8_t pixel[] = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0xFF, 0xFF,
+			      0xFF, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00,
+			      0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3B };
+    const auto gif = GifAnimation::open (pixel, sizeof (pixel));
+
+    REQUIRE (gif != nullptr);
+    CHECK (gif->advance (0.0f));
+    CHECK (gif->width () == 1);
+    CHECK (gif->height () == 1);
+}

이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.