當你嘗試在WSL上運行32位的程序時,shell將會報錯:cannot execute binary file: Exec format error. 這是因為WSL目前暫不支持32位的ELF可執行文件。有人請求在WSL中添加該支持,微軟的回復是在做了咕咕咕。但是,沒有官方支持和不能用是兩回事,StackOverflow上的一個workaround很好地解決了這個問題。原理簡而言之,就是利用一個解釋器(QEMU)來將32位程序轉譯成64位程序執行。這個方法在Ubuntu-WSL上的步驟如下:
- 安裝qemu-user-static:
sudo apt install qemu-user-static
- 設置binfmts:
sudo update-binfmts --install i386 /usr/bin/qemu-i386-static --magic '\x7fELF\x01\x01\x01\x03\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x03\x00\x01\x00\x00\x00' --mask '\xff\xff\xff\xff\xff\xff\xff\xfc\xff\xff\xff\xff\xff\xff\xff\xff\xf8\xff\xff\xff\xff\xff\xff\xff'
- 重啟binfmt服務:
sudo service binfmt-support start
- 啟用 i386 架構相關的包:
sudo dpkg --add-architecture i386
sudo apt update sudo apt
install gcc:i386
這在Ubuntu-WSL上被證明可以工作得很好。但是,對於Arch-WSL,事情變得略微麻煩了,因為Arch-WSL沒有模擬systemd的功能,所以無法像支持systemd的系統一樣使用systemd內嵌的binfmt服務,而需要另外安裝binfmt-support的包,該包只有AUR提供(以yay作為AUR包管理器為例): yay -S binfmt-support
另外,qemu在Arch上也只有AUR提供: yay -S qemu-user-static
該包依賴於glib2-static,我在安裝時,glib2-static的編譯過程因為test不通過而失敗,只好在PKGBUILD中手動注釋掉test的步驟,然后makepkg -sri
進行編譯安裝。 安裝完成后,每次啟動系統都要執行
sudo update-binfmts --install i386 /usr/bin/qemu-i386-static --magic '\x7fELF\x01\x01\x01\x03\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x03\x00\x01\x00\x00\x00' --mask '\xff\xff\xff\xff\xff\xff\xff\xfc\xff\xff\xff\xff\xff\xff\xff\xff\xf8\xff\xff\xff\xff\xff\xff\xff'
添加支持,這很不方便。可以通過將這一命令添加到/etc/profile中來在每次登錄時自動執行這一過程。該命令需要以superuser身份執行,如果你沒有設置為sudo所有命令免除密碼的話,需要用visudo修改sudoer文件,添加
%USERNAME% ALL=(ALL) NOPASSWD:/usr/bin/update-binfmts
避免在執行update-binfmts時需要密碼。注意將%USERNAME%替換成你的用戶名,同時命令必須以絕對路徑形式列出,否則sudoer文件不能生效。