| 1 | /*++ |
| 2 | |
| 3 | Copyright (c) Microsoft. All rights reserved. |
| 4 | |
| 5 | Module Name: |
| 6 | |
| 7 | WSLCSessionReference.cpp |
| 8 | |
| 9 | Abstract: |
| 10 | |
| 11 | Implementation for WSLCSessionReference. |
| 12 | |
| 13 | This class provides a weak reference to a session that the SYSTEM service |
| 14 | can use to: |
| 15 | - Check if a session is still alive (OpenSession fails if session is gone) |
| 16 | - Terminate sessions when requested by elevated callers |
| 17 | |
| 18 | --*/ |
| 19 | |
| 20 | #include "WSLCSessionReference.h" |
| 21 | #include "WSLCSession.h" |
| 22 | |
| 23 | namespace wslc = wsl::windows::service::wslc; |
| 24 | |
| 25 | wslc::WSLCSessionReference::WSLCSessionReference(_In_ WSLCSession* Session) |
| 26 | { |
| 27 | Microsoft::WRL::ComPtr<IWeakReferenceSource> weakRefSource; |
| 28 | THROW_IF_FAILED(Session->QueryInterface(IID_PPV_ARGS(&weakRefSource))); |
| 29 | THROW_IF_FAILED(weakRefSource->GetWeakReference(&m_weakSession)); |
| 30 | } |
| 31 | |
| 32 | wslc::WSLCSessionReference::~WSLCSessionReference() = default; |
| 33 | |
| 34 | HRESULT wslc::WSLCSessionReference::OpenSession(_Out_ IWSLCSession** Session) |
| 35 | { |
| 36 | RETURN_HR_IF_NULL(E_POINTER, Session); |
| 37 | |
| 38 | *Session = nullptr; |
| 39 | |
| 40 | Microsoft::WRL::ComPtr<IWSLCSession> lockedSession; |
| 41 | RETURN_IF_FAILED(m_weakSession->Resolve(__uuidof(IWSLCSession), reinterpret_cast<IInspectable**>(lockedSession.GetAddressOf()))); |
| 42 | |
| 43 | RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_OBJECT_NO_LONGER_EXISTS), !lockedSession); |
| 44 | |
| 45 | WSLCSessionState state{}; |
| 46 | RETURN_IF_FAILED(lockedSession->GetState(&state)); |
| 47 | |
| 48 | RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_INVALID_STATE), state != WSLCSessionStateRunning); |
| 49 | |
| 50 | *Session = lockedSession.Detach(); |
| 51 | return S_OK; |
| 52 | } |
| 53 | |
| 54 | HRESULT wslc::WSLCSessionReference::Terminate() |
| 55 | try |
| 56 | { |
| 57 | // Resolve the weak reference directly (bypassing OpenSession which checks GetState). |
| 58 | // We want to terminate regardless of session state. |
| 59 | Microsoft::WRL::ComPtr<IWSLCSession> session; |
| 60 | RETURN_IF_FAILED(m_weakSession->Resolve(__uuidof(IWSLCSession), reinterpret_cast<IInspectable**>(session.GetAddressOf()))); |
| 61 | |
| 62 | if (session) |
| 63 | { |
| 64 | return session->Terminate(); |
| 65 | } |
| 66 | |
| 67 | return S_OK; // Session already released |
| 68 | } |
| 69 | CATCH_RETURN() |