Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Refresh WSL shortcut icons through a Windows Python instead of an emitted P/Invoke (#12184)

Daniel Han407bb3be951b
diff --git a/install.sh b/install.sh
index aa40e0ff4f1..22b7540ae43 100755
--- a/install.sh
+++ b/install.sh
@@ -2483,56 +2483,60 @@ if (\$hasIcon) {
} elseif (\$preIconHash) {
\$iconChanged = \$true
}
-# Per-item refresh always (cheap, non-disruptive) so the rewritten .lnk renders
-# immediately instead of a stale/blank (generic) icon. The reliable fix (no
-# explorer restart) is a PER-ITEM SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATHW,
-# <lnk>) -- the global SHCNE_ASSOCCHANGED alone does not recover a stale item.
-#
-# Emitted, not compiled. Add-Type -MemberDefinition writes C# to %TEMP% and runs
-# csc.exe on Windows PowerShell 5.1, and security software blocks the DLL that comes
-# out. install.ps1 carries the same reflection-emit form for the same reason; this
-# copy was missed when that one changed. Reflection emit builds the identical stub in
-# memory: no compiler process, no source on disk, no DLL.
-# Which product blocked what: tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD)
-try {
- \$refreshType = 'UnslothShellIconRefresh' -as [type]
- if (-not \$refreshType) {
- \$asmName = New-Object System.Reflection.AssemblyName 'UnslothShellIconRefreshAsm'
- # Both spellings, matching New-StudioDynamicAssembly in install.ps1. The static
- # AssemblyBuilder::DefineDynamicAssembly is documented for .NET Framework 4.5 through
- # 4.8.1, so the 5.1 host this script is launched under should take the first branch; it
- # is tried rather than assumed because the outer catch here is empty, so guessing wrong
- # costs the icon refresh with nothing printed. AppDomain.CurrentDomain is the .NET
- # Framework spelling and is absent on .NET Core, so it is the fallback and not the lead.
- \$access = [System.Reflection.Emit.AssemblyBuilderAccess]::Run
+# Per-item SHCNE_UPDATEITEM so a rewritten same-name .lnk re-reads its icon; the global broadcast
+# alone does not. Called through a Windows Python's ctypes, as install.ps1 does, so this script
+# defines no native types. Without one the shortcut still works, and the heavier refresh below
+# still runs on a first install or an icon change.
+if (\$created.Count -gt 0) {
+ \$isAdmin = \$true
+ try {
+ \$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+ } catch {}
+ # Never launch a user-writable interpreter from an elevated shell.
+ \$pyCandidates = @()
+ if (-not \$isAdmin) {
+ \$pyCandidates += Join-Path \$env:USERPROFILE '.unsloth\studio\unsloth_studio\Scripts\python.exe'
+ foreach (\$name in @('python3', 'python')) {
+ try {
+ foreach (\$cmd in @(Get-Command \$name -All -CommandType Application -ErrorAction SilentlyContinue)) {
+ if (\$cmd -and \$cmd.Source) { \$pyCandidates += \$cmd.Source }
+ }
+ } catch {}
+ }
+ }
+ # SHCNF_FLUSH (0x1000): the child exits at once and a queued notification would be lost.
+ \$refreshCode = "import ctypes,os;from ctypes import wintypes as w;f=ctypes.WinDLL('shell32').SHChangeNotify;f.restype=None;f.argtypes=[w.LONG,w.UINT,w.LPCWSTR,w.LPCWSTR];[f(0x2000,0x1005,p,None) for p in os.environ['UNSLOTH_SHORTCUT_PATHS'].split('|') if p];f(0x8000000,0x1000,None,None);print('ok')"
+ foreach (\$py in \$pyCandidates) {
+ # The WindowsApps alias opens the Store instead of running anything.
+ if (-not \$py -or \$py -like '*\Microsoft\WindowsApps\*') { continue }
+ if (-not (Test-Path -LiteralPath \$py -PathType Leaf)) { continue }
+ \$proc = \$null
try {
- \$asm = [System.Reflection.Emit.AssemblyBuilder]::DefineDynamicAssembly(\$asmName, \$access)
- } catch [System.Management.Automation.MethodException] {
- \$asm = [AppDomain]::CurrentDomain.DefineDynamicAssembly(\$asmName, \$access)
- } catch [System.Management.Automation.RuntimeException] {
- # Some hosts surface a missing static as RuntimeException rather than
- # MethodException. Both mean "no such method here", and a real emit failure throws
- # from the AppDomain call too, so a genuine refusal still reaches the outer catch.
- \$asm = [AppDomain]::CurrentDomain.DefineDynamicAssembly(\$asmName, \$access)
+ \$psi = New-Object System.Diagnostics.ProcessStartInfo
+ \$psi.FileName = \$py
+ # -I -S: no user site, no PYTHON* variables, no sitecustomize. -B: write no .pyc.
+ \$psi.Arguments = '-I -S -B -c "' + \$refreshCode + '"'
+ # '|' cannot appear in a Windows path, so it separates them safely.
+ \$psi.EnvironmentVariables['UNSLOTH_SHORTCUT_PATHS'] = (\$created -join '|')
+ \$psi.WorkingDirectory = Split-Path -Parent \$py
+ \$psi.UseShellExecute = \$false
+ \$psi.RedirectStandardOutput = \$true
+ \$psi.RedirectStandardError = \$true
+ \$psi.CreateNoWindow = \$true
+ \$proc = [System.Diagnostics.Process]::Start(\$psi)
+ \$out = \$proc.StandardOutput.ReadToEndAsync()
+ \$null = \$proc.StandardError.ReadToEndAsync()
+ if (-not \$proc.WaitForExit(10000)) {
+ try { \$proc.Kill() } catch {}
+ continue
+ }
+ if (\$proc.ExitCode -eq 0 -and \$out.Wait(2000) -and "\$(\$out.Result)".Trim() -eq 'ok') { break }
+ } catch {
+ } finally {
+ if (\$proc) { try { \$proc.Dispose() } catch {} }
}
- \$module = \$asm.DefineDynamicModule('UnslothShellIconRefreshMod')
- \$typeBuilder = \$module.DefineType('UnslothShellIconRefresh',
- 'Public, Class, AutoClass, AnsiClass, BeforeFieldInit')
- \$method = \$typeBuilder.DefinePInvokeMethod(
- 'SHChangeNotify', 'shell32.dll', 'SHChangeNotify',
- 'Public, Static, PinvokeImpl',
- [System.Reflection.CallingConventions]::Standard,
- [System.Void],
- @([int], [uint32], [string], [IntPtr]),
- [System.Runtime.InteropServices.CallingConvention]::Winapi,
- [System.Runtime.InteropServices.CharSet]::Unicode)
- \$method.SetImplementationFlags(
- \$method.GetMethodImplementationFlags() -bor [System.Reflection.MethodImplAttributes]::PreserveSig)
- \$refreshType = \$typeBuilder.CreateType()
}
- foreach (\$p in \$created) { try { \$refreshType::SHChangeNotify(0x00002000, 0x0005, \$p, [System.IntPtr]::Zero) } catch {} }
- \$refreshType::SHChangeNotify(0x08000000, 0, \$null, [System.IntPtr]::Zero)
-} catch {}
+}
# Heavier on-disk icon-cache clear + StartMenuExperienceHost tile rebuild
# (preserve start2.bin) only on first install or a real icon change, so a no-op
# WSL reinstall does not purge caches and kill a shell process for nothing.
diff --git a/scripts/av_shapes_baseline.json b/scripts/av_shapes_baseline.json
index 20a447656f5..2214c5a29c2 100644
--- a/scripts/av_shapes_baseline.json
+++ b/scripts/av_shapes_baseline.json
@@ -186,20 +186,6 @@
"e90000fd628f2cd7": 1
}
},
- {
- "file": "install.sh",
- "rule": "AV003",
- "severity": "error",
- "reason": "Follow-up: the WSL shortcut helper still emits the SHChangeNotify stub. install.ps1 moved to a Python ctypes call, which the Windows side of a WSL install cannot assume; porting needs a Windows-side answer first.",
- "digests": {
- "1897f2aa96938163": 1,
- "3317dda9215e254f": 1,
- "c8db648faf495659": 2,
- "c8fa2e7a650eb3af": 1,
- "c96dd772e1920082": 1,
- "cb6ff73cf7b8ed0c": 1
- }
- },
{
"file": "install.sh",
"rule": "AV015",
@@ -827,15 +813,6 @@
"d08d063ea93f28d2": 1
}
},
- {
- "file": "tests/sh/test_wsl_shortcut_script_location.sh",
- "rule": "AV003",
- "severity": "error",
- "reason": "Pins the install.sh WSL helper recorded above; goes with it.",
- "digests": {
- "ed5258165f0a8925": 1
- }
- },
{
"file": "tests/sh/test_wsl_shortcut_script_location.sh",
"rule": "AV015",
@@ -1293,24 +1270,6 @@
"a4083e2a30bc3f7e": 1
}
},
- {
- "file": "tests/studio/test_wsl_shortcut_script_is_valid_powershell.py",
- "rule": "AV003",
- "severity": "error",
- "reason": "Validates the install.sh WSL helper recorded above; goes with it.",
- "digests": {
- "14db729e0d1df21f": 1,
- "605726d25d6c74fe": 1,
- "611de8088070073f": 1,
- "8d7e802bd274b18c": 1,
- "9ba5999e0a404e34": 1,
- "9d08db7625c25e4b": 1,
- "a7adeb5fbb15c560": 1,
- "b0099be6101029bb": 1,
- "c4c5312af5715290": 1,
- "fbd34206a5c7c998": 1
- }
- },
{
"file": "tests/studio/test_xpu_arm64_torchaudio.ps1",
"rule": "AV015",
diff --git a/tests/sh/test_wsl_shortcut_script_location.sh b/tests/sh/test_wsl_shortcut_script_location.sh
index 84a1b7ba8a8..08547745497 100755
--- a/tests/sh/test_wsl_shortcut_script_location.sh
+++ b/tests/sh/test_wsl_shortcut_script_location.sh
@@ -191,18 +191,19 @@ assert_not_contains "the shortcut launch does not relax the policy" "$LAUNCH" "-
POLICY_HITS=$(grep -c -- '-ExecutionPolicy Bypass' "$INSTALL_SH" || true)
assert_eq "install.sh relaxes the execution policy nowhere" "0" "$POLICY_HITS"
-# The generated script declares SHChangeNotify by emitting it. Add-Type -MemberDefinition writes C#
-# to %TEMP% and runs csc.exe on PowerShell 5.1, and behavioural antivirus blocks the DLL that comes
-# out; #10540 removed that from install.ps1 and this copy was missed for a release.
+# The generated script declares no native type at all: Add-Type runs csc.exe on PowerShell 5.1,
+# and emitting the stub instead is its own scored shape. SHChangeNotify goes through a Windows
+# Python's ctypes, as in install.ps1.
ADDTYPE_HITS=$(grep -c '^[[:space:]]*Add-Type' "$INSTALL_SH" || true)
assert_eq "install.sh compiles no C#" "0" "$ADDTYPE_HITS"
-assert_contains "SHChangeNotify is emitted instead" "$(cat "$INSTALL_SH")" "DefinePInvokeMethod"
+assert_not_contains "install.sh emits no P/Invoke stub" "$(cat "$INSTALL_SH")" "DefinePInvoke""Method"
+assert_not_contains "install.sh defines no dynamic assembly" "$(cat "$INSTALL_SH")" "DefineDynamic""Assembly"
# Both notifications survive. The per-item one is the only thing that recovers a rewritten
# same-name .lnk; the global broadcast alone does not, so losing it would show as a stale icon.
BODY=$(cat "$INSTALL_SH")
-assert_contains "per-item SHCNE_UPDATEITEM refresh kept" "$BODY" "SHChangeNotify(0x00002000, 0x0005"
-assert_contains "global SHCNE_ASSOCCHANGED refresh kept" "$BODY" "SHChangeNotify(0x08000000, 0"
+assert_contains "per-item SHCNE_UPDATEITEM refresh kept" "$BODY" "f(0x2000,0x1005,p,None)"
+assert_contains "global SHCNE_ASSOCCHANGED refresh kept" "$BODY" "f(0x8000000,0x1000,None,None)"
# A cmd.exe stub that reproduces the ORDER cmd works in: %VAR% is expanded first, and the result is
# then parsed for metacharacters. That is what makes an & inside the value dangerous, and the
diff --git a/tests/studio/test_installer_av_shapes.py b/tests/studio/test_installer_av_shapes.py
index f1b4d59ab63..211572196c5 100644
--- a/tests/studio/test_installer_av_shapes.py
+++ b/tests/studio/test_installer_av_shapes.py
@@ -184,8 +184,10 @@ shell process, repeat on every run" is a cluster behavioural engines score, and
changed nothing it is also pure waste. So both install.ps1 and install.sh snapshot the icon and run
the heavy path only on a first install or an actual change, preserving start2.bin.
-SHChangeNotify stays, and with it one shell32 import: a permanently wrong desktop icon is a worse
-outcome than one import.
+SHChangeNotify stays, called through a Windows Python's ctypes in both install.ps1 and the WSL
+shortcut script install.sh generates, so neither defines a native type. Where no interpreter can be
+reached the per-item refresh is skipped: a stale icon on a shortcut that works is cosmetic, and the
+heavier refresh above still runs on a first install or an icon change.
## uv comes from a pinned archive, not from a remote install script
diff --git a/tests/studio/test_wsl_shortcut_script_is_valid_powershell.py b/tests/studio/test_wsl_shortcut_script_is_valid_powershell.py
index a9350248914..2ae7071f6d6 100644
--- a/tests/studio/test_wsl_shortcut_script_is_valid_powershell.py
+++ b/tests/studio/test_wsl_shortcut_script_is_valid_powershell.py
@@ -10,25 +10,14 @@ into a best-effort `&& _css_created=1`. A parse error there is not a crash and n
whole script fails to load, no shortcut appears, and the user gets the "WSL interop may be
disabled" notice, which points at the wrong thing entirely.
-That path is one edit away at all times. The block this guards was just rewritten from a
-one-line `Add-Type -MemberDefinition` into a twenty-line reflection-emit sequence with nested
-calls, an array literal and a here-string escaping every `$` it means to keep -- and it sits
-inside `try { } catch { }`, so even at RUNTIME on the right machine a mistake inside it is
-swallowed.
-
-The emit test is the other half: syntax is not enough, the API sequence has to be real. shell32
-is Windows-only, but DefineDynamicAssembly / DefineDynamicModule / DefineType /
-DefinePInvokeMethod / CreateType is not, so the same sequence is pointed at a symbol this host
-does export and the resulting method is called. A wrong call order or a wrong argument count
-fails here, on Linux, instead of silently on a user's desktop.
-
-What that is worth, measured rather than asserted. Mutating the shipped file five ways: a dropped
-closing paren in DefinePInvokeMethod, an unterminated string literal in DefineType and a stray
-closing brace all fail both tests or the parse one; giving the P/Invoke the wrong number of
-parameters fails the emit one. Dropping SetImplementationFlags does NOT fail, and cannot: it sets
-PreserveSig, whose only effect is on how a failing HRESULT is surfaced, and the retargeted symbol
-here returns a plain int. That line is unguarded and is the one place a reviewer still has to
-read for themselves.
+That path is one edit away at all times, and the icon refresh inside it sits in `try { } catch { }`,
+so even at RUNTIME on the right machine a mistake there is swallowed.
+
+The refresh tests are the other half: syntax is not enough. The per-item SHChangeNotify runs in a
+Windows Python through ctypes, and both halves of that are checked here on Linux: the Python it
+passes is run against a recording stand-in for shell32, and the PowerShell that launches it is run
+under pwsh against a stand-in interpreter, so a quoting mistake in the command line, a lost path or
+a wrong flag fails here instead of silently on a user's desktop.
"""
from __future__ import annotations
@@ -135,47 +124,130 @@ def test_the_generated_wsl_shortcut_script_parses() -> None:
)
+_SHELL32_STUB = """
+import ctypes, json, os, sys
+calls = []
+class _Fn:
+ def __call__(self, *a):
+ calls.append(list(a))
+class _Dll:
+ def __init__(self, name):
+ assert name == "shell32", name
+ self.SHChangeNotify = _Fn()
+ctypes.WinDLL = _Dll
+exec(sys.argv[1])
+sys.stderr.write(json.dumps(calls))
+"""
+
+
+def _refresh_code(rendered: str) -> str:
+ match = re.search(r'(?m)^ \$refreshCode = "([^"\r\n]*)"$', rendered)
+ assert match, "could not find the icon refresh's Python in the generated script"
+ return match.group(1)
+
+
+_LINKS = [
+ "C:\\Users\\O'Brien\\Desktop\\Unsloth Studio (WSL - O'Brien 24.04).lnk",
+ "C:\\Users\\O'Brien\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\x.lnk",
+]
+_EXPECTED_CALLS = [[0x2000, 0x1005, link, None] for link in _LINKS] + [
+ [0x8000000, 0x1000, None, None]
+]
+
+
+def test_the_icon_refresh_python_notifies_each_shortcut_then_the_shell() -> None:
+ """Per-item SHCNE_UPDATEITEM for every shortcut, then SHCNE_ASSOCCHANGED, all flushed."""
+ import json
+
+ done = subprocess.run(
+ [sys.executable, "-I", "-S", "-B", "-c", _SHELL32_STUB, _refresh_code(_render())],
+ capture_output = True,
+ text = True,
+ env = {"UNSLOTH_SHORTCUT_PATHS": "|".join(_LINKS)},
+ )
+ assert done.returncode == 0, done.stderr
+ assert done.stdout.strip() == "ok", done.stdout
+ assert json.loads(done.stderr) == _EXPECTED_CALLS
+
+
@needs_pwsh
-def test_the_icon_refresh_emit_sequence_builds_a_callable_type() -> None:
+def test_the_icon_refresh_launch_runs_one_interpreter_with_every_shortcut(tmp_path: Path) -> None:
+ """The PowerShell half: candidate order, the WindowsApps skip, argv quoting, stop on success.
+
+ The block is lifted from the rendered script as written; only the elevation probe, which has
+ no answer off Windows, is pinned to "not elevated".
+ """
+ import json
+
rendered = _render()
- emit = re.search(r"(?ms)^try \{\n( \$refreshType = .*?)\n\} catch \{\}", rendered)
- assert emit, (
- "could not find the icon-refresh emit block in the generated script; if SHChangeNotify "
- "is now declared some other way, update this test rather than deleting it"
+ match = re.search(r"(?ms)^(if \(\$created\.Count -gt 0\) \{\n.*?^\})\n", rendered)
+ assert match, "could not find the icon refresh block in the generated script"
+ block = match.group(1)
+ elevation = re.search(r"(?m)^ \$isAdmin = \(\[Security.*$", block)
+ assert elevation, "the refresh no longer checks elevation before launching an interpreter"
+ block = block.replace(elevation.group(0), " $isAdmin = $false")
+
+ log = tmp_path / "calls.jsonl"
+ stub = tmp_path / "stub.py"
+ stub.write_text(
+ _SHELL32_STUB.replace(
+ "sys.stderr.write(json.dumps(calls))",
+ "open(os.environ['STUB_LOG'], 'a').write(json.dumps("
+ "{'argv': sys.argv[2:], 'cwd': os.getcwd(), 'calls': calls}) + '\\n')",
+ )
)
- # Retargeted, not rewritten: only the library, the symbol and its signature change, so the
- # call sequence under test is the shipped one character for character.
- body = emit.group(1)
- body = body.replace(
- "'SHChangeNotify', 'shell32.dll', 'SHChangeNotify'", "'getpid', 'libc', 'getpid'"
+ # A stand-in interpreter taking the real one's argv, which is what the quoting has to survive.
+ venv_python = (
+ tmp_path / "home" / ".unsloth" / "studio" / "unsloth_studio" / "Scripts" / "python.exe"
)
- body = re.sub(r"\[System\.Void\],", "[int],", body)
- body = re.sub(r"@\(\[int\], \[uint32\], \[string\], \[IntPtr\]\),", "@(),", body)
- body = body.replace(
- "[System.Runtime.InteropServices.CharSet]::Unicode)",
- "[System.Runtime.InteropServices.CharSet]::Ansi)",
+ venv_python.parent.mkdir(parents = True)
+ venv_python.write_text(
+ "#!/bin/sh\n"
+ f'[ "$1 $2 $3 $4" = "-I -S -B -c" ] || exit 7\n'
+ f'exec {shlex.quote(sys.executable)} -I -S -B {shlex.quote(str(stub))} "$5"\n'
)
- body = "\n".join(l for l in body.splitlines() if "SHChangeNotify(" not in l)
- body = body.replace("UnslothShellIconRefresh", "UnslothEmitProbe")
- assert "DefinePInvokeMethod" in body and "getpid" in body, body
-
- # Twice, because the block caches on `-as [type]`: a second pass must reuse the type rather
- # than throw on a duplicate name, which is what makes the guard safe to leave in.
- script = body + "\nWrite-Output ('EMIT_A ' + [string]$refreshType::getpid())\n"
- script += body + "\nWrite-Output ('EMIT_B ' + [string]$refreshType::getpid())\n"
+ venv_python.chmod(0o755)
+ # The same stand-in on PATH: reaching it would mean the loop did not stop at the first success.
+ path_dir = tmp_path / "bin"
+ path_dir.mkdir()
+ (path_dir / "python3").write_bytes(venv_python.read_bytes())
+ (path_dir / "python3").chmod(0o755)
+ links = ", ".join("'" + link.replace("'", "''") + "'" for link in _LINKS)
+ script = (
+ f"$env:USERPROFILE = '{tmp_path / 'home'}'\n"
+ f"$env:STUB_LOG = '{log}'\n"
+ f"$env:PATH = '{path_dir}' + [IO.Path]::PathSeparator + $env:PATH\n"
+ f"$created = @({links})\n" + block + "\n"
+ "Write-Output 'BLOCK_DONE'\n"
+ )
+ runner = tmp_path / "refresh.ps1"
+ runner.write_text(script, encoding = "utf-8")
done = run_pwsh(
- ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],
+ ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(runner)],
capture_output = True,
text = True,
- verdict = "EMIT_B",
- )
- pids = re.findall(r"EMIT_[AB] (\d+)", done.stdout)
- assert len(pids) == 2, (
- "the reflection-emit sequence in the generated script does not build a callable P/Invoke "
- "type. shell32 is Windows-only but this sequence is not, so this is the sequence itself "
- f"being wrong:\n{done.stdout.strip()}\n{done.stderr.strip()}"
+ verdict = "BLOCK_DONE",
)
- assert pids[0] == pids[1], f"the cached type was rebuilt instead of reused: {pids}"
+ assert "BLOCK_DONE" in done.stdout, f"{done.stdout}\n{done.stderr}"
+ entries = [json.loads(line) for line in log.read_text().splitlines()]
+ # Exactly one run: the first interpreter answered ok, so PATH's are never tried.
+ assert len(entries) == 1, entries
+ assert entries[0]["calls"] == _EXPECTED_CALLS
+ assert entries[0]["cwd"] == str(venv_python.parent)
+
+
+def test_the_generated_script_defines_no_native_type() -> None:
+ """install.sh held the last reflection-emit P/Invoke in the tree; it must not come back."""
+ rendered = _render()
+ for token in (
+ "Add-Type",
+ "DefinePInvoke" + "Method",
+ "DefineDynamic" + "Assembly",
+ "DllImport",
+ ):
+ assert (
+ token not in rendered
+ ), f"the WSL shortcut script declares a native type again: {token}"
if __name__ == "__main__":
@@ -270,30 +342,3 @@ def test_the_wsl_lane_arms_the_4688_half_of_the_watch() -> None:
"nothing proves the detector fires on this runner, so a clean verdict is indistinguishable "
"from a detector that never attached"
)
-
-
-def test_the_generated_emit_carries_both_spellings_of_define_dynamic_assembly() -> None:
- """The outer catch is empty, so guessing the wrong spelling costs the icon refresh silently.
-
- `install.sh` generates this script and emits its own icon-refresh thunk in it, which is the
- last emit left in the tree: `install.ps1` no longer defines a type at all. The block tries the
- static `AssemblyBuilder::DefineDynamicAssembly` and falls back to
- `AppDomain.CurrentDomain.DefineDynamicAssembly`, and the reason is worth keeping written down:
- the static form is documented for .NET Framework 4.5 through 4.8.1, so the Windows PowerShell
- 5.1 host this script is launched under should take the first branch, but nothing in this
- repository can run a .NET Framework host to confirm it. The generated script had only the static
- form under a bare `catch {}`, which is the combination that fails invisibly. Keep both.
- """
- script = _render()
- assert (
- "[System.Reflection.Emit.AssemblyBuilder]::DefineDynamicAssembly" in script
- ), "the generated script no longer tries the documented static spelling first"
- assert "[AppDomain]::CurrentDomain.DefineDynamicAssembly" in script, (
- "the generated script has no AppDomain fallback, so on a host without the static overload "
- "the empty outer catch swallows the failure and both icon refreshes stop happening"
- )
- static_at = script.index("[System.Reflection.Emit.AssemblyBuilder]::DefineDynamicAssembly")
- appdomain_at = script.index("[AppDomain]::CurrentDomain.DefineDynamicAssembly")
- assert (
- static_at < appdomain_at
- ), "AppDomain.CurrentDomain is absent on .NET Core, so leading with it would break pwsh"