Commit

fdfcd7543e8c2c045ea215b17e6e772a9770018a

rust: discard hash context when finished

When we allocate a context but then abandon it, we never discard it,
which means that the underlying crypto library context may leak.  This
doesn't happen with our default block code, but it may with OpenSSL.
Note that we do call git_hash_free, which frees the memory we called
from git_hash_alloc, but doesn't discard the underlying context itself.

This can be seen with the following command when compiling with OpenSSL
and running with nightly Rust:

    RUSTFLAGS='-Z sanitizer=leak' cargo test

Discard the context in our context handler.  Note that it is fine to do
so even after finalizing the context, so our final functions which take
self instead of &mut self will not mishandle memory.

Signed-off-by: brian m. carlson <sandals@crustytoothpaste.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>

brian m. carlson <sandals@crustytoothpaste.net> · 2026-07-19 01:08 UTC · committed by Junio C Hamano

Browse files
1 file changed, +7 −1
modified src/hash.rs
@@ -194,7 +194,10 @@ impl Clone for CryptoHasher {
194 194
195 195 impl Drop for CryptoHasher {
196 196 fn drop(&mut self) {
197 - unsafe { c::git_hash_free(self.ctx) };
197 + unsafe {
198 + c::git_hash_discard(self.ctx);
199 + c::git_hash_free(self.ctx);
200 + };
198 201 }
199 202 }
200 203
@@ -356,6 +359,7 @@ pub mod c {
356 359 pub fn git_hash_clone(dst: *mut c_void, src: *const c_void);
357 360 pub fn git_hash_update(ctx: *mut c_void, inp: *const c_void, len: usize);
358 361 pub fn git_hash_final(hash: *mut u8, ctx: *mut c_void);
362 + pub fn git_hash_discard(ctx: *mut c_void);
359 363 pub fn git_hash_final_oid(hash: *mut c_void, ctx: *mut c_void);
360 364 }
361 365 }
@@ -450,6 +454,7 @@ mod tests {
450 454 h.update(&data[2..]);
451 455
452 456 let h2 = h.clone();
457 + let h3 = h2.clone();
453 458
454 459 let actual_oid = h.into_oid();
455 460 assert_eq!(**oid, actual_oid);
@@ -463,6 +468,7 @@ mod tests {
463 468
464 469 let actual_oid = h.into_oid();
465 470 assert_eq!(**oid, actual_oid);
471 + std::mem::drop(h3);
466 472 }
467 473 }
468 474 }