From d3ff2d6b62b095f37582affe84e267d7e5be88c6 Mon Sep 17 00:00:00 2001 From: Josh Bleecher Snyder Date: Fri, 4 Dec 2020 15:36:21 -0800 Subject: device: clear pointers when returning elems to pools Signed-off-by: Josh Bleecher Snyder --- device/pools.go | 2 ++ device/receive.go | 11 +++++++++++ device/send.go | 12 +++++++++++- 3 files changed, 24 insertions(+), 1 deletion(-) (limited to 'device') diff --git a/device/pools.go b/device/pools.go index e778d2e..6939eeb 100644 --- a/device/pools.go +++ b/device/pools.go @@ -65,6 +65,7 @@ func (device *Device) GetInboundElement() *QueueInboundElement { } func (device *Device) PutInboundElement(msg *QueueInboundElement) { + msg.clearPointers() if PreallocatedBuffersPerPool == 0 { device.pool.inboundElementPool.Put(msg) } else { @@ -81,6 +82,7 @@ func (device *Device) GetOutboundElement() *QueueOutboundElement { } func (device *Device) PutOutboundElement(msg *QueueOutboundElement) { + msg.clearPointers() if PreallocatedBuffersPerPool == 0 { device.pool.outboundElementPool.Put(msg) } else { diff --git a/device/receive.go b/device/receive.go index e4a94b5..0a8228c 100644 --- a/device/receive.go +++ b/device/receive.go @@ -37,6 +37,17 @@ type QueueInboundElement struct { endpoint conn.Endpoint } +// clearPointers clears elem fields that contain pointers. +// This makes the garbage collector's life easier and +// avoids accidentally keeping other objects around unnecessarily. +// It also reduces the possible collateral damage from use-after-free bugs. +func (elem *QueueInboundElement) clearPointers() { + elem.buffer = nil + elem.packet = nil + elem.keypair = nil + elem.endpoint = nil +} + func (elem *QueueInboundElement) Drop() { atomic.StoreInt32(&elem.dropped, AtomicTrue) } diff --git a/device/send.go b/device/send.go index fa4da0e..cb3e3f6 100644 --- a/device/send.go +++ b/device/send.go @@ -58,9 +58,19 @@ func (device *Device) NewOutboundElement() *QueueOutboundElement { elem.buffer = device.GetMessageBuffer() elem.Mutex = sync.Mutex{} elem.nonce = 0 + // keypair and peer were cleared (if necessary) by clearPointers. + return elem +} + +// clearPointers clears elem fields that contain pointers. +// This makes the garbage collector's life easier and +// avoids accidentally keeping other objects around unnecessarily. +// It also reduces the possible collateral damage from use-after-free bugs. +func (elem *QueueOutboundElement) clearPointers() { + elem.buffer = nil + elem.packet = nil elem.keypair = nil elem.peer = nil - return elem } func (elem *QueueOutboundElement) Drop() { -- cgit v1.2.3-59-g8ed1b