Created
November 30, 2023 23:44
-
-
Save grepwood/8e42b2bd0e56cd964cbd77b6d182aff0 to your computer and use it in GitHub Desktop.
malloc and free WSL interop sockets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# malloc_wsl_interop_socket synopsis | |
# stdout: absolute path to valid interop socket | |
function malloc_wsl_interop_socket { | |
local INTEROP_PARENT_PID=0 | |
local INTEROP_SOCKET_PID=0 | |
local INTEROP_BAIT_PROCESS='sleep infinity' | |
pushd / >/dev/null | |
(/mnt/c/Windows/system32/wsl.exe ${INTEROP_BAIT_PROCESS[@]} >/dev/null) & | |
INTEROP_PARENT_PID=${!} | |
popd >/dev/null | |
# Give time for wsl.exe to fork our process | |
sleep 1 | |
local CHECKSUM=$(printf "${INTEROP_BAIT_PROCESS}" | sed 's/\ *$/\ /' | tr ' ' '\0' | sha256sum - | awk '{ print $1 }') | |
local CHILD_PID_OF_WSL_SOCKET=$(ps -o uid,pid= -p $(find /proc -mindepth 2 -maxdepth 2 -type f -name cmdline -exec sha256sum {} \; | awk '{ if ( $1 == "'${CHECKSUM}'" ) { print $2 } }' | awk -F '/' '{ print $3 }' | sed 1d | awk '{ if ( $1 != 0 ) { print $2 } }') | |
if [ "x${CHILD_PID_OF_WSL_SOCKET}" = "x" ]; then | |
echo "No process found" >&2 | |
return -1 | |
fi | |
local VALID_INTEROP_SOCKET="/run/WSL/$(ps -o ppid= -p ${CHILD_PID_OF_WSL_SOCKET} | grep -Eo [0-9]+)_interop" | |
kill -15 ${INTEROP_PARENT_PID} | |
echo ${VALID_INTEROP_SOCKET} | |
} | |
# free_wsl_interop_socket synopsis | |
# return value: same as kill's | |
# stdout: none hopefully | |
function free_wsl_interop_socket { | |
local CHILD_PID_OF_WSL_SOCKET=${1} | |
kill -15 ${CHILD_PID_OF_WSL_SOCKET} | |
local retval=${?} | |
# Allow the socket to actually close | |
sleep 1 | |
return ${retval} | |
} | |
# Example usage | |
socket_path=$(malloc_wsl_interop_socket) | |
socket_pid=$(echo ${socket_path} | sed 's_^.*/__;s/_interop$//') | |
pointer=$(awk '{ print $1 }' /proc/${socket_pid}/task/${socket_pid}/children | head -n1) | |
# There exists a socket | |
ls -l /run/WSL | |
echo "Pointer is: ${pointer}" | |
echo "Socket is: ${socket_path}" | |
echo "Socket PID: ${socket_pid}" | |
# Let's free what we malloc'd | |
free_wsl_interop_socket ${pointer} | |
# Let's check if it's gone :) | |
ls -l /run/WSL |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment