libtorrent icon indicating copy to clipboard operation
libtorrent copied to clipboard

Possible out-of-bounds

Open glassez opened this issue 8 months ago • 5 comments

https://github.com/arvidn/libtorrent/blob/21cbbf74ee4cdf41c5877fddb84bde128d217914/src/merkle_tree.cpp#L760-L762 https://github.com/arvidn/libtorrent/blob/21cbbf74ee4cdf41c5877fddb84bde128d217914/src/merkle_tree.cpp#L768-L770

Isn't end = i + m_tree.end_index() an "out-of-bounds"? Or am I misunderstanding something in this code?

glassez avatar Apr 17 '25 13:04 glassez

it looks suspicious.

arvidn avatar Apr 27 '25 12:04 arvidn

when m_mode is mode_t::piece_layer, m_tree only contains the piece layer, and m_tree.size()is the number of pieces. whenm_nodeismode_t::block_layer, m_treeonly contains the block layer (i.e. the 16kiB blocks) andm_tree.size()is the number of blocks. the index,i`, in those loops are indexing the absolute address of the full tree. So, that's correct.

arvidn avatar Apr 27 '25 12:04 arvidn

If so I would at least rewrite it to be more clear. Using m_tree.end_index() (directly) within the loop condition confusing, IMO.

glassez avatar Apr 27 '25 12:04 glassez

Couldn't num_pieces()/m_num_blocks be used instead?

glassez avatar Apr 27 '25 12:04 glassez

BTW, I would expect the following to be more efficient:

aux::vector<bool> mask;
mask.reserve(size());
mask.resize(merkle_first_leaf(piece_layer_size), false);
mask.resize(mask.size() + num_pieces(), true);
mask.resize(size(), false);

glassez avatar Apr 27 '25 13:04 glassez