Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-4213

CryptClient.StartDecryptionContext pins buffer but never unpins

      The following code is located in CryptClient.cs:

      public CryptContext StartDecryptionContext(byte[] buffer)
      {
          ContextSafeHandle handle = Library.mongocrypt_ctx_new(_handle);
                                                                                                        
          GCHandle gch = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                                                                                                        
          unsafe
          {
              fixed (byte* p = buffer)
              {
                  IntPtr ptr = (IntPtr)p;
                  using (PinnedBinary pinned = new PinnedBinary(ptr, (uint)buffer.Length))
                  {
                      handle.Check(_status, Library.mongocrypt_ctx_decrypt_init(handle, pinned.Handle));
                  }
              }
          }
                                                                                                        
          return new CryptContext(handle);
      }
      

      Note the 5th line where gch is allocated. The allocated GCHandle is a struct that represents a pointer that can be passed to unmanaged code. You must explicitly free it. It has no finalizer or Dispose method. If you allocate it pinned (as done here), it acts as a rooted reference which will keep the referenced memory (and anything it points to) alive indefinitely.

      Note that we later allocate a PinnedBinary, which implements IDisposable and allows us to pin the buffer to be passed to the unmanaged code and correctly unpins it upon return.

      Based on my review of the code, the 5th line allocating gch is dead code that should be deleted. Not only is it dead code, it is responsible for keeping alive any System.Byte[] buffer passed into this method. Because we attempt to decrypt any response from the server (in case there are encrypted fields in the response), this results in a slow build-up of System.Byte[] objects when CSFLE is enabled for the .NET/C# Driver.

            Assignee:
            dmitry.lukyanov@mongodb.com Dmitry Lukyanov (Inactive)
            Reporter:
            james.kovacs@mongodb.com James Kovacs
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: