1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265

use std::error::Error;
use std::convert::TryFrom;

use super::*;

/// Error structure containing the available information on a COM error.
pub struct ComError {

    /// `HRESULT` that triggered the error.
    pub hresult : HRESULT,

    /// Possible detailed error info.
    pub error_info : Option<ErrorInfo>,
}

impl ComError {

    /// Constructs a new `ComError` from a `HRESULT` code.
    pub fn new_hr( hresult : HRESULT ) -> ComError
    {
        ComError { hresult, error_info: None }
    }

    /// Construts a new `ComError` with a given message.
    pub fn new_message(
        hresult: HRESULT,
        description: String
    ) -> ComError
    {
        ComError {
            hresult,
            error_info: Some( ErrorInfo::new( description ) )
        }
    }

    /// Gets the description if it's available.
    pub fn description( &self ) -> Option< &str >
    {
        self.error_info.as_ref().map( |e| e.description.as_str() )
    }
}

impl From<ComError> for std::io::Error {

    fn from( com_error : ComError ) -> std::io::Error {

        let error_kind = match com_error.hresult {

            ::STG_E_FILENOTFOUND => std::io::ErrorKind::NotFound,
            ::E_ACCESSDENIED => std::io::ErrorKind::PermissionDenied,
            ::RPC_E_CALL_REJECTED => std::io::ErrorKind::ConnectionRefused,
            ::RPC_E_DISCONNECTED => std::io::ErrorKind::ConnectionReset,
            ::RPC_E_CALL_CANCELED => std::io::ErrorKind::ConnectionAborted,
            ::RPC_E_TIMEOUT => std::io::ErrorKind::TimedOut,
            ::E_INVALIDARG => std::io::ErrorKind::InvalidInput,
            _ => std::io::ErrorKind::Other,
        };

        std::io::Error::new(
                error_kind,
                com_error.description().unwrap_or( "Unknown error" ) )
    }
}

impl From<std::io::Error> for ComError {

    fn from( io_error : std::io::Error ) -> ComError {

        let hresult = match io_error.kind() {

            std::io::ErrorKind::NotFound => ::STG_E_FILENOTFOUND,
            std::io::ErrorKind::PermissionDenied => ::E_ACCESSDENIED,
            std::io::ErrorKind::ConnectionRefused => ::RPC_E_CALL_REJECTED,
            std::io::ErrorKind::ConnectionReset => ::RPC_E_DISCONNECTED,
            std::io::ErrorKind::ConnectionAborted => ::RPC_E_CALL_CANCELED,
            std::io::ErrorKind::TimedOut => ::RPC_E_TIMEOUT,
            std::io::ErrorKind::InvalidInput => ::E_INVALIDARG,
            _ => ::E_FAIL,
        };

        ComError::new_message( hresult, io_error.description().to_owned() )
    }
}

#[cfg(windows)]
#[allow(non_snake_case)]
mod error_store {

    #[link(name = "oleaut32")]
    extern "system" {
        pub fn SetErrorInfo(
            dw_reserved: u32,
            errorinfo: ::RawComPtr,
        ) -> ::HRESULT;

        pub fn GetErrorInfo(
            dw_reserved: u32,
            errorinfo: &mut ::RawComPtr,
        ) -> ::HRESULT;
    }
}

#[cfg(not(windows))]
#[allow(non_snake_case)]
mod error_store {

    pub unsafe fn SetErrorInfo(
        _dw_reserved: u32,
        _errorinfo: ::RawComPtr,
    ) -> ::HRESULT { ::S_OK }

    pub unsafe fn GetErrorInfo(
        _dw_reserved: u32,
        _errorinfo: &mut ::RawComPtr,
    ) -> ::HRESULT { ::S_OK }
}

/// Error info COM object data.
#[com_class( NO_GUID, IErrorInfo )]
pub struct ErrorInfo {
    guid : GUID,
    source : String,
    description : String,
    help_file: String,
    help_context: u32,
}

impl ErrorInfo {
    pub fn new( description : String ) -> ErrorInfo {
        ErrorInfo {
            description,
            guid: GUID::zero_guid(),
            source: String::new(),
            help_file: String::new(),
            help_context: 0,
        }
    }

    pub fn guid( &self ) -> &GUID { &self.guid }
    pub fn source( &self ) -> &str { &self.source }
    pub fn description( &self ) -> &str { &self.description }
    pub fn help_file( &self ) -> &str { &self.help_file }
    pub fn help_context( &self ) -> u32 { self.help_context }
}

impl<'a> TryFrom<&'a IErrorInfo> for ErrorInfo {

    type Error = ::HRESULT;

    fn try_from( source : &'a IErrorInfo ) -> Result<Self, Self::Error> {

        Ok( ErrorInfo {
            guid: source.get_guid()?,
            source: source.get_source()?.to_owned(),
            description: source.get_description()?.to_owned(),
            help_file: source.get_help_file()?.to_owned(),
            help_context: source.get_help_context()?,
        } )
    }
}

#[com_interface( "1CF2B120-547D-101B-8E65-08002B2BD119" )]
trait IErrorInfo
{
    fn get_guid( &self ) -> ComResult< GUID >;
    fn get_source( &self ) -> ComResult< String >;
    fn get_description( &self ) -> ComResult< String >;
    fn get_help_file( &self ) -> ComResult< String >;
    fn get_help_context( &self ) -> ComResult< u32 >;
}

#[com_impl]
impl IErrorInfo for ErrorInfo
{
    fn get_guid( &self ) -> ComResult< GUID > { Ok( self.guid.clone() ) }
    fn get_source( &self ) -> ComResult< String > { Ok( self.source.clone() ) }
    fn get_description( &self ) -> ComResult< String > { Ok( self.description.clone() ) }
    fn get_help_file( &self ) -> ComResult< String > { Ok( self.help_file.clone() ) }
    fn get_help_context( &self ) -> ComResult< u32 > { Ok( self.help_context ) }
}

/// Extracts the HRESULT from the error result and stores the extended error
/// information in thread memory so it can be fetched by the COM client.
pub fn return_hresult< E >( error : E ) -> HRESULT
    where E : Into< ComError >
{
    // Convet the error.
    let com_error = error.into();

    match com_error.error_info {

        Some( error_info ) => {

            // ComError contains ErrorInfo. We need to set this in the OS error
            // store.

            // Construct the COM class used for IErrorInfo. The class contains the
            // description in memory.
            let mut info = ComBox::< ErrorInfo >::new( error_info );

            // Get the IErrorInfo interface and set it in thread memory.
            let mut error_ptr : RawComPtr = std::ptr::null_mut();
            unsafe {

                // We are intentionally ignoring the HRESULT codes here. We don't
                // want to override the original error HRESULT with these codes.
                ComBox::query_interface(
                        info.as_mut(),
                        &IID_IErrorInfo,
                        &mut error_ptr );
                error_store::SetErrorInfo( 0, error_ptr );

                // SetErrorInfo took ownership of the error.
                // Forget it from the Box.
                Box::into_raw( info );
            }
        },
        None => {
            // No error info in the ComError.
            unsafe { error_store::SetErrorInfo( 0, std::ptr::null_mut() ); }
        }
    }

    // Return the HRESULT of the original error.
    com_error.hresult
}

/// Gets the last COM error that occurred on the current thread.
pub fn get_last_error< E >( last_hr : HRESULT ) -> E
    where E : From< ComError >
{
    let com_error = ComError {
        hresult: last_hr,
        error_info: unsafe {

            // Get the last error COM interface.
            let mut error_ptr : RawComPtr = std::ptr::null_mut();
            let hr = error_store::GetErrorInfo( 0, &mut error_ptr );

            if hr == S_OK {

                let ierrorinfo = ComItf::< IErrorInfo >::wrap( error_ptr );;

                // Construct a proper ErrorInfo struct from the COM interface.
                let error_info = ErrorInfo::try_from(
                        &ierrorinfo as &IErrorInfo ).ok();

                // Release the interface.
                let iunk : &ComItf<IUnknown> = ierrorinfo.as_ref();
                iunk.release();

                error_info

            } else {

                // GetErrorInfo didn't return proper error. Don't provide one
                // in the ComError.
                None
            }
        },
    };

    E::from( com_error )
}