Skip to content

Commit ea18b56

Browse files
committed
Add better error messages for negative sequence indexing in count_kmers_from_sequence
1 parent f8bb730 commit ea18b56

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

src/newmap-count.c

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,9 @@ static PyObject* py_count_kmers_from_sequence(PyObject* self, PyObject* args) {
132132
struct AwFmKmerSearchList *searchList =
133133
awFmCreateKmerSearchList(numKmers);
134134

135+
// Error value for erroneous size_t conversions from negative python longs
136+
const size_t ERROR_VALUE = (size_t)-1;
137+
135138
// Fill the search list with the kmers
136139
searchList->count = numKmers;
137140
for(size_t i = 0; i < numKmers; i++) {
@@ -147,11 +150,28 @@ static PyObject* py_count_kmers_from_sequence(PyObject* self, PyObject* args) {
147150
return NULL;
148151
}
149152

153+
// NB: Throws an OverflowError if negative when converting to size_t
154+
// and returns a (size_t)-1 value. Note size_t is unsigned.
150155
size_t kmer_index = PyLong_AsSize_t(indexObj);
156+
if (kmer_index == ERROR_VALUE &&
157+
PyErr_Occurred()) {
158+
PyErr_Clear();
159+
PyErr_SetString(PyExc_IndexError, "All elements of the the index "
160+
"list must be non-negative integers");
161+
return NULL;
162+
}
163+
151164
size_t kmer_length = PyLong_AsSize_t(lengthObj);
165+
if (kmer_index == ERROR_VALUE &&
166+
PyErr_Occurred()) {
167+
PyErr_Clear();
168+
PyErr_SetString(PyExc_ValueError, "All lengths in the length list"
169+
"list must be non-negative integers");
170+
return NULL;
171+
}
152172

153173
// TODO: Assert or check that the index + length does not go out of
154-
// bounds
174+
// bounds to protect against nonsense input and segmentation faults
155175
searchList->kmerSearchData[i].kmerLength = kmer_length;
156176
searchList->kmerSearchData[i].kmerString =
157177
&inputByteSequence[kmer_index];

0 commit comments

Comments
 (0)