Fix use after free when advanced indexing tensors with tensors #4559
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When indexing tensors with tensors, like the following code, a use after free occurs. This doesn't actually impact anything in practice (nothing crashes or errors out) but is theoretically undefined behavior.
Advanced indexing on Variables doesn't exhibit this behavior because it's a different codepath.
Sample code:
Explanation
In
THPTensor_(_convertToTensorIndexers), avector<THPIndexTensor>is created by constructingTHPTensors from sequences/tensors/etc. EachTHPIndexTensoris then freed with the following:This is a problem because
Py_DECREF(idx)will turnidx->ob_refcntto 0 since this function created the relevantTHPIndexTensors and owns them, causingTHPTensor_(dealloc)to be called.THPTensor_(dealloc)already has a line that callsTHIndexTensor_(free)(LIBRARY_STATE idx->cdata).So
THIndexTensor_(free)(LIBRARY_STATE idx->cdata)gets called twice on the samecdata. After the first call freescdata, the second attempts to access flags/members ofcdatato determine if it should free it.