blockcache: fix heap escape in GetBlock
This commit fixes a heap escape found in `GetBlock`. This happens because the `msgBlock` is a pointer returned from `getBlockImpl`, and the whole `getBlockImpl` escapes to the heap because it's referenced in two places, - in the `Cache`, it's used as a reference type to create the new block. - this pointer is also returned and now needs to stay on the heap. The fix is simple, we now make a copy of the block and use the copy instead, freeing `getBlockImpl` from the heap.
This commit is contained in:
1 file changed
+7
-3
@@ -52,22 +52,26 @@ func (bc *BlockCache) GetBlock(hash *chainhash.Hash,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fetch the block from the chain backends.
|
// Fetch the block from the chain backends.
|
||||||
block, err := getBlockImpl(hash)
|
msgBlock, err := getBlockImpl(hash)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Make a copy of the block so it won't escape to the heap.
|
||||||
|
msgBlockCopy := msgBlock.Copy()
|
||||||
|
block := btcutil.NewBlock(msgBlockCopy)
|
||||||
|
|
||||||
// Add the new block to blockCache. If the Cache is at its maximum
|
// Add the new block to blockCache. If the Cache is at its maximum
|
||||||
// capacity then the LFU item will be evicted in favour of this new
|
// capacity then the LFU item will be evicted in favour of this new
|
||||||
// block.
|
// block.
|
||||||
_, err = bc.Cache.Put(
|
_, err = bc.Cache.Put(
|
||||||
*inv, &neutrino.CacheableBlock{
|
*inv, &neutrino.CacheableBlock{
|
||||||
Block: btcutil.NewBlock(block),
|
Block: block,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return block, nil
|
return msgBlockCopy, nil
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user