wolfSSL / wolfTPM

wolfTPM is a highly portable TPM 2.0 library, designed for embedded use.
https://www.wolfssl.com
GNU General Public License v2.0
230 stars 56 forks source link

Error handling in C# wrapper #222

Closed zhichao-h closed 1 year ago

zhichao-h commented 2 years ago

The wolftpm.cs bridges the native calls and transparently returns the error codes. This forces the high level code must research the different error returns. This can be hard to use or abuse.

I recommend raise C# Exceptions such as WolfTpmException("message", error_code) when the return code indicates error. So the following code:

[DllImport(DLLNAME, EntryPoint = "wolfTPM2_GetRandom")]
        private static extern int wolfTPM2_GetRandom(IntPtr dev,
                                                     byte[] buf,
                                                     int len);
        public int GetRandom(byte[] buf)
        {
            return wolfTPM2_GetRandom(device, buf, buf.Length);
        }

should better be implemented as

[DllImport(DLLNAME, EntryPoint = "wolfTPM2_GetRandom")]
        private static extern int wolfTPM2_GetRandom(IntPtr dev,
                                                     byte[] buf,
                                                     int len);
        public void GetRandom(byte[] buf)
        {
            int ret = wolfTPM2_GetRandom(device, buf, buf.Length);
            if ( ret != TPM_RC_SUCCESS)
            {
                 throw new wolfTpm2Exception("wolfTPM2_GetRandom failed", ret);
            }
        }

With this modification, the high level code will not need to get into the details of understanding the error codes from native side.

dgarske commented 2 years ago

Hi @zhichao-h , also great suggestion!

Does this look like a good example for what WolfTpm2Exception would look like?

[Serializable]
public class WolfTpm2Exception : Exception
{
    public int ErrorCode { get; }

    public WolfTpm2Exception() { }

    public WolfTpm2Exception(string message)
        : base(message) { }

    public WolfTpm2Exception(string message, Exception inner)
        : base(message, inner) { }

    public WolfTpm2Exception(string message, int errorCode)
        : this(message)
    {
        ErrorCode = errorCode;
    }
}

Thanks, David Garske, wolfSSL

dgarske commented 1 year ago

Fixed in PR #224. Marking closed.